xclim.indices package

Indices module.

Subpackages

Submodules

xclim.indices._agro module

Agroclimatic indice definitions.

xclim.indices._agro.biologically_effective_degree_days(tasmin, tasmax, lat=None, thresh_tasmin='10 degC', method='gladstones', low_dtr='10 degC', high_dtr='13 degC', max_daily_degree_days='9 degC', start_date='04-01', end_date='11-01', freq='YS')[source]

Biologically effective growing degree days.

Growing-degree days with a base of 10°C and an upper limit of 19°C and adjusted for latitudes between 40°N and 50°N for April to October (Northern Hemisphere; October to April in Southern Hemisphere). A temperature range adjustment also promotes small and large swings in daily temperature range. Used as a heat-summation metric in viticulture agroclimatology.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • lat (xarray.DataArray, optional) – Latitude coordinate. If None and method in [“gladstones”, “icclim”], a CF-conformant “latitude” field must be available within the passed DataArray.

  • thresh_tasmin (Quantified) – The minimum temperature threshold.

  • method ({“gladstones”, “icclim”, “jones”}) – The formula to use for the calculation. The “gladstones” integrates a daily temperature range and latitude coefficient. End_date should be “11-01”. The “icclim” method ignores daily temperature range and latitude coefficient. End date should be “10-01”. The “jones” method integrates axial tilt, latitude, and day-of-year on coefficient. End_date should be “11-01”.

  • low_dtr (Quantified) – The lower bound for daily temperature range adjustment (default: 10°C).

  • high_dtr (Quantified) – The higher bound for daily temperature range adjustment (default: 13°C).

  • max_daily_degree_days (Quantified) – The maximum amount of biologically effective degrees days that can be summed daily.

  • start_date (DayOfYearStr) – The hemisphere-based start date to consider (north = April, south = October).

  • end_date (DayOfYearStr) – The hemisphere-based start date to consider (north = October, south = April). This date is non-inclusive.

  • freq (str) – Resampling frequency (default: “YS”; For Southern Hemisphere, should be “YS-JUL”).

Return type:

DataArray

Returns:

xarray.DataArray, [K days] – Biologically effective growing degree days (BEDD).

Warning

Lat coordinate must be provided if method is “gladstones” or “jones”.

Notes

The tasmax ceiling of 19°C is assumed to be the max temperature beyond which no further gains from daily temperature occur. Indice originally published in Gladstones [1992].

Let \(TX_{i}\) and \(TN_{i}\) be the daily maximum and minimum temperature at day \(i\), \(lat\) the latitude of the point of interest, \(degdays_{max}\) the maximum amount of degrees that can be summed per day (typically, 9). Then the sum of daily biologically effective growing degree day (BEDD) units between 1 April and 31 October is:

\[BEDD_i = \sum_{i=\text{April 1}}^{\text{October 31}} min\left( \left( max\left( \frac{TX_i + TN_i)}{2} - 10, 0 \right) * k \right) + TR_{adj}, degdays_{max}\right)\]
\[\begin{split}TR_{adj} = f(TX_{i}, TN_{i}) = \begin{cases} 0.25(TX_{i} - TN_{i} - 13), & \text{if } (TX_{i} - TN_{i}) > 13 \\ 0, & \text{if } 10 < (TX_{i} - TN_{i}) < 13\\ 0.25(TX_{i} - TN_{i} - 10), & \text{if } (TX_{i} - TN_{i}) < 10 \\ \end{cases}\end{split}\]
\[k = f(lat) = 1 + \left(\frac{\left| lat \right|}{50} * 0.06, \text{if }40 < ``|lat|`` <50, \text{else } 0\right)\]

A second version of the BEDD (method=”icclim”) does not consider \(TR_{adj}\) and \(k\) and employs a different end date (30 September) [Project team ECA&D and KNMI, 2013]. The simplified formula is as follows:

\[BEDD_i = \sum_{i=\text{April 1}}^{\text{September 30}} min\left( max\left(\frac{TX_i + TN_i)}{2} - 10, 0\right), degdays_{max}\right)\]

References

Gladstones [1992], Project team ECA&D and KNMI [2013]

xclim.indices._agro.chill_portions(tas, freq='YS', **indexer)[source]

Chill portion based on the dynamic model.

Chill portions are a measure to estimate the bud breaking potential of different crop. The constants and functions are taken from Luedeling et al. (2009) which formalises the method described in Fishman et al. (1987). The model computes the accumulation of an intermediate product that is transformed to the final product once it exceeds a certain concentration. The intermediate product can be broken down at higher temperatures but the final product is stable even at higher temperature. Thus, the dynamic model is more accurate than the Utah model especially in moderate climates like Israel, California, or Spain.

Parameters:
  • tas (xr.DataArray) – Hourly temperature.

  • freq (str) – Resampling frequency.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xr.DataArray, [unitless] – Chill portions after the Dynamic Model.

Notes

Typically, this indicator is computed for a period of the year. You can use the **indexer arguments of select_time in combination with the freq argument to select e.g. a winter period:

cp = chill_portions(tas, date_bounds=("09-01", "03-30"), freq="YS-JUL")

Note that incomplete periods will lead to NaNs.

References

Fishman, Erez, and Couvillon [1987], Luedeling [2012]

Examples

>>> from xclim.indices import chill_portions
>>> from xclim.indices.helpers import make_hourly_temperature
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
>>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax
>>> tas_hourly = make_hourly_temperature(tasmin, tasmax)
>>> cp = chill_portions(tasmin)
xclim.indices._agro.chill_units(tas, positive_only=False, freq='YS')[source]

Chill units using the Utah model.

Chill units are a measure to estimate the bud breaking potential of different crop based on Richardson et al. (1974). The Utah model assigns a weight to each hour depending on the temperature recognising that high temperatures can actual decrease, the potential for bud breaking. Providing positive_only=True will ignore days with negative chill units.

Parameters:
  • tas (xr.DataArray) – Hourly temperature.

  • positive_only (bool) – If True, only positive daily chill units are aggregated.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xr.DataArray, [unitless] – Chill units using the Utah model.

References

Richardson, Seeley, and Walker [1974]

Examples

>>> from xclim.indices import chill_units
>>> from xclim.indices.helpers import make_hourly_temperature
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
>>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax
>>> tas_hourly = make_hourly_temperature(tasmin, tasmax)
>>> cu = chill_units(tasmin)
xclim.indices._agro.cool_night_index(tasmin, lat=None, freq='YS')[source]

Cool Night Index.

Mean minimum temperature for September (northern hemisphere) or March (Southern hemisphere). Used in calculating the Géoviticulture Multicriteria Classification System (Tonietto and Carbonneau [2004]).

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • lat (xarray.DataArray or {“north”, “south”}, optional) – Latitude coordinate as an array, float or string. If None, a CF-conformant “latitude” field must be available within the passed DataArray.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [degC] – Mean of daily minimum temperature for month of interest.

Warning

This indice is calculated using minimum temperature resampled to monthly average, and therefore will accept monthly averaged data as inputs.

Notes

Given that this indice only examines September and March months, it is possible to send in DataArrays containing only these timesteps. Users should be aware that due to the missing values checks in wrapped Indicators, datasets that are missing several months will be flagged as invalid. This check can be ignored by setting the following context:

with xclim.set_options(check_missing="skip"):
    cni = cool_night_index(tasmin)

References

Tonietto and Carbonneau [2004]

Examples

>>> from xclim.indices import cool_night_index
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
>>> cni = cool_night_index(tasmin)
xclim.indices._agro.corn_heat_units(tasmin, tasmax, thresh_tasmin='4.44 degC', thresh_tasmax='10 degC')[source]

Corn heat units.

Temperature-based index used to estimate the development of corn crops. Formula adapted from Bootsma et al. [1999].

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh_tasmin (Quantified) – The minimum temperature threshold needed for corn growth.

  • thresh_tasmax (Quantified) – The maximum temperature threshold needed for corn growth.

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – Daily corn heat units.

Notes

Formula used in calculating the Corn Heat Units for the Agroclimatic Atlas of Quebec [Audet et al., 2012].

The thresholds of 4.44°C for minimum temperatures and 10°C for maximum temperatures were selected following the assumption that no growth occurs below these values.

Let \(TX_{i}\) and \(TN_{i}\) be the daily maximum and minimum temperature at day \(i\). Then the daily corn heat unit is:

\[CHU_i = \frac{YX_{i} + YN_{i}}{2}\]

with

\[YX_i & = 3.33(TX_i -10) - 0.084(TX_i -10)^2, &\text{if } TX_i > 10°C YN_i & = 1.8(TN_i -4.44), &\text{if } TN_i > 4.44°C\]

Where \(YX_{i}\) and \(YN_{i}\) is 0 when \(TX_i \leq 10°C\) and \(TN_i \leq 4.44°C\), respectively.

References

Audet, Côté, Bachand, and Mailhot [2012], Bootsma, Tremblay, and Filion [1999]

xclim.indices._agro.dryness_index(pr, evspsblpot, lat=None, wo='200 mm', freq='YS')[source]

Dryness Index.

Approximation of the water balance for the categorizing the winegrowing season. Uses both precipitation and an adjustment of potential evapotranspiration between April and September (Northern Hemisphere) or October and March (Southern hemisphere). Used in calculating the Géoviticulture Multicriteria Classification System (Tonietto and Carbonneau [2004]).

Parameters:
  • pr (xarray.DataArray) – Precipitation.

  • evspsblpot (xarray.DataArray) – Potential evapotranspiration.

  • lat (xarray.DataArray or {“north”, “south”}, optional) – Latitude coordinate as an array, float or string. If None, a CF-conformant “latitude” field must be available within the passed DataArray.

  • wo (Quantified) – The initial soil water reserve accessible to root systems [length]. Default: 200 mm.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [mm] – Dryness Index.

Warning

Dryness Index expects CF-Convention conformant potential evapotranspiration (positive up). This indice is calculated using evapotranspiration and precipitation resampled and converted to monthly total accumulations, and therefore will accept monthly fluxes as inputs.

Notes

Given that this indice only examines monthly total accumulations for six-month periods depending on the hemisphere, it is possible to send in DataArrays containing only these timesteps. Users should be aware that due to the missing values checks in wrapped Indicators, datasets that are missing several months will be flagged as invalid. This check can be ignored by setting the following context:

with xclim.set_options(check_missing="skip"):
    di = dryness_index(pr, evspsblpot)

Let \(Wo\) be the initial useful soil water reserve (typically “200 mm”), \(P\) be precipitation, \(T_{v}\) be the potential transpiration in the vineyard, and \(E_{s}\) be the direct evaporation from the soil. Then the Dryness Index, or the estimate of soil water reserve at the end of a period (1 April to 30 September in the Northern Hemispherere or 1 October to 31 March in the Southern Hemisphere), can be given by the following formulae:

\[W = \sum_{\text{April 1}}^{\text{September 30}} \left( Wo + P - T_{v} - E_{s} \right)\]

or (for the Southern Hemisphere):

\[W = \sum_{\text{October 1}}^{\text{March 31}} \left( Wo + P - T_{v} - E_{s} \right)\]

Where \(T_{v}\) and \(E_{s}\) are given by the following formulae:

\[T_{v} = ETP * k\]

and

\[E_{s} = \frac{ETP}{N}\left( 1 - k \right) * JPm\]

Where \(ETP\) is evapotranspiration, \(N\) is the number of days in the given month. \(k\) is the coefficient for radiative absorption given by the vine plant architecture, and \(JPm\) is the number of days of effective evaporation from the soil per month, both provided by the following formulae:

\[\begin{split}k = \begin{cases} 0.1, & \text{if month = April (NH) or October (SH)} \\ 0.3, & \text{if month = May (NH) or November (SH)} \\ 0.5, & \text{if month = June - September (NH) or December - March (SH)} \\ \end{cases}\end{split}\]
\[JPm = \max\left( P / 5, N \right)\]

References

Riou [1994], Tonietto and Carbonneau [2004]

Examples

>>> from xclim.indices import dryness_index
>>> dryi = dryness_index(pr_dataset, evspsblpot_dataset, wo="200 mm")
xclim.indices._agro.effective_growing_degree_days(tasmax, tasmin, *, thresh='5 degC', method='bootsma', after_date='07-01', dim='time', freq='YS')[source]

Effective growing degree days.

Growing degree days based on a dynamic start and end of the growing season, as defined in [Bootsma and Gameda and D.W. McKenney, 2005].

Parameters:
  • tasmax (xr.DataArray) – Daily mean temperature.

  • tasmin (xr.DataArray) – Daily minimum temperature.

  • thresh (Quantified) – The minimum temperature threshold.

  • method ({“bootsma”, “qian”}) – The window method used to determine the temperature-based start date. For “bootsma”, the start date is defined as 10 days after the average temperature exceeds a threshold. For “qian”, the start date is based on a weighted 5-day rolling average, based on :py:func`qian_weighted_mean_average`.

  • after_date (str) – Date of the year after which to look for the first frost event. Should have the format ‘%m-%d’.

  • dim (str) – Time dimension.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [K days] – Effective growing degree days (EGDD).

Notes

The effective growing degree days for a given year \(EGDD_i\) can be calculated as follows:

\[EGDD_i = \sum_{i=\text{j_{start}}^{\text{j_{end}}} max\left(TG - Thresh, 0 \right)\]

Where \(TG\) is the mean daly temperature, and \(j_{start}\) and \(j_{end}\) are the start and end dates of the growing season. The growing season start date methodology is determined via the method flag. For “bootsma”, the start date is defined as 10 days after the average temperature exceeds a threshold (5 degC). For “qian”, the start date is based on a weighted 5-day rolling average, based on qian_weighted_mean_average().

The end date is determined as the day preceding the first day with minimum temperature below 0 degC.

References

Bootsma and Gameda and D.W. McKenney [2005]

xclim.indices._agro.hardiness_zones(tasmin, window=30, method='usda', freq='YS')[source]

Hardiness zones.

Hardiness zones are a categorization of the annual extreme temperature minima, averaged over a certain period. The USDA method defines 14 zones, each divided into two sub-zones, using steps of 5°F, starting at -60°F. The Australian National Botanic Gardens method defines 7 zones, using steps of 5°C, starting at -15°C.

Parameters:
  • tasmin (xr.DataArray) – Minimum temperature.

  • window (int) – The length of the averaging window, in years.

  • method ({“usda”, “anbg”}) – Whether to return the American (usda) or the Australian (anbg) classification zones.

  • freq (str) – Resampling frequency.

Returns:

xr.DataArray, [dimensionless] – {method} hardiness zones. US sub-zones are denoted by using a half step. For example, Zone 4b is given as 4.5. Values are given at the end of the averaging window.

References

Dawson [1991], USDA Agricultural Research Service [2012]

xclim.indices._agro.huglin_index(tas, tasmax, lat=None, thresh='10 degC', method='smoothed', start_date='04-01', end_date='10-01', freq='YS')[source]

Huglin Heliothermal Index.

Growing-degree days with a base of 10°C and adjusted for latitudes between 40°N and 50°N for April-September (Northern Hemisphere; October-March in Southern Hemisphere). Originally proposed in Huglin [1978]. Used as a heat-summation metric in viticulture agroclimatology.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • lat (xarray.DataArray) – Latitude coordinate. If None, a CF-conformant “latitude” field must be available within the passed DataArray.

  • thresh (Quantified) – The temperature threshold.

  • method ({“smoothed”, “icclim”, “jones”}) – The formula to use for the latitude coefficient calculation.

  • start_date (DayOfYearStr) – The hemisphere-based start date to consider (north = April, south = October).

  • end_date (DayOfYearStr) – The hemisphere-based start date to consider (north = October, south = April). This date is non-inclusive.

  • freq (str) – Resampling frequency (default: “YS”; For Southern Hemisphere, should be “YS-JUL”).

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – Huglin heliothermal index (HI).

Notes

Let \(TX_{i}\) and \(TG_{i}\) be the daily maximum and mean temperature at day \(i\) and \(T_{thresh}\) the base threshold needed for heat summation (typically, 10 degC). A day-length multiplication, \(k\), based on latitude, \(lat\), is also considered. Then the Huglin heliothermal index for dates between 1 April and 30 September is:

\[HI = \sum_{i=\text{April 1}}^{\text{September 30}} \left( \frac{TX_i + TG_i)}{2} - T_{thresh} \right) * k\]

For the smoothed method, the day-length multiplication factor, \(k\), is calculated as follows:

\[\begin{split}k = f(lat) = \begin{cases} 1, & \text{if } | lat | <= 40 \\ 1 + ((abs(lat) - 40) / 10) * 0.06, & \text{if } 40 < | lat | <= 50 \\ NaN, & \text{if } | lat | > 50 \\ \end{cases}\end{split}\]

For compatibility with ICCLIM, end_date should be set to 11-01, method should be set to icclim. The day-length multiplication factor, \(k\), is calculated as follows:

\[\begin{split}k = f(lat) = \begin{cases} 1.0, & \text{if } | lat | <= 40 \\ 1.02, & \text{if } 40 < | lat | <= 42 \\ 1.03, & \text{if } 42 < | lat | <= 44 \\ 1.04, & \text{if } 44 < | lat | <= 46 \\ 1.05, & \text{if } 46 < | lat | <= 48 \\ 1.06, & \text{if } 48 < | lat | <= 50 \\ NaN, & \text{if } | lat | > 50 \\ \end{cases}\end{split}\]

A more robust day-length calculation based on latitude, calendar, day-of-year, and obliquity is available with method=”jones”. See: xclim.indices.generic.day_lengths() or Hall and Jones [2010] for more information.

References

Hall and Jones [2010], Huglin [1978]

xclim.indices._agro.latitude_temperature_index(tas, lat=None, lat_factor=75, freq='YS')[source]

Latitude-Temperature Index.

Mean temperature of the warmest month with a latitude-based scaling factor [Jackson and Cherry, 1988]. Used for categorizing wine-growing regions.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • lat (xarray.DataArray, optional) – Latitude coordinate. If None, a CF-conformant “latitude” field must be available within the passed DataArray.

  • lat_factor (float) – Latitude factor. Maximum poleward latitude. Default: 75.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – Latitude Temperature Index.

Notes

The latitude factor of 75 is provided for examining the poleward expansion of wine-growing climates under scenarios of climate change (modified from Kenny and Shao [1992]). For comparing 20th century/observed historical records, the original scale factor of 60 is more appropriate.

Let \(Tn_{j}\) be the average temperature for a given month \(j\), \(lat_{f}\) be the latitude factor, and \(lat\) be the latitude of the area of interest. Then the Latitude-Temperature Index (\(LTI\)) is:

\[LTI = max(TN_{j}: j = 1..12)(lat_f - | lat | )\]

References

Jackson and Cherry [1988], Kenny and Shao [1992]

xclim.indices._agro.qian_weighted_mean_average(tas, dim='time')[source]

Binomial smoothed, five-day weighted mean average temperature.

Calculates a five-day weighted moving average with emphasis on temperatures closer to day of interest.

Parameters:
  • tas (xr.DataArray) – Daily mean temperature.

  • dim (str) – Time dimension.

Return type:

DataArray

Returns:

xr.DataArray, [same as tas] – Binomial smoothed, five-day weighted mean average temperature.

Notes

Qian Modified Weighted Mean Indice originally proposed in [Qian et al., 2010], based on [Bootsma and Gameda and D.W. McKenney, 2005].

Let \(X_{n}\) be the average temperature for day \(n\) and \(X_{t}\) be the daily mean temperature on day \(t\). Then the weighted mean average can be calculated as follows:

\[\overline{X}_{n} = \frac{X_{n-2} + 4X_{n-1} + 6X_{n} + 4X_{n+1} + X_{n+2}}{16}\]

References

Bootsma and Gameda and D.W. McKenney [2005], Qian, Zhang, Chen, Feng, and O’Brien [2010]

xclim.indices._agro.rain_season(pr, thresh_wet_start='25.0 mm', window_wet_start=3, window_not_dry_start=30, thresh_dry_start='1.0 mm', window_dry_start=7, method_dry_start='per_day', date_min_start='05-01', date_max_start='12-31', thresh_dry_end='0.0 mm', window_dry_end=20, method_dry_end='per_day', date_min_end='09-01', date_max_end='12-31', freq='YS-JAN')[source]

Find the length of the rain season and the day of year of its start and its end.

The rain season begins when two conditions are met: 1) There must be a number of wet days with precipitations above or equal to a given threshold; 2) There must be another sequence following, where, for a given period in time, there are no dry sequence (i.e. a certain number of days where precipitations are below or equal to a certain threshold). The rain season ends when there is a dry sequence.

Parameters:
  • pr (xr.DataArray) – Precipitation data.

  • thresh_wet_start (Quantified) – Accumulated precipitation threshold associated with window_wet_start.

  • window_wet_start (int) – Number of days when accumulated precipitation is above thresh_wet_start. Defines the first condition to start the rain season.

  • window_not_dry_start (int) – Number of days, after window_wet_start days, during which no dry period must be found as a second and last condition to start the rain season. A dry sequence is defined with thresh_dry_start, window_dry_start and method_dry_start.

  • thresh_dry_start (Quantified) – Threshold length defining a dry day in the sequence related to window_dry_start.

  • window_dry_start (int) – Number of days used to define a dry sequence in the start of the season. Daily precipitations lower than thresh_dry_start during window_dry_start days are considered a dry sequence. The precipitations must be lower than thresh_dry_start for either every day in the sequence (method_dry_start == “per_day”) or for the total (method_dry_start == “total”).

  • method_dry_start ({“per_day”, “total”}) – Method used to define a dry sequence associated with window_dry_start. The threshold thresh_dry_start is either compared to every daily precipitation (method_dry_start == “per_day”) or to total precipitations (method_dry_start == “total”) in the sequence window_dry_start days.

  • date_min_start (DayOfYearStr) – First day of year when season can start (“mm-dd”).

  • date_max_start (DayOfYearStr) – Last day of year when season can start (“mm-dd”).

  • thresh_dry_end (str) – Threshold length defining a dry day in the sequence related to window_dry_end.

  • window_dry_end (int) – Number of days used to define a dry sequence in the end of the season. Daily precipitations lower than thresh_dry_end during window_dry_end days are considered a dry sequence. The precipitations must be lower than thresh_dry_end for either every day in the sequence (method_dry_end == “per_day”) or for the total (method_dry_end == “total”).

  • method_dry_end ({“per_day”, “total”}) – Method used to define a dry sequence associated with window_dry_end. The threshold thresh_dry_end is either compared to every daily precipitation (method_dry_end == “per_day”) or to total precipitations (method_dry_end == “total”) in the sequence window_dry days.

  • date_min_end (DayOfYearStr) – First day of year when season can end (“mm-dd”).

  • date_max_end (DayOfYearStr) – Last day of year when season can end (“mm-dd”).

  • freq (str) – Resampling frequency.

Return type:

tuple[DataArray, DataArray, DataArray]

Returns:

  • rain_season_start (xr.DataArray, [dimensionless]) – The beginning of the rain season.

  • rain_season_end (xr.DataArray, [dimensionless]) – The end of the rain season.

  • rain_season_length (xr.DataArray, [time]) – The length of the rain season.

Notes

The rain season starts at the end of a period of raining (a total precipitation of thresh_wet_start over window_wet_start days). This must be directly followed by a period of window_not_dry_start days with no dry sequence. The dry sequence is a period of window_dry_start days where precipitations are below thresh_dry_start (either the total precipitations over the period, or the daily precipitations, depending on method_dry_start). The rain season stops when a dry sequence happens (the dry sequence is defined as in the start sequence, but with parameters window_dry_end, thresh_dry_end and method_dry_end). The dates on which the season can start are constrained by date_min_start`and `date_max_start (and similarly for the end of the season).

References

Sivakumar [1988]

xclim.indices._agro.standardized_precipitation_evapotranspiration_index(wb, freq='MS', window=1, dist='gamma', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, **indexer)[source]

Standardized Precipitation Evapotranspiration Index (SPEI).

Precipitation minus potential evapotranspiration data (PET) fitted to a statistical distribution (dist), transformed to a cdf, and inverted back to a gaussian normal pdf. The potential evapotranspiration is calculated with a given method (method).

Parameters:
  • wb (xarray.DataArray) – Daily water budget (pr - pet).

  • freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.

  • window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.

  • dist ({‘gamma’, ‘fisk’} or rv_continuous function) – Name of the univariate distribution, or a callable rv_continuous (see scipy.stats).

  • method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization. PWM should be used with a lmoments3 distribution.

  • fitkwargs (dict, optional) – Kwargs passed to xclim.indices.stats.fit used to impose values of certains parameters (floc, fscale). If method is PWM, fitkwargs should be empty, except for floc with dist`=`gamma which is allowed.

  • cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.

  • cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.

  • params (xarray.DataArray, optional) – Fit parameters. The params can be computed using xclim.indices.stats.standardized_index_fit_params in advance. The output can be given here as input, and it overrides other options.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray – Standardized Precipitation Evapotranspiration Index.

See also

standardized_precipitation_index

Standardized Precipitation Index.

xclim.indices.stats.standardized_index

Standardized Index.

xclim.indices.stats.standardized_index_fit_params

Standardized Index Fit Params.

xclim.indices._agro.standardized_precipitation_index(pr, freq='MS', window=1, dist='gamma', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, **indexer)[source]

Standardized Precipitation Index (SPI).

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.

  • window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.

  • dist ({‘gamma’, ‘fisk’} or rv_continuous function) – Name of the univariate distribution, or a callable rv_continuous (see scipy.stats).

  • method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization. PWM should be used with a lmoments3 distribution.

  • fitkwargs (dict, optional) – Kwargs passed to xclim.indices.stats.fit used to impose values of certains parameters (floc, fscale). If method is PWM, fitkwargs should be empty, except for floc with dist`=`gamma which is allowed.

  • cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.

  • cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.

  • params (xarray.DataArray) – Fit parameters. The params can be computed using xclim.indices.stats.standardized_index_fit_params in advance. The output can be given here as input, and it overrides other options.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – Standardized Precipitation Index.

See also

xclim.indices.stats.standardized_index

Standardized Index.

xclim.indices.stats.standardized_index_fit_params

Standardized Index Fit Params.

Notes

  • N-month SPI / N-day SPI is determined by choosing the window = N and the appropriate frequency freq.

  • Supported statistical distributions are: [“gamma”, “fisk”], where “fisk” is scipy’s implementation of a log-logistic distribution

  • Supported frequencies are daily (“D”), weekly (“W”), and monthly (“MS”).

  • Weekly frequency will only work if the input array has a “standard” (non-cftime) calendar.

  • If params is given as input, it overrides the cal_start, cal_end, freq and window, dist and method options.

  • “APP” method only supports two-parameter distributions. Parameter loc needs to be fixed to use method APP.

  • The results from climate_indices library can be reproduced with method = “APP” and fitwkargs = {“floc”: 0}, except for the maximum and minimum values allowed which are greater in xclim ±8.21, . See xclim.indices.stats.standardized_index

References

McKee, Doesken, and Kleist [1993]

Examples

>>> from datetime import datetime
>>> from xclim.indices import standardized_precipitation_index
>>> ds = xr.open_dataset(path_to_pr_file)
>>> pr = ds.pr
>>> cal_start, cal_end = "1990-05-01", "1990-08-31"
>>> spi_3 = standardized_precipitation_index(
...     pr,
...     freq="MS",
...     window=3,
...     dist="gamma",
...     method="ML",
...     cal_start=cal_start,
...     cal_end=cal_end,
... )  # Computing SPI-3 months using a gamma distribution for the fit
>>> # Fitting parameters can also be obtained first, then reused as input.
>>> # To properly reproduce the example, we also need to specify that we use a
>>> # (potentially) zero-inflated distribution. For a monthly SPI, this should rarely
>>> # make a difference.
>>> from xclim.indices.stats import standardized_index_fit_params
>>> params = standardized_index_fit_params(
...     pr.sel(time=slice(cal_start, cal_end)),
...     freq="MS",
...     window=3,
...     dist="gamma",
...     method="ML",
...     zero_inflated=True,
... )  # First getting params
>>> spi_3_fitted = standardized_precipitation_index(pr, params=params)
xclim.indices._agro.water_budget(pr, evspsblpot=None, tasmin=None, tasmax=None, tas=None, lat=None, hurs=None, rsds=None, rsus=None, rlds=None, rlus=None, sfcWind=None, method='BR65')[source]

Precipitation minus potential evapotranspiration.

Precipitation minus potential evapotranspiration as a measure of an approximated surface water budget, where the potential evapotranspiration can be calculated with a given method.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • evspsblpot (xarray.DataArray, optional) – Potential evapotranspiration.

  • tasmin (xarray.DataArray, optional) – Minimum daily temperature.

  • tasmax (xarray.DataArray, optional) – Maximum daily temperature.

  • tas (xarray.DataArray, optional) – Mean daily temperature.

  • lat (xarray.DataArray, optional) – Latitude coordinate, needed if evspsblpot is not given. If None, a CF-conformant “latitude” field must be available within the pr DataArray.

  • hurs (xarray.DataArray, optional) – Relative humidity.

  • rsds (xarray.DataArray, optional) – Surface Downwelling Shortwave Radiation.

  • rsus (xarray.DataArray, optional) – Surface Upwelling Shortwave Radiation.

  • rlds (xarray.DataArray, optional) – Surface Downwelling Longwave Radiation.

  • rlus (xarray.DataArray, optional) – Surface Upwelling Longwave Radiation.

  • sfcWind (xarray.DataArray, optional) – Surface wind velocity (at 10 m).

  • method (str) – Method to use to calculate the potential evapotranspiration.

Return type:

DataArray

Returns:

xarray.DataArray – Precipitation minus potential evapotranspiration.

See also

xclim.indicators.atmos.potential_evapotranspiration

Potential evapotranspiration calculation.

xclim.indices._anuclim module

ANUCLIM indice definitions.

xclim.indices._anuclim.isothermality(tasmin, tasmax, freq='YS')[source]

Isothermality.

The mean diurnal temperature range divided by the annual temperature range.

Parameters:
  • tasmin (xarray.DataArray) – Average daily minimum temperature at daily, weekly, or monthly frequency.

  • tasmax (xarray.DataArray) – Average daily maximum temperature at daily, weekly, or monthly frequency.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [%] – Isothermality.

Notes

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the output with input data with daily frequency as well. As such weekly or monthly input values, if desired, should be calculated prior to calling the function.

References

Xu and Hutchinson [2010]

xclim.indices._anuclim.prcptot(pr, thresh='0 mm/d', freq='YS')[source]

Accumulated total precipitation.

The total accumulated precipitation from days where precipitation exceeds a given amount. A threshold is provided to allow the option of reducing the impact of days with trace precipitation amounts on period totals.

Parameters:
  • pr (xarray.DataArray) – Total precipitation flux [mm d-1], [mm week-1], [mm month-1] or similar.

  • thresh (str) – Threshold over which precipitation starts being cumulated.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [length] – Total {freq} precipitation.

xclim.indices._anuclim.prcptot_warmcold_quarter(pr, tas, op, freq='YS')[source]

Total precipitation of warmest/coldest quarter.

The warmest (or coldest) quarter of the year is determined, and the total precipitation of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”), quarters are defined as 13-week periods, otherwise as three (3) months.

Parameters:
  • pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency.

  • tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.

  • op ({“warmest”, “coldest”}) – Operation to perform: “warmest” calculates for the warmest quarter; “coldest” calculates for the coldest quarter.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [mm] – Precipitation of {op} quarter.

Notes

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the result with input data with daily frequency as well. As such, weekly or monthly input values, if desired, should be calculated prior to calling the function.

References

Xu and Hutchinson [2010]

xclim.indices._anuclim.prcptot_wetdry_period(pr, *, op, freq='YS')[source]

Precipitation of the wettest/driest day, week, or month, depending on the time step.

The wettest (or driest) period is determined, and the total precipitation of this period is calculated.

Parameters:
  • pr (xarray.DataArray) – Total precipitation flux [mm d-1], [mm week-1], [mm month-1] or similar.

  • op ({“wettest”, “driest”}) – Operation to perform: “wettest” calculates the wettest quarter. “driest” calculates the driest quarter.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [length] – Precipitation of {op} period.

Notes

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the result with input data with daily frequency as well. As such, weekly or monthly input values, if desired, should be calculated prior to calling the function.

References

Xu and Hutchinson [2010]

xclim.indices._anuclim.prcptot_wetdry_quarter(pr, op, freq='YS')[source]

Total precipitation of wettest/driest quarter.

The wettest (or driest) quarter of the year is determined, and the total precipitation of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”) quarters are defined as 13-week periods, otherwise as three (3) months.

Parameters:
  • pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency.

  • op ({“wettest”, “driest”}) – Operation to perform: ‘wettest’ calculates the wettest quarter. ‘driest’ calculates the driest quarter.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [length] – Precipitation of {op} quarter.

Notes

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the result with input data with daily frequency as well. As such, weekly or monthly input values, if desired, should be calculated before calling the function.

References

Xu and Hutchinson [2010]

Examples

The following would compute for each grid cell of file pr.day.nc the annual wettest quarter total precipitation:

>>> from xclim.indices import prcptot_wetdry_quarter
>>> p = xr.open_dataset(path_to_pr_file)
>>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op="wettest")
xclim.indices._anuclim.precip_seasonality(pr, freq='YS')[source]

Precipitation Seasonality (C of V).

The annual precipitation Coefficient of Variation (C of V) expressed in percent. Calculated as the standard deviation of precipitation values for a given year expressed as a percentage of the mean of those values.

Parameters:
  • pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency. Units need to be defined as a rate (e.g. mm d-1, mm week-1).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [%] – Precipitation coefficient of variation.

Notes

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the result with input data with daily frequency as well. As such weekly or monthly input values, if desired, should be calculated prior to calling the function.

If input units are in mm s-1 (or equivalent), values are converted to mm/day to avoid potentially small denominator values.

References

Xu and Hutchinson [2010]

Examples

The following would compute for each grid cell of file pr.day.nc the annual precipitation seasonality:

>>> import xclim.indices as xci
>>> p = xr.open_dataset(path_to_pr_file).pr
>>> pday_seasonality = xci.precip_seasonality(p)
>>> p_weekly = xci.precip_accumulation(p, freq="7D")

# Input units need to be a rate >>> p_weekly.attrs[“units”] = “mm/week” >>> pweek_seasonality = xci.precip_seasonality(p_weekly)

xclim.indices._anuclim.temperature_seasonality(tas, freq='YS')[source]

Temperature seasonality (coefficient of variation).

The annual temperature coefficient of variation expressed in percent. Calculated as the standard deviation of temperature values for a given year expressed as a percentage of the mean of those temperatures.

Parameters:
  • tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

  • xarray.DataArray, [%] – Mean temperature coefficient of variation.

  • freq (str) – Resampling frequency.

Notes

For this calculation, the mean in degrees Kelvin is used. This avoids the possibility of having to divide by zero, but it does mean that the values are usually quite small.

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the result with input data with daily frequency as well. As such weekly or monthly input values, if desired, should be calculated prior to calling the function.

References

Xu and Hutchinson [2010]

Examples

The following would compute for each grid cell of file tas.day.nc the annual temperature seasonality:

>>> import xclim.indices as xci
>>> t = xr.open_dataset(path_to_tas_file).tas
>>> tday_seasonality = xci.temperature_seasonality(t)
>>> t_weekly = xci.tg_mean(t, freq="7D")
>>> tweek_seasonality = xci.temperature_seasonality(t_weekly)
xclim.indices._anuclim.tg_mean_warmcold_quarter(tas, op, freq='YS')[source]

Mean temperature of warmest/coldest quarter.

The warmest (or coldest) quarter of the year is determined, and the mean temperature of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”), quarters are defined as 13-week periods, otherwise as three (3) months.

Parameters:
  • tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.

  • op ({‘warmest’, ‘coldest’}) – Operation to perform: ‘wettest’ calculates the wettest quarter. ‘driest’ calculates the driest quarter.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same as tas] – Mean temperature of {op} quarter.

Notes

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the result with input data with daily frequency as well. As such weekly or monthly input values, if desired, should be calculated prior to calling the function.

References

Xu and Hutchinson [2010]

Examples

The following would compute for each grid cell of file tas.day.nc the annual temperature of the warmest quarter mean temperature:

>>> from xclim.indices import tg_mean_warmcold_quarter
>>> t = xr.open_dataset(path_to_tas_file)
>>> t_warm_qrt = tg_mean_warmcold_quarter(tas=t.tas, op="warmest")
xclim.indices._anuclim.tg_mean_wetdry_quarter(tas, pr, op, freq='YS')[source]

Mean temperature of wettest/driest quarter.

The wettest (or driest) quarter of the year is determined, and the mean temperature of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”), quarters are defined as 13-week periods, otherwise as three (3) months.

Parameters:
  • tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.

  • pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency.

  • op ({“wettest”, “driest”}) – Operation to perform: ‘wettest’ calculates the wettest quarter. ‘driest’ calculates the driest quarter.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same as tas] – Mean temperature of {op} quarter.

Notes

According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.indices implementation here will calculate the result with input data with daily frequency as well. As such, weekly or monthly input values, if desired, should be calculated before calling the function.

References

Xu and Hutchinson [2010]

xclim.indices._conversion module

Conversion and approximation functions.

xclim.indices._conversion.clausius_clapeyron_scaled_precipitation(delta_tas, pr_baseline, cc_scale_factor=1.07)[source]

Scale precipitation according to the Clausius-Clapeyron relation.

Parameters:
  • delta_tas (xarray.DataArray) – Difference in temperature between a baseline climatology and another climatology.

  • pr_baseline (xarray.DataArray) – Baseline precipitation to adjust with Clausius-Clapeyron.

  • cc_scale_factor (float) – Clausius Clapeyron scale factor. (default = 1.07).

Return type:

DataArray

Returns:

xarray.DataArray – Baseline precipitation scaled to other climatology using Clausius-Clapeyron relationship.

Warning

Make sure that delta_tas is computed over a baseline compatible with pr_baseline. So for example, if delta_tas is the climatological difference between a baseline and a future period, then pr_baseline should be precipitations over a period within the same baseline.

Notes

The Clausius-Clapeyron equation for water vapour under typical atmospheric conditions states that the saturation water vapour pressure \(e_s\) changes approximately exponentially with temperature

\[\frac{\mathrm{d}e_s(T)}{\mathrm{d}T} \approx 1.07 e_s(T)\]

This function assumes that precipitation can be scaled by the same factor.

xclim.indices._conversion.clearness_index(rsds)[source]

Compute the clearness index.

The clearness index is the ratio between the shortwave downwelling radiation and the total extraterrestrial radiation on a given day.

Parameters:

rsds (xr.DataArray) – Surface downwelling solar radiation.

Return type:

DataArray

Returns:

xr.DataArray, [unitless] – Clearness index.

Notes

Clearness Index (ci) is defined as:

References

Lauret, Alonso-Suárez, Le Gal La Salle, and David [2022]

xclim.indices._conversion.fao_allen98(net_radiation, tas, wind, es, ea, delta_svp, gamma, G='0 MJ m-2 day-1')[source]

FAO-56 Penman-Monteith equation.

Estimates reference evapotranspiration from a hypothetical short grass reference surface ( height = 0.12m, surface resistance = 70 s m-1, albedo = 0.23 and a moderately dry soil surface resulting from about a weekly irrigation frequency). Based on equation 6 in based on Allen et al. [1998].

Parameters:
  • net_radiation (xarray.DataArray) – Net radiation at crop surface [MJ m-2 day-1].

  • tas (xarray.DataArray) – Air temperature at 2 m height [degC].

  • wind (xarray.DataArray) – Wind speed at 2 m height [m s-1].

  • es (xarray.DataArray) – Saturation vapour pressure [kPa].

  • ea (xarray.DataArray) – Actual vapour pressure [kPa].

  • delta_svp (xarray.DataArray) – Slope of saturation vapour pressure curve [kPa degC-1].

  • gamma (xarray.DataArray) – Psychrometric constant [kPa deg C].

  • G (float, optional) – Soil heat flux (G) [MJ m-2 day-1] (For daily default to 0).

Returns:

xarray.DataArray – Potential Evapotranspiration from a hypothetical grass reference surface [mm day-1].

References

Allen et al. [1998]

xclim.indices._conversion.heat_index(tas, hurs)[source]

Heat index.

Perceived temperature after relative humidity is taken into account [Blazejczyk et al., 2012]. The index is only valid for temperatures above 20°C.

Parameters:
  • tas (xr.DataArray) – Mean Temperature. The equation assumes an instantaneous value.

  • hurs (xr.DataArray) – Relative Humidity. The equation assumes an instantaneous value.

Return type:

DataArray

Returns:

xr.DataArray, [temperature] – Heat index for moments with temperature above 20°C.

Notes

While both the Humidex and the heat index are calculated using dew point the Humidex uses a dew point of 7 °C (45 °F) as a base, whereas the heat index uses a dew point base of 14 °C (57 °F). Further, the heat index uses heat balance equations which account for many variables other than vapour pressure, which is used exclusively in the Humidex calculation.

References

Blazejczyk, Epstein, Jendritzky, Staiger, and Tinz [2012]

xclim.indices._conversion.humidex(tas, tdps=None, hurs=None)[source]

Humidex Index.

The Humidex indicates how hot the air feels to an average person, accounting for the effect of humidity. It can be loosely interpreted as the equivalent perceived temperature when the air is dry.

Parameters:
  • tas (xarray.DataArray) – Mean Temperature.

  • tdps (xarray.DataArray, optional) – Dewpoint Temperature, used to compute the vapour pressure.

  • hurs (xarray.DataArray, optional) – Relative Humidity, used as an alternative way to compute the vapour pressure if the dewpoint temperature is not available.

Return type:

DataArray

Returns:

xarray.DataArray, [temperature] – The Humidex Index.

Notes

The humidex is usually computed using hourly observations of dry bulb and dewpoint temperatures. It is computed using the formula based on Masterton and Richardson [1979]:

\[T + {\frac {5}{9}}\left[e - 10\right]\]

where \(T\) is the dry bulb air temperature (°C). The term \(e\) can be computed from the dewpoint temperature \(T_{dewpoint}\) in °K:

\[e = 6.112 \times \exp(5417.7530\left({\frac {1}{273.16}}-{\frac {1}{T_{\text{dewpoint}}}}\right)\]

where the constant 5417.753 reflects the molecular weight of water, latent heat of vaporization, and the universal gas constant [Mekis et al., 2015]. Alternatively, the term \(e\) can also be computed from the relative humidity h expressed in percent using Sirangelo et al. [2020]:

\[e = \frac{h}{100} \times 6.112 * 10^{7.5 T/(T + 237.7)}.\]

The humidex comfort scale [Canada, 2011] can be interpreted as follows:

  • 20 to 29 : no discomfort;

  • 30 to 39 : some discomfort;

  • 40 to 45 : great discomfort, avoid exertion;

  • 46 and over : dangerous, possible heat stroke;

Please note that while both the humidex and the heat index are calculated using dew point, the humidex uses a dew point of 7 °C (45 °F) as a base, whereas the heat index uses a dew point base of 14 °C (57 °F). Further, the heat index uses heat balance equations which account for many variables other than vapour pressure, which is used exclusively in the humidex calculation.

References

Canada [2011], Masterton and Richardson [1979], Mekis, Vincent, Shephard, and Zhang [2015], Sirangelo, Caloiero, Coscarelli, Ferrari, and Fusto [2020]

xclim.indices._conversion.longwave_upwelling_radiation_from_net_downwelling(rls, rlds)[source]

Calculate upwelling thermal radiation from net thermal radiation and downwelling thermal radiation.

Parameters:
  • rls (xr.DataArray) – Surface net thermal radiation.

  • rlds (xr.DataArray) – Surface downwelling thermal radiation.

Return type:

DataArray

Returns:

xr.DataArray, [same units as rlds] – Surface upwelling thermal radiation (rlus).

xclim.indices._conversion.mean_radiant_temperature(rsds, rsus, rlds, rlus, stat='sunlit')[source]

Mean radiant temperature.

The mean radiant temperature is the incidence of radiation on the body from all directions.

Parameters:
  • rsds (xr.DataArray) – Surface Downwelling Shortwave Radiation.

  • rsus (xr.DataArray) – Surface Upwelling Shortwave Radiation.

  • rlds (xr.DataArray) – Surface Downwelling Longwave Radiation.

  • rlus (xr.DataArray) – Surface Upwelling Longwave Radiation.

  • stat ({‘instant’, ‘sunlit’}) – Which statistic to apply. If “instant”, the instantaneous cosine of the solar zenith angle is calculated. If “sunlit”, the cosine of the solar zenith angle is calculated during the sunlit period of each interval.

Return type:

DataArray

Returns:

xarray.DataArray, [K] – Mean Radiant Temperature.

Warning

There are some issues in the calculation of mrt in extreme polar regions.

Notes

This code was inspired by the thermofeel package [Brimicombe et al., 2021].

References

Di Napoli, Hogan, and Pappenberger [2020]

xclim.indices._conversion.potential_evapotranspiration(tasmin=None, tasmax=None, tas=None, lat=None, hurs=None, rsds=None, rsus=None, rlds=None, rlus=None, sfcWind=None, pr=None, method='BR65', peta=0.00516409319477, petb=0.0874972822289)[source]

Potential evapotranspiration.

The potential for water evaporation from soil and transpiration by plants if the water supply is sufficient, according to a given method.

Parameters:
  • tasmin (xarray.DataArray, optional) – Minimum daily Temperature.

  • tasmax (xarray.DataArray, optional) – Maximum daily Temperature.

  • tas (xarray.DataArray, optional) – Mean daily Temperature.

  • lat (xarray.DataArray, optional) – Latitude. If not provided, it is sought on tasmin or tas using cf-xarray accessors.

  • hurs (xarray.DataArray, optional) – Relative Humidity.

  • rsds (xarray.DataArray, optional) – Surface Downwelling Shortwave Radiation.

  • rsus (xarray.DataArray, optional) – Surface Upwelling Shortwave Radiation.

  • rlds (xarray.DataArray, optional) – Surface Downwelling Longwave Radiation.

  • rlus (xarray.DataArray, optional) – Surface Upwelling Longwave Radiation.

  • sfcWind (xarray.DataArray, optional) – Surface Wind Velocity (at 10 m).

  • pr (xarray.DataArray) – Mean daily Precipitation Flux.

  • method ({“baierrobertson65”, “BR65”, “hargreaves85”, “HG85”, “thornthwaite48”, “TW48”, “mcguinnessbordne05”, “MB05”, “allen98”, “FAO_PM98”, “droogersallen02”, “DA02”}) – Which method to use, see Notes.

  • peta (float) – Used only with method MB05 as \(a\) for calculation of PET, see Notes section. Default value resulted from calibration of PET over the UK.

  • petb (float) – Used only with method MB05 as \(b\) for calculation of PET, see Notes section. Default value resulted from calibration of PET over the UK.

Return type:

DataArray

Returns:

xarray.DataArray – Potential Evapotranspiration.

Notes

Available methods are:

  • “baierrobertson65” or “BR65”, based on Baier and Robertson [1965]. Requires tasmin and tasmax, daily [D] freq.

  • “hargreaves85” or “HG85”, based on George H. Hargreaves and Zohrab A. Samani [1985]. Requires tasmin and tasmax, daily [D] freq. (optional: tas can be given in addition of tasmin and tasmax).

  • “mcguinnessbordne05” or “MB05”, based on Tanguy et al. [2018]. Requires tas, daily [D] freq, with latitudes ‘lat’.

  • “thornthwaite48” or “TW48”, based on Thornthwaite [1948]. Requires tasmin and tasmax, monthly [MS] or daily [D] freq. (optional: tas can be given instead of tasmin and tasmax).

  • “allen98” or “FAO_PM98”, based on Allen et al. [1998]. Modification of Penman-Monteith method. Requires tasmin and tasmax, relative humidity, radiation flux and wind speed (10 m wind will be converted to 2 m).

  • “droogersallen02” or “DA02”, based on Droogers and Allen [2002]. Requires tasmin, tasmax and precipitation, monthly [MS] or daily [D] freq. (optional: tas can be given in addition of tasmin and tasmax).

The McGuinness-Bordne [McGuinness and Borone, 1972] equation is:

\[PET[mm day^{-1}] = a * \frac{S_0}{\lambda}T_a + b * \frac{S_0}{\lambda}\]

where \(a\) and \(b\) are empirical parameters; \(S_0\) is the extraterrestrial radiation [MJ m-2 day-1], assuming a solar constant of 1367 W m-2; \(\\lambda\) is the latent heat of vaporisation [MJ kg-1] and \(T_a\) is the air temperature [°C]. The equation was originally derived for the USA, with \(a=0.0147\) and \(b=0.07353\). The default parameters used here are calibrated for the UK, using the method described in Tanguy et al. [2018].

Methods “BR65”, “HG85”, “MB05” and “DA02” use an approximation of the extraterrestrial radiation. See extraterrestrial_solar_radiation().

References

Allen, Pereira, Raes, and Smith [1998], Baier and Robertson [1965], Droogers and Allen [2002], McGuinness and Borone [1972], Tanguy, Prudhomme, Smith, and Hannaford [2018], Thornthwaite [1948], George H. Hargreaves and Zohrab A. Samani [1985]

xclim.indices._conversion.prsn_to_prsnd(prsn, snr=None, const='100 kg m-3', out_units=None)[source]

Snowfall rate from snowfall flux and density.

Parameters:
  • prsn (xr.DataArray) – Snowfall Flux.

  • snr (xr.DataArray, optional) – Snow Density.

  • const (Quantified) – Constant snow density. const is only used if snr is None.

  • out_units (str, optional) – Desired units of the snowfall rate. If None, output units simply follow from snd * snr.

Return type:

DataArray

Returns:

xr.DataArray – Snowfall Rate.

Notes

The estimated mean snow density value of 100 kg m-3 is taken from Frei, Kotlarski, Liniger, and Schär [2018], CBCL [2020].

References

Frei, Kotlarski, Liniger, and Schär [2018], CBCL [2020]

xclim.indices._conversion.prsnd_to_prsn(prsnd, snr=None, const='100 kg m-3', out_units=None)[source]

Snowfall flux from snowfall rate and density.

Parameters:
  • prsnd (xr.DataArray) – Snowfall Rate.

  • snr (xr.DataArray, optional) – Snow Density.

  • const (Quantified) – Constant Snow Density. const is only used if snr is None.

  • out_units (str, optional) – Desired units of the snowfall rate. If None, output units simply follow from snd * snr.

Return type:

DataArray

Returns:

xr.DataArray – Snowfall Flux.

Notes

The estimated mean snow density value of 100 kg m-3 is taken from Frei, Kotlarski, Liniger, and Schär [2018], CBCL [2020].

References

Frei, Kotlarski, Liniger, and Schär [2018], CBCL [2020]

xclim.indices._conversion.rain_approximation(pr, tas, thresh='0 degC', method='binary')[source]

Rainfall approximation from total precipitation and temperature.

Liquid precipitation estimated from precipitation and temperature according to a given method. This is a convenience method based on snowfall_approximation(), see the latter for details.

Parameters:
  • pr (xarray.DataArray) – Mean daily Precipitation Flux.

  • tas (xarray.DataArray, optional) – Mean, Maximum, or Minimum daily Temperature.

  • thresh (Quantified) – Freezing point temperature. Non-scalar values are not allowed with method ‘brown’.

  • method ({“binary”, “brown”, “auer”}) – Which method to use when approximating snowfall from total precipitation. See notes.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as pr] – Liquid precipitation rate.

See also

snowfall_approximation

Snowfall approximation from total precipitation and temperature.

Notes

This method computes the snowfall approximation and subtracts it from the total precipitation to estimate the liquid rain precipitation.

xclim.indices._conversion.relative_humidity(tas, tdps=None, huss=None, ps=None, ice_thresh=None, method='sonntag90', invalid_values='clip')[source]

Relative humidity.

Compute relative humidity from temperature and either dewpoint temperature or specific humidity and pressure through the saturation vapour pressure.

Parameters:
  • tas (xr.DataArray) – Mean Temperature.

  • tdps (xr.DataArray, optional) – Dewpoint Temperature. If specified, overrides huss and ps.

  • huss (xr.DataArray, optional) – Specific Humidity. Must be given if tdps is not given.

  • ps (xr.DataArray, optional) – Air Pressure. Must be given if tdps is not given.

  • ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water. Does nothing if ‘method’ is “bohren98”.

  • method ({“bohren98”, “goffgratch46”, “sonntag90”, “tetens30”, “wmo08”}) – Which method to use, see notes of this function and of saturation_vapor_pressure().

  • invalid_values ({“clip”, “mask”, None}) – What to do with values outside the 0-100 range. If “clip” (default), clips everything to 0 - 100, if “mask”, replaces values outside the range by np.nan, and if None, does nothing.

Return type:

DataArray

Returns:

xr.DataArray, [%] – Relative Humidity.

Notes

In the following, let \(T\), \(T_d\), \(q\) and \(p\) be the temperature, the dew point temperature, the specific humidity and the air pressure.

For the “bohren98” method : This method does not use the saturation vapour pressure directly, but rather uses an approximation of the ratio of \(\frac{e_{sat}(T_d)}{e_{sat}(T)}\). With \(L\) the enthalpy of vaporization of water and \(R_w\) the gas constant for water vapour, the relative humidity is computed as:

\[RH = e^{\frac{-L (T - T_d)}{R_wTT_d}}\]

From Bohren and Albrecht [1998], formula taken from Lawrence [2005]. \(L = 2.5\times 10^{-6}\) J kg-1, exact for \(T = 273.15\) K, is used.

Other methods: With \(w\), \(w_{sat}\), \(e_{sat}\) the mixing ratio, the saturation mixing ratio and the saturation vapour pressure. If the dewpoint temperature is given, relative humidity is computed as:

\[RH = 100\frac{e_{sat}(T_d)}{e_{sat}(T)}\]

Otherwise, the specific humidity and the air pressure must be given so relative humidity can be computed as:

\[RH = 100\frac{w}{w_{sat}} w = \frac{q}{1-q} w_{sat} = 0.622\frac{e_{sat}}{P - e_{sat}}\]

The methods differ by how \(e_{sat}\) is computed. See the doc of xclim.core.utils.saturation_vapor_pressure().

References

Bohren and Albrecht [1998], Lawrence [2005]

Examples

>>> from xclim.indices import relative_humidity
>>> rh = relative_humidity(
...     tas=tas_dataset,
...     tdps=tdps_dataset,
...     huss=huss_dataset,
...     ps=ps_dataset,
...     ice_thresh="0 degC",
...     method="wmo08",
...     invalid_values="clip",
... )
xclim.indices._conversion.saturation_vapor_pressure(tas, ice_thresh=None, method='sonntag90')[source]

Saturation vapour pressure from temperature.

Parameters:
  • tas (xr.DataArray) – Mean Temperature.

  • ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water.

  • method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”, “its90”}) – Which method to use, see notes.

Return type:

DataArray

Returns:

xarray.DataArray, [Pa] – Saturation Vapour Pressure.

Notes

In all cases implemented here \(log(e_{sat})\) is an empirically fitted function (usually a polynomial) where coefficients can be different when ice is taken as reference instead of water. Available methods are:

  • “goffgratch46” or “GG46”, based on Goff and Gratch [1946], values and equation taken from Vömel [2016].

  • “sonntag90” or “SO90”, taken from SONNTAG [1990].

  • “tetens30” or “TE30”, based on Tetens [1930], values and equation taken from Vömel [2016].

  • “wmo08” or “WMO08”, taken from World Meteorological Organization [2008].

  • “its90” or “ITS90”, taken from Hardy [1998].

References

Goff and Gratch [1946], Hardy [1998], SONNTAG [1990], Tetens [1930], Vömel [2016], World Meteorological Organization [2008]

Examples

>>> from xclim.indices import saturation_vapor_pressure
>>> rh = saturation_vapor_pressure(tas=tas_dataset, ice_thresh="0 degC", method="wmo08")
xclim.indices._conversion.sfcwind_to_uas_vas(sfcWind, sfcWindfromdir)[source]

Eastward and northward wind components from the wind speed and direction.

Compute the eastward and northward wind components from the wind speed and direction.

Parameters:
  • sfcWind (xr.DataArray) – Wind Velocity.

  • sfcWindfromdir (xr.DataArray) – Direction from which the wind blows, following the meteorological convention, where “360” denotes “North”.

Return type:

tuple[DataArray, DataArray]

Returns:

  • uas (xr.DataArray, [m s-1]) – Eastward Wind Velocity.

  • vas (xr.DataArray, [m s-1]) – Northward Wind Velocity.

Examples

>>> from xclim.indices import sfcwind_to_uas_vas
>>> uas, vas = sfcwind_to_uas_vas(sfcWind=sfcWind_dataset, sfcWindfromdir=sfcWindfromdir_dataset)
xclim.indices._conversion.shortwave_downwelling_radiation_from_clearness_index(ci)[source]

Compute the surface downwelling solar radiation from clearness index.

Parameters:

ci (xr.DataArray) – Clearness index.

Return type:

DataArray

Returns:

xr.DataArray, [unitless] – Surface downwelling solar radiation.

See also

clearness_index

Inverse transformation, and definition of the clearness index.

Notes

The conversion from Clearness Index is defined as:

xclim.indices._conversion.shortwave_upwelling_radiation_from_net_downwelling(rss, rsds)[source]

Calculate upwelling solar radiation from net solar radiation and downwelling solar radiation.

Parameters:
  • rss (xr.DataArray) – Surface net solar radiation.

  • rsds (xr.DataArray) – Surface downwelling solar radiation.

Return type:

DataArray

Returns:

xr.DataArray, [same units as rsds] – Surface upwelling solar radiation (rsus).

xclim.indices._conversion.snd_to_snw(snd, snr=None, const='312 kg m-3', out_units=None)[source]

Snow amount from snow depth and density.

Parameters:
  • snd (xr.DataArray) – Snow Depth.

  • snr (Quantified, optional) – Snow Density.

  • const (Quantified) – Constant snow density. const is only used if snr is None.

  • out_units (str, optional) – Desired units of the snow amount output. If None, output units simply follow from snd * snr.

Return type:

DataArray

Returns:

xr.DataArray – Snow Amount.

Notes

The estimated mean snow density value of 312 kg m-3 is taken from Sturm et al. [2010].

References

Sturm, Taras, Liston, Derksen, Jonas, and Lea [2010]

xclim.indices._conversion.snowfall_approximation(pr, tas, thresh='0 degC', method='binary')[source]

Snowfall approximation from total precipitation and temperature.

Solid precipitation estimated from precipitation and temperature according to a given method.

Parameters:
  • pr (xarray.DataArray) – Mean daily Precipitation Flux.

  • tas (xarray.DataArray, optional) – Mean, Maximum, or Minimum daily Temperature.

  • thresh (Quantified) – Freezing point temperature. Non-scalar values are not allowed with method “brown”.

  • method ({“binary”, “brown”, “auer”}) – Which method to use when approximating snowfall from total precipitation. See notes.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as pr] – Solid Precipitation Flux.

See also

rain_approximation

Rainfall approximation from total precipitation and temperature.

Notes

The following methods are available to approximate snowfall and are drawn from the Canadian Land Surface Scheme [Melton, 2019, Verseghy, 2009].

  • 'binary' : When the temperature is under the freezing threshold, precipitation is assumed to be solid. The method is agnostic to the type of temperature used (mean, maximum or minimum).

  • 'brown' : The phase between the freezing threshold goes from solid to liquid linearly over a range of 2°C over the freezing point.

  • 'auer' : The phase between the freezing threshold goes from solid to liquid as a degree six polynomial over a range of 6°C over the freezing point.

References

Melton [2019], Verseghy [2009]

xclim.indices._conversion.snw_to_snd(snw, snr=None, const='312 kg m-3', out_units=None)[source]

Snow depth from snow amount and density.

Parameters:
  • snw (xr.DataArray) – Snow amount.

  • snr (Quantified, optional) – Snow density.

  • const (Quantified) – Constant snow density. const is only used if snr is None.

  • out_units (str, optional) – Desired units of the snow depth output. If None, output units simply follow from snw / snr.

Return type:

DataArray

Returns:

xr.DataArray – Snow Depth.

Notes

The estimated mean snow density value of 312 kg m-3 is taken from Sturm et al. [2010].

References

Sturm, Taras, Liston, Derksen, Jonas, and Lea [2010]

xclim.indices._conversion.specific_humidity(tas, hurs, ps, ice_thresh=None, method='sonntag90', invalid_values=None)[source]

Specific humidity from temperature, relative humidity, and pressure.

Specific humidity is the ratio between the mass of water vapour and the mass of moist air [World Meteorological Organization, 2008].

Parameters:
  • tas (xr.DataArray) – Mean Temperature.

  • hurs (xr.DataArray) – Relative Humidity.

  • ps (xr.DataArray) – Air Pressure.

  • ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water.

  • method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”}) – Which method to use, see notes of this function and of saturation_vapor_pressure().

  • invalid_values ({“clip”, “mask”, None}) – What to do with values larger than the saturation specific humidity and lower than 0. If “clip” (default), clips everything to 0 - q_sat if “mask”, replaces values outside the range by np.nan, if None, does nothing.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Specific Humidity.

Notes

In the following, let \(T\), \(hurs\) (in %) and \(p\) be the temperature, the relative humidity and the air pressure. With \(w\), \(w_{sat}\), \(e_{sat}\) the mixing ratio, the saturation mixing ratio and the saturation vapour pressure, specific humidity \(q\) is computed as:

\[w_{sat} = 0.622\frac{e_{sat}}{P - e_{sat}} w = w_{sat} * hurs / 100 q = w / (1 + w)\]

The methods differ by how \(e_{sat}\) is computed. See xclim.core.utils.saturation_vapor_pressure().

If invalid_values is not None, the saturation specific humidity \(q_{sat}\) is computed as:

\[q_{sat} = w_{sat} / (1 + w_{sat})\]

References

World Meteorological Organization [2008]

Examples

>>> from xclim.indices import specific_humidity
>>> rh = specific_humidity(
...     tas=tas_dataset,
...     hurs=hurs_dataset,
...     ps=ps_dataset,
...     ice_thresh="0 degC",
...     method="wmo08",
...     invalid_values="mask",
... )
xclim.indices._conversion.specific_humidity_from_dewpoint(tdps, ps, method='sonntag90')[source]

Specific humidity from dewpoint temperature and air pressure.

Specific humidity is the ratio between the mass of water vapour and the mass of moist air [World Meteorological Organization, 2008].

Parameters:
  • tdps (xr.DataArray) – Dewpoint Temperature.

  • ps (xr.DataArray) – Air Pressure.

  • method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”}) – Method to compute the saturation vapour pressure.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Specific Humidity.

Notes

If \(e\) is the water vapour pressure, and \(p\) the total air pressure, then specific humidity is given by

\[q = m_w e / ( m_a (p - e) + m_w e )\]

where \(m_w\) and \(m_a\) are the molecular weights of water and dry air respectively. This formula is often written with \(ε = m_w / m_a\), which simplifies to \(q = ε e / (p - e (1 - ε))\).

References

World Meteorological Organization [2008]

Examples

>>> from xclim.indices import specific_humidity_from_dewpoint
>>> rh = specific_humidity_from_dewpoint(
...     tdps=tas_dataset,
...     ps=ps_dataset,
...     method="wmo08",
... )
xclim.indices._conversion.tas(tasmin, tasmax)[source]

Average temperature from minimum and maximum temperatures.

We assume a symmetrical distribution for the temperature and retrieve the average value as Tg = (Tx + Tn) / 2.

Parameters:
  • tasmin (xarray.DataArray) – Minimum (daily) Temperature.

  • tasmax (xarray.DataArray) – Maximum (daily) Temperature.

Return type:

DataArray

Returns:

xarray.DataArray – Mean (daily) Temperature [same units as tasmin].

Examples

>>> from xclim.indices import tas
>>> tas = tas(tasmin_dataset, tasmax_dataset)
xclim.indices._conversion.uas_vas_to_sfcwind(uas, vas, calm_wind_thresh='0.5 m/s')[source]

Wind speed and direction from the eastward and northward wind components.

Computes the magnitude and angle of the wind vector from its northward and eastward components, following the meteorological convention that sets calm wind to a direction of 0° and northerly wind to 360°.

Parameters:
  • uas (xr.DataArray) – Eastward Wind Velocity.

  • vas (xr.DataArray) – Northward Wind Velocity.

  • calm_wind_thresh (Quantified) – The threshold under which winds are considered “calm” and for which the direction is set to 0. On the Beaufort scale, calm winds are defined as < 0.5 m/s.

Return type:

tuple[DataArray, DataArray]

Returns:

  • wind (xr.DataArray, [m s-1]) – Wind Velocity.

  • wind_from_dir (xr.DataArray, [°]) – Direction from which the wind blows, following the meteorological convention where 360 stands for North and 0 for calm winds.

Notes

Winds with a velocity less than calm_wind_thresh are given a wind direction of 0°, while stronger northerly winds are set to 360°.

Examples

>>> from xclim.indices import uas_vas_to_sfcwind
>>> sfcWind = uas_vas_to_sfcwind(uas=uas_dataset, vas=vas_dataset, calm_wind_thresh="0.5 m/s")
xclim.indices._conversion.universal_thermal_climate_index(tas, hurs, sfcWind, mrt=None, rsds=None, rsus=None, rlds=None, rlus=None, stat='sunlit', mask_invalid=True, wind_cap_min=False)[source]

Universal thermal climate index (UTCI).

The UTCI is the equivalent temperature for the environment derived from a reference environment and is used to evaluate heat stress in outdoor spaces.

Parameters:
  • tas (xarray.DataArray) – Mean Temperature.

  • hurs (xarray.DataArray) – Relative Humidity.

  • sfcWind (xarray.DataArray) – Wind Velocity.

  • mrt (xarray.DataArray, optional) – Mean Radiant Temperature.

  • rsds (xr.DataArray, optional) – Surface Downwelling Shortwave Radiation. This is necessary if mrt is not None.

  • rsus (xr.DataArray, optional) – Surface Upwelling Shortwave Radiation. This is necessary if mrt is not None.

  • rlds (xr.DataArray, optional) – Surface Downwelling Longwave Radiation. This is necessary if mrt is not None.

  • rlus (xr.DataArray, optional) – Surface Upwelling Longwave Radiation. This is necessary if mrt is not None.

  • stat ({‘instant’, ‘sunlit’}) – Which statistic to apply. If “instant”, the instantaneous cosine of the solar zenith angle is calculated. If “sunlit”, the cosine of the solar zenith angle is calculated during the sunlit period of each interval. This is necessary if mrt is not None.

  • mask_invalid (bool) – If True (default), UTCI values are NaN where any of the inputs are outside their validity ranges: - -50°C < tas < 50°C. - -30°C < tas - mrt < 30°C. - 0.5 m/s < sfcWind < 17.0 m/s.

  • wind_cap_min (bool) – If True, wind velocities are capped to a minimum of 0.5 m/s following Bröde et al. [2012] usage guidelines. This ensures UTCI calculation for low winds. Default value False.

Return type:

DataArray

Returns:

xarray.DataArray – Universal Thermal Climate Index.

Notes

The calculation uses water vapour partial pressure, which is derived from relative humidity and saturation vapour pressure computed according to the ITS-90 equation.

This code was inspired by the pythermalcomfort and thermofeel packages.

For more information: https://www.utci.org/

References

Bröde [2009], Bröde, Fiala, Błażejczyk, Holmér, Jendritzky, Kampmann, Tinz, and Havenith [2012], Błażejczyk, Jendritzky, Bröde, Fiala, Havenith, Epstein, Psikuta, and Kampmann [2013]

xclim.indices._conversion.vapor_pressure_deficit(tas, hurs, ice_thresh=None, method='sonntag90')[source]

Vapour pressure deficit.

The measure of the moisture deficit of the air.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • hurs (xarray.DataArray) – Relative humidity.

  • ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water.

  • method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”, “its90”}) – Method used to calculate saturation vapour pressure, see notes of saturation_vapor_pressure(). Default is “sonntag90”.

Return type:

DataArray

Returns:

xarray.DataArray, [Pa] – Vapour pressure deficit.

See also

saturation_vapor_pressure

Vapour pressure at saturation.

xclim.indices._conversion.wind_chill_index(tas, sfcWind, method='CAN', mask_invalid=True)[source]

Wind chill index.

The Wind Chill Index is an estimation of how cold the weather feels to the average person. It is computed from the air temperature and the 10-m wind. As defined by the Environment and Climate Change Canada (Mekis, Vincent, Shephard, and Zhang [2015]), two equations exist, the conventional one and one for slow winds (usually < 5 km/h), see Notes.

Parameters:
  • tas (xarray.DataArray) – Surface air temperature.

  • sfcWind (xarray.DataArray) – Surface wind speed (10 m).

  • method ({‘CAN’, ‘US’}) – If “CAN” (default), a “slow wind” equation is used where winds are slower than 5 km/h, see Notes.

  • mask_invalid (bool) – Whether to mask values when the inputs are outside their validity range. or not. If True (default), points where the temperature is above a threshold are masked. The threshold is 0°C for the canadian method and 50°F for the american one. With the latter method, points where sfcWind < 3 mph are also masked.

Return type:

DataArray

Returns:

xarray.DataArray, [degC] – Wind Chill Index.

Notes

Following the calculations of Environment and Climate Change Canada, this function switches from the standardized index to another one for slow winds. The standard index is the same as used by the National Weather Service of the USA [US Department of Commerce, n.d.]. Given a temperature at surface \(T\) (in °C) and 10-m wind speed \(V\) (in km/h), the Wind Chill Index \(W\) (dimensionless) is computed as:

\[W = 13.12 + 0.6125*T - 11.37*V^0.16 + 0.3965*T*V^0.16\]

Under slow winds (\(V < 5\) km/h), and using the canadian method, it becomes:

\[W = T + \frac{-1.59 + 0.1345 * T}{5} * V\]

Both equations are invalid for temperature over 0°C in the canadian method.

The american Wind Chill Temperature index (WCT), as defined by USA’s National Weather Service, is computed when method=’US’. In that case, the maximal valid temperature is 50°F (10 °C) and minimal wind speed is 3 mph (4.8 km/h).

For more information, see:

References

Mekis, Vincent, Shephard, and Zhang [2015], US Department of Commerce [n.d.]

xclim.indices._conversion.wind_power_potential(wind_speed, air_density=None, cut_in='3.5 m/s', rated='13 m/s', cut_out='25 m/s')[source]

Wind power potential estimated from an idealized wind power production factor.

The actual power production of a wind farm can be estimated by multiplying its nominal (nameplate) capacity by the wind power potential, which depends on wind speed at the hub height, the turbine specifications and air density.

Parameters:
  • wind_speed (xarray.DataArray) – Wind Speed at the hub height. Use the wind_profile function to estimate from the surface wind speed.

  • air_density (xarray.DataArray) – Air Density at the hub height. Defaults to 1.225 kg/m³. This is worth changing if applying in cold or mountainous regions with non-standard air density.

  • cut_in (Quantified) – Cut-in wind speed. Default is 3.5 m/s.

  • rated (Quantified) – Rated wind speed. Default is 13 m/s.

  • cut_out (Quantified) – Cut-out wind speed. Default is 25 m/s.

Return type:

DataArray

Returns:

xr.DataArray – The power production factor. Multiply by the nominal capacity to get the actual power production.

See also

wind_profile

Estimate wind speed at the hub height from the surface wind speed.

Notes

This estimate of wind power production is based on an idealized power curve with four wind regimes specified by the cut-in wind speed (\(u_i\)), the rated speed (\(u_r\)) and the cut-out speed (\(u_o\)). Power production is zero for wind speeds below the cut-in speed, increases cubically between the cut-in and rated speed, is constant between the rated and cut-out speed, and is zero for wind speeds above the cut-out speed to avoid damage to the turbine [Tobin et al., 2018]:

\[\begin{split}\begin{cases} 0, & v < u_i \\ (v^3 - u_i^3) / (u_r^3 - u_i^3), & u_i ≤ v < u_r \\ 1, & u_r ≤ v < u_o \\ 0, & v ≥ u_o \end{cases}\end{split}\]

For non-standard air density (\(\rho\)), the wind speed is scaled using \(v_n = v \left( \frac{\rho}{\rho_0} \right)^{1/3}\).

The temporal resolution of wind time series has a significant influence on the results: mean daily wind speeds yield lower values than hourly wind speeds. Note however that percent changes in the wind power potential climate projections are similar across resolutions [Chen, 2020].

To compute the power production, multiply the power production factor by the nominal turbine capacity (e.g. 100), set the units attribute (e.g. “MW”), resample and sum with xclim.indices.generic.select_resample_op(power, op=”sum”, freq=”D”), then convert to the desired units (e.g. “MWh”) using xclim.core.units.convert_units_to.

References

Chen [2020], Tobin, Greuell, Jerez, Ludwig, Vautard, van Vliet, and Bréon [2018].

xclim.indices._conversion.wind_profile(wind_speed, h, h_r, method='power_law', **kwds)[source]

Wind speed at a given height estimated from the wind speed at a reference height.

Estimate the wind speed based on a power law profile relating wind speed to height above the surface.

Parameters:
  • wind_speed (xarray.DataArray) – Wind Speed at the reference height.

  • h (Quantified) – Height at which to compute the Wind Speed.

  • h_r (Quantified) – Reference height.

  • method ({“power_law”}) – Method to use. Currently only “power_law” is implemented.

  • **kwds (dict) – Additional keyword arguments to pass to the method.For power_law, this is alpha, which takes a default value of 1/7, but is highly variable based on topography, surface cover and atmospheric stability.

Return type:

DataArray

Returns:

xarray.DataArray – Wind Speed at the desired height.

Notes

The power law profile is given by:

\[v = v_r \left( \frac{h}{h_r} \right)^{\alpha},\]

where \(v_r\) is the wind speed at the reference height, \(h\) is the height at which the wind speed is desired, and \(h_r\) is the reference height.

xclim.indices._hydrology module

Hydrological indice definitions.

xclim.indices._hydrology.antecedent_precipitation_index(pr, window=7, p_exp=0.935)[source]

Antecedent Precipitation Index.

Calculate the running weighted sum of daily precipitation values given a window and weighting exponent. This index serves as an indicator for soil moisture.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation data.

  • window (int) – Window for the days of precipitation data to be weighted and summed, default is 7.

  • p_exp (float) – Weighting exponent, default is 0.935.

Return type:

DataArray

Returns:

xarray.DataArray – Antecedent Precipitation Index.

References

Li, Wei, and Li [2021], Schröter, Kunz, Elmer, Mühr, and Merz [2015]

xclim.indices._hydrology.base_flow_index(q, freq='YS')[source]

Base flow index.

Return the base flow index, defined as the minimum 7-day average flow divided by the mean flow.

Parameters:
  • q (xarray.DataArray) – Rate of river discharge.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Base flow index.

Notes

Let \(\mathbf{q}=q_0, q_1, \ldots, q_n\) be the sequence of daily discharge and \(\overline{\mathbf{q}}\) the mean flow over the period. The base flow index is given by:

\[\frac{\min(\mathrm{CMA}_7(\mathbf{q}))}{\overline{\mathbf{q}}}\]

where \(\mathrm{CMA}_7\) is the seven days moving average of the daily flow:

\[\mathrm{CMA}_7(q_i) = \frac{\sum_{j=i-3}^{i+3} q_j}{7}\]
xclim.indices._hydrology.flow_index(q, p=0.95)[source]

Flow index.

Calculate the pth percentile of daily streamflow normalized by the median flow.

Parameters:
  • q (xarray.DataArray) – Daily streamflow data.

  • p (float) – Percentile for calculating the flow index, between 0 and 1. Default of 0.95 is for high flows.

Return type:

DataArray

Returns:

xarray.DataArray – Normalized Qp, which is the p th percentile of daily streamflow normalized by the median flow.

References

Clausen and Biggs [2000]

xclim.indices._hydrology.high_flow_frequency(q, threshold_factor=9, freq='YS-OCT')[source]

High flow frequency.

Calculate the number of days in a given period with flows greater than a specified threshold, given as a multiple of the median flow. By default, the period is the water year starting on 1st October and ending on 30th September, as commonly defined in North America.

Parameters:
  • q (xarray.DataArray) – Daily streamflow data.

  • threshold_factor (int) – Factor by which the median flow is multiplied to set the high flow threshold, default is 9.

  • freq (str, optional) – Resampling frequency, default is ‘YS-OCT’ for water year starting in October and ending in September.

Return type:

DataArray

Returns:

xarray.DataArray – Number of high flow days.

References

Addor, Nearing, Prieto, Newman, Le Vine, and Clark [2018], Clausen and Biggs [2000]

xclim.indices._hydrology.low_flow_frequency(q, threshold_factor=0.2, freq='YS-OCT')[source]

Low flow frequency.

Calculate the number of days in a given period with flows lower than a specified threshold, given by a fraction of the mean flow. By default, the period is the water year starting on 1st October and ending on 30th September, as commonly defined in North America.

Parameters:
  • q (xarray.DataArray) – Daily streamflow data.

  • threshold_factor (float) – Factor by which the mean flow is multiplied to set the low flow threshold, default is 0.2.

  • freq (str, optional) – Resampling frequency, default is ‘YS-OCT’ for water year starting in October and ending in September.

Return type:

DataArray

Returns:

xarray.DataArray – Number of low flow days.

References

Olden and Poff [2003]

xclim.indices._hydrology.melt_and_precip_max(snw, pr, window=3, freq='YS-JUL')[source]

Maximum snow melt and precipitation.

The maximum snow melt plus precipitation over a given number of days expressed in snow water equivalent.

Parameters:
  • snw (xarray.DataArray) – Snow amount (mass per area).

  • pr (xarray.DataArray) – Daily precipitation flux.

  • window (int) – Number of days during which the water input is accumulated.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The maximum snow melt plus precipitation over a given number of days for each period. [mass/area].

xclim.indices._hydrology.rb_flashiness_index(q, freq='YS')[source]

Richards-Baker flashiness index.

Measures oscillations in flow relative to total flow, quantifying the frequency and rapidity of short term changes in flow, based on Baker et al. [2004].

Parameters:
  • q (xarray.DataArray) – Rate of river discharge.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – R-B Index.

Notes

Let \(\mathbf{q}=q_0, q_1, \ldots, q_n\) be the sequence of daily discharge, the R-B Index is given by:

\[\frac{\sum_{i=1}^n |q_i - q_{i-1}|}{\sum_{i=1}^n q_i}\]

References

Baker, Richards, Loftus, and Kramer [2004]

xclim.indices._hydrology.snd_max(snd, freq='YS-JUL')[source]

Maximum snow depth.

The maximum daily snow depth.

Parameters:
  • snd (xarray.DataArray) – Snow depth (mass per area).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The maximum snow depth over a given number of days for each period. [length].

xclim.indices._hydrology.snd_max_doy(snd, freq='YS-JUL')[source]

Day of year of maximum snow depth.

Day of year when surface snow reaches its peak value. If snow depth is 0 over entire period, return NaN.

Parameters:
  • snd (xarray.DataArray) – Surface snow depth.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The day of year at which snow depth reaches its maximum value.

xclim.indices._hydrology.snow_melt_we_max(snw, window=3, freq='YS-JUL')[source]

Maximum snow melt.

The maximum snow melt over a given number of days expressed in snow water equivalent.

Parameters:
  • snw (xarray.DataArray) – Snow amount (mass per area).

  • window (int) – Number of days during which the melt is accumulated.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The maximum snow melt over a given number of days for each period. [mass/area].

xclim.indices._hydrology.snw_max(snw, freq='YS-JUL')[source]

Maximum snow amount.

The maximum daily snow amount.

Parameters:
  • snw (xarray.DataArray) – Snow amount (mass per area).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The maximum snow amount over a given number of days for each period. [mass/area].

xclim.indices._hydrology.snw_max_doy(snw, freq='YS-JUL')[source]

Day of year of maximum snow amount.

Day of year when surface snow amount reaches its peak value. If snow amount is 0 over entire period, return NaN.

Parameters:
  • snw (xarray.DataArray) – Surface snow amount.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The day of year at which snow amount reaches its maximum value.

xclim.indices._hydrology.standardized_groundwater_index(gwl, freq='MS', window=1, dist='genextreme', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, **indexer)[source]

Standardized Groundwater Index (SGI).

Parameters:
  • gwl (xarray.DataArray) – Groundwater head level.

  • freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.

  • window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.

  • dist ({“gamma”, “genextreme”, “lognorm”} or rv_continuous) – Name of the univariate distribution, or a callable rv_continuous (see scipy.stats).

  • method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization. PWM should be used with a lmoments3 distribution.

  • fitkwargs (dict, optional) – Kwargs passed to xclim.indices.stats.fit used to impose values of certain parameters (floc, fscale).

  • cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.

  • cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.

  • params (xarray.DataArray, optional) – Fit parameters. The params can be computed using xclim.indices.stats.standardized_index_fit_params in advance. The output can be given here as input, and it overrides other options.

  • **indexer (Indexer) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – Standardized Groundwater Index.

See also

xclim.indices._agro.standardized_precipitation_index

Standardized Precipitation Index.

xclim.indices.stats.standardized_index

Standardized Index.

xclim.indices.stats.standardized_index_fit_params

Standardized Index Fit Params.

Notes

  • N-month SGI / N-day SGI is determined by choosing the window = N and the appropriate frequency freq.

  • Supported statistical distributions are: [“gamma”, “genextreme”, “lognorm”].

  • If params is provided, it overrides the cal_start, cal_end, freq, window, dist, method options.

  • “APP” method only supports two-parameter distributions. Parameter loc needs to be fixed to use method “APP”.

References

Bloomfield and Marchant [2013]

Examples

>>> from datetime import datetime
>>> from xclim.indices import standardized_groundwater_index
>>> ds = xr.open_dataset(path_to_gwl_file)
>>> gwl = ds.gwl
>>> cal_start, cal_end = "1980-05-01", "1982-06-01"
>>> sgi_3 = standardized_groundwater_index(
...     gwl,
...     freq="MS",
...     window=3,
...     dist="gamma",
...     method="ML",
...     cal_start=cal_start,
...     cal_end=cal_end,
... )  # Computing SGI-3 months using a Gamma distribution for the fit
>>> # Fitting parameters can also be obtained first, then reused as input.
>>> from xclim.indices.stats import standardized_index_fit_params
>>> params = standardized_index_fit_params(
...     gwl.sel(time=slice(cal_start, cal_end)),
...     freq="MS",
...     window=3,
...     dist="gamma",
...     method="ML",
... )  # First getting params
>>> sgi_3 = standardized_groundwater_index(gwl, params=params)
xclim.indices._hydrology.standardized_streamflow_index(q, freq='MS', window=1, dist='genextreme', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, **indexer)[source]

Standardized Streamflow Index (SSI).

Parameters:
  • q (xarray.DataArray) – Rate of river discharge.

  • freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.

  • window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.

  • dist ({“genextreme”, “fisk”} or rv_continuous function) – Name of the univariate distribution, or a callable rv_continuous (see scipy.stats).

  • method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization. PWM should be used with a lmoments3 distribution.

  • fitkwargs (dict, optional) – Kwargs passed to xclim.indices.stats.fit used to impose values of certain parameters (floc, fscale).

  • cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.

  • cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.

  • params (xarray.DataArray, optional) – Fit parameters. The params can be computed using xclim.indices.stats.standardized_index_fit_params in advance. The output can be given here as input, and it overrides other options.

  • **indexer (Indexer) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – Standardized Streamflow Index.

See also

xclim.indices._agro.standardized_precipitation_index

Standardized Precipitation Index.

xclim.indices.stats.standardized_index

Standardized Index.

xclim.indices.stats.standardized_index_fit_params

Standardized Index Fit Params.

Notes

  • N-month SSI / N-day SSI is determined by choosing the window = N and the appropriate frequency freq.

  • Supported statistical distributions are: [“genextreme”, “fisk”], where “fisk” is scipy’s implementation of

    a log-logistic distribution.

  • If params is provided, it overrides the cal_start, cal_end, freq, window, dist, and method options.

  • “APP” method only supports two-parameter distributions. Parameter loc needs to be fixed to use method “APP”.

  • The standardized index is bounded by ±8.21. 8.21 is the largest standardized index as constrained by the float64 precision in the inversion to the normal distribution.

References

Vicente-Serrano, López-Moreno, Beguería, Lorenzo-Lacruz, Azorin-Molina, and Morán-Tejeda [2012]

Examples

>>> from datetime import datetime
>>> from xclim.indices import standardized_streamflow_index
>>> ds = xr.open_dataset(path_to_q_file)
>>> q = ds.q_sim
>>> cal_start, cal_end = "2006-05-01", "2008-06-01"
>>> ssi_3 = standardized_streamflow_index(
...     q,
...     freq="MS",
...     window=3,
...     dist="genextreme",
...     method="ML",
...     cal_start=cal_start,
...     cal_end=cal_end,
... )  # Computing SSI-3 months using a GEV distribution for the fit
>>> # Fitting parameters can also be obtained first, then reused as input.
>>> from xclim.indices.stats import standardized_index_fit_params
>>> params = standardized_index_fit_params(
...     q.sel(time=slice(cal_start, cal_end)),
...     freq="MS",
...     window=3,
...     dist="genextreme",
...     method="ML",
... )  # First getting params
>>> ssi_3 = standardized_streamflow_index(q, params=params)

xclim.indices._multivariate module

Multivariate indice definitions.

xclim.indices._multivariate.blowing_snow(snd, sfcWind, snd_thresh='5 cm', sfcWind_thresh='15 km/h', window=3, freq='YS-JUL', **indexer)[source]

Blowing snow days.

Number of days when both snowfall over the last days and daily wind speeds are above respective thresholds.

Parameters:
  • snd (xarray.DataArray) – Surface snow depth.

  • sfcWind (xr.DataArray) – Wind velocity.

  • snd_thresh (Quantified) – Threshold on net snowfall accumulation over the last window days.

  • sfcWind_thresh (Quantified) – Wind speed threshold.

  • window (int) – Period over which snow is accumulated before comparing against threshold.

  • freq (str) – Resampling frequency.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. The subset is taken after summing the snowfall over the window. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray – Number of days when snowfall and wind speeds are above respective thresholds.

xclim.indices._multivariate.cold_and_dry_days(tas, pr, tas_per, pr_per, freq='YS')[source]

Cold and dry days.

Returns the total number of days when “Cold” and “Dry” conditions coincide.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature values.

  • pr (xarray.DataArray) – Daily precipitation.

  • tas_per (xarray.DataArray) – First quartile of daily mean temperature computed by month.

  • pr_per (xarray.DataArray) – First quartile of daily total precipitation computed by month.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The total number of days when cold and dry conditions coincide.

Warning

Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.

Notes

Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.

Formula to be written (Beniston [2009]).

References

Beniston [2009]

xclim.indices._multivariate.cold_and_wet_days(tas, pr, tas_per, pr_per, freq='YS')[source]

Cold and wet days.

Returns the total number of days when “cold” and “wet” conditions coincide.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature values.

  • pr (xarray.DataArray) – Daily precipitation.

  • tas_per (xarray.DataArray) – First quartile of daily mean temperature computed by month.

  • pr_per (xarray.DataArray) – Third quartile of daily total precipitation computed by month.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The total number of days when cold and wet conditions coincide.

Warning

Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.

Notes

Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.

Formula to be written (Beniston [2009]).

References

Beniston [2009]

xclim.indices._multivariate.cold_spell_duration_index(tasmin, tasmin_per, window=6, freq='YS', resample_before_rl=True, bootstrap=False, op='<')[source]

Cold spell duration index.

Number of days with at least window consecutive days when the daily minimum temperature is below the tasmin_per percentiles.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmin_per (xarray.DataArray) – The nth percentile of daily minimum temperature with dayofyear coordinate.

  • window (int) – Minimum number of days with temperature below threshold to qualify as a cold spell.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Keep bootstrap to False when there is no common period, as bootstrapping is computationally expensive, and it might provide the wrong results.

  • op ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with at least six consecutive days when the daily minimum temperature is below the 10th percentile.

Notes

Let \(TN_i\) be the minimum daily temperature for the day of the year \(i\) and \(TN10_i\) the 10th percentile of the minimum daily temperature over the 1961-1990 period for day of the year \(i\), the cold spell duration index over period \(\phi\) is defined as:

\[\sum_{i \in \phi} \prod_{j=i}^{i+6} \left[ TN_j < TN10_j \right]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false.

References

From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI; [Zhang et al., 2011]).

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import cold_spell_duration_index
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin.isel(lat=0, lon=0)
>>> tn10 = percentile_doy(tasmin, per=10).sel(percentiles=10)
>>> cold_spell_duration_index(tasmin, tn10)

Note that this example does not use a proper 1961-1990 reference period.

xclim.indices._multivariate.daily_temperature_range(tasmin, tasmax, freq='YS', op='mean')[source]

Statistics of daily temperature range.

The mean difference between the daily maximum temperature and the daily minimum temperature.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • freq (str) – Resampling frequency.

  • op ({“min”, “max”, “mean”, “std”} or Callable) – Reduce operation. Can either be a DataArray method or a function that can be applied to a DataArray.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – The average variation in daily temperature range for the given time period.

Notes

For a default calculation using op=’mean’:

Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then the mean diurnal temperature range in period \(j\) is:

\[DTR_j = \frac{ \sum_{i=1}^I (TX_{ij} - TN_{ij}) }{I}\]
xclim.indices._multivariate.daily_temperature_range_variability(tasmin, tasmax, freq='YS')[source]

Mean absolute day-to-day variation in daily temperature range.

Mean absolute day-to-day variation in daily temperature range.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – The average day-to-day variation in daily temperature range for the given time period.

Notes

Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then calculated is the absolute day-to-day differences in period \(j\) is:

\[vDTR_j = \frac{ \sum_{i=2}^{I} |(TX_{ij}-TN_{ij})-(TX_{i-1,j}-TN_{i-1,j})| }{I}\]
xclim.indices._multivariate.days_over_precip_thresh(pr, pr_per, thresh='1 mm/day', freq='YS', bootstrap=False, op='>')[source]

Number of wet days with daily precipitation over a given percentile.

Number of days over a period where the precipitation is above a threshold defining wet days and above a given percentile for that day.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • pr_per (xarray.DataArray) – Percentile of wet day precipitation flux. Either computed daily (one value per day of year) or computed over a period (one value per spatial point).

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with daily precipitation above the given percentile [days].

Examples

>>> from xclim.indices import days_over_precip_thresh
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> p75 = pr.quantile(0.75, dim="time", keep_attrs=True)
>>> r75p = days_over_precip_thresh(pr, p75)
xclim.indices._multivariate.extreme_temperature_range(tasmin, tasmax, freq='YS')[source]

Extreme intra-period temperature range.

The maximum of max temperature (TXx) minus the minimum of min temperature (TNn) for the given time period.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – Extreme intra-period temperature range for the given time period.

Notes

Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then the extreme temperature range in period \(j\) is:

\[ETR_j = max(TX_{ij}) - min(TN_{ij})\]
xclim.indices._multivariate.fraction_over_precip_thresh(pr, pr_per, thresh='1 mm/day', freq='YS', bootstrap=False, op='>')[source]

Fraction of precipitation due to wet days with daily precipitation over a given percentile.

The percentage of the total precipitation over a period occurring for days when the precipitation is above a threshold defining wet days and above a given percentile for that day.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • pr_per (xarray.DataArray) – Percentile of wet day precipitation flux. Either computed daily (one value per day of year) or computed over a period (one value per spatial point).

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Fraction of precipitation over threshold during wet days.

xclim.indices._multivariate.heat_wave_frequency(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]

Heat wave frequency.

Number of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceed specific thresholds over a minimum number of days.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh_tasmin (Quantified) – The minimum temperature threshold needed to trigger a heatwave event.

  • thresh_tasmax (Quantified) – The maximum temperature threshold needed to trigger a heatwave event.

  • window (int) – Minimum number of days with temperatures above thresholds to qualify as a heatwave.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Number of heatwave at the requested frequency.

Notes

The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001], the parameters would be thresh_tasmin=27.22, thresh_tasmax=39.44, window=2 (81F, 103F).

References

Casati, Yagouti, and Chaumont [2013], Robinson [2001]

xclim.indices._multivariate.heat_wave_max_length(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]

Heat wave max length.

Maximum length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceed specific thresholds over a minimum number of days.

By definition, heat_wave_max_length must be >= window.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh_tasmin (Quantified) – The minimum temperature threshold needed to trigger a heatwave event.

  • thresh_tasmax (Quantified) – The maximum temperature threshold needed to trigger a heatwave event.

  • window (int) – Minimum number of days with temperatures above thresholds to qualify as a heatwave.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Maximum length of heatwave at the requested frequency.

Notes

The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001], the parameters would be: thresh_tasmin=27.22, thresh_tasmax=39.44, window=2 (81F, 103F).

References

Casati, Yagouti, and Chaumont [2013], Robinson [2001]

xclim.indices._multivariate.heat_wave_total_length(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]

Heat wave total length.

Total length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceed specific thresholds over a minimum number of days. This is the sum of all days in such events.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh_tasmin (str) – The minimum temperature threshold needed to trigger a heatwave event.

  • thresh_tasmax (str) – The maximum temperature threshold needed to trigger a heatwave event.

  • window (int) – Minimum number of days with temperatures above thresholds to qualify as a heatwave.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Total length of heatwave at the requested frequency.

Notes

See notes and references of heat_wave_max_length

xclim.indices._multivariate.high_precip_low_temp(pr, tas, pr_thresh='0.4 mm/d', tas_thresh='-0.2 degC', freq='YS')[source]

Number of days with precipitation above threshold and temperature below threshold.

Number of days when precipitation is greater or equal to some threshold, and temperatures are colder than some threshold. This can be used for example to identify days with the potential for freezing rain or icing conditions.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • tas (xarray.DataArray) – Daily mean, minimum or maximum temperature.

  • pr_thresh (Quantified) – Precipitation threshold to exceed.

  • tas_thresh (Quantified) – Temperature threshold not to exceed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with high precipitation and low temperatures.

Examples

To compute the number of days with intense rainfall while minimum temperatures dip below -0.2C: >>> pr = xr.open_dataset(path_to_pr_file).pr >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin >>> high_precip_low_temp(pr, tas=tasmin, pr_thresh=”10 mm/d”, tas_thresh=”-0.2 degC”)

xclim.indices._multivariate.liquid_precip_ratio(pr, prsn=None, tas=None, thresh='0 degC', freq='QS-DEC')[source]

Ratio of rainfall to total precipitation.

The ratio of total liquid precipitation over the total precipitation. If solid precipitation is not provided, it is approximated with pr, tas and thresh, using the snowfall_approximation function with method ‘binary’.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • prsn (xarray.DataArray, optional) – Mean daily solid precipitation flux.

  • tas (xarray.DataArray, optional) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature under which precipitation is assumed to be solid.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Ratio of rainfall to total precipitation.

See also

winter_rain_ratio

The ratio of rainfall to total precipitation during winter.

Notes

Let \(PR_i\) be the mean daily precipitation of day \(i\), then for a period \(j\) starting at day \(a\) and finishing on day \(b\):

\[ \begin{align}\begin{aligned}PR_{ij} = \sum_{i=a}^{b} PR_i\\PRwet_{ij}\end{aligned}\end{align} \]
xclim.indices._multivariate.multiday_temperature_swing(tasmin, tasmax, thresh_tasmin='0 degC', thresh_tasmax='0 degC', window=1, op='mean', op_tasmin='<=', op_tasmax='>', freq='YS', resample_before_rl=True)[source]

Statistics of consecutive diurnal temperature swing events.

A diurnal swing of max and min temperature event is when Tmax > thresh_tasmax and Tmin <= thresh_tasmin. This indice finds all days that constitute these events and computes statistics over the length and frequency of these events.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh_tasmin (Quantified) – The temperature threshold needed to trigger a freeze event.

  • thresh_tasmax (Quantified) – The temperature threshold needed to trigger a thaw event.

  • window (int) – The minimal length of spells to be included in the statistics.

  • op ({“mean”, “sum”, “max”, “min”, “std”, “count”}) – The statistical operation to use when reducing the list of spell lengths.

  • op_tasmin ({“<”, “<=”, “lt”, “le”}) – Comparison operation for tasmin. Default: “<=”.

  • op_tasmax ({“>”, “>=”, “gt”, “ge”}) – Comparison operation for tasmax. Default: “>”.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – {freq} {op} length of diurnal temperature cycles exceeding thresholds.

Notes

Let \(TX_{i}\) be the maximum temperature at day \(i\) and \(TN_{i}\) be the daily minimum temperature at day \(i\). Then freeze thaw spells during a given period are consecutive days where:

\[TX_{i} > 0℃ \land TN_{i} < 0℃\]

This indice returns a given statistic of the found lengths, optionally dropping those shorter than the window argument. For example, window=1 and op=’sum’ returns the same value as daily_freezethaw_cycles().

xclim.indices._multivariate.precip_accumulation(pr, tas=None, phase=None, thresh='0 degC', freq='YS')[source]

Accumulated total (liquid and/or solid) precipitation.

Resample the original daily mean precipitation flux and accumulate over each period. If a daily temperature is provided, the phase keyword can be used to sum precipitation of a given phase only. When the temperature is under the given threshold, precipitation is assumed to be snow, and liquid rain otherwise. This indice is agnostic to the type of daily temperature (tas, tasmax or tasmin) given.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • tas (xarray.DataArray, optional) – Mean, maximum or minimum daily temperature.

  • phase ({None, ‘liquid’, ‘solid’}) – Which phase to consider, “liquid” or “solid”, if None (default), both are considered.

  • thresh (Quantified) – Threshold of tas over which the precipication is assumed to be liquid rain.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [length] – The total daily precipitation at the given time frequency for the given phase.

Notes

Let \(PR_i\) be the mean daily precipitation of day \(i\), then for a period \(j\) starting at day \(a\) and finishing on day \(b\):

\[PR_{ij} = \sum_{i=a}^{b} PR_i\]

If tas and phase are given, the corresponding phase precipitation is estimated before computing the accumulation, using one of snowfall_approximation or rain_approximation with the binary method.

Examples

The following would compute, for each grid cell of a dataset, the total precipitation at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import precip_accumulation
>>> pr_day = xr.open_dataset(path_to_pr_file).pr
>>> prcp_tot_seasonal = precip_accumulation(pr_day, freq="QS-DEC")
xclim.indices._multivariate.precip_average(pr, tas=None, phase=None, thresh='0 degC', freq='YS')[source]

Averaged (liquid and/or solid) precipitation.

Resample the original daily mean precipitation flux and average over each period. If a daily temperature is provided, the phase keyword can be used to average precipitation of a given phase only. When the temperature is under the given threshold, precipitation is assumed to be snow, and liquid rain otherwise. This indice is agnostic to the type of daily temperature (tas, tasmax or tasmin) given.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • tas (xarray.DataArray, optional) – Mean, maximum or minimum daily temperature.

  • phase ({None, ‘liquid’, ‘solid’}) – Which phase to consider, “liquid” or “solid”, if None (default), both are considered.

  • thresh (Quantified) – Threshold of tas over which the precipication is assumed to be liquid rain.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [length] – The averaged daily precipitation at the given time frequency for the given phase.

Notes

Let \(PR_i\) be the mean daily precipitation of day \(i\), then for a period \(j\) starting at day \(a\) and finishing on day \(b\):

\[PR_{ij} =\frac{ \sum_{i=a}^{b} PR_i }{b - a + 1}\]

If tas and phase are given, the corresponding phase precipitation is estimated before computing the accumulation, using one of snowfall_approximation or rain_approximation with the binary method.

Examples

The following would compute, for each grid cell of a dataset, the total precipitation at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import precip_average
>>> pr_day = xr.open_dataset(path_to_pr_file).pr
>>> prcp_tot_seasonal = precip_average(pr_day, freq="QS-DEC")
xclim.indices._multivariate.rain_on_frozen_ground_days(pr, tas, thresh='1 mm/d', window=7, freq='YS')[source]

Number of rain on frozen ground events.

Number of days with rain above a threshold after a series of consecutive days below freezing temperature. Precipitation is assumed to be rain when the temperature is above 0℃.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Precipitation threshold to consider a day as a rain event.

  • window (int) – Minimum number of days below freezing temperature needed to consider the ground frozen.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The number of rain on frozen ground events per period.

Notes

Let \(PR_i\) be the mean daily precipitation and \(TG_i\) be the mean daily temperature of day \(i\). Then for a period \(j\), rain on frozen grounds days are counted where:

\[PR_{i} > Threshold [mm]\]

and where

\[TG_{i} ≤ 0℃\]

is true for continuous periods where \(i ≥ window\)

xclim.indices._multivariate.tg10p(tas, tas_per, freq='YS', bootstrap=False, op='<')[source]

Number of days with daily mean temperature below the 10th percentile.

Number of days with daily mean temperature below the 10th percentile.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • tas_per (xarray.DataArray) – 10th percentile of daily mean temperature.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with daily mean temperature below the 10th percentile [days].

Notes

The 10th percentile should be computed for a 5-day window centered on each calendar day for a reference period.

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tg10p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tas_per = percentile_doy(tas, per=10).sel(percentiles=10)
>>> cold_days = tg10p(tas, tas_per)
xclim.indices._multivariate.tg90p(tas, tas_per, freq='YS', bootstrap=False, op='>')[source]

Number of days with daily mean temperature over the 90th percentile.

Number of days with daily mean temperature over the 90th percentile.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • tas_per (xarray.DataArray) – 90th percentile of daily mean temperature.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with daily mean temperature below the 10th percentile [days].

Notes

The 90th percentile should be computed for a 5-day window centered on each calendar day for a reference period.

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tg90p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tas_per = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tg90p(tas, tas_per)
xclim.indices._multivariate.tn10p(tasmin, tasmin_per, freq='YS', bootstrap=False, op='<')[source]

Number of days with daily minimum temperature below the 10th percentile.

Number of days with daily minimum temperature below the 10th percentile.

Parameters:
  • tasmin (xarray.DataArray) – Mean daily temperature.

  • tasmin_per (xarray.DataArray) – 10th percentile of daily minimum temperature.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with daily minimum temperature below the 10th percentile [days].

Notes

The 10th percentile should be computed for a 5-day window centered on each calendar day for a reference period.

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tn10p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tas_per = percentile_doy(tas, per=10).sel(percentiles=10)
>>> cold_days = tn10p(tas, tas_per)
xclim.indices._multivariate.tn90p(tasmin, tasmin_per, freq='YS', bootstrap=False, op='>')[source]

Number of days with daily minimum temperature over the 90th percentile.

Number of days with daily minimum temperature over the 90th percentile.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmin_per (xarray.DataArray) – 90th percentile of daily minimum temperature.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with daily minimum temperature below the 10th percentile [days].

Notes

The 90th percentile should be computed for a 5-day window centered on each calendar day for a reference period.

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tn90p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tas_per = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tn90p(tas, tas_per)
xclim.indices._multivariate.tx10p(tasmax, tasmax_per, freq='YS', bootstrap=False, op='<')[source]

Number of days with daily maximum temperature below the 10th percentile.

Number of days with daily maximum temperature below the 10th percentile.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • tasmax_per (xarray.DataArray) – 10th percentile of daily maximum temperature.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with daily maximum temperature below the 10th percentile [days].

Notes

The 10th percentile should be computed for a 5-day window centered on each calendar day for a reference period.

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tx10p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tasmax_per = percentile_doy(tas, per=10).sel(percentiles=10)
>>> cold_days = tx10p(tas, tasmax_per)
xclim.indices._multivariate.tx90p(tasmax, tasmax_per, freq='YS', bootstrap=False, op='>')[source]

Number of days with daily maximum temperature over the 90th percentile.

Number of days with daily maximum temperature over the 90th percentile.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • tasmax_per (xarray.DataArray) – 90th percentile of daily maximum temperature.

  • freq (str) – Resampling frequency.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Count of days with daily maximum temperature below the 10th percentile [days].

Notes

The 90th percentile should be computed for a 5-day window centered on each calendar day for a reference period.

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tx90p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tasmax_per = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tx90p(tas, tasmax_per)
xclim.indices._multivariate.tx_tn_days_above(tasmin, tasmax, thresh_tasmin='22 degC', thresh_tasmax='30 degC', freq='YS', op='>')[source]

Number of days with both hot maximum and minimum daily temperatures.

The number of days per period with tasmin above a threshold and tasmax above another threshold.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh_tasmin (Quantified) – Threshold temperature for tasmin on which to base evaluation.

  • thresh_tasmax (Quantified) – Threshold temperature for tasmax on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The number of days with tasmin > thresh_tasmin and tasmax > thresh_tasmax per period.

Notes

Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\), \(TN_{ij}\) the daily minimum temperature at day \(i\) of period \(j\), \(TX_{thresh}\) the threshold for maximum daily temperature, and \(TN_{thresh}\) the threshold for minimum daily temperature. Then counted is the number of days where:

\[TX_{ij} > TX_{thresh} [℃]\]

and where:

\[TN_{ij} > TN_{thresh} [℃]\]
xclim.indices._multivariate.warm_and_dry_days(tas, pr, tas_per, pr_per, freq='YS')[source]

Warm and dry days.

Returns the total number of days when “warm” and “Dry” conditions coincide.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature values.

  • pr (xarray.DataArray) – Daily precipitation.

  • tas_per (xarray.DataArray) – Third quartile of daily mean temperature computed by month.

  • pr_per (xarray.DataArray) – First quartile of daily total precipitation computed by month.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, – The total number of days when warm and dry conditions coincide.

Warning

Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.

Notes

Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.

Formula to be written (Beniston [2009]).

References

Beniston [2009]

xclim.indices._multivariate.warm_and_wet_days(tas, pr, tas_per, pr_per, freq='YS')[source]

Warm and wet days.

Returns the total number of days when “warm” and “wet” conditions coincide.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature values.

  • pr (xarray.DataArray) – Daily precipitation.

  • tas_per (xarray.DataArray) – Third quartile of daily mean temperature computed by month.

  • pr_per (xarray.DataArray) – Third quartile of daily total precipitation computed by month.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The total number of days when warm and wet conditions coincide.

Warning

Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.

Notes

Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.

Formula to be written (Beniston [2009]).

References

Beniston [2009]

xclim.indices._multivariate.warm_spell_duration_index(tasmax, tasmax_per, window=6, freq='YS', resample_before_rl=True, bootstrap=False, op='>')[source]

Warm spell duration index.

Number of days inside spells of a minimum number of consecutive days when the daily maximum temperature is above the 90th percentile. The 90th percentile should be computed for a 5-day moving window, centered on each calendar day in the 1961-1990 period.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • tasmax_per (xarray.DataArray) – Percentile(s) of daily maximum temperature.

  • window (int) – Minimum number of days with temperature above threshold to qualify as a warm spell.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Warm spell duration index.

References

From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI; [Zhang et al., 2011]). Used in Alexander, Zhang, Peterson, Caesar, Gleason, Klein Tank, Haylock, Collins, Trewin, Rahimzadeh, Tagipour, Rupa Kumar, Revadekar, Griffiths, Vincent, Stephenson, Burn, Aguilar, Brunet, Taylor, New, Zhai, Rusticucci, and Vazquez-Aguirre [2006]

Examples

Note that this example does not use a proper 1961-1990 reference period.

>>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax.isel(lat=0, lon=0)
>>> tasmax_per = percentile_doy(tasmax, per=90).sel(percentiles=90)
>>> warm_spell_duration_index(tasmax, tasmax_per)
xclim.indices._multivariate.water_cycle_intensity(pr, evspsbl, freq='YS')[source]

Water cycle intensity.

The sum of precipitation and actual evapotranspiration.

Parameters:
  • pr (xarray.DataArray) – Precipitation flux.

  • evspsbl (xarray.DataArray) – Actual evapotranspiration flux.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – The sum of precipitation and actual evapotranspiration for each period.

References

Huntington, Weiskel, Wolock, and McCabe [2018]

xclim.indices._multivariate.winter_rain_ratio(*, pr, prsn=None, tas=None, freq='QS-DEC')[source]

Ratio of rainfall to total precipitation during winter.

The ratio of total liquid precipitation over the total precipitation over the winter months (DJF). If solid precipitation is not provided, then precipitation is assumed solid if the temperature is below 0°C.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • prsn (xarray.DataArray, optional) – Mean daily solid precipitation flux.

  • tas (xarray.DataArray, optional) – Mean daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Ratio of rainfall to total precipitation during winter months (DJF).

xclim.indices._simple module

Simple indice definitions.

xclim.indices._simple.frost_days(tasmin, thresh='0 degC', freq='YS')[source]

Frost days index.

Number of days where daily minimum temperatures are below a threshold temperature.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Freezing temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Frost days index.

Notes

Let \(TN_{ij}\) be the daily minimum temperature at day \(i\) of period \(j\) and :math`TT` the threshold. Then counted is the number of days where:

\[TN_{ij} < TT\]
xclim.indices._simple.ice_days(tasmax, thresh='0 degC', freq='YS')[source]

Number of ice/freezing days.

Number of days when daily maximum temperatures are below a threshold.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – Freezing temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of ice/freezing days.

Notes

Let \(TX_{ij}\) be the daily maximum temperature at day \(i\) of period \(j\), and :math`TT` the threshold. Then counted is the number of days where:

\[TX_{ij} < TT\]
xclim.indices._simple.max_1day_precipitation_amount(pr, freq='YS')[source]

Highest 1-day precipitation amount for a period (frequency).

Resample the original daily total precipitation temperature series by taking the max over each period.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation values.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as pr] – The highest 1-period precipitation flux value at the given time frequency.

Notes

Let \(PR_i\) be the mean daily precipitation of day i, then for a period j:

\[PRx_{ij} = max(PR_{ij})\]

Examples

The following would compute for each grid cell the highest 1-day total at an annual frequency:

>>> from xclim.indices import max_1day_precipitation_amount
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> rx1day = max_1day_precipitation_amount(pr, freq="YS")
xclim.indices._simple.max_n_day_precipitation_amount(pr, window=1, freq='YS', **indexer)[source]

Highest precipitation amount cumulated over a n-day moving window.

Calculate the n-day rolling sum of the original daily total precipitation series and determine the maximum value over each period.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation values.

  • window (int) – Window size in days.

  • freq (str) – Resampling frequency.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. The subset is taken after the N-day sum, thus including data from up to window -1 days before the selected period (and none after). It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray, [length] – The highest cumulated n-period precipitation value at the given time frequency.

Examples

The following would compute for each grid cell the highest 5-day total precipitation at an annual frequency:

>>> from xclim.indices import max_n_day_precipitation_amount
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> out = max_n_day_precipitation_amount(pr, window=5, freq="YS")
xclim.indices._simple.max_pr_intensity(pr, window=1, freq='YS', **indexer)[source]

Highest precipitation intensity over a n-hour moving window.

Calculate the n-hour rolling average of the original hourly total precipitation series and determine the maximum value over each period.

Parameters:
  • pr (xarray.DataArray) – Hourly precipitation values.

  • window (int) – Window size in hours.

  • freq (str) – Resampling frequency.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. The subset is taken after the N-hour average, thus including data from up to window - 1 hours before the selected period, and none after. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray, [same units as pr] – The highest cumulated n-hour precipitation intensity at the given time frequency.

Examples

The following would compute the maximum 6-hour precipitation intensity at an annual frequency:

>>> from xclim.indices import max_pr_intensity
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> out = max_pr_intensity(pr, window=5, freq="YS")
xclim.indices._simple.sfcWind_max(sfcWind, freq='YS')[source]

Highest daily mean wind speed.

The maximum of daily mean wind speed.

Parameters:
  • sfcWind (xarray.DataArray) – Mean daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWind] – Maximum of daily mean wind speed.

Notes

Let \(FG_{ij}\) be the mean wind speed at day \(i\) of period \(j\). Then the maximum daily mean wind speed for period \(j\) is:

\[FGx_j = max(FG_{ij})\]

Examples

The following would compute for each grid cell the maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWind_max
>>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind
>>> fg_max = sfcWind_max(fg, freq="QS-DEC")
xclim.indices._simple.sfcWind_mean(sfcWind, freq='YS')[source]

Mean of daily mean wind speed.

Resample the original daily mean wind speed series by taking the mean over each period.

Parameters:
  • sfcWind (xarray.DataArray) – Mean daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWind] – The mean daily wind speed at the given time frequency.

Notes

Let \(FG_i\) be the mean wind speed of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):

\[FG_m = \frac{\sum_{i=a}^{b} FG_i}{b - a + 1}\]

Examples

The following would compute for each grid cell the mean wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWind_mean
>>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind
>>> fg_mean = sfcWind_mean(fg, freq="QS-DEC")
xclim.indices._simple.sfcWind_min(sfcWind, freq='YS')[source]

Lowest daily mean wind speed.

The minimum of daily mean wind speed.

Parameters:
  • sfcWind (xarray.DataArray) – Mean daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWind] – Minimum of daily mean wind speed.

Notes

Let \(FG_{ij}\) be the mean wind speed at day \(i\) of period \(j\). Then the minimum daily mean wind speed for period \(j\) is:

\[FGn_j = min(FG_{ij})\]

Examples

The following would compute for each grid cell the minimum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWind_min
>>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind
>>> fg_min = sfcWind_min(fg, freq="QS-DEC")
xclim.indices._simple.sfcWindmax_max(sfcWindmax, freq='YS')[source]

Highest maximum wind speed.

The maximum of daily maximum wind speed.

Parameters:
  • sfcWindmax (xarray.DataArray) – Maximum daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWindmax] – Maximum value of daily maximum wind speed.

Notes

Let \(FX_{ij}\) be the maximum wind speed at day \(i\) of period \(j\). Then the maximum daily maximum wind speed for period \(j\) is:

\[FXx_j = max(FX_{ij})\]

Examples

The following would compute for each grid cell of the dataset the extreme maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWindmax_max
>>> max_sfcWindmax = sfcWindmax_max(sfcWindmax_dataset, freq="QS-DEC")
xclim.indices._simple.sfcWindmax_mean(sfcWindmax, freq='YS')[source]

Mean of daily maximum wind speed.

Resample the original daily maximum wind speed series by taking the mean over each period.

Parameters:
  • sfcWindmax (xarray.DataArray) – Maximum daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWindmax] – The mean daily maximum wind speed at the given time frequency.

Notes

Let \(FX_i\) be the maximum wind speed of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):

\[FX_m = \frac{\sum_{i=a}^{b} FX_i}{b - a + 1}\]

Examples

The following would compute for each grid cell of the dataset the mean of maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWindmax_mean
>>> mean_sfcWindmax = sfcWindmax_mean(sfcWindmax_dataset, freq="QS-DEC")
xclim.indices._simple.sfcWindmax_min(sfcWindmax, freq='YS')[source]

Lowest daily maximum wind speed.

The minimum of daily maximum wind speed.

Parameters:
  • sfcWindmax (xarray.DataArray) – Maximum daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWindmax] – Minimum of daily maximum wind speed.

Notes

Let \(FX_{ij}\) be the maximum wind speed at day \(i\) of period \(j\). Then the minimum daily maximum wind speed for period \(j\) is:

\[FXn_j = min(FX_{ij})\]

Examples

The following would compute for each grid cell of the dataset the minimum of maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWindmax_min
>>> min_sfcWindmax = sfcWindmax_min(sfcWindmax_dataset, freq="QS-DEC")
xclim.indices._simple.snow_depth(snd, freq='YS')[source]

Mean of daily average snow depth.

Resample the original daily mean snow depth series by taking the mean over each period.

Parameters:
  • snd (xarray.DataArray) – Mean daily snow depth.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as snd] – The mean daily snow depth at the given time frequency.

xclim.indices._simple.tg_max(tas, freq='YS')[source]

Highest mean temperature.

The maximum of daily mean temperature.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tas] – Maximum of daily mean temperature.

Notes

Let \(TN_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the maximum daily mean temperature for period \(j\) is:

\[TNx_j = max(TN_{ij})\]
xclim.indices._simple.tg_mean(tas, freq='YS')[source]

Mean of daily average temperature.

Resample the original daily mean temperature series by taking the mean over each period.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tas] – The mean daily temperature at the given time frequency.

Notes

Let \(TN_i\) be the mean daily temperature of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):

\[TG_p = \frac{\sum_{i=a}^{b} TN_i}{b - a + 1}\]

Examples

The following would compute for each grid cell of file tas.day.nc the mean temperature at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import tg_mean
>>> t = xr.open_dataset(path_to_tas_file).tas
>>> tg = tg_mean(t, freq="QS-DEC")
xclim.indices._simple.tg_min(tas, freq='YS')[source]

Lowest mean temperature.

Minimum of daily mean temperature.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tas] – Minimum of daily minimum temperature.

Notes

Let \(TG_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the minimum daily mean temperature for period \(j\) is:

\[TGn_j = min(TG_{ij})\]
xclim.indices._simple.tn_max(tasmin, freq='YS')[source]

Highest minimum temperature.

The maximum of daily minimum temperature.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – Maximum of daily minimum temperature.

Notes

Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then the maximum daily minimum temperature for period \(j\) is:

\[TNx_j = max(TN_{ij})\]
xclim.indices._simple.tn_mean(tasmin, freq='YS')[source]

Mean minimum temperature.

Mean of daily minimum temperature.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – Mean of daily minimum temperature.

Notes

Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:

\[TN_{ij} = \frac{ \sum_{i=1}^{I} TN_{ij} }{I}\]
xclim.indices._simple.tn_min(tasmin, freq='YS')[source]

Lowest minimum temperature.

Minimum of daily minimum temperature.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – Minimum of daily minimum temperature.

Notes

Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then the minimum daily minimum temperature for period \(j\) is:

\[TNn_j = min(TN_{ij})\]
xclim.indices._simple.tx_max(tasmax, freq='YS')[source]

Highest max temperature.

The maximum value of daily maximum temperature.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmax] – Maximum value of daily maximum temperature.

Notes

Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then the maximum daily maximum temperature for period \(j\) is:

\[TXx_j = max(TX_{ij})\]
xclim.indices._simple.tx_mean(tasmax, freq='YS')[source]

Mean max temperature.

The mean of daily maximum temperature.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmax] – Mean of daily maximum temperature.

Notes

Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:

\[TX_{ij} = \frac{ \sum_{i=1}^{I} TX_{ij} }{I}\]
xclim.indices._simple.tx_min(tasmax, freq='YS')[source]

Lowest max temperature.

The minimum of daily maximum temperature.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmax] – Minimum of daily maximum temperature.

Notes

Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then the minimum daily maximum temperature for period \(j\) is:

\[TXn_j = min(TX_{ij})\]

xclim.indices._synoptic module

Synoptic indice definitions.

xclim.indices._synoptic.jetstream_metric_woollings(ua)[source]

Strength and latitude of jetstream.

Identify latitude and strength of maximum smoothed zonal wind speed in the region from 15 to 75°N and -60 to 0°E, using the formula outlined in [Woollings et al., 2010]. Wind is smoothened using a Lanczos filter approach.

Parameters:

ua (xarray.DataArray) – Eastward wind component (u) at between 750 and 950 hPa.

Return type:

tuple[DataArray, DataArray]

Returns:

(xarray.DataArray, xarray.DataArray) – Daily time series of latitude of jetstream and daily time series of strength of jetstream.

Warning

This metric expects eastward wind component (u) to be on a regular grid (i.e. Plate Carree, 1D lat and lon)

References

Woollings, Hannachi, and Hoskins [2010]

xclim.indices._threshold module

Threshold indice definitions.

xclim.indices._threshold.calm_days(sfcWind, thresh='2 m s-1', freq='MS')[source]

Calm days.

The number of days with average near-surface wind speed below threshold (default: 2 m/s).

Parameters:
  • sfcWind (xarray.DataArray) – Daily windspeed.

  • thresh (Quantified) – Threshold average near-surface wind speed on which to base evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with average near-surface wind speed below the threshold.

Notes

Let \(WS_{ij}\) be the windspeed at day \(i\) of period \(j\). Then counted is the number of days where:

\[WS_{ij} < Threshold [m s-1]\]
xclim.indices._threshold.cold_spell_days(tas, thresh='-10 degC', window=5, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Cold spell days.

The number of days that are part of cold spell events, defined as a sequence of consecutive days with mean daily temperature below a threshold (default: -10°C).

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature below which a cold spell begins.

  • window (int) – Minimum number of days with temperature below the threshold to qualify as a cold spell.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Cold spell days.

Notes

Let \(T_i\) be the mean daily temperature on day \(i\), the number of cold spell days during period \(\phi\) is given by:

\[\sum_{i \in \phi} \prod_{j=i}^{i+5} [T_j < thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false.

xclim.indices._threshold.cold_spell_frequency(tas, thresh='-10 degC', window=5, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Cold spell frequency.

The number of cold spell events, defined as a sequence of consecutive {window} days with mean daily temperature below a {thresh}.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature below which a cold spell begins.

  • window (int) – Minimum number of days with temperature below the threshold to qualify as a cold spell.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run.

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of cold periods of minimum {window} days.

xclim.indices._threshold.cold_spell_max_length(tas, thresh='-10 degC', window=1, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Longest cold spell.

Longest spell of low temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or below {thresh}.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – The temperature threshold needed to trigger a cold spell.

  • window (int) – Minimum number of days with temperatures below the threshold to qualify as a cold spell.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in cold periods of minimum {window} days.

xclim.indices._threshold.cold_spell_total_length(tas, thresh='-10 degC', window=3, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Total length of cold spells.

Total length of spells of low temperatures over a given period. Total length of series of at least {window} consecutive days with temperature at or below {thresh}.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – The temperature threshold needed to trigger a cold spell.

  • window (int) – Minimum number of days with temperatures below the threshold to qualify as a cold spell.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} total number of days in cold periods of minimum {window} days.

xclim.indices._threshold.cooling_degree_days(tas, thresh='18 degC', freq='YS')[source]

Cooling degree days.

Returns the sum of degree days above the temperature threshold at which spaces are cooled (default: 18℃).

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Temperature threshold above which air is cooled.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time][temperature] – Cooling degree days.

Notes

Let \(x_i\) be the daily mean temperature at day \(i\). Then the cooling degree days above temperature threshold \(thresh\) over period \(\phi\) is given by:

\[\sum_{i \in \phi} (x_{i}-{thresh} [x_i > thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false.

xclim.indices._threshold.cooling_degree_days_approximation(tasmax, tasmin, tas, thresh='18 degC', freq='YS')[source]

Cooling degree days approximation.

A more robust approximation of cooling degree days as a function of the daily cycle of temperature.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Temperature threshold above which air is cooled.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Approximation of cooling degree days.

References

Spinoni, Vogt, Barbosa, Dosio, McCormick, Bigano, and Füssel [2018]

xclim.indices._threshold.daily_pr_intensity(pr, thresh='1 mm/day', freq='YS', op='>=')[source]

Average daily precipitation intensity.

Return the average precipitation over wet days. Wet days are those with precipitation over a given threshold (default: 1 mm/day).

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [precipitation] – The average precipitation over wet days for each period.

Notes

Let \(\mathbf{p} = p_0, p_1, \ldots, p_n\) be the daily precipitation and \(thresh\) be the precipitation threshold defining wet days. Then the daily precipitation intensity is defined as:

\[\frac{\sum_{i=0}^n p_i [p_i \leq thresh]}{\sum_{i=0}^n [p_i \leq thresh]}\]

where \([P]\) is 1 if \(P\) is true, and 0 if false.

Examples

The following would compute for each grid cell of file pr.day.nc the average precipitation fallen over days with precipitation >= 5 mm at seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import daily_pr_intensity
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> daily_int = daily_pr_intensity(pr, thresh="5 mm/day", freq="QS-DEC")
xclim.indices._threshold.days_with_snow(prsn, low='0 kg m-2 s-1', high='1E6 kg m-2 s-1', freq='YS-JUL')[source]

Days with snow.

Return the number of days where snowfall is within low and high thresholds.

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • low (Quantified) – Minimum threshold snowfall flux or liquid water equivalent snowfall rate.

  • high (Quantified) – Maximum threshold snowfall flux or liquid water equivalent snowfall rate.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – Number of days where snowfall is between low and high thresholds.

Warning

The default freq is valid for the northern hemisphere.

Notes

If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.

References

Matthews, Andrey, and Picketts [2017].

xclim.indices._threshold.degree_days_exceedance_date(tas, thresh='0 degC', sum_thresh='25 K days', op='>', after_date=None, never_reached=None, freq='YS')[source]

Degree-days exceedance date.

Day of year when the sum of degree days exceeds a threshold (default: 25 K days). Degree days are computed above or below a given temperature threshold (default: 0℃).

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base degree-days evaluation.

  • sum_thresh (Quantified) – Threshold of the degree days sum.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – If equivalent to ‘>’, degree days are computed as tas - thresh and if equivalent to ‘<’, they are computed as thresh - tas.

  • after_date (str, optional) – Date at which to start the cumulative sum. In “MM-DD” format, defaults to the start of the sampling period.

  • never_reached (int, str, optional) – What to do when sum_thresh is never exceeded. If an int, the value to assign as a day-of-year. If a string, must be in “MM-DD” format, the day-of-year of that date is assigned. Default (None) assigns “NaN”.

  • freq (str) – Resampling frequency. If after_date is given, freq should be annual.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Degree-days exceedance date.

Notes

Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\), \(T\) is the reference threshold and \(ST\) is the sum threshold. Then, starting at day :math:i_0:, the degree days exceedance date is the first day \(k\) such that:

\[\begin{split}\begin{cases} ST < \sum_{i=i_0}^{k} \max(TG_{ij} - T, 0) & \text{if $op$ is '>'} \\ ST < \sum_{i=i_0}^{k} \max(T - TG_{ij}, 0) & \text{if $op$ is '<'} ST < \sum_{i=i_0}^{k} \max(T - TG_{ij}, 0) & \text{if $op$ is '<'} \end{cases} \end{cases}\end{split}\]

The resulting \(k\) is expressed as a day of year.

Cumulated degree days have numerous applications including plant and insect phenology. See: https://en.wikipedia.org/wiki/Growing_degree-day for examples (Wikipedia Contributors [2021]).

xclim.indices._threshold.dry_days(pr, thresh='0.2 mm/d', freq='YS', op='<')[source]

Dry days.

The number of days with daily precipitation below threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Threshold precipitation on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with daily precipitation {op} threshold.

Notes

Let \(PR_{ij}\) be the daily precipitation at day \(i\) of period \(j\). Then counted is the number of days where:

\[\sum PR_{ij} < Threshold [mm/day]\]
xclim.indices._threshold.dry_spell_frequency(pr, thresh='1.0 mm', window=3, freq='YS', resample_before_rl=True, op='sum', **indexer)[source]

Return the number of dry periods of n days and more.

Periods during which the accumulated or maximal daily precipitation amount within a window of n days is under a given threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation amount under which a period is considered dry. The value against which the threshold is compared depends on op.

  • window (int) – Minimum length of the spells.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • op ({“sum”, “max”, “min”, “mean”}) – Operation to perform on the window. Default is “sum”, which checks that the sum of accumulated precipitation over the whole window is less than the threshold. “max” checks that the maximal daily precipitation amount within the window is less than the threshold. This is the same as verifying that each individual day is below the threshold.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the dry days, but before finding the spells.

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of dry periods of minimum {window} days.

See also

xclim.indices.generic.spell_length_statistics

The parent function that computes the spell length statistics.

Examples

>>> from xclim.indices import dry_spell_frequency
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> dsf_sum = dry_spell_frequency(pr=pr, op="sum")
>>> dsf_max = dry_spell_frequency(pr=pr, op="max")
xclim.indices._threshold.dry_spell_max_length(pr, thresh='1.0 mm', window=1, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Longest dry spell.

The maximum number of consecutive days in a dry period of minimum length, during which the maximum or accumulated precipitation within a window of the same length is under a threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Accumulated precipitation value under which a period is considered dry.

  • window (int) – Number of days when the maximum or accumulated precipitation is under the threshold.

  • op ({“max”, “sum”}) – Reduce operation.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the dry days, but before finding the spells.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in dry periods of minimum {window} days.

See also

xclim.indices.generic.spell_length_statistics

The parent function that computes the spell length statistics.

Notes

The algorithm assumes days before and after the timeseries are “wet”, meaning that the condition for being considered part of a dry spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a dry spell only if the accumulated precipitation within the first three days is under the threshold. In comparison, a day in the middle of the series is considered part of a dry spell if any of the three 3-day periods of which it is part are considered dry (so a total of five days are included in the computation, compared to only three).

xclim.indices._threshold.dry_spell_total_length(pr, thresh='1.0 mm', window=3, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Total length of dry spells.

The total number of days in dry periods of a minimum length, during which the maximum or accumulated precipitation within a window of the same length is under a given threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Accumulated precipitation value under which a period is considered dry.

  • window (int) – Number of days when the maximum or accumulated precipitation is under the threshold.

  • op ({“sum”, “max”, “min”, “mean”}) – Operation to perform on the window. Default is “sum”, which checks that the sum of accumulated precipitation over the whole window is less than the threshold. “max” checks that the maximal daily precipitation amount within the window is less than the threshold. This is the same as verifying that each individual day is below the threshold.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the dry days, but before finding the spells.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} total number of days in dry periods of minimum {window} days.

See also

xclim.indices.generic.spell_length_statistics

The parent function that computes the spell length statistics.

Notes

The algorithm assumes days before and after the timeseries are “wet”, meaning that the condition for being considered part of a dry spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a dry spell only if the accumulated precipitation within the first three days is under the threshold. In comparison, a day in the middle of the series is considered part of a dry spell if any of the three 3-day periods of which it is part are considered dry (so a total of five days are included in the computation, compared to only three).

xclim.indices._threshold.first_day_temperature_above(tas, thresh='0 degC', op='>', after_date='01-01', window=1, freq='YS')[source]

First day of temperatures superior to a given temperature threshold.

Returns first day of period where temperature is superior to a threshold over a given number of days (default: 1), limited to a starting calendar date (default: January 1st).

Parameters:
  • tas (xarray.DataArray) – Daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

  • after_date (str) – Date of the year after which to look for the first event. Should have the format ‘%m-%d’.

  • window (int) – Minimum number of days with temperature above the threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when temperature is superior to a threshold over a given number of days for the first time. If there is no such day, returns np.nan.

Warning

The default freq and after_date parameters are valid for the northern hemisphere.

Notes

Let \(x_i\) be the daily mean|max|min temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The first day above temperature threshold is given by the smallest index \(i\):

\[\prod_{j=i}^{i+w} [x_j > thresh]\]

where \(w\) is the number of days the temperature threshold should be exceeded, and \([P]\) is 1 if \(P\) is true, and 0 if false.

xclim.indices._threshold.first_day_temperature_below(tas, thresh='0 degC', op='<', after_date='07-01', window=1, freq='YS')[source]

First day of temperatures inferior to a given temperature threshold.

Returns first day of period where temperature is inferior to a threshold over a given number of days (default: 1), limited to a starting calendar date (default: July 1st).

Parameters:
  • tas (xarray.DataArray) – Daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “>”.

  • after_date (str) – Date of the year after which to look for the first event. Should have the format ‘%m-%d’.

  • window (int) – Minimum number of days with temperature below the threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when temperature is inferior to a threshold over a given number of days for the first time. If there is no such day, returns np.nan.

Warning

The default freq and after_date parameters are valid for the Northern Hemisphere.

xclim.indices._threshold.first_snowfall(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

First day with snowfall rate above a given threshold.

Returns the first day of a period where snowfall exceeds a threshold (default: 1 mm/day).

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate. (default: 1 mm/day).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Last day of the year where snowfall is superior to a threshold. If there is no such day, returns np.nan.

Warning

The default freq is valid for the northern hemisphere.

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If the threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed, and the threshold is converted using a 1000 kg m-3 density.

References

CBCL [2020].

xclim.indices._threshold.frost_free_season_end(tasmin, thresh='0.0 degC', window=5, mid_date='07-01', op='>=', freq='YS')[source]

End of the frost-free season.

The frost-free season starts when a sequence of window consecutive days are above the threshold and ends when a sequence of consecutive days of the same length are under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, the start must occur before and the end after for the season to be valid.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above/under the threshold to start/end the season.

  • mid_date (DayOfYearStr, optional) – A date what must be included in the season. None removes that constraint.

  • op ({“>”, “gt”, “>=”, “ge”}) – How to compare tasmin and the threshold.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when the frost-free season starts.

Notes

Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date is given by the smallest index \(i\):

\[\prod_{k=i}^{i+w} [x_k >= thresh]\]

while the end date is given bt the largest index \(j\):

\[\prod_{k=j}^{j+w} [x_k < thresh]\]

where \(w\) is the number of days the temperature threshold should be exceeded/subceeded. An end is only valid if a start is also found and the end must happen later than mid_date while the start must happen earlier.

xclim.indices._threshold.frost_free_season_length(tasmin, thresh='0.0 degC', window=5, mid_date='07-01', op='>=', freq='YS')[source]

Length of the frost-free season.

The frost-free season starts when a sequence of window consecutive days are above the threshold and ends when a sequence of consecutive days of the same length are under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, the start must occur before and the end after for the season to be valid.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above/under the threshold to start/end the season.

  • mid_date (DayOfYearStr, optional) – A date what must be included in the season. None removes that constraint.

  • op ({“>”, “gt”, “>=”, “ge”}) – How to compare tasmin and the threshold.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Length of the frost free season.

Notes

Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date is given by the smallest index \(i\):

\[\prod_{k=i}^{i+w} [x_k >= thresh]\]

while the end date is given bt the largest index \(j\):

\[\prod_{k=j}^{j+w} [x_k < thresh]\]

where \(w\) is the number of days the temperature threshold should be exceeded/subceeded. An end is only valid if a start is also found and the end must happen later than mid_date while the start must happen earlier.

Examples

>>> from xclim.indices import frost_season_length
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin

For the Northern Hemisphere:

>>> ffsl_nh = frost_free_season_length(tasmin, freq="YS")

If working in the Southern Hemisphere, one can use:

>>> ffsl_sh = frost_free_season_length(tasmin, freq="YS-JUL")
xclim.indices._threshold.frost_free_season_start(tasmin, thresh='0.0 degC', window=5, mid_date='07-01', op='>=', freq='YS')[source]

Start of the frost-free season.

The frost-free season starts when a sequence of window consecutive days are above the threshold and ends when a sequence of consecutive days of the same length are under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, the start must occur before and the end after for the season to be valid.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above/under the threshold to start/end the season.

  • mid_date (DayOfYearStr, optional) – A date that must be included in the season. None removes that constraint.

  • op ({“>”, “gt”, “>=”, “ge”}) – How to compare tasmin and the threshold.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when the frost-free season starts.

Notes

Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date of the season is given by the smallest index \(i\):

\[\prod_{j=i}^{i+w} [x_j >= thresh]\]

where \(w\) is the number of days the temperature threshold should be met or exceeded, and i must be earlier than mid_date.

xclim.indices._threshold.frost_free_spell_max_length(tasmin, thresh='0.0 degC', window=1, freq='YS-JUL', op='>=', resample_before_rl=True)[source]

Longest frost-free spell.

Longest spell of warm temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or above the threshold.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – The temperature threshold needed to trigger a frost-free spell.

  • window (int) – Minimum number of days with temperatures above thresholds to qualify as a frost-free day.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in frost-free periods of minimum {window} days.

xclim.indices._threshold.frost_season_length(tasmin, window=5, mid_date='01-01', thresh='0.0 degC', freq='YS-JUL', op='<')[source]

Frost season length.

The number of days between the first occurrence of at least N (default: 5) consecutive days with minimum daily temperature under a threshold (default: 0℃) and the first occurrence of at least N consecutive days with minimum daily temperature above the same threshold. A mid-date can be given to limit the earliest day the end of season can take.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • window (int) – Minimum number of days with temperature below threshold to mark the beginning and end of frost season.

  • mid_date (str, optional) – The date must be included in the season. It is the earliest the end of the season can be. None removes that constraint.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Frost season length.

Warning

The default freq and mid_date parameters are valid for the Northern Hemisphere.

Notes

Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least N consecutive days with:

\[TN_{ij} > 0 ℃\]

and the first subsequent occurrence of at least N consecutive days with:

\[TN_{ij} < 0 ℃\]

Examples

>>> from xclim.indices import frost_season_length
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin

For the Northern Hemisphere:

>>> fsl_nh = frost_season_length(tasmin, freq="YS-JUL")

If working in the Southern Hemisphere, one can use:

>>> fsl_sh = frost_season_length(tasmin, freq="YS")
xclim.indices._threshold.growing_degree_days(tas, thresh='4.0 degC', freq='YS')[source]

Growing degree-days over threshold temperature value.

The sum of growing degree-days over a given mean daily temperature threshold (default: 4℃).

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time][temperature] – The sum of growing degree-days above a given threshold.

Notes

Let \(TG_{ij}\) be the mean daily temperature at day \(i\) of period \(j\). Then the growing degree days are:

\[GD4_j = \sum_{i=1}^I (TG_{ij}-{4} | TG_{ij} > {4}℃)\]
xclim.indices._threshold.growing_season_end(tas, thresh='5.0 degC', mid_date='07-01', window=5, freq='YS', op='>')[source]

End of the growing season.

The growing season starts with the first sequence of a minimum length of consecutive days above the threshold and ends with the first sequence of the same minimum length of consecutive days under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, a start can’t happen later and an end can’t happen earlier.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • mid_date (str, optional) – Date of the year after which to look for the end of the season. Should have the format ‘%m-%d’. None removes that constraint.

  • window (int) – Minimum number of days with temperature below threshold needed for evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”. Note that this comparison is what defines the season. The end of the season happens when the condition is NOT met for window consecutive days.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – End of the growing season.

Warning

The default freq and mid_date parameters are valid for the northern hemisphere.

Notes

Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date of the end of growing season is given by the smallest index \(i\):

\[\prod_{j=i}^{i+w} [x_j < thresh]\]

where \(w\) is the number of days where temperature should be inferior to a given threshold after a given date, and \([P]\) is 1 if \(P\) is true, and 0 if false.

xclim.indices._threshold.growing_season_length(tas, thresh='5.0 degC', window=6, mid_date='07-01', freq='YS', op='>=')[source]

Growing season length.

The growing season starts with the first sequence of a minimum length of consecutive days above the threshold and ends with the first sequence of the same minimum length of consecutive days under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, a start can’t happen later and an end can’t happen earlier. If the season starts but never ends, the length is computed up to the end of the resampling period. If no season start is found, but the data is valid, a length of 0 is returned.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above the threshold to mark the beginning and end of growing season.

  • mid_date (str, optional) – Date of the year before which the season must start and after which it can end. Should have the format ‘%m-%d’. Setting None removes that constraint.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Growing season length.

Warning

The default freq and mid_date parameters are valid for the Northern Hemisphere.

Notes

Let \(TG_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least 6 consecutive days with:

\[TG_{ij} >= 5 ℃\]

and the first occurrence after 1 July of at least six (6) consecutive days with:

\[TG_{ij} < 5 ℃\]

References

Project team ECA&D and KNMI [2013]

Examples

>>> from xclim.indices import growing_season_length
>>> tas = xr.open_dataset(path_to_tas_file).tas

For the Northern Hemisphere:

>>> gsl_nh = growing_season_length(tas, mid_date="07-01", freq="YS")

If working in the Southern Hemisphere, one can use:

>>> gsl_sh = growing_season_length(tas, mid_date="01-01", freq="YS-JUL")
xclim.indices._threshold.growing_season_start(tas, thresh='5.0 degC', mid_date='07-01', window=5, freq='YS', op='>=')[source]

Start of the growing season.

The growing season starts with the first sequence of a minimum length of consecutive days above the threshold and ends with the first sequence of the same minimum length of consecutive days under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, a start can’t happen later and an end can’t happen earlier.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • mid_date (str, optional) – Date of the year before which the season must start. Should have the format ‘%m-%d’. None removes that constraint.

  • window (int) – Minimum number of days with temperature above threshold needed for evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Start of the growing season.

Warning

The default freq and mid_date parameters are valid for the northern hemisphere.

xclim.indices._threshold.heat_wave_index(tasmax, thresh='25.0 degC', window=5, freq='YS', op='>', resample_before_rl=True)[source]

Heat wave index.

Number of days that are part of a heatwave, defined as five or more consecutive days over a threshold of 25℃.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to designate a heatwave.

  • window (int) – Minimum number of days with temperature above the threshold to qualify as a heatwave.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

DataArray, [time] – Heat wave index.

xclim.indices._threshold.heating_degree_days(tas, thresh='17.0 degC', freq='YS')[source]

Heating degree days.

Sum of degree days below the temperature threshold (default: 17℃) at which spaces are heated.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time][temperature] – Heating degree days index.

Notes

This index intentionally differs from its ECA&D [Project team ECA&D and KNMI, 2013] equivalent: HD17. In HD17, values below zero are not clipped before the sum. The present definition should provide a better representation of the energy demand for heating buildings to the given threshold.

Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\). Then the heating degree days are:

\[HD17_j = \sum_{i=1}^{I} (17℃ - TG_{ij}) | TG_{ij} < 17℃)\]
xclim.indices._threshold.heating_degree_days_approximation(tasmax, tasmin, tas, thresh='17.0 degC', freq='YS')[source]

Heating degree days approximation.

A more robust approximation of heating degree days as a function of the daily cycle of temperature.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Approximation of heating degree days.

References

Spinoni, Vogt, Barbosa, Dosio, McCormick, Bigano, and Füssel [2018]

xclim.indices._threshold.holiday_snow_and_snowfall_days(snd, prsn=None, snd_thresh='20 mm', prsn_thresh='1 mm', snd_op='>=', prsn_op='>=', date_start='12-25', date_end=None, freq='YS-JUL')[source]

Perfect Christmas Days.

Whether there is a significant amount of snow on the ground and measurable snowfall occurring on December 25th.

Parameters:
  • snd (xarray.DataArray) – Surface snow depth.

  • prsn (xarray.DataArray) – Snowfall flux.

  • snd_thresh (Quantified) – Threshold snow amount. Default: 20 mm.

  • prsn_thresh (Quantified) – Threshold daily snowfall liquid-water equivalent thickness. Default: 1 mm.

  • snd_op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation for snow depth. Default: “>=”.

  • prsn_op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation for snowfall flux. Default: “>=”.

  • date_start (str) – Beginning of analysis period. Default: “12-25” (December 25th).

  • date_end (str, optional) – End of analysis period. If not provided, date_start is used. Default: None.

  • freq (str) – Resampling frequency. Default: “YS-JUL”. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [int] – The total number of days with snow and snowfall during the holiday.

References

https://www.canada.ca/en/environment-climate-change/services/weather-general-tools-resources/historical-christmas-snowfall-data.html

xclim.indices._threshold.holiday_snow_days(snd, snd_thresh='20 mm', op='>=', date_start='12-25', date_end=None, freq='YS')[source]

Christmas Days.

Whether there is a significant amount of snow on the ground on December 25th (or a given date range).

Parameters:
  • snd (xarray.DataArray) – Surface snow depth.

  • snd_thresh (Quantified) – Threshold snow amount. Default: 20 mm.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

  • date_start (str) – Beginning of the analysis period. Default: “12-25” (December 25th).

  • date_end (str, optional) – End of analysis period. If not provided, date_start is used. Default: None.

  • freq (str) – Resampling frequency. Default: “YS”. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [bool] – Boolean array of years with Christmas Days.

References

https://www.canada.ca/en/environment-climate-change/services/weather-general-tools-resources/historical-christmas-snowfall-data.html

xclim.indices._threshold.hot_spell_frequency(tasmax, thresh='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]

Hot spell frequency.

The number of hot spell events, defined as a sequence of consecutive {window} days with mean daily temperature above a {thresh}.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – Threshold temperature below which a hot spell begins.

  • window (int) – Minimum number of days with temperature above the threshold to qualify as a hot spell.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run.

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of hot periods of minimum {window} days.

Notes

The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).

References

Casati, Yagouti, and Chaumont [2013], Robinson [2001]

xclim.indices._threshold.hot_spell_max_length(tasmax, thresh='30 degC', window=1, freq='YS', op='>', resample_before_rl=True)[source]

Longest hot spell.

Longest spell of high temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or above {thresh}.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – The temperature threshold needed to trigger a hot spell.

  • window (int) – Minimum number of days with temperatures below thresholds to qualify as a hot spell.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in hot periods of minimum {window} days.

Notes

The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterizes the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).

References

Casati, Yagouti, and Chaumont [2013], Robinson [2001]

xclim.indices._threshold.hot_spell_max_magnitude(tasmax, thresh='25.0 degC', window=3, freq='YS', resample_before_rl=True)[source]

Hot spell maximum magnitude.

Magnitude of the most intensive heat wave event as the sum of differences between tasmax and the given threshold for Heat Wave days, defined as three or more consecutive days over the threshold.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (xarray.DataArray) – Threshold temperature on which to designate a heatwave.

  • window (int) – Minimum number of days with temperature above the threshold to qualify as a heatwave.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

DataArray, [time] – Hot spell maximum magnitude.

References

Russo, Dosio, Graversen, Sillmann, Carrao, Dunbar, Singleton, Montagna, Barbola, and Vogt [2014], Zhang, She, Zhang, Wang, Chen, and Hao [2022].

xclim.indices._threshold.hot_spell_total_length(tasmax, thresh='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]

Total length of hot spells.

Total length of spells of high temperatures over a given period. Total length of series of at least {window} consecutive days with temperature at or above {thresh}.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – The temperature threshold needed to trigger a hot spell.

  • window (int) – Minimum number of days with temperatures below the threshold to qualify as a hot spell.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} total number of days in hot periods of minimum {window} days.

Notes

The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).

xclim.indices._threshold.last_snowfall(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

Last day with snowfall above a given threshold.

Returns the last day of a period where snowfall exceeds a threshold (default: 1 mm/day)

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Last day of the year where snowfall is superior to a threshold. If there is no such day, returns np.nan.

Warning

The default freq is valid for the Northern Hemisphere.

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If the threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed, and the threshold is converted using a 1000 kg m-3 density.

References

CBCL [2020].

xclim.indices._threshold.last_spring_frost(tasmin, thresh='0 degC', op='<', before_date='07-01', window=1, freq='YS')[source]

Last day of temperatures inferior to a threshold temperature.

Returns last day of period where minimum temperature is inferior to a threshold over a given number of days (default: 1) and limited to a final calendar date (default: July 1st).

Parameters:
  • tasmin (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

  • before_date (str,) – Date of the year before which to look for the final frost event. Should have the format ‘%m-%d’.

  • window (int) – Minimum number of days with temperature below the threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when temperature is inferior to a threshold over a given number of days for the first time. If there is no such day, returns np.nan.

Warning

The default freq and before_date parameters are valid for the Northern Hemisphere.

xclim.indices._threshold.maximum_consecutive_dry_days(pr, thresh='1 mm/day', freq='YS', resample_before_rl=True)[source]

Maximum number of consecutive dry days.

Return the maximum number of consecutive days within the period where precipitation is below a certain threshold (default: 1 mm/day).

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • thresh (Quantified) – Threshold precipitation on which to base evaluation.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The maximum number of consecutive dry days (precipitation < threshold per period).

Notes

Let \(\mathbf{p}=p_0, p_1, \ldots, p_n\) be a daily precipitation series and \(thresh\) the threshold under which a day is considered dry. Then let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([p_i < thresh] \neq [p_{i+1} < thresh]\), that is, the days where the precipitation crosses the threshold. Then the maximum number of consecutive dry days is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [p_{s_j} < thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices._threshold.maximum_consecutive_frost_days(tasmin, thresh='0.0 degC', freq='YS-JUL', resample_before_rl=True)[source]

Maximum number of consecutive frost days (Tn < 0℃).

The maximum number of consecutive days within the period where the minimum daily temperature is under a given threshold (default: 0°C).

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The maximum number of consecutive frost days (tasmin < threshold per period).

Warning

The default freq is valid for the Northern Hemisphere.

Notes

Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a minimum daily temperature series and \(thresh\) the threshold below which a day is considered a frost day. Let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([t_i < thresh] \neq [t_{i+1} < thresh]\), that is, the days where the temperature crosses the threshold. Then the maximum number of consecutive frost days is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [t_{s_j} < thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices._threshold.maximum_consecutive_frost_free_days(tasmin, thresh='0 degC', freq='YS', resample_before_rl=True)[source]

Maximum number of consecutive frost-free days (Tn >= 0℃).

Return the maximum number of consecutive days within the period where the minimum daily temperature is above or equal to a given threshold (default: 0℃).

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The maximum number of consecutive frost free days (tasmin >= threshold per period).

Warning

The default freq is valid for the Northern Hemisphere.

Notes

Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a daily minimum temperature series and \(thresh\) the threshold above or equal to which a day is considered a frost free day. Let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([t_i <= thresh] \neq [t_{i+1} <= thresh]\), that is, the days where the temperature crosses the threshold. Then the maximum number of consecutive frost free days is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [t_{s_j} >= thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices._threshold.maximum_consecutive_tx_days(tasmax, thresh='25 degC', freq='YS', resample_before_rl=True)[source]

Maximum number of consecutive days with tasmax above a given threshold (summer days).

Return the maximum number of consecutive days within the period where the maximum daily temperature is above a certain threshold (default: 25℃).

Parameters:
  • tasmax (xarray.DataArray) – Max daily temperature.

  • thresh (Quantified) – Threshold temperature.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The maximum number of days with tasmax > thresh per periods (summer days).

Notes

Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a daily maximum temperature series and \(thresh\) the threshold above which a day is considered a summer day. Let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([t_i < thresh] \neq [t_{i+1} < thresh]\), that is, the days where the temperature crosses the threshold. Then the maximum number of consecutive tx_days (summer days) is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [t_{s_j} > thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices._threshold.maximum_consecutive_wet_days(pr, thresh='1 mm/day', freq='YS', resample_before_rl=True)[source]

Consecutive wet days.

Returns the maximum number of consecutive days with precipitation above a given threshold (default: 1 mm/day).

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • thresh (Quantified) – Threshold precipitation on which to base evaluation.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The maximum number of consecutive wet days.

Notes

Let \(\mathbf{x}=x_0, x_1, \ldots, x_n\) be a daily precipitation series and \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([p_i > thresh] \neq [p_{i+1} > thresh]\), that is, the days where the precipitation crosses the wet day threshold. Then the maximum number of consecutive wet days is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [x_{s_j} > 0^\circ C]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices._threshold.rprctot(pr, prc, thresh='1.0 mm/day', freq='YS', op='>=')[source]

Proportion of accumulated precipitation arising from convective processes.

Return the proportion of total accumulated precipitation due to convection on days with total precipitation greater or equal to a given threshold (default: 1.0 mm/day) during the given period.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • prc (xarray.DataArray) – Daily convective precipitation.

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – The proportion of the total precipitation accounted for by convective precipitation for each period.

xclim.indices._threshold.sea_ice_area(siconc, areacello, thresh='15 %')[source]

Total sea ice area.

Sea ice area measures the total sea ice covered area where sea ice concentration is above a given threshold, usually set to 15%.

Parameters:
  • siconc (xarray.DataArray) – Sea ice concentration (area fraction).

  • areacello (xarray.DataArray) – Grid cell area (usually over the ocean).

  • thresh (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.

Return type:

DataArray

Returns:

xarray.DataArray, [length]^2 – Sea ice area.

Notes

To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.

References

“What is the difference between sea ice area and extent?” - NSIDC [2008]

xclim.indices._threshold.sea_ice_extent(siconc, areacello, thresh='15 %')[source]

Total sea ice extent.

Sea ice extent measures the ice-covered area, where a region is considered ice-covered if its sea ice concentration is above a given threshold, usually set to 15%.

Parameters:
  • siconc (xarray.DataArray) – Sea ice concentration (area fraction).

  • areacello (xarray.DataArray) – Grid cell area.

  • thresh (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.

Return type:

DataArray

Returns:

xarray.DataArray, [length]^2 – Sea ice extent.

Notes

To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.

References

“What is the difference between sea ice area and extent?” - NSIDC [2008]

xclim.indices._threshold.snd_days_above(snd, thresh='2 cm', freq='YS-JUL', op='>=')[source]

The number of days with snow depth above a threshold.

Number of days where surface snow depth is greater or equal to a given threshold (default: 2 cm).

Parameters:
  • snd (xarray.DataArray) – Surface snow thickness.

  • thresh (Quantified) – Threshold snow thickness.

  • freq (str) – Resampling frequency. The default value is chosen for the Northern Hemisphere.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days where snow depth is greater than or equal to {thresh}.

xclim.indices._threshold.snd_season_end(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]

Snow cover end date (depth).

First day after the start of the continuous snow depth cover when snow depth is below a threshold for at least window consecutive days.

Parameters:
  • snd (xarray.DataArray) – Surface snow thickness.

  • thresh (Quantified) – Threshold snow thickness.

  • window (int) – Minimum number of days with snow depth below the threshold.

  • freq (str) – Resampling frequency. Default: “YS-JUL”. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day after the start of the continuous snow depth cover.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices._threshold.snd_season_length(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]

Snow cover duration (depth).

The season starts when snow depth is above a threshold for at least N consecutive days and stops when it drops below the same threshold for the same number of days.

Parameters:
  • snd (xarray.DataArray) – Surface snow thickness.

  • thresh (Quantified) – Threshold snow thickness.

  • window (int) – Minimum number of days with snow depth above and below threshold.

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – Length of the snow season.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices._threshold.snd_season_start(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]

Snow cover start date (depth).

Day of year when snow depth is above or equal to a threshold for at least N consecutive days.

Parameters:
  • snd (xarray.DataArray) – Surface snow thickness.

  • thresh (Quantified) – Threshold snow thickness.

  • window (int) – Minimum number of days with snow depth above or equal to the threshold.

  • freq (str) – Resampling frequency. The default value is chosen for the Northern Hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day of the year when the snow depth is superior to a threshold for a minimum duration.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices._threshold.snd_storm_days(snd, thresh='25 cm', freq='YS-JUL')[source]

Days with snowfall over threshold.

Number of days with snowfall depth accumulation greater or equal to threshold (default: 25 cm).

Parameters:
  • snd (xarray.DataArray) – Surface snow depth.

  • thresh (Quantified) – Threshold on snowfall depth accumulation require to label an event a snd storm.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Number of days per period identified as winter storms.

Warning

The default freq is valid for the northern hemisphere.

Notes

Snowfall accumulation is estimated by the change in snow depth.

xclim.indices._threshold.snowfall_frequency(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

Percentage of snow days.

Return the percentage of days where snowfall exceeds a threshold (default: 1 mm/day).

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [%] – Percentage of days where snowfall exceeds a given threshold.

Warning

The default freq is valid for the Northern Hemisphere.

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If the threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed, and the threshold is converted using a 1000 kg m-3 density.

References

Frei, Kotlarski, Liniger, and Schär [2018].

xclim.indices._threshold.snowfall_intensity(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

Mean daily snowfall rate during snow days.

Return the mean daily snowfall rate during days where snowfall exceeds a threshold (default: 1 mm/day).

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, – Mean daily liquid water equivalent snowfall rate during days where snowfall exceeds a threshold.

Warning

The default freq is valid for the Northern Hemisphere.

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.

References

Frei, Kotlarski, Liniger, and Schär [2018].

xclim.indices._threshold.snw_days_above(snw, thresh='4 kg m-2', freq='YS-JUL', op='>=')[source]

The number of days with snow amount above a given threshold.

Number of days where surface snow amount is greater or equal to a given threshold.

Parameters:
  • snw (xarray.DataArray) – Surface snow amount.

  • thresh (str) – Threshold snow amount.

  • freq (str) – Resampling frequency. The default value is chosen for the Northern hemisphere.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days where snow amount is greater than or equal to {thresh}.

xclim.indices._threshold.snw_season_end(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]

Snow cover end date (amount).

First day after the start of the continuous snow water cover when snow water is below a threshold for at least N consecutive days.

Parameters:
  • snw (xarray.DataArray) – Surface snow amount.

  • thresh (str) – Threshold snow amount.

  • window (int) – Minimum number of days with snow water below the threshold.

  • freq (str) – Resampling frequency. The default value is chosen for the Northern Hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day after the start of the continuous snow amount cover.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices._threshold.snw_season_length(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]

Snow cover duration (amount).

The season starts when the snow amount is above a threshold for at least N consecutive days and stops when it drops below the same threshold for the same number of days.

Parameters:
  • snw (xarray.DataArray) – Surface snow amount.

  • thresh (Quantified) – Threshold snow amount.

  • window (int) – Minimum number of days with snow amount above and below threshold.

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – Length of the snow season.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices._threshold.snw_season_start(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]

Snow cover start date (amount).

Day of year when snow water is above or equal to a threshold for at least N consecutive days.

Parameters:
  • snw (xarray.DataArray) – Surface snow amount.

  • thresh (str) – Threshold snow amount.

  • window (int) – Minimum number of days with snow amount above or equal to the threshold.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day of the year when the snow amount is superior to a threshold for a minimum duration.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices._threshold.snw_storm_days(snw, thresh='10 kg m-2', freq='YS-JUL')[source]

Days with snowfall over threshold.

Number of days with snowfall amount accumulation greater or equal to threshold (default: 10 kg m-2).

Parameters:
  • snw (xarray.DataArray) – Surface snow amount.

  • thresh (Quantified) – Threshold on snowfall amount accumulation require to label an event a snw storm.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Number of days per period identified as winter storms.

Warning

The default freq is valid for the northern hemisphere.

Notes

Snowfall accumulation is estimated by the change in snow amount.

xclim.indices._threshold.tg_days_above(tas, thresh='10.0 degC', freq='YS', op='>')[source]

The number of days with tas above a given threshold.

Number of days where mean daily temperature exceeds a threshold (default: 10℃).

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

Returns:

xarray.DataArray, [time] – Number of days where tas {op} threshold.

Notes

Let \(TG_{ij}\) be the mean daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TG_{ij} > Threshold [℃]\]
xclim.indices._threshold.tg_days_below(tas, thresh='10.0 degC', freq='YS', op='<')[source]

The number of days with tas below a given threshold.

Number of days where mean daily temperature is below a given threshold (default: 10℃).

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

Returns:

xarray.DataArray, [time] – Number of days where tas {op} threshold.

Notes

Let \(TG_{ij}\) be the mean daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TG_{ij} < Threshold [℃]\]
xclim.indices._threshold.tn_days_above(tasmin, thresh='20.0 degC', freq='YS', op='>')[source]

The number of days with tasmin above a threshold (number of tropical nights).

Number of days where minimum daily temperature exceeds a threshold (default: 20℃).

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

Returns:

xarray.DataArray, [time] – Number of days where tasmin {op} threshold.

Notes

Let \(TN_{ij}\) be the minimum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} > Threshold [℃]\]
xclim.indices._threshold.tn_days_below(tasmin, thresh='-10.0 degC', freq='YS', op='<')[source]

Number of days with tasmin below a given threshold.

Number of days where minimum daily temperature is below a given threshold (default: -10℃).

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days where tasmin {op} threshold.

Notes

Let \(TN_{ij}\) be the minimum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} < Threshold [℃]\]
xclim.indices._threshold.tx_days_above(tasmax, thresh='25.0 degC', freq='YS', op='>')[source]

The number of days with tasmax above a given threshold (number of summer days).

Number of days where maximum daily temperature exceeds a given threshold (default: 25℃).

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days where tasmax {op} threshold (number of summer days).

Notes

Let \(TX_{ij}\) be the maximum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TX_{ij} > Threshold [℃]\]
xclim.indices._threshold.tx_days_below(tasmax, thresh='25.0 degC', freq='YS', op='<')[source]

The number of days with tasmax below a given threshold.

Number of days where maximum daily temperature is below a given threshold (default: 25℃).

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.

Returns:

xarray.DataArray, [time] – Number of days where tasmin {op} threshold.

Notes

Let \(TX_{ij}\) be the maximum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TX_{ij} < Threshold [℃]\]
xclim.indices._threshold.warm_day_frequency(tasmax, thresh='30 degC', freq='YS', op='>')[source]

Frequency of extreme warm days.

Return the number of days with maximum daily temperature exceeding a given threshold (default: 30℃) per period.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with tasmax {op} threshold per period.

Notes

Let \(TX_{ij}\) be the maximum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} > Threshold [℃]\]
xclim.indices._threshold.warm_night_frequency(tasmin, thresh='22 degC', freq='YS', op='>')[source]

Frequency of extreme warm nights.

Return the number of days with minimum daily temperatures exceeding a given threshold (default: 22℃) per period.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with tasmin {op} threshold per period.

xclim.indices._threshold.wet_spell_frequency(pr, thresh='1.0 mm', window=3, freq='YS', resample_before_rl=True, op='sum', **indexer)[source]

Return the number of wet periods of n days and more.

Periods during which the accumulated, minimal, or maximal daily precipitation amount within a window of n days is over a given threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation amount over which a period is considered dry. The value against which the threshold is compared depends on op.

  • window (int) – Minimum length of the spells.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • op ({“sum”, “min”, “max”, “mean”}) – Operation to perform on the window. Default is “sum”, which checks that the sum of accumulated precipitation over the whole window is more than the threshold. “min” checks that the maximal daily precipitation amount within the window is more than the threshold. This is the same as verifying that each individual day is above the threshold.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the wet days, but before finding the spells.

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of wet periods of minimum {window} days.

See also

xclim.indices.generic.spell_length_statistics

The parent function that computes the spell length statistics.

Examples

>>> from xclim.indices import wet_spell_frequency
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> dsf_sum = wet_spell_frequency(pr=pr, op="sum")
>>> dsf_min = wet_spell_frequency(pr=pr, op="min")
xclim.indices._threshold.wet_spell_max_length(pr, thresh='1.0 mm', window=1, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Longest wet spell.

The maximum number of consecutive days in a wet period of minimum length, during which the minimum or accumulated precipitation within a window of the same length is over a threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Accumulated precipitation value over which a period is considered wet.

  • window (int) – Number of days when the maximum or accumulated precipitation is over threshold.

  • op ({“min”, “sum”, “max”, “mean”}) – Reduce operation. min means that all days within the minimum window must exceed the threshold. sum means that the accumulated precipitation within the window must exceed the threshold. In all cases, the whole window is marked a part of a wet spell.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the wet days, but before finding the spells.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in wet periods of minimum {window} days.

See also

xclim.indices.generic.spell_length_statistics

The parent function that computes the spell length statistics.

Notes

The algorithm assumes days before and after the timeseries are “dry”, meaning that the condition for being considered part of a wet spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a wet spell only if the accumulated precipitation within the first three days is over the threshold. In comparison, a day in the middle of the series is considered part of a wet spell if any of the three 3-day periods of which it is part are considered wet (so a total of five days are included in the computation, compared to only three).

xclim.indices._threshold.wet_spell_total_length(pr, thresh='1.0 mm', window=3, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Total length of wet spells.

Total number of days in wet periods of a minimum length, during which the minimum or accumulated precipitation within a window of the same length is over a threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Accumulated precipitation value over which a period is considered wet.

  • window (int) – Number of days when the maximum or accumulated precipitation is over the threshold.

  • op ({“min”, “sum”, “max”, “mean”}) – Reduce operation. min means that all days within the minimum window must exceed the threshold. sum means that the accumulated precipitation within the window must exceed the threshold. In all cases, the whole window is marked a part of a wet spell.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • **indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the wet days, but before finding the spells.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} total number of days in wet periods of minimum {window} days.

See also

xclim.indices.generic.spell_length_statistics

The parent function that computes the spell length statistics.

Notes

The algorithm assumes days before and after the timeseries are “dry”, meaning that the condition for being considered part of a wet spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a wet spell only if the accumulated precipitation within the first three days is over the threshold. In comparison, a day in the middle of the series is considered part of a wet spell if any of the three 3-day periods of which it is part are considered wet (so a total of five days are included in the computation, compared to only three).

xclim.indices._threshold.wetdays(pr, thresh='1.0 mm/day', freq='YS', op='>=')[source]

Wet days.

Return the total number of days during period with precipitations over a given threshold (default: 1.0 mm/day).

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The number of wet days for each period [day].

Examples

The following would compute for each grid cell of file pr.day.nc the number days with precipitation over 5 mm at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import wetdays
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> wd = wetdays(pr, thresh="5 mm/day", freq="QS-DEC")
xclim.indices._threshold.wetdays_prop(pr, thresh='1.0 mm/day', freq='YS', op='>=')[source]

Proportion of wet days.

Return the proportion of days during period with precipitations over a given threshold (default: 1.0 mm/day).

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The proportion of wet days for each period [1].

Examples

The following would compute for each grid cell of file pr.day.nc the proportion of days with precipitation over 5 mm at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import wetdays_prop
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> wd = wetdays_prop(pr, thresh="5 mm/day", freq="QS-DEC")
xclim.indices._threshold.windy_days(sfcWind, thresh='10.8 m s-1', freq='MS')[source]

Windy days.

The number of days with average near-surface wind speed above a given threshold (default: 10.8 m/s).

Parameters:
  • sfcWind (xarray.DataArray) – Daily average near-surface wind speed.

  • thresh (Quantified) – Threshold average near-surface wind speed on which to base evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with average near-surface wind speed above threshold.

Notes

Let \(WS_{ij}\) be the windspeed at day \(i\) of period \(j\). Then counted is the number of days where:

\[WS_{ij} >= Threshold [m s-1]\]

xclim.indices.generic module

Generic Indices Submodule

Helper functions for common generic actions done in the computation of indices.

xclim.indices.generic.aggregate_between_dates(data, start, end, op='sum', freq=None)[source]

Aggregate the data over a period between start and end dates and apply the operator on the aggregated data.

Parameters:
  • data (xr.DataArray) – Data to aggregate between start and end dates.

  • start (xr.DataArray or DayOfYearStr) – Start dates (as day-of-year) for the aggregation periods.

  • end (xr.DataArray or DayOfYearStr) – End (as day-of-year) dates for the aggregation periods.

  • op ({‘min’, ‘max’, ‘sum’, ‘mean’, ‘std’}) – Operator.

  • freq (str, optional) – Resampling frequency defining the periods as defined in Resampling. Default: None.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Aggregated data between the start and end dates. If the end date is before the start date, returns np.nan. If there is no start and/or end date, returns np.nan.

xclim.indices.generic.bivariate_count_occurrences(*, data_var1, data_var2, threshold_var1, threshold_var2, freq, op_var1, op_var2, var_reducer, constrain_var1=None, constrain_var2=None)[source]

Calculate the number of times some conditions are met for two variables.

First, the thresholds are transformed to the same standard_name and units as their corresponding input data; Then the thresholding is performed as condition(data, threshold) for each variable, i.e. if condition is <, then this counts the number of times data < threshold; Then the conditions are combined according to var_reducer; Finally, the number of occurrences where conditions are met for “all” or “any” events are counted.

Parameters:
  • data_var1 (xr.DataArray) – An array.

  • data_var2 (xr.DataArray) – An array.

  • threshold_var1 (Quantified) – Threshold for data variable 1.

  • threshold_var2 (Quantified) – Threshold for data variable 2.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op_var1 ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator for data variable 1. e.g. arr > thresh.

  • op_var2 ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator for data variable 2. e.g. arr > thresh.

  • var_reducer ({“all”, “any”}) – The condition must either be fulfilled on all or any variables for the period to be considered an occurrence.

  • constrain_var1 (sequence of str, optional) – Optionally allowed comparison operators for variable 1.

  • constrain_var2 (sequence of str, optional) – Optionally allowed comparison operators for variable 2.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray of counted occurrences.

Notes

Sampling and variable units are derived from data_var1.

xclim.indices.generic.bivariate_spell_length_statistics(data1, threshold1, data2, threshold2, window, win_reducer, op, spell_reducer, freq, min_gap=1, resample_before_rl=True, **indexer)[source]

Generate statistic on spells lengths based on two variables.

A spell is when a statistic (win_reducer) over a minimum number (window) of consecutive timesteps respects a condition (op thresh). This returns a statistic over the spells count or lengths. In this bivariate version, conditions on both variables must be fulfilled.

Parameters:
  • data1 (xr.DataArray) – First input data.

  • threshold1 (Quantified) – Threshold to test against data1.

  • data2 (xr.DataArray) – Second input data.

  • threshold2 (Quantified) – Threshold to test against data2.

  • window (int) – Minimum length of a spell.

  • win_reducer ({‘min’, ‘max’, ‘sum’, ‘mean’}) – Reduction along the spell length to compute the spell value. Note that this does not matter when window is 1.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. Ex: spell_value > thresh.

  • spell_reducer ({‘max’, ‘sum’, ‘count’} or sequence of str) – Statistic on the spell lengths. If a list, multiple statistics are computed.

  • freq (str) – Resampling frequency.

  • min_gap (int) – The shortest possible gap between two spells. Spells closer than this are merged by assigning the gap steps to the merged spell.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • **indexer ({dim: indexer, }, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the days part of a spell, but before taking the spell statistics.

Return type:

DataArray | Sequence[DataArray]

Returns:

xr.DataArray or sequence of xr.DataArray – The length of the longest of such spells.

See also

spell_length_statistics

The univariate version.

spell_mask

The lower level functions that finds spells.

xclim.indices.generic.compare(left, op, right, constrain=None)[source]

Compare a DataArray to a threshold using given operator.

Parameters:
  • left (xr.DataArray) – A DatArray being evaluated against right.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • right (float, int, np.ndarray, or xr.DataArray) – A value or array-like being evaluated against left`.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – Boolean mask of the comparison.

xclim.indices.generic.count_level_crossings(low_data, high_data, threshold, freq, *, op_low='<', op_high='>=')[source]

Calculate the number of times low_data is below threshold while high_data is above threshold.

First, the threshold is transformed to the same standard_name and units as the input data, then the thresholding is performed, and finally, the number of occurrences is counted.

Parameters:
  • low_data (xr.DataArray) – Variable that must be under the threshold.

  • high_data (xr.DataArray) – Variable that must be above the threshold.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op_low ({“<”, “<=”, “lt”, “le”}) – Comparison operator for low_data. Default: “<”.

  • op_high ({“>”, “>=”, “gt”, “ge”}) – Comparison operator for high_data. Default: “>=”.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray of level crossing events.

xclim.indices.generic.count_occurrences(data, threshold, freq, op, constrain=None)[source]

Calculate the number of times some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data; Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, then this counts the number of times data < threshold; Finally, count the number of occurrences when condition is met.

Parameters:
  • data (xr.DataArray) – An array.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray of counted occurrences.

xclim.indices.generic.cumulative_difference(data, threshold, op, freq=None)[source]

Calculate the cumulative difference below/above a given value threshold.

Parameters:
  • data (xr.DataArray) – Data for which to determine the cumulative difference.

  • threshold (Quantified) – The value threshold.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – Logical operator. e.g. arr > thresh.

  • freq (str, optional) – Resampling frequency defining the periods as defined in Resampling. If None, no resampling is performed. Default: None.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray for the cumulative difference between values and a given threshold.

xclim.indices.generic.default_freq(**indexer)[source]

Return the default frequency.

Parameters:

**indexer ({dim: indexer, }) – The indexer to use to compute the frequency.

Return type:

str

Returns:

str – The default frequency.

xclim.indices.generic.detrend(ds, dim='time', deg=1)[source]

Detrend data along a given dimension computing a polynomial trend of a given order.

Parameters:
  • ds (xr.Dataset or xr.DataArray) – The data to detrend. If a Dataset, detrending is done on all data variables.

  • dim (str) – Dimension along which to compute the trend.

  • deg (int) – Degree of the polynomial to fit.

Return type:

DataArray | Dataset

Returns:

xr.Dataset or xr.DataArray – Same as ds, but with its trend removed (subtracted).

xclim.indices.generic.diurnal_temperature_range(low_data, high_data, reducer, freq)[source]

Calculate the diurnal temperature range and reduce according to a statistic.

Parameters:
  • low_data (xr.DataArray) – The lowest daily temperature (tasmin).

  • high_data (xr.DataArray) – The highest daily temperature (tasmax).

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray of the diurnal temperature range.

xclim.indices.generic.domain_count(da, low, high, freq)[source]

Count number of days where value is within low and high thresholds.

A value is counted if it is larger than low, and smaller or equal to high, i.e. in ]low, high].

Parameters:
  • da (xr.DataArray) – Input data.

  • low (scalar or DataArray) – Minimum threshold value.

  • high (scalar or DataArray) – Maximum threshold value.

  • freq (str) – Resampling frequency defining the periods defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray – The number of days where value is within [low, high] for each period.

xclim.indices.generic.doymax(da)[source]

Return the day of year of the maximum value.

Parameters:

da (xr.DataArray) – The DataArray to process.

Return type:

DataArray

Returns:

xr.DataArray – The day of year of the maximum value.

xclim.indices.generic.doymin(da)[source]

Return the day of year of the minimum value.

Parameters:

da (xr.DataArray) – The DataArray to process.

Return type:

DataArray

Returns:

xr.DataArray – The day of year of the minimum value.

xclim.indices.generic.extreme_temperature_range(low_data, high_data, freq)[source]

Calculate the extreme daily temperature range.

The maximum of daily maximum temperature minus the minimum of daily minimum temperature.

Parameters:
  • low_data (xr.DataArray) – The lowest daily temperature (tasmin).

  • high_data (xr.DataArray) – The highest daily temperature (tasmax).

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray for the extreme temperature range.

xclim.indices.generic.first_day_threshold_reached(data, *, threshold, op, after_date, window=1, freq='YS', constrain=None)[source]

First day of values exceeding threshold.

Returns first day of period where values reach or exceed a threshold over a given number of days, limited to a starting calendar date.

Parameters:
  • data (xr.DataArray) – Dataset being evaluated.

  • threshold (str) – Threshold on which to base evaluation.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • after_date (str) – Date of the year after which to look for the first event. Should have the format ‘%m-%d’.

  • window (int) – Minimum number of days with values above threshold needed for evaluation. Default: 1.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling. Default: “YS”.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Day of the year when value reaches or exceeds a threshold over a given number of days for the first time. If there is no such day, returns np.nan.

xclim.indices.generic.first_occurrence(data, threshold, freq, op, constrain=None)[source]

Calculate the first time some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, locate the first occurrence when condition is met.

Parameters:
  • data (xr.DataArray) – Input data.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray of times of first occurrences.

xclim.indices.generic.get_daily_events(da, threshold, op, constrain=None)[source]

Return a 0/1 mask when a condition is True or False.

Parameters:
  • da (xr.DataArray) – Input data.

  • threshold (float) – Threshold value.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – The mask array of daily events.

Notes

The function returns:

  • 1 where operator(da, da_value) is True

  • 0 where operator(da, da_value) is False

  • nan where da is nan

xclim.indices.generic.get_op(op, constrain=None)[source]

Get python’s comparing function according to its name of representation and validate allowed usage.

Accepted op string are keys and values of xclim.indices.generic.binary_ops.

Parameters:
  • op (Sequence of {“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Operator.

  • constrain (sequence of {“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}, optional) – A tuple of allowed operators.

Return type:

Callable

Returns:

Callable – The operator function.

xclim.indices.generic.get_zones(da, zone_min=None, zone_max=None, zone_step=None, bins=None, exclude_boundary_zones=True, close_last_zone_right_boundary=True)[source]

Divide data into zones and attribute a zone coordinate to each input value.

Divide values into zones corresponding to bins of width zone_step beginning at zone_min and ending at zone_max. Bins are inclusive on the left values and exclusive on the right values.

Parameters:
  • da (xr.DataArray) – Input data.

  • zone_min (Quantity, optional) – Left boundary of the first zone.

  • zone_max (Quantity, optional) – Right boundary of the last zone.

  • zone_step (Quantity, optional) – Size of zones.

  • bins (xr.DataArray or list of Quantity, optional) – Zones to be used, either as a DataArray with appropriate units or a list of Quantity.

  • exclude_boundary_zones (bool) – Determines whether a zone value is attributed for values in ]`-np.inf`, zone_min`[ and [`zone_max, np.inf[.

  • close_last_zone_right_boundary (bool) – Determines if the right boundary of the last zone is closed.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Zone index for each value in da. Zones are returned as an integer range, starting from 0.

xclim.indices.generic.interday_diurnal_temperature_range(low_data, high_data, freq)[source]

Calculate the average absolute day-to-day difference in diurnal temperature range.

Parameters:
  • low_data (xr.DataArray) – The lowest daily temperature (tasmin).

  • high_data (xr.DataArray) – The highest daily temperature (tasmax).

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray for the average absolute day-to-day difference in diurnal temperature range.

xclim.indices.generic.last_occurrence(data, threshold, freq, op, constrain=None)[source]

Calculate the last time some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, locate the last occurrence when condition is met.

Parameters:
  • data (xr.DataArray) – Input data.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray of times of last occurrences.

xclim.indices.generic.season(data, thresh, window, op, stat, freq, mid_date=None, constrain=None)[source]

Season.

A season starts when a variable respects some condition for a consecutive run of N days. It stops when the condition is inverted for N days. Runs where the condition is not met for fewer than N days are thus allowed. Additionally, a middle date can serve as a maximal start date and minimum end date.

Parameters:
  • data (xr.DataArray) – Variable.

  • thresh (Quantified) – Threshold on which to base evaluation.

  • window (int) – Minimum number of days that the condition must be met / not met for the start / end of the season.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Comparison operation.

  • stat ({‘start’, ‘end’, ‘length’}) – Which season facet to return.

  • freq (str) – Resampling frequency.

  • mid_date (DayOfYearStr, optional) – An optional middle date. The start must happen before and the end after for the season to be valid.

  • constrain (Sequence of strings, optional) – A list of acceptable comparison operators. Optional, but indicators wrapping this function should inject it.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] or [time] – Depends on ‘stat’. If ‘start’ or ‘end’, this is the day of year of the season’s start or end. If ‘length’, this is the length of the season.

See also

xclim.indices.run_length.season_start

The function that finds the start of the season.

xclim.indices.run_length.season_length

The function that finds the length of the season.

xclim.indices.run_length.season_end

The function that finds the end of the season.

Examples

>>> season(tas, thresh="0 °C", window=5, op=">", stat="start", freq="YS")

Returns the start of the “frost-free” season. The season starts with 5 consecutive days with mean temperature above 0°C and ends with as many days under or equal to 0°C, and end does not need to be found for a start to be valid.

>>> season(
...     pr,
...     thresh="2 mm/d",
...     window=7,
...     op="<=",
...     mid_date="08-01",
...     stat="length",
...     freq="YS",
... )

Returns the length of the “dry” season. The season starts with 7 consecutive days with precipitation under or equal to 2 mm/d and ends with as many days above 2 mm/d. If no start is found before the first of august, the season is invalid. If a start is found but no end, the end is set to the last day of the period (December 31st if the dataset is complete).

xclim.indices.generic.season_length_from_boundaries(season_start, season_end)[source]

Season length using pre-computed boundaries.

Parameters:
  • season_start (xr.DataArray) – Day of year where the season starts.

  • season_end (xr.DataArray) – Day of year where the season ends.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Length of the season.

Notes

If season_start and season_end are computed with different resampling frequencies, the time of season_start are selected to write the output. This is only useful when season start and end were computed at an annual frequency but with different anchor months. Otherwise, functions in xclim.indices.run_length will be appropriate. season_start and season_end should be annual indicators with the same length. season_end should be in the same year as season_start or one year later.

xclim.indices.generic.select_resample_op(da, op, freq='YS', out_units=None, **indexer)[source]

Apply operation over each period that is part of the index selection.

Parameters:
  • da (xr.DataArray) – Input data.

  • op ({“min”, “max”, “mean”, “std”, “var”, ‘count’, ‘sum’, ‘integral’, ‘argmax’, ‘argmin’} or Callable) – Reduce operation. It can either be a DataArray method or a function that can be applied to a DataArray.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • out_units (str, optional) – Output units to assign. Only necessary if op is function not supported by xclim.core.units.to_agg_units().

  • **indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. For example, use season=’DJF’ to select winter values, month=1 to select January, or month=[6,7,8] to select summer months. If not indexer is given, all values are considered.

Return type:

DataArray

Returns:

xr.DataArray – The maximum value for each period.

xclim.indices.generic.select_rolling_resample_op(da, op, window, window_center=True, window_op='mean', freq='YS', out_units=None, **indexer)[source]

Apply operation over each period that is part of the index selection, using a rolling window before the operation.

Parameters:
  • da (xr.DataArray) – Input data.

  • op ({“min”, “max”, “mean”, “std”, “var”, “count”, “sum”, “integral”, “argmax”, “argmin”} or Callable) – Reduce operation. Can either be a DataArray method or a function that can be applied to a DataArray.

  • window (int) – Size of the rolling window (centered).

  • window_center (bool) – If True, the window is centered on the date. If False, the window is right-aligned.

  • window_op ({“min”, “max”, “mean”, “std”, “var”, “count”, “sum”, “integral”}) – Operation to apply to the rolling window. Default: ‘mean’.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling. Applied after the rolling window.

  • out_units (str, optional) – Output units to assign. Only necessary if op is a function not supported by xclim.core.units.to_agg_units().

  • **indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. For example, use season=’DJF’ to select winter values, month=1 to select January, or month=[6,7,8] to select summer months. If not indexer is given, all values are considered.

Return type:

DataArray

Returns:

xr.DataArray – The array for which the operation has been applied over each period.

xclim.indices.generic.spell_length(data, threshold, reducer, freq, op)[source]

Calculate statistics on lengths of spells.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Then the spells are determined, and finally the statistics according to the specified reducer are calculated.

Parameters:
  • data (xr.DataArray) – Input data.

  • threshold (Quantified) – Threshold.

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray of spell lengths.

xclim.indices.generic.spell_length_statistics(data, threshold, window, win_reducer, op, spell_reducer, freq, min_gap=1, resample_before_rl=True, **indexer)[source]

Generate statistic on spells lengths.

A spell is when a statistic (win_reducer) over a minimum number (window) of consecutive timesteps respects a condition (op thresh). This returns a statistic over the spells count or lengths.

Parameters:
  • data (xr.DataArray) – Input data.

  • threshold (Quantified) – Threshold to test against.

  • window (int) – Minimum length of a spell.

  • win_reducer ({‘min’, ‘max’, ‘sum’, ‘mean’}) – Reduction along the spell length to compute the spell value. Note that this does not matter when window is 1.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. Ex: spell_value > thresh.

  • spell_reducer ({‘max’, ‘sum’, ‘count’} or sequence of str) – Statistic on the spell lengths. If a list, multiple statistics are computed.

  • freq (str) – Resampling frequency.

  • min_gap (int) – The shortest possible gap between two spells. Spells closer than this are merged by assigning the gap steps to the merged spell.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • **indexer ({dim: indexer, }, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time(). Indexing is done after finding the days part of a spell, but before taking the spell statistics.

Return type:

DataArray | Sequence[DataArray]

Returns:

xr.DataArray or sequence of xr.DataArray – The length of the longest of such spells.

See also

spell_mask

The lower level functions that finds spells.

bivariate_spell_length_statistics

The bivariate version of this function.

Examples

>>> spell_length_statistics(
...     tas,
...     threshold="35 °C",
...     window=7,
...     op=">",
...     win_reducer="min",
...     spell_reducer="sum",
...     freq="YS",
... )

Here, a day is part of a spell if it is in any seven (7) day period where the minimum temperature is over 35°C. We then return the annual sum of the spell lengths, so the total number of days in such spells. >>> from xclim.core.units import rate2amount >>> pram = rate2amount(pr, out_units=”mm”) >>> spell_length_statistics( … pram, … threshold=”20 mm”, … window=5, … op=”>=”, … win_reducer=”sum”, … spell_reducer=”max”, … freq=”YS”, … )

Here, a day is part of a spell if it is in any five (5) day period where the total accumulated precipitation reaches or exceeds 20 mm. We then return the length of the longest of such spells.

xclim.indices.generic.spell_mask(data, window, win_reducer, op, thresh, min_gap=1, weights=None, var_reducer='all')[source]

Compute the boolean mask of data points that are part of a spell as defined by a rolling statistic.

A day is part of a spell (True in the mask) if it is contained in any period that fulfills the condition.

Parameters:
  • data (DataArray or sequence of DataArray) – The input data. Can be a list, in which case the condition is checked on all variables. See var_reducer for the latter case.

  • window (int) – The length of the rolling window in which to compute statistics.

  • win_reducer ({‘min’, ‘max’, ‘sum’, ‘mean’}) – The statistics to compute on the rolling window.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – The comparison operator to use when finding spells.

  • thresh (float or sequence of floats) – The threshold to compare the rolling statistics against, as {window_stats} {op} {threshold}. If data is a list, this must be a list of the same length with a threshold for each variable. This function does not handle units and can’t accept Quantified objects.

  • min_gap (int) – The shortest possible gap between two spells. Spells closer than this are merged by assigning the gap steps to the merged spell.

  • weights (sequence of floats) – A list of weights of the same length as the window. Only supported if win_reducer is “mean”.

  • var_reducer ({‘all’, ‘any’}) – If the data is a list, the condition must either be fulfilled on all or any variables for the period to be considered a spell.

Return type:

DataArray

Returns:

xr.DataArray – Same shape as data, but boolean. If data was a list, this is a DataArray of the same shape as the alignment of all variables.

xclim.indices.generic.statistics(data, reducer, freq)[source]

Calculate a simple statistic of the data.

Parameters:
  • data (xr.DataArray) – Input data.

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray for the given statistic.

xclim.indices.generic.temperature_sum(data, op, threshold, freq)[source]

Calculate the temperature sum above/below a threshold.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, the sum is calculated for those data values that fulfill the condition after subtraction of the threshold value. If the sum is for values below the threshold the result is multiplied by -1.

Parameters:
  • data (xr.DataArray) – Input data.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – Logical operator. e.g. arr > thresh.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray for the sum of temperatures above or below a threshold.

xclim.indices.generic.threshold_count(da, op, threshold, freq, constrain=None)[source]

Count number of days where value is above or below a given threshold.

Parameters:
  • da (xr.DataArray) – Input data.

  • op ({“>”, “<”, “>=”, “<=”, “gt”, “lt”, “ge”, “le”}) – Logical operator. e.g. arr > thresh.

  • threshold (Union[float, int]) – Threshold value.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – The number of days meeting the constraints for each period.

xclim.indices.generic.thresholded_statistics(data, op, threshold, reducer, freq, constrain=None)[source]

Calculate a simple statistic of the data for which some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, the statistic is calculated for those data values that fulfill the condition.

Parameters:
  • data (xr.DataArray) – Input data.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • threshold (Quantified) – Threshold.

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • constrain (sequence of str, optional) – Optionally allowed conditions. Default: None.

Return type:

DataArray

Returns:

xr.DataArray – The DataArray for the given thresholded statistic.

xclim.indices.helpers module

Indices Helper Functions Submodule

Functions that encapsulate logic and can be shared by many indices, but are not particularly index-like themselves (those should go in the xclim.indices.generic module).

xclim.indices.helpers._add_one_day(time)[source]

Add one day to a time coordinate.

Depending on the calendar/dtype of the time array we need to use numpy’s or datetime’s (for cftimes) timedelta.

Parameters:

time (xr.DataArray) – Time coordinate.

Return type:

DataArray

Returns:

xr.DataArray – Next day.

xclim.indices.helpers._compute_daytime_temperature(hour_after_sunrise, tasmin, tasmax, daylength)[source]

Compute daytime temperature based on a sinusoidal profile.

Minimum temperature is reached at sunrise and maximum temperature 2h before sunset.

Parameters:
  • hour_after_sunrise (xarray.DataArray) – Hours after the last sunrise.

  • tasmin (xarray.DataArray) – Daily minimum temperature.

  • tasmax (xarray.DataArray) – Daily maximum temperature.

  • daylength (xarray.DataArray) – Length of the day in hours.

Return type:

DataArray

Returns:

xarray.DataArray – Hourly daytime temperature.

xclim.indices.helpers._compute_nighttime_temperature(hours_after_sunset, tasmin, tas_sunset, daylength)[source]

Compute nighttime temperature based on a logarithmic profile.

Temperature at sunset is computed from previous daytime temperature, minimum temperature is reached at sunrise.

Parameters:
  • hours_after_sunset (xarray.DataArray) – Hours after the last sunset.

  • tasmin (xarray.DataArray) – Daily minimum temperature.

  • tas_sunset (xarray.DataArray) – Temperature at last sunset.

  • daylength (xarray.DataArray) – Length of the day in hours.

Return type:

DataArray

Returns:

xarray.DataArray – Hourly nighttime temperature.

xclim.indices.helpers._gather_lat(da)[source]

Gather latitude coordinate using cf-xarray.

Parameters:

da (xarray.DataArray) – CF-conformant DataArray with a “latitude” coordinate.

Return type:

DataArray

Returns:

xarray.DataArray – Latitude coordinate.

xclim.indices.helpers._gather_lon(da)[source]

Gather longitude coordinate using cf-xarray.

Parameters:

da (xarray.DataArray) – CF-conformant DataArray with a “longitude” coordinate.

Return type:

DataArray

Returns:

xarray.DataArray – Longitude coordinate.

xclim.indices.helpers._wrap_radians(da)[source]
xclim.indices.helpers.cosine_of_solar_zenith_angle(time, declination, lat, lon='0 °', time_correction=None, stat='average', sunlit=False, chunks=None)[source]

Cosine of the solar zenith angle.

The solar zenith angle is the angle between a vertical line (perpendicular to the ground) and the sun rays. This function computes a statistic of its cosine : its instantaneous value, the integral from sunrise to sunset or the average over the same period or over a subdaily interval. Based on Kalogirou [2014] and Di Napoli et al. [2020].

Parameters:
  • time (xr.DataArray) – The UTC time. If not daily and stat is “integral” or “average”, the timestamp is taken as the start of interval. If daily, the interval is assumed to be centered on Noon. If fewer than three timesteps are given, a daily frequency is assumed.

  • declination (xr.DataArray) – Solar declination. See solar_declination().

  • lat (Quantified) – Latitude.

  • lon (Quantified) – Longitude. Needed if the input timeseries is subdaily.

  • time_correction (xr.DataArray, optional) – Time correction for solar angle. See time_correction_for_solar_angle() This is necessary if stat is “instant”.

  • stat ({‘average’, ‘integral’, ‘instant’}) – Which daily statistic to return. If “average”, this returns the average of the cosine of the zenith angle If “integral”, this returns the integral of the cosine of the zenith angle If “instant”, this returns the instantaneous cosine of the zenith angle

  • sunlit (bool) – If True, only the sunlit part of the interval is considered in the integral or average. Does nothing if stat is “instant”.

  • chunks (dictionary) – When time, lat and lon originate from coordinates of a large chunked dataset, this dataset’s chunking can be passed here to ensure the computation is also chunked.

Return type:

DataArray

Returns:

xr.DataArray, [rad] or [dimensionless] – Cosine of the solar zenith angle. If stat is “integral”, dimensions can be said to be “time” as the integral is on the hour angle. For seconds, multiply by the number of seconds in a complete day cycle (24*60*60) and divide by 2π.

Notes

This code was inspired by the thermofeel and PyWBGT package.

References

Di Napoli, Hogan, and Pappenberger [2020], Kalogirou [2014]

xclim.indices.helpers.day_angle(time)[source]

Day of year as an angle.

Assuming the Earth makes a full circle in a year, this is the angle covered from the beginning of the year up to that timestep. Also called the “julian day fraction”.

Parameters:

time (xr.DataArray) – Time coordinate.

Return type:

DataArray

Returns:

xr.DataArray, [rad] – Day angle.

xclim.indices.helpers.day_lengths(dates, lat, method='spencer')[source]

Calculate day-length according to latitude and day of year.

See solar_declination() for the approximation used to compute the solar declination angle. Based on Kalogirou [2014].

Parameters:
  • dates (xr.DataArray) – Daily datetime data. This function makes no sense with data of other frequency.

  • lat (xarray.DataArray) – Latitude coordinate.

  • method ({‘spencer’, ‘simple’}) – Which approximation to use when computing the solar declination angle. See solar_declination().

Return type:

DataArray

Returns:

xarray.DataArray, [hours] – Day-lengths in hours per individual day.

References

Kalogirou [2014]

xclim.indices.helpers.distance_from_sun(dates)[source]

Sun-earth distance.

The distance from sun to earth in astronomical units.

Parameters:

dates (xr.DataArray) – Series of dates and time of days.

Return type:

DataArray

Returns:

xr.DataArray, [astronomical units] – Sun-earth distance.

References

# TODO: Find a way to reference this U.S. Naval Observatory:Astronomical Almanac. Washington, D.C.: U.S. Government Printing Office (1985).

xclim.indices.helpers.eccentricity_correction_factor(time, method='spencer')[source]

Eccentricity correction factor of the Earth’s orbit.

The squared ratio of the mean distance Earth-Sun to the distance at a specific moment. As approximated by Spencer [1971].

Parameters:
  • time (xr.DataArray) – Time coordinate.

  • method ({‘spencer’, ‘simple’}) – Which approximation to use. The default (“spencer”) uses the first five (5) terms of the fourier series of the eccentricity. The “simple” method approximates with only the first two (2).

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Eccentricity correction factor.

References

Perrin [1975], Spencer [1971]

xclim.indices.helpers.extraterrestrial_solar_radiation(times, lat, solar_constant='1361 W m-2', method='spencer', chunks=None)[source]

Extraterrestrial solar radiation.

This is the daily energy received on a surface parallel to the ground at the mean distance of the earth to the sun. It neglects the effect of the atmosphere. Computation is based on Kalogirou [2014] and the default solar constant is taken from Matthes et al. [2017].

Parameters:
  • times (xr.DataArray) – Daily datetime data. This function makes no sense with data of other frequency.

  • lat (xr.DataArray) – Latitude.

  • solar_constant (str) – The solar constant, the energy received on earth from the sun per surface per time.

  • method ({‘spencer’, ‘simple’}) – Which method to use when computing the solar declination and the eccentricity correction factor. See solar_declination() and eccentricity_correction_factor().

  • chunks (dict) – When times and lat originate from coordinates of a large chunked dataset, passing the dataset’s chunks here will ensure the computation is chunked as well.

Return type:

DataArray

Returns:

xr.DataArray, [J m-2 d-1] – Extraterrestrial solar radiation.

References

Kalogirou [2014], Matthes, Funke, Andersson, Barnard, Beer, Charbonneau, Clilverd, Dudok de Wit, Haberreiter, Hendry, Jackman, Kretzschmar, Kruschke, Kunze, Langematz, Marsh, Maycock, Misios, Rodger, Scaife, Seppälä, Shangguan, Sinnhuber, Tourpali, Usoskin, van de Kamp, Verronen, and Versick [2017]

xclim.indices.helpers.make_hourly_temperature(tasmin, tasmax)[source]

Compute hourly temperatures from tasmin and tasmax.

Based on the Linvill et al. “Calculating Chilling Hours and Chill Units from Daily Maximum and Minimum Temperature Observations”, HortScience, 1990 we assume a sinusoidal temperature profile during daylight and a logarithmic decrease after sunset with tasmin reached at sunsrise and tasmax reached 2h before sunset.

For simplicity and because it’s used for daily aggregation, we assume that sunrise globally happens at midnight and the sunsets after daylength hours computed via the day_lengths() function.

Parameters:
  • tasmin (xarray.DataArray) – Daily minimum temperature.

  • tasmax (xarray.DataArray) – Daily maximum temperature.

Return type:

DataArray

Returns:

xarray.DataArray – Hourly temperature.

xclim.indices.helpers.resample_map(obj, dim, freq, func, map_blocks='from_context', resample_kwargs=None, map_kwargs=None)[source]

Wrap xarray’s resample(…).map() with a xarray.map_blocks().

Ensures that the chunking is appropriate using flox.

Parameters:
  • obj (DataArray or Dataset) – The xarray object to resample.

  • dim (str) – Dimension over which to resample.

  • freq (str) – Resampling frequency along dim.

  • func (callable) – Function to map on each resampled group.

  • map_blocks (bool or “from_context”) – If True, the resample().map() call is wrapped inside a map_blocks. If False, this does not do anything special. If “from_context”, xclim’s “resample_map_blocks” option is used. If the object is not using dask, this is set to False.

  • resample_kwargs (dict, optional) – Other arguments to pass to obj.resample().

  • map_kwargs (dict, optional) – Arguments to pass to map.

Return type:

DataArray | Dataset

Returns:

xr.DataArray or xr.Dataset – Resampled object.

xclim.indices.helpers.solar_declination(time, method='spencer')[source]

Solar declination.

The angle between the sun rays and the earth’s equator, in radians, as approximated by Spencer [1971] or assuming the orbit is a circle.

Parameters:
  • time (xr.DataArray) – Time coordinate.

  • method ({‘spencer’, ‘simple’}) – Which approximation to use. The default (“spencer”) uses the first seven (7) terms of the Fourier series representing the observed declination, while “simple” assumes the orbit is a circle with a fixed obliquity and that the solstice/equinox happen at fixed angles on the orbit (the exact calendar date changes for leap years).

Return type:

DataArray

Returns:

xr.DataArray, [rad] – Solar declination angle.

References

Spencer [1971]

xclim.indices.helpers.time_correction_for_solar_angle(time)[source]

Time correction for solar angle.

Every 1° of angular rotation on earth is equal to 4 minutes of time. The time correction is needed to adjust local watch time to solar time.

Parameters:

time (xr.DataArray) – Time coordinate.

Return type:

DataArray

Returns:

xr.DataArray, [rad] – Time correction of solar angle.

References

Di Napoli, Hogan, and Pappenberger [2020]

xclim.indices.helpers.wind_speed_height_conversion(ua, h_source, h_target, method='log')[source]

Wind speed at two meters.

Parameters:
  • ua (xarray.DataArray) – Wind speed at height h.

  • h_source (str) – Height of the input wind speed ua (e.g. h == “10 m” for a wind speed at 10 meters).

  • h_target (str) – Height of the output wind speed.

  • method ({“log”}) – Method used to convert wind speed from one height to another.

Return type:

DataArray

Returns:

xarray.DataArray – Wind speed at height h_target.

References

Allen, Pereira, Raes, and Smith [1998]

xclim.indices.run_length module

Run-Length Algorithms Submodule

Computation of statistics on runs of True values in boolean arrays.

xclim.indices.run_length._boundary_run(da, window, dim, freq, coord, ufunc_1dim, position)[source]

Return the index of the first item of the first or last run of at least a given length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run.

  • freq (str) – Resampling frequency.

  • coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

  • position ({“first”, “last”}) – Determines if the algorithm finds the “first” or “last” run

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of first item in first (last) valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length._cumsum_reset(da, dim='time', index='last')[source]

Compute the cumulative sum for each series of numbers separated by zero.

Parameters:
  • da (xr.DataArray) – Input array.

  • dim (str) – Dimension name along which the cumulative sum is taken.

  • index ({‘first’, ‘last’}) – If ‘first’, the largest value of the cumulative sum is indexed with the first element in the run. If ‘last’(default), with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray – An array with cumulative sums.

Notes

This function converts nan to 0, and uses integers. The fast track will only work correctly with binary entries. To avoid these limitations, use directly _cumsum_reset_xr.

xclim.indices.run_length._cumsum_reset_np(arr, index, one)[source]

100110111 -> 100120123

xclim.indices.run_length._cumsum_reset_xr(da, dim, index, reset_on_zero)[source]

100110111 -> 100120123

xclim.indices.run_length._find_events(da_start, da_stop, data, window_start, window_stop)[source]

Actual finding of events for each period.

Get basic blocks to work with, our runs with holes and the lengths of those runs. Series of ones indicating where we have continuous runs with pauses not exceeding window_stop

xclim.indices.run_length._is_chunked(da, dim)[source]

Check if da has non-trivial chunks

xclim.indices.run_length._rle_1d(ia)[source]
xclim.indices.run_length._smallest_uint(da, dim)[source]
xclim.indices.run_length.find_events(condition, window, condition_stop=None, window_stop=1, data=None, freq=None)[source]

Find events (runs).

An event starts with a run of window consecutive True values in the condition and stops with window_stop consecutive True values in the stop condition.

This returns a Dataset with each event along an event dimension. It does not perform statistics over the events like other function in this module do.

Parameters:
  • condition (DataArray of bool) – The boolean mask, true where the start condition of the event is fulfilled.

  • window (int) – The number of consecutive True values for an event to start.

  • condition_stop (DataArray of bool, optional) – The stopping boolean mask, true where the end condition of the event is fulfilled. Defaults to the opposite of condition.

  • window_stop (int) – The number of consecutive True values in condition_stop for an event to end. Defaults to 1.

  • data (DataArray, optional) – The actual data. If present, its sum within each event is added to the output.

  • freq (str, optional) – A frequency to divide the data into periods. If absent, the output has not time dimension. If given, the events are searched within in each resample period independently.

Returns:

xr.Dataset, same shape as the data (and the time dimension is resample or removed, according to freq). –

The Dataset has the following variables:

event_length: The number of time steps in each event event_effective_length: The number of time steps of even event where the start condition is true. event_start: The datetime of the start of the run. event_sum: The sum within each event, only considering steps where start condition is true (if data).

xclim.indices.run_length.first_run(da, window, dim='time', freq=None, coord=False, ufunc_1dim='from_context')[source]

Return the index of the first item of the first run of at least a given length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of first item in first valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.first_run_1d(arr, window)[source]

Return the index of the first item of a run of at least a given length.

Parameters:
  • arr (sequence of int or float) – Input array.

  • window (int) – Minimum duration of consecutive run to accumulate values.

Return type:

int | np.nan

Returns:

int or np.nan – Index of first item in first valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.first_run_after_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]

Return the index of the first item of the first run after a given date.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • date (DayOfYearStr) – The date after which to look for the run.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of first item in the first valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.first_run_before_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]

Return the index of the first item of the first run before a given date.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • date (DayOfYearStr) – The date before which to look for the run.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (bool or str, optional) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (e.g. ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of first item in the first valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.first_run_ufunc(x, window, dim)[source]

Dask-parallel version of first_run_1d.

The first entry in array of consecutive true values.

Parameters:
  • x (Union[xr.DataArray, Sequence[bool]]) – Input array (bool).

  • window (int) – Minimum run length.

  • dim (str) – The dimension along which the runs are found.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.index_of_date(time, date, max_idxs=None, default=0)[source]

Get the index of a date in a time array.

Parameters:
  • time (xr.DataArray) – An array of datetime values, any calendar.

  • date (DayOfYearStr or DateStr, optional) – A string in the “yyyy-mm-dd” or “mm-dd” format. If None, returns default.

  • max_idxs (int, optional) – Maximum number of returned indexes.

  • default (int) – Index to return if date is None.

Return type:

ndarray

Returns:

numpy.ndarray – 1D array of integers, indexes of date in time.

Raises:

ValueError – If there are most instances of date in time than max_idxs.

xclim.indices.run_length.keep_longest_run(da, dim='time', freq=None)[source]

Keep the longest run along a dimension.

Parameters:
  • da (xr.DataArray) – Boolean array.

  • dim (str) – Dimension along which to check for the longest run.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xr.DataArray, [bool] – Boolean array similar to da but with only one run, the (first) longest.

xclim.indices.run_length.last_run(da, window, dim='time', freq=None, coord=False, ufunc_1dim='from_context')[source]

Return the index of the last item of the last run of at least a given length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for a DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.last_run_before_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]

Return the index of the last item of the last run before a given date.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • date (DayOfYearStr) – The date before which to look for the last event.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.lazy_indexing(da, index, dim=None)[source]

Get values of da at indices index in a NaN-aware and lazy manner.

Parameters:
  • da (xr.DataArray) – Input array. If not 1D, dim must be given and must not appear in index.

  • index (xr.DataArray) – N-d integer indices, if DataArray is not 1D, all dimensions of index must be in DataArray.

  • dim (str, optional) – Dimension along which to index, unused if da is 1D, should not be present in index.

Return type:

DataArray

Returns:

xr.DataArray – Values of da at indices index.

xclim.indices.run_length.longest_run(da, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the length of the longest consecutive run of True values.

Parameters:
  • da (xr.DataArray) – N-dimensional array (boolean).

  • dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Length of the longest run of True values along dimension (int).

xclim.indices.run_length.npts_opt = 9000

Arrays with less than this number of data points per slice will trigger the use of the ufunc version of run lengths algorithms.

xclim.indices.run_length.resample_and_rl(da, resample_before_rl, compute, *args, freq, dim='time', **kwargs)[source]

Wrap run length algorithms to control if resampling occurs before or after the algorithms.

Parameters:
  • da (xr.DataArray) – N-dimensional array (boolean).

  • resample_before_rl (bool) – Determines whether if input arrays of runs da should be separated in period before or after the run length algorithms are applied.

  • compute (Callable) – Run length function to apply.

  • *args (Any) – Positional arguments needed in compute.

  • freq (str) – Resampling frequency.

  • dim (str) – The dimension along which to find runs.

  • **kwargs (Any) – Keyword arguments needed in compute.

Return type:

DataArray

Returns:

xr.DataArray – Output of compute resampled according to frequency {freq}.

xclim.indices.run_length.rle(da, dim='time', index='first')[source]

Run length.

Despite its name, this is not an actual run-length encoder : it returns an array of the same shape as the input with 0 where the input was <= 0, nan where the input was > 0, except on the first (or last) element of each run of consecutive > 0 values, where it is set to the sum of the elements within the run. For an actual run length encoder, see rle_1d().

Usually, the input would be a boolean mask and the first element of each run would then be set to the run’s length (thus the name), but the function also accepts int and float inputs.

Parameters:
  • da (xr.DataArray) – Input array.

  • dim (str) – Dimension name.

  • index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray – The run length array.

xclim.indices.run_length.rle_1d(arr)[source]

Return the length, starting position and value of consecutive identical values.

In opposition to py:func:rle, this is an actuel run length encoder.

Parameters:

arr (Sequence[Union[int, float, bool]]) – Array of values to be parsed.

Return type:

tuple[array, array, array]

Returns:

  • values (np.array) – The values taken by arr over each run.

  • run lengths (np.array) – The length of each run.

  • start position (np.array) – The starting index of each run.

Examples

>>> from xclim.indices.run_length import rle_1d
>>> a = [1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3]
>>> rle_1d(a)
(array([1, 2, 3]), array([2, 4, 6]), array([0, 2, 6]))
xclim.indices.run_length.rle_statistics(da, reducer, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the length of consecutive run of True values, according to a reducing operator.

Parameters:
  • da (xr.DataArray) – N-dimensional array (boolean).

  • reducer (str) – Name of the reducing function.

  • window (int) – Minimal length of consecutive runs to be included in the statistics.

  • dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Length of runs of True values along dimension, according to the reducing function (float) If there are no runs (but the data is valid), returns 0.

xclim.indices.run_length.run_bounds(mask, dim='time', coord=True)[source]

Return the start and end dates of boolean runs along a dimension.

Parameters:
  • mask (xr.DataArray) – Boolean array.

  • dim (str) – Dimension along which to look for runs.

  • coord (bool or str) – If True, return values of the coordinate, if a string, returns values from dim.dt.<coord>. If False, return indexes.

Returns:

xr.DataArray – With dim reduced to “events” and “bounds”. The events dim is as long as needed, padded with NaN or NaT.

xclim.indices.run_length.run_end_after_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]

Return the index of the first item after the end of a run after a given date.

The run must begin before the date.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • date (str) – The date after which to look for the end of a run.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.runs_with_holes(da_start, window_start, da_stop, window_stop, dim='time')[source]

Extract events, i.e. runs whose starting and stopping points are defined through run length conditions.

Parameters:
  • da_start (xr.DataArray) – Input array where run sequences are searched to define the start points in the main runs.

  • window_start (int) – Number of True (1) values needed to start a run in da_start.

  • da_stop (xr.DataArray) – Input array where run sequences are searched to define the stop points in the main runs.

  • window_stop (int) – Number of True (1) values needed to start a run in da_stop.

  • dim (str) – Dimension name.

Return type:

DataArray

Returns:

xr.DataArray – Output array with 1’s when in a run sequence and with 0’s elsewhere.

Notes

A season (as defined in season) could be considered as an event with window_stop == window_start and da_stop == 1 - da_start, although it has more constraints on when to start and stop a run through the date argument and only one season can be found.

xclim.indices.run_length.season(da, window, mid_date=None, dim='time', stat=None, coord=False)[source]

Calculate the bounds of a season along a dimension.

A “season” is a run of True values that may include breaks under a given length (window). The start is computed as the first run of window True values, and the end as the first subsequent run of window False values. The end element is the first element after the season. If a date is given, it must be included in the season (i.e. the start cannot occur later and the end cannot occur earlier).

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive values to start and end the season.

  • mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • stat (str, optional) – Not currently implemented. If not None, return a statistic of the season. The statistic is calculated on the season’s values.

  • coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

Dataset | DataArray

Returns:

xr.Dataset

The Dataset variables:

start : start of the season (index or units depending on coord) end : end of the season (index or units depending on coord) length : length of the season (in number of elements along dim)

See also

season_start

Start of a season.

season_end

End of a season.

season_length

Length of a season.

Notes

The run can include holes of False or NaN values, so long as they do not exceed the window size.

If a date is given, the season start and end are forced to be on each side of this date. This means that even if the “real” season has been over for a long time, this is the date used in the length calculation. e.g. Length of the “warm season”, where T > 25°C, with date = 1st August. Let’s say the temperature is over 25 for all June, but July and august have very cold temperatures. Instead of returning 30 days (June), the function will return 61 days (July + June).

The season’s length is always the difference between the end and the start. Except if no season end was found before the end of the data. In that case the end is set to last element and the length is set to the data size minus the start index. Thus, for the specific case, \(length = end - start + 1\), because the end falls on the last element of the season instead of the subsequent one.

xclim.indices.run_length.season_end(da, window, mid_date=None, dim='time', coord=False, _beg=None)[source]

End of a season.

See season(). Similar to first_run_after_date() but here a season must have a start for an end to be valid. Also, if no end is found but a start was found the end is set to the last element of the series.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive values to start and end the season.

  • mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (str, optional) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

  • _beg (xr.DataArray, optional) – If given, the start of the season. This is used to avoid recomputing the start.

Return type:

DataArray

Returns:

xr.DataArray – End of the season, units depend on coord. If there is a start is found but no end, the end is set to the last element.

See also

season

Calculate the bounds of a season along a dimension.

season_start

Start of a season.

season_length

Length of a season.

xclim.indices.run_length.season_length(da, window, mid_date=None, dim='time')[source]

Length of a season.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive values to start and end the season.

  • mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

Return type:

DataArray

Returns:

xr.DataArray, [int] – Length of the season, in number of elements along dimension time.

See also

season

Calculate the bounds of a season along a dimension.

season_start

Start of a season.

season_end

End of a season.

xclim.indices.run_length.season_start(da, window, mid_date=None, dim='time', coord=False)[source]

Start of a season.

See season().

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive values to start and end the season.

  • mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a season must include to be considered valid.

  • dim (str) – Dimension along which to calculate the season (default: ‘time’).

  • coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Start of the season, units depend on coord.

See also

season

Calculate the bounds of a season along a dimension.

season_end

End of a season.

season_length

Length of a season.

xclim.indices.run_length.statistics_run_1d(arr, reducer, window)[source]

Return statistics on lengths of run of identical values.

Parameters:
  • arr (sequence of bool) – Input array (bool).

  • reducer ({“mean”, “sum”, “min”, “max”, “std”, “count”}) – Reducing function name.

  • window (int) – Minimal length of runs to be included in the statistics.

Return type:

int

Returns:

int – Statistics on length of runs.

xclim.indices.run_length.statistics_run_ufunc(x, reducer, window, dim='time')[source]

Dask-parallel version of statistics_run_1d.

The {reducer} number of consecutive true values in array.

Parameters:
  • x (sequence of bool) – Input array (bool).

  • reducer ({‘min’, ‘max’, ‘mean’, ‘sum’, ‘std’}) – Reducing function name.

  • window (int) – Minimal length of runs.

  • dim (str) – The dimension along which the runs are found.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.suspicious_run(arr, dim='time', window=10, op='>', thresh=None)[source]

Return True where the array contains has runs of identical values, vectorized version.

In opposition to other run length functions, here the output has the same shape as the input.

Parameters:
  • arr (xr.DataArray) – Array of values to be parsed.

  • dim (str) – Dimension along which to check for runs (default: “time”).

  • window (int) – Minimum run length.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Operator for threshold comparison, defaults to “>”.

  • thresh (float, optional) – Threshold above which values are checked for identical values.

Return type:

DataArray

Returns:

xarray.DataArray – A boolean array of the same shape as the input, indicating where runs of identical values are found.

xclim.indices.run_length.suspicious_run_1d(arr, window=10, op='>', thresh=None)[source]

Return True where the array contains a run of identical values.

Parameters:
  • arr (numpy.ndarray) – Array of values to be parsed.

  • window (int) – Minimum run length.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Operator for threshold comparison. Defaults to “>”.

  • thresh (float, optional) – Threshold compared against which values are checked for identical values.

Return type:

ndarray

Returns:

numpy.ndarray – Whether the data points are part of a run of identical values or not.

xclim.indices.run_length.use_ufunc(ufunc_1dim, da, dim='time', freq=None, index='first')[source]

Return whether the ufunc version of run length algorithms should be used with this DataArray or not.

If ufunc_1dim is ‘from_context’, the parameter is read from xclim’s global (or context) options. If it is ‘auto’, this returns False for dask-backed array and for arrays with more than npts_opt points per slice along dim.

Parameters:
  • ufunc_1dim ({‘from_context’, ‘auto’, True, False}) – The method for handling the ufunc parameters.

  • da (xr.DataArray) – Input array.

  • dim (str) – The dimension along which to find runs.

  • freq (str) – Resampling frequency.

  • index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

bool

Returns:

bool – If ufunc_1dim is “auto”, returns True if the array is on dask or too large. Otherwise, returns ufunc_1dim.

xclim.indices.run_length.windowed_max_run_sum(da, window, dim='time', freq=None, index='first')[source]

Return the maximum sum of consecutive float values for runs at least as long as the given window length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray.

  • window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [float] – Cumulative sum of input values part of a consecutive runs of at least window long.

Notes

The input da is expected to be non-negative, e.g. temperature exceedances (tasmax - thresh).clip(0,None)

xclim.indices.run_length.windowed_run_count(da, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the number of consecutive true values in array for runs at least as long as given duration.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Total number of True values part of a consecutive runs of at least window long.

xclim.indices.run_length.windowed_run_count_1d(arr, window)[source]

Return the number of consecutive true values in array for runs at least as long as given duration.

Parameters:
  • arr (Sequence[bool]) – Input array (bool).

  • window (int) – Minimum duration of consecutive run to accumulate values.

Return type:

int

Returns:

int – Total number of true values part of a consecutive run at least window long.

xclim.indices.run_length.windowed_run_count_ufunc(x, window, dim)[source]

Dask-parallel version of windowed_run_count_1d.

The number of consecutive true values in array for runs at least as long as given duration.

Parameters:
  • x (Sequence[bool]) – Input array (bool).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • dim (str) – Dimension along which to calculate windowed run.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.windowed_run_events(da, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the number of runs of a minimum length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Number of distinct runs of a minimum length (int).

xclim.indices.run_length.windowed_run_events_1d(arr, window)[source]

Return the number of runs of a minimum length.

Parameters:
  • arr (Sequence[bool]) – Input array (bool).

  • window (int) – Minimum run length.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Number of distinct runs of a minimum length.

xclim.indices.run_length.windowed_run_events_ufunc(x, window, dim)[source]

Dask-parallel version of windowed_run_events_1d.

The number of runs at least as long as given duration.

Parameters:
  • x (Sequence[bool]) – Input array (bool).

  • window (int) – Minimum run length.

  • dim (str) – Dimension along which to calculate windowed run.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.stats module

Statistical indices module

Functions to aid in computing various statistical indices.

See the frequency_analysis notebook for working examples.

xclim.indices.stats._fit_start(x, dist, **fitkwargs)[source]

Return initial values for distribution parameters.

Providing the ML fit method initial values can help the optimizer find the global optimum.

Parameters:
  • x (array-like) – Input data.

  • dist (str) – Name of the univariate distribution, e.g. beta, expon, genextreme, gamma, gumbel_r, lognorm, norm. (see :py:mod:scipy.stats). Only genextreme and weibull_exp distributions are supported.

  • **fitkwargs (dict) – Kwargs passed to fit.

Return type:

tuple[tuple, dict]

Returns:

tuple, dict

References

Cohen and Whitten [2019], Coles [2001], Cooke [1979], Muralidhar and Zanakis [1992], Thom [1958].

xclim.indices.stats.dist_method(function, fit_params, arg=None, dist=None, **kwargs)[source]

Vectorized statistical function for given argument on given distribution initialized with params.

Methods where “*args” are the distribution parameters can be wrapped, except those that reduce dimensions (e.g. nnlf) or create new dimensions (e.g. ‘rvs’ with size != 1, ‘stats’ with more than one moment, ‘interval’, ‘support’).

Parameters:
  • function (str) – The name of the function to call.

  • fit_params (xr.DataArray) – Distribution parameters are along dparams, in the same order as given by fit().

  • arg (array_like, optional) – The first argument for the requested function if different from fit_params.

  • dist (str or rv_continuous distribution object, optional) – The distribution name or instance. Defaults to the scipy_dist attribute or fit_params.

  • **kwargs (dict) – Other parameters to pass to the function call.

Return type:

DataArray

Returns:

array_like – Same shape as arg.

See also

scipy.stats.rv_continuous

For all available functions and their arguments.

xclim.indices.stats.fa(da, t, dist='norm', mode='max', method='ML')[source]

Return the value corresponding to the given return period.

Parameters:
  • da (xr.DataArray) – Maximized/minimized input data with a time dimension.

  • t (int or Sequence of int) – Return period. The period depends on the resolution of the input data. If the input array’s resolution is yearly, then the return period is in years.

  • dist (str or rv_continuous distribution object) – Name of the univariate distribution, such as: beta, expon, genextreme, gamma, gumbel_r, lognorm, norm Or the distribution instance itself.

  • mode ({‘min’, ‘max}) – Whether we are looking for a probability of exceedance (max) or a probability of non-exceedance (min).

  • method ({“ML”, “MLE”, “MOM”, “PWM”, “APP”}) – Fitting method, either maximum likelihood (ML or MLE), method of moments (MOM) or approximate method (APP). If dist is an instance from the lmoments3 library, accepts probability weighted moments (PWM; “L-Moments”). The PWM method is usually more robust to outliers.

Return type:

DataArray

Returns:

xarray.DataArray – An array of values with a 1/t probability of exceedance (if mode==’max’).

See also

scipy.stats

For descriptions of univariate distribution types.

xclim.indices.stats.fit(da, dist='norm', method='ML', dim='time', **fitkwargs)[source]

Fit an array to a univariate distribution along the time dimension.

Parameters:
  • da (xr.DataArray) – Time series to be fitted along the time dimension.

  • dist (str or rv_continuous distribution object) – Name of the univariate distribution, such as beta, expon, genextreme, gamma, gumbel_r, lognorm, norm (see :py:mod:scipy.stats for full list) or the distribution object itself.

  • method ({“ML”, “MLE”, “MM”, “PWM”, “APP”, “MSE”, “MPS”}) – Fitting method, either maximum likelihood (ML or MLE), method of moments (MM), maximum product of spacings (MSE or MPS) or approximate method (APP). If dist is an instance from the lmoments3 library, accepts probability weighted moments (PWM; “L-Moments”). The PWM method is usually more robust to outliers. The MSE method is more consistent than the MLE method, although it can be more sensitive to repeated data. For the MSE method, each variable parameter must be given finite bounds (provided with keyword argument bounds={‘param_name’:(min,max),…}).

  • dim (str) – The dimension upon which to perform the indexing (default: “time”).

  • **fitkwargs (dict) – Other arguments passed directly to _fitstart() and to the distribution’s fit.

Return type:

DataArray

Returns:

xr.DataArray – An array of fitted distribution parameters.

Notes

Coordinates for which all values are NaNs will be dropped before fitting the distribution. If the array still contains NaNs, the distribution parameters will be returned as NaNs.

xclim.indices.stats.frequency_analysis(da, mode, t, dist, window=1, freq=None, method='ML', **indexer)[source]

Return the value corresponding to a return period.

Parameters:
  • da (xarray.DataArray) – Input data.

  • mode ({‘min’, ‘max’}) – Whether we are looking for a probability of exceedance (high) or a probability of non-exceedance (low).

  • t (int or sequence) – Return period. The period depends on the resolution of the input data. If the input array’s resolution is yearly, then the return period is in years.

  • dist (str or rv_continuous distribution object) – Name of the univariate distribution, e.g. beta, expon, genextreme, gamma, gumbel_r, lognorm, norm. Or an instance of the distribution.

  • window (int) – Averaging window length (days).

  • freq (str, optional) – Resampling frequency. If None, the frequency is assumed to be ‘YS’ unless the indexer is season=’DJF’, in which case freq would be set to YS-DEC.

  • method ({“ML”, “MLE”, “MOM”, “PWM”, “APP”}) – Fitting method, either maximum likelihood (ML or MLE), method of moments (MOM) or approximate method (APP). If dist is an instance from the lmoments3 library, accepts probability weighted moments (PWM; “L-Moments”). The PWM method is usually more robust to outliers.

  • **indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. For example, use season=’DJF’ to select winter values, month=1 to select January, or month=[6,7,8] to select summer months. If indexer is not provided, all values are considered.

Return type:

DataArray

Returns:

xarray.DataArray – An array of values with a 1/t probability of exceedance or non-exceedance when mode is high or low respectively.

See also

scipy.stats

For descriptions of univariate distribution types.

xclim.indices.stats.get_dist(dist)[source]

Return a distribution object from scipy.stats.

Parameters:

dist (str or rv_continuous distribution object) – Name of the univariate distribution, e.g. beta, expon, genextreme, gamma, gumbel_r, lognorm, norm. Or an instance of the distribution.

Return type:

rv_continuous

Returns:

rv_continuous – A distribution object from scipy.stats.

xclim.indices.stats.parametric_cdf(p, v, dist=None)[source]

Return the cumulative distribution function corresponding to the given distribution parameters and value.

Parameters:
  • p (xr.DataArray) – Distribution parameters returned by the fit function. The array should have dimension dparams storing the distribution parameters, and attribute scipy_dist, storing the name of the distribution.

  • v (float or Sequence of float) – Value to compute the CDF.

  • dist (str or rv_continuous distribution object, optional) – The distribution name or instance is the scipy_dist attribute is not available on p.

Return type:

DataArray

Returns:

xarray.DataArray – An array of parametric CDF values estimated from the distribution parameters.

xclim.indices.stats.parametric_quantile(p, q, dist=None)[source]

Return the value corresponding to the given distribution parameters and quantile.

Parameters:
  • p (xr.DataArray) – Distribution parameters returned by the fit function. The array should have dimension dparams storing the distribution parameters, and attribute scipy_dist, storing the name of the distribution.

  • q (float or Sequence of float) – Quantile to compute, which must be between 0 and 1, inclusive.

  • dist (str or rv_continuous distribution object, optional) – The distribution name or instance if the scipy_dist attribute is not available on p.

Return type:

DataArray

Returns:

xarray.DataArray – An array of parametric quantiles estimated from the distribution parameters.

Notes

When all quantiles are above 0.5, the isf method is used instead of ppf because accuracy is sometimes better.

xclim.indices.stats.standardized_index(da, freq, window, dist, method, zero_inflated, fitkwargs, cal_start, cal_end, params=None, **indexer)[source]

Standardized Index (SI).

This computes standardized indices which measure the deviation of variables in the dataset compared to a reference distribution. The reference is a statistical distribution computed with fitting parameters params over a given calibration period of the dataset. Those fitting parameters are obtained with xclim.standardized_index_fit_params.

Parameters:
  • da (xarray.DataArray) – Daily input data.

  • freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.

  • window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.

  • dist (str or rv_continuous instance) – Name of the univariate distribution. (see scipy.stats).

  • method (str) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that doesn’t involve any optimization.

  • zero_inflated (bool) – If True, the zeroes of da are treated separately.

  • fitkwargs (dict, optional) – Kwargs passed to xclim.indices.stats.fit used to impose values of certains parameters (floc, fscale). If method is PWM, fitkwargs should be empty, except for floc with dist`=`gamma which is allowed.

  • cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.

  • cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.

  • params (xarray.DataArray) – Fit parameters. The params can be computed using xclim.indices.stats.standardized_index_fit_params in advance. The output can be given here as input, and it overrides other options.

  • **indexer ({dim: indexer, }, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – Standardized Precipitation Index.

See also

standardized_index_fit_params

Standardized Index Fit Params.

Notes

  • The standardized index is bounded by ±8.21. 8.21 is the largest standardized index as constrained by the float64 precision in the inversion to the normal distribution.

  • window, dist, method, zero_inflated are only optional if params is given. If params is given as input, it overrides the cal_start, cal_end, freq and window, dist and method options.

  • Supported combinations of dist and method are: * Gamma (“gamma”) : “ML”, “APP” * Log-logistic (“fisk”) : “ML”, “APP” * “APP” method only supports two-parameter distributions. Parameter loc will be set to 0 (setting floc=0 in fitkwargs). * Otherwise, generic rv_continuous methods can be used. This includes distributions from lmoments3 which should be used with method=”PWM”.

References

McKee, Doesken, and Kleist [1993].

xclim.indices.stats.standardized_index_fit_params(da, freq, window, dist, method, zero_inflated=False, fitkwargs=None, **indexer)[source]

Standardized Index fitting parameters.

A standardized index measures the deviation of a variable averaged over a rolling temporal window and fitted with a given distribution dist with respect to a calibration dataset. The comparison is done by porting back results to a normalized distribution. The fitting parameters of the calibration dataset fitted with dist are obtained here.

Parameters:
  • da (xarray.DataArray) – Input array.

  • freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.

  • window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.

  • dist ({‘gamma’, ‘fisk’} or rv_continuous distribution object) – Name of the univariate distribution. (see scipy.stats).

  • method ({‘ML’, ‘APP’, ‘PWM’}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that doesn’t involve any optimization.

  • zero_inflated (bool) – If True, the zeroes of da are treated separately when fitting a probability density function.

  • fitkwargs (dict, optional) – Kwargs passed to xclim.indices.stats.fit used to impose values of certains parameters (floc, fscale).

  • **indexer ({dim: indexer, }, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as xclim.indices.generic.select_time().

Return type:

DataArray

Returns:

xarray.DataArray – Standardized Index fitting parameters. The time dimension of the initial array is reduced to.

Notes

Supported combinations of dist and method are: * Gamma (“gamma”) : “ML”, “APP” * Log-logistic (“fisk”) : “ML”, “APP” * “APP” method only supports two-parameter distributions. Parameter loc will be set to 0 (setting floc=0 in fitkwargs). * Otherwise, generic rv_continuous methods can be used. This includes distributions from lmoments3 which should be used with method=”PWM”.

When using the zero inflated option, : A probability density function \(\texttt{pdf}_0(X)\) is fitted for \(X \neq 0\) and a supplementary parameter \(\pi\) takes into account the probability of \(X = 0\). The full probability density function is a piecewise function:

\[\texttt{pdf}(X) = \pi \texttt{ if } X=0 \texttt{ else } (1-\pi) \texttt{pdf}_0(X)\]