Indices library

This module contains climate indices functions operating on xarray.DataArray. Most of these functions operate on daily time series, but might accept other sampling frequencies as well. All functions perform units checks to make sure that inputs have the expected dimensions (for example have units of temperature, whether it is celsius, kelvin or fahrenheit), and set the units attribute of the output DataArray.

The calendar, fwi, generic, run_length and utils submodule provide helpers to simplify the implementation of the indices.

Note

Indices functions do not perform missing value checks, and do not set CF-Convention attributes (long_name, standard_name, description, cell_methods, etc.). These functionalities are provided by xclim.indicators.Indicator instances found in the xclim.indicators.atmos, xclim.indicators.land and xclim.indicators.seaIce modules, documented in Climate indicators.

xclim.indices.base_flow_index(q: xarray.DataArray, freq: str = 'YS') xarray.DataArray[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.

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.biologically_effective_degree_days(tasmin: xarray.DataArray, tasmax: xarray.DataArray, lat: Optional[xarray.DataArray] = None, thresh_tasmin: str = '10 degC', method: str = 'gladstones', low_dtr: str = '10 degC', high_dtr: str = '13 degC', max_daily_degree_days: str = '9 degC', start_date: DayOfYearStr = '04-01', end_date: DayOfYearStr = '11-01', freq: str = 'YS') xarray.DataArray[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.

  • thresh_tasmin (str) – 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 (str) – The lower bound for daily temperature range adjustment (default: 10°C).

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

  • max_daily_degree_days (str) – 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 “AS-JUL”).

Returns

xarray.DataArray – 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.

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). 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

Indice originally from Gladstones, J.S. (1992). Viticulture and environment: a study of the effects of environment on grapegrowing and wine qualities, with emphasis on present and future areas for growing winegrapes in Australia. Adelaide: Winetitles.

ICCLIM modified formula originally from Project team ECA&D, KNMI (2013). EUMETNET/ECSN optional programme: European Climate Assessment & Dataset (ECA&D) - Algorithm Theoretical Basis Document (ATBD). (KNMI Project number: EPJ029135, v10.7). https://www.ecad.eu/documents/atbd.pdf

xclim.indices.blowing_snow(snd: xarray.DataArray, sfcWind: xarray.DataArray, snd_thresh: str = '5 cm', sfcWind_thresh: str = '15 km/h', window: int = 3, freq: str = 'AS-JUL') xarray.DataArray[source]

Days with blowing snow events

Number of days where 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 (str) – Threshold on net snowfall accumulation over the last window days.

  • sfcWind_thresh (str) – Wind speed threshold.

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

  • freq (str) – Resampling frequency.

Returns

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

xclim.indices.calm_days(sfcWind: xarray.DataArray, thresh: str = '2 m s-1', freq: str = 'MS') xarray.DataArray[source]

Calm days.

The number of days with average near-surface wind speed below threshold.

Parameters
  • sfcWind (xarray.DataArray) – Daily windspeed.

  • thresh (str) – Threshold average near-surface wind speed on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days with average near-surface wind speed below 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.clausius_clapeyron_scaled_precipitation(delta_tas: xarray.DataArray, pr_baseline: xarray.DataArray, cc_scale_factor: float = 1.07) xarray.DataArray[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 (default = 1.07)) – Clausius Clapeyron scale factor.

Returns

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

Notes

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

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

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

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.

xclim.indices.cold_and_dry_days(tas: xarray.DataArray, tas_25: xarray.DataArray, pr: xarray.DataArray, pr_25: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Cold and dry days.

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

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

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

  • pr (xarray.DataArray) – Daily precipitation.

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

    Warning

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

  • freq (str) – Resampling frequency.

Returns

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

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 [cold_dry_days].

References

cold_dry_days

Beniston, M. (2009). Trends in joint quantiles of temperature and precipitation in Europe since 1901 and projected for 2100. Geophysical Research Letters, 36(7). https://doi.org/10.1029/2008GL037119

xclim.indices.cold_and_wet_days(tas: xarray.DataArray, tas_25: xarray.DataArray, pr: xarray.DataArray, pr_75: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

cold and wet days.

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

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

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

  • pr (xarray.DataArray) – Daily precipitation.

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

    Warning

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

  • freq (str) – Resampling frequency.

Returns

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

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 [cold_wet_days].

References

cold_wet_days

Beniston, M. (2009). Trends in joint quantiles of temperature and precipitation in Europe since 1901 and projected for 2100. Geophysical Research Letters, 36(7). https://doi.org/10.1029/2008GL037119

xclim.indices.cold_spell_days(tas: xarray.DataArray, thresh: str = '-10 degC', window: int = 5, freq: str = 'AS-JUL') xarray.DataArray[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 in °C.

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

  • thresh (str) – Threshold temperature below which a cold spell begins.

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

  • freq (str) – Resampling frequency.

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.cold_spell_duration_index(tasmin: xarray.DataArray, tn10: xarray.DataArray, window: int = 6, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[source]

Cold spell duration index.

Number of days with at least six consecutive days where the daily minimum temperature is below the 10th percentile.

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

  • tn10 (xarray.DataArray) – 10th 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.

  • 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, it would give wrong results plus, bootstrapping is computationally expensive.

Returns

xarray.DataArray, [time] – Count of days with at least six consecutive days where 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).

Examples

# Note that this example does not use a proper 1961-1990 reference period. >>> 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)
xclim.indices.cold_spell_frequency(tas: xarray.DataArray, thresh: str = '-10 degC', window: int = 5, freq: str = 'AS-JUL') xarray.DataArray[source]

Cold spell frequency.

The number of cold spell events, defined as a sequence of consecutive days with mean daily temperature below a threshold.

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

  • thresh (str) – Threshold temperature below which a cold spell begins.

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

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – Cold spell frequency.

xclim.indices.continuous_snow_cover_end(snd: xarray.DataArray, thresh: str = '2 cm', window: int = 14, freq: str = 'AS-JUL') xarray.DataArray[source]

End date of continuous snow cover.

First day after the start of the continuous snow cover when snow depth is below threshold for at least window consecutive days. WARNING: The default freq is valid for the northern hemisphere.

Parameters
  • snd (xarray.DataArray) – Surface snow thickness.

  • thresh (str) – Threshold snow thickness.

  • window (int) – Minimum number of days with snow depth below threshold.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – First day after the start of the continuous snow cover when the snow depth goes below a threshold for a minimum duration. If there is no such day, return np.nan.

References

Chaumont D., Mailhot A., Diaconescu E.P., Fournier É., Logan T. 2017: Élaboration du portrait bioclimatique futur du Nunavik – Tome II. [Rapport présenté au Ministère de la forêt, de la faune et des parcs], Ouranos.

xclim.indices.continuous_snow_cover_start(snd: xarray.DataArray, thresh: str = '2 cm', window: int = 14, freq: str = 'AS-JUL') xarray.DataArray[source]

Start date of continuous snow cover.

Day of year when snow depth is above or equal threshold for at least window consecutive days. WARNING: The default freq is valid for the northern hemisphere.

Parameters
  • snd (xarray.DataArray) – Surface snow thickness.

  • thresh (str) – Threshold snow thickness.

  • window (int) – Minimum number of days with snow depth above or equal to threshold.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – First day of the year when the snow depth is superior to a threshold for a minimum duration. If there is no such day, return np.nan.

References

Chaumont D., Mailhot A., Diaconescu E.P., Fournier É., Logan T. 2017: Élaboration du portrait bioclimatique futur du Nunavik – Tome II. [Rapport présenté au Ministère de la forêt, de la faune et des parcs], Ouranos.

xclim.indices.cool_night_index(tasmin: xarray.DataArray, lat: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Cool Night Index.

Mean minimum temperature for September (northern hemisphere) or March (Southern hemishere). Used in calculating the Géoviticulture Multicriteria Classification System.

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

  • lat (xarray.DataArray, optional) – Latitude coordinate.

  • freq (str) – Resampling frequency.

Returns

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

Notes

Given that this indice only examines September and March months, it 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', data_validation='log'):
>>>     cni = xclim.atmos.cool_night_index(...)  # xdoctest: +SKIP

References

Indice originally published in Tonietto, J., & Carbonneau, A. (2004). A multicriteria climatic classification system or grape-growing regions worldwide. Agricultural and Forest Meteorology, 124(1–2), 81‑97. https://doi.org/10.1016/j.agrformet.2003.06.001

xclim.indices.cooling_degree_days(tas: xarray.DataArray, thresh: str = '18 degC', freq: str = 'YS') xarray.DataArray[source]

Cooling degree days.

Sum of degree days above the temperature threshold at which spaces are cooled.

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

  • thresh (str) – Temperature threshold above which air is cooled.

  • freq (str) – Resampling frequency.

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.corn_heat_units(tasmin: xarray.DataArray, tasmax: xarray.DataArray, thresh_tasmin: str = '4.44 degC', thresh_tasmax: str = '10 degC') xarray.DataArray[source]

Corn heat units.

Temperature-based index used to estimate the development of corn crops.

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

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

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

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

Returns

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

Notes

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

\[ \begin{align}\begin{aligned}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\end{aligned}\end{align} \]

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

References

Equations from Bootsma, A., G. Tremblay et P. Filion. 1999: Analyse sur les risques associés aux unités thermiques disponibles pour la production de maïs et de soya au Québec. Centre de recherches de l’Est sur les céréales et oléagineux, Ottawa, 28 p.

Can be found in Audet, R., Côté, H., Bachand, D. and Mailhot, A., 2012: Atlas agroclimatique du Québec. Évaluation des opportunités et des risques agroclimatiques dans un climat en évolution.

xclim.indices.daily_freezethaw_cycles(tasmin: xarray.DataArray, tasmax: xarray.DataArray, thresh_tasmin: str = '0 degC', thresh_tasmax: str = '0 degC', freq: str = 'YS') xarray.DataArray[source]

Number of days with a diurnal freeze-thaw cycle.

The number of days where Tmax > thresh_tasmax and Tmin <= thresh_tasmin.

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

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

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

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

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days with a diurnal freeze-thaw cycle

Notes

Let \(TX_{i}\) be the maximum temperature at day \(i\) and \(TN_{i}\) be the daily minimum temperature at day \(i\). Then the number of freeze thaw cycles during period \(\phi\) is given by :

\[\sum_{i \in \phi} [ TX_{i} > 0℃ ] [ TN_{i} < 0℃ ]\]

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

Warning

The daily_freezethaw_cycles indice is being deprecated in favour of multiday_temperature_swing with thresh_tasmax=’0 degC, thresh_tasmin=’0 degC’, window=1, op=’sum’ by default. The indicator reflects this change. This indice will be removed in a future version of xclim.

xclim.indices.daily_pr_intensity(pr: xarray.DataArray, thresh: str = '1 mm/day', freq: str = 'YS') xarray.DataArray[source]

Average daily precipitation intensity.

Return the average precipitation over wet days.

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

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

  • freq (str) – Resampling frequency.

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, ie 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.daily_temperature_range(tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str = 'YS', op: str = 'mean') xarray.DataArray[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 func) – Reduce operation. Can either be a DataArray method or a function that can be applied to a 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.daily_temperature_range_variability(tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str = 'YS') xarray.DataArray[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.

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.days_over_precip_thresh(pr: xarray.DataArray, per: xarray.DataArray, thresh: str = '1 mm/day', freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[source]

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

Number of days over 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.

  • 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 (str) – 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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

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(.75, dim="time", keep_attrs=True)
>>> r75p = days_over_precip_thresh(pr, p75)
xclim.indices.days_with_snow(prsn: xarray.DataArray, low: str = '0 kg m-2 s-1', high: str = '1E6 kg m-2 s-1', freq: str = 'AS-JUL') xarray.DataArray[source]

Days with snow.

Return the number of days where snowfall is within low and high thresholds.

Parameters
Returns

xarray.DataArray, [time] – Number of days where snowfall is between low and high thresholds.

References

Matthews, L., Andrey, J., & Picketts, I. (2017). Planning for Winter Road Maintenance in the Context of Climate Change, Weather, Climate, and Society, 9(3), 521-532, https://doi.org/10.1175/WCAS-D-16-0103.1

xclim.indices.degree_days_exceedance_date(tas: xarray.DataArray, thresh: str = '0 degC', sum_thresh: str = '25 K days', op: str = '>', after_date: Optional[DayOfYearStr] = None, freq: str = 'YS') xarray.DataArray[source]

Degree days exceedance date.

Day of year when the sum of degree days exceeds a threshold. Degree days are computed above or below a given temperature threshold.

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

  • thresh (str) – Threshold temperature on which to base degree days evaluation.

  • sum_thresh (str) – 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.

  • freq (str) – Resampling frequency. If after_date is given, freq should be annual.

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 '<'} \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.

xclim.indices.drought_code(tas: xarray.DataArray, pr: xarray.DataArray, lat: xarray.DataArray, snd: Optional[xarray.DataArray] = None, dc0: Optional[xarray.DataArray] = None, season_mask: Optional[xarray.DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]

Drought code (FWI component).

The drought code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of organic layers.

Parameters
  • tas (xr.DataArray) – Noon temperature.

  • pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.

  • lat (xr.DataArray) – Latitude coordinate

  • snd (xr.DataArray) – Noon snow depth.

  • dc0 (xr.DataArray) – Initial values of the drought code.

  • season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.

  • season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fwi function. Ignored if season_mask is given.

  • overwintering (bool) – Whether to activate DC overwintering or not. If True, either season_method or season_mask must be given.

  • dry_start ({None, “CFS”, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism and which method to use. , see fire_weather_ufunc().

  • initial_start_up (bool) – If True (default), grid points where the fire season is active on the first timestep go through a start_up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.

  • params – Any other keyword parameters as defined in xclim.indices.fwi.fire_weather_ufunc and in default_params.

Returns

xr.DataArray, [dimensionless] – Drought code

Notes

See https://cwfis.cfs.nrcan.gc.ca/background/dsm/fwi, the module’s doc and doc of fire_weather_ufunc() for more information.

References

Updated source code for calculating fire danger indexes in the Canadian Forest Fire Weather Index System, Y. Wang, K.R. Anderson, and R.M. Suddaby, INFORMATION REPORT NOR-X-424, 2015.

xclim.indices.dry_days(pr: xarray.DataArray, thresh: str = '0.2 mm/d', freq: str = 'YS') xarray.DataArray[source]

Dry days.

The number of days with daily precipitation below threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days with daily precipitation below 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.dry_spell_frequency(pr: xarray.DataArray, thresh: str = '1.0 mm', window: int = 3, freq: str = 'YS', op: str = 'sum') xarray.DataArray[source]

Return the number of dry periods of n days and more, during which the accumulated or maximal daily precipitation amount on a window of n days is under the threshold.

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

  • thresh (str) – 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.

  • op ({“sum”,”max”}) – 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.

Returns

xarray.DataArray – The {freq} number of dry periods of minimum {window} days.

Examples

>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> dry_spell_frequency(pr=pr, op="sum")
>>> dry_spell_frequency(pr=pr, op="max")
xclim.indices.dry_spell_total_length(pr: xarray.DataArray, thresh: str = '1.0 mm', window: int = 3, op: str = 'sum', freq: str = 'YS', **indexer) xarray.DataArray[source]

Total length of dry spells

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 threshold.

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

  • thresh (str) – Accumulated precipitation value under which a period is considered dry.

  • window (int) – Number of days where the maximum or accumulated precipitation is under threshold.

  • op ({“max”, “sum”}) – Reduce operation.

  • freq (str) – Resampling frequency.

  • 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(). Indexing is done after finding the dry days, but before finding the spells.

Returns

xarray.DataArray – The {freq} total number of days in dry periods of minimum {window} days.

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 3 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 3.)

xclim.indices.effective_growing_degree_days(tasmax: xarray.DataArray, tasmin: xarray.DataArray, *, thresh: str = '5 degC', method: str = 'bootsma', after_date: DayOfYearStr = '07-01', dim: str = 'time', freq: str = 'YS') xarray.DataArray[source]

Effective growing degree days.

Growing degree days based on a dynamic start and end of the growing season.

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

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

  • thresh (str) – 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 (5 degC). For “qian”, the start date is based on a weighted 5-day rolling average, based on 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.

Returns

xarray.DataArray

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

Indice originally published in Bootsma, A., & Gameda and D.W. McKenney, S. (2005). Impacts of potential climate change on selected agroclimatic indices in Atlantic Canada. Canadian Journal of Soil Science, 85(2), 329‑343. https://doi.org/10.4141/S04-019

xclim.indices.extreme_temperature_range(tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str = 'YS') xarray.DataArray[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.

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.fire_season(tas: xarray.DataArray, snd: Optional[xarray.DataArray] = None, method: str = 'WF93', freq: Optional[str] = None, temp_start_thresh: str = '12 degC', temp_end_thresh: str = '5 degC', temp_condition_days: int = 3, snow_condition_days: int = 3, snow_thresh: str = '0.01 m')[source]

Fire season mask.

Binary mask of the active fire season, defined by conditions on consecutive daily temperatures and, optionally, snow depths.

Parameters
  • tas (xr.DataArray) – Daily surface temperature, cffdrs recommends using maximum daily temperature.

  • snd (xr.DataArray, optional) – Snow depth, used with method == ‘LA08’.

  • method ({“WF93”, “LA08”, “GFWED”}) – Which method to use. “LA08” and “GFWED” need the snow depth.

  • freq (str, optional) – If given only the longest fire season for each period defined by this frequency, Every “seasons” are returned if None, including the short shoulder seasons.

  • temp_start_thresh (str) – Minimal temperature needed to start the season.

  • temp_end_thresh (str) – Maximal temperature needed to end the season.

  • temp_condition_days (int) – Number of days with temperature above or below the thresholds to trigger a start or an end of the fire season.

  • snow_condition_days (int) – Parameters for the fire season determination. See fire_season(). Temperature is in degC, snow in m. The snow_thresh parameters is also used when dry_start is set to “GFWED”.

  • snow_thresh (str) – Minimal snow depth level to end a fire season, only used with method “LA08”.

Returns

fire_season (xr.DataArray) – Fire season mask

References

Wotton, B.M. and Flannigan, M.D. (1993). Length of the fire season in a changing climate. ForestryChronicle, 69, 187-192. Lawson, B.D. and O.B. Armitage. 2008. Weather guide for the Canadian Forest Fire Danger Rating System. NRCAN, CFS, Edmonton, AB

xclim.indices.fire_weather_indexes(tas: xarray.DataArray, pr: xarray.DataArray, sfcWind: xarray.DataArray, hurs: xarray.DataArray, lat: xarray.DataArray, snd: Optional[xarray.DataArray] = None, ffmc0: Optional[xarray.DataArray] = None, dmc0: Optional[xarray.DataArray] = None, dc0: Optional[xarray.DataArray] = None, season_mask: Optional[xarray.DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]

Fire weather indexes.

Computes the 6 fire weather indexes as defined by the Canadian Forest Service: the Drought Code, the Duff-Moisture Code, the Fine Fuel Moisture Code, the Initial Spread Index, the Build Up Index and the Fire Weather Index.

Parameters
  • tas (xr.DataArray) – Noon temperature.

  • pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.

  • sfcWind (xr.DataArray) – Noon wind speed.

  • hurs (xr.DataArray) – Noon relative humidity.

  • lat (xr.DataArray) – Latitude coordinate

  • snd (xr.DataArray) – Noon snow depth, only used if season_method=’LA08’ is passed.

  • ffmc0 (xr.DataArray) – Initial values of the fine fuel moisture code.

  • dmc0 (xr.DataArray) – Initial values of the Duff moisture code.

  • dc0 (xr.DataArray) – Initial values of the drought code.

  • season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.

  • season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fwi function. Ignored if season_mask is given.

  • overwintering (bool) – Whether to activate DC overwintering or not. If True, either season_method or season_mask must be given.

  • dry_start ({None, ‘CFS’, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism or not, see fire_weather_ufunc().

  • initial_start_up (bool) – If True (default), gridpoints where the fire season is active on the first timestep go through a start_up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.

  • params – Any other keyword parameters as defined in fire_weather_ufunc() and in default_params.

Returns

  • DC (xr.DataArray, [dimensionless])

  • DMC (xr.DataArray, [dimensionless])

  • FFMC (xr.DataArray, [dimensionless])

  • ISI (xr.DataArray, [dimensionless])

  • BUI (xr.DataArray, [dimensionless])

  • FWI (xr.DataArray, [dimensionless])

Notes

See https://cwfis.cfs.nrcan.gc.ca/background/dsm/fwi, the module’s doc and doc of fire_weather_ufunc() for more information.

References

Updated source code for calculating fire danger indexes in the Canadian Forest Fire Weather Index System, Y. Wang, K.R. Anderson, and R.M. Suddaby, INFORMATION REPORT NOR-X-424, 2015.

xclim.indices.first_day_above(tasmin: xarray.DataArray, thresh: str = '0 degC', after_date: DayOfYearStr = '01-01', window: int = 1, freq: str = 'YS') xarray.DataArray[source]

First day of temperatures superior to a threshold temperature.

Returns first day of period where a temperature is superior to a threshold over a given number of days, limited to a starting calendar date.

WARNING: The default date and freq are valid for the northern hemisphere.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • 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 threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – Day of the year when minimum 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.

xclim.indices.first_day_below(tasmin: xarray.DataArray, thresh: str = '0 degC', after_date: DayOfYearStr = '07-01', window: int = 1, freq: str = 'YS') xarray.DataArray[source]

First day of temperatures inferior to a threshold temperature.

Returns first day of period where a temperature is inferior to a threshold over a given number of days, limited to a starting calendar date.

WARNING: The default date and freq are valid for the northern hemisphere.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

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

  • window (int) – Minimum number of days with temperature below threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – Day of the year when minimum 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.

xclim.indices.first_snowfall(prsn: xarray.DataArray, thresh: str = '0.5 mm/day', freq: str = 'AS-JUL') xarray.DataArray[source]

First day with solid precipitation above a threshold.

Returns the first day of a period where the solid precipitation exceeds a threshold. WARNING: The default freq is valid for the northern hemisphere.

Parameters
  • prsn (xarray.DataArray) – Solid precipitation flux.

  • thresh (str) – Threshold precipitation flux on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – First day of the year when the solid precipitation is superior to a threshold. If there is no such day, returns np.nan.

References

Climate Projections for the National Capital Region (2020), Volume 1: Results and Interpretation for Key Climate Indices, Report 193600.00, Prepared for Ottawa by CBCL.

xclim.indices.fraction_over_precip_thresh(pr: xarray.DataArray, per: xarray.DataArray, thresh: str = '1 mm/day', freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[source]

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

Percentage of the total precipitation over period occurring in days 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.

  • 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 (str) – 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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

Returns

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

xclim.indices.freshet_start(tas: xarray.DataArray, thresh: str = '0 degC', window: int = 5, freq: str = 'YS') xarray.DataArray[source]

First day consistently exceeding threshold temperature.

Returns first day of period where a temperature threshold is exceeded over a given number of days.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – Day of the year when temperature exceeds threshold over a given number of days for the first time. If there is no such day, return np.nan.

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 freshet is given by the smallest index \(i\) for which

\[\prod_{j=i}^{i+w} [x_j > thresh]\]

is true, 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.frost_days(tasmin: xarray.DataArray, thresh: str = '0 degC', freq: str = 'YS') xarray.DataArray[source]

Frost days index.

Number of days where daily minimum temperatures are below a threshold temperature.

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

  • thresh (str) – Freezing temperature.

  • freq (str) – Resampling frequency.

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.frost_free_season_end(tasmin: xarray.DataArray, thresh: str = '0.0 degC', mid_date: DayOfYearStr = '07-01', window: int = 5, freq: str = 'YS') xarray.DataArray[source]

End of the frost free season.

Day of the year of the start of a sequence of days with minimum temperatures consistently below a threshold, after a period with minimum temperatures consistently above the same threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • mid_date (str) – Date of the year after which to look for the end of the season. Should have the format ‘%m-%d’.

  • window (int) – Minimum number of days with temperature below threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – Day of the year when minimum temperature is inferior to a threshold over a given number of days for the first time. If there is no such day or if a frost free season is not detected, returns np.nan. If the frost free season does not end within the time period, returns the last day of the period.

xclim.indices.frost_free_season_length(tasmin: xarray.DataArray, window: int = 5, mid_date: Optional[DayOfYearStr] = '07-01', thresh: str = '0.0 degC', freq: str = 'YS') xarray.DataArray[source]

Frost free season length.

The number of days between the first occurrence of at least N (def: 5) consecutive days with minimum daily temperature above a threshold (default: 0℃) and the first occurrence of at least N (def 5) consecutive days with minimum daily temperature below the same threshold A mid date can be given to limit the earliest day the end of season can take. WARNING: The default freq and mid_date values are valid for the northern hemisphere.

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

  • window (int) – Minimum number of days with temperature above threshold to mark the beginning and end of frost free season.

  • mid_date (str, optional) – Date the must be included in the season. It is the earliest the end of the season can be. If None, there is no limit.

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Frost free season length.

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: >>> 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=’AS-JUL’)

xclim.indices.frost_free_season_start(tasmin: xarray.DataArray, thresh: str = '0.0 degC', window: int = 5, freq: str = 'YS') xarray.DataArray[source]

Start of the frost free season.

Day of the year of the start of a sequence of days with minimum temperatures consistently above or equal to a threshold, after a period with minimum temperatures consistently above the same threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above threshold needed for evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – Day of the year when minimum temperature is superior to a threshold over a given number of days for the first time. If there is no such day or if a frost free season is not detected, returns np.nan.

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 start of growing season is given by the smallest index \(i\) for which:

\[\prod_{j=i}^{i+w} [x_j >= thresh]\]

is true, where \(w\) is the number of days the temperature threshold should be met or exceeded, and \([P]\) is 1 if \(P\) is true, and 0 if false.

xclim.indices.frost_season_length(tasmin: xarray.DataArray, window: int = 5, mid_date: Optional[DayOfYearStr] = '01-01', thresh: str = '0.0 degC', freq: str = 'AS-JUL') xarray.DataArray[source]

Frost season length.

The number of days between the first occurrence of at least N (def: 5) consecutive days with minimum daily temperature under a threshold (default: 0℃) and the first occurrence of at least N (def 5) 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. WARNING: The default freq and mid_date values are valid for the northern hemisphere.

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) – Date the must be included in the season. It is the earliest the end of the season can be. If None, there is no limit.

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Frost season length.

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=’AS-JUL’)

# If working in the Southern Hemisphere, one can use: >>> fsl_sh = frost_season_length(tasmin, freq=’YS’)

xclim.indices.growing_degree_days(tas: xarray.DataArray, thresh: str = '4.0 degC', freq: str = 'YS') xarray.DataArray[source]

Growing degree-days over threshold temperature value.

The sum of degree-days over the threshold temperature.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time][temperature] – The sum of growing degree-days above a given threshold.

Notes

Let \(TG_{ij}\) be the daily mean 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.growing_season_end(tas: xarray.DataArray, thresh: str = '5.0 degC', mid_date: DayOfYearStr = '07-01', window: int = 5, freq: str = 'YS') xarray.DataArray[source]

End of the growing season.

Day of the year of the start of a sequence of days with mean temperatures consistently below a threshold, after a period with mean temperatures consistently above the same threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • mid_date (str) – Date of the year after which to look for the end of the season. Should have the format ‘%m-%d’.

  • window (int) – Minimum number of days with temperature below threshold needed for evaluation.

  • freq (str) – Resampling frequency.

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 or if a growing season is not detected, returns np.nan. If the growing season does not end within the time period, returns the last day of the period.

xclim.indices.growing_season_length(tas: xarray.DataArray, thresh: str = '5.0 degC', window: int = 6, mid_date: DayOfYearStr = '07-01', freq: str = 'YS') xarray.DataArray[source]

Growing season length.

The number of days between the first occurrence of at least six consecutive days with mean daily temperature over a threshold (default: 5℃) and the first occurrence of at least six consecutive days with mean daily temperature below the same threshold after a certain date. (Usually July 1st in the northern emisphere and January 1st in the southern hemisphere.)

WARNING: The default calendar values are only valid for the northern hemisphere.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above threshold to mark the beginning and end of growing season.

  • mid_date (str) – Date of the year after which to look for the end of the season. Should have the format ‘%m-%d’.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Growing season length.

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 6 consecutive days with:

\[TG_{ij} < 5 ℃\]

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=’AS’)

# If working in the Southern Hemisphere, one can use: >>> gsl_sh = growing_season_length(tas, mid_date=’01-01’, freq=’AS-JUL’)

xclim.indices.growing_season_start(tas: xarray.DataArray, thresh: str = '5.0 degC', window: int = 5, freq: str = 'YS') xarray.DataArray[source]

Start of the growing season.

Day of the year of the start of a sequence of days with mean temperatures consistently above or equal to a threshold, after a period with mean temperatures consistently above the same threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • window (int) – Minimum number of days with temperature above threshold needed for evaluation.

  • freq (str) – Resampling frequency.

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 or if a growing season is not detected, returns np.nan.

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 start of growing season is given by the smallest index \(i\) for which:

\[\prod_{j=i}^{i+w} [x_j >= thresh]\]

is true, where \(w\) is the number of days the temperature threshold should be met or exceeded, and \([P]\) is 1 if \(P\) is true, and 0 if false.

xclim.indices.heat_index(tasmax: xarray.DataArray, hurs: xarray.DataArray) xarray.DataArray[source]

Daily heat index.

Perceived temperature after relative humidity is taken into account. The index is only valid for temperatures above 20°C.

Parameters
  • tasmax (xr.DataArray) – Maximum daily temperature.

  • hurs (xr.DataArray) – Relative humidity.

Returns

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

References

blazejczyk2012

Blazejczyk, K., Epstein, Y., Jendritzky, G., Staiger, H., & Tinz, B. (2012). Comparison of UTCI to selected thermal indices. International journal of biometeorology, 56(3), 515-535.

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 vapor pressure, which is used exclusively in the humidex calculation.

xclim.indices.heat_wave_frequency(tasmin: xarray.DataArray, tasmax: xarray.DataArray, thresh_tasmin: str = '22.0 degC', thresh_tasmax: str = '30 degC', window: int = 3, freq: str = 'YS') xarray.DataArray[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 exceeds specific thresholds over a minimum number of days.

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.

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 ([casati2013]).

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

References

casati2013

Casati, B., Yagouti, A., & Chaumont, D. (2013). Regional Climate Projections of Extreme Heat Events in Nine Pilot Canadian Communities for Public Health Planning. Journal of Applied Meteorology and Climatology, 52(12), 2669‑2698. https://doi.org/10.1175/JAMC-D-12-0341.1

robinson2001

Robinson, P. J. (2001). On the Definition of a Heat Wave. Journal of Applied Meteorology and Climatology, 40(4), 762‑775. https://doi.org/10.1175/1520-0450(2001)040<0762:OTDOAH>2.0.CO;2

xclim.indices.heat_wave_index(tasmax: xarray.DataArray, thresh: str = '25.0 degC', window: int = 5, freq: str = 'YS') xarray.DataArray[source]

Heat wave index.

Number of days that are part of a heatwave, defined as five or more consecutive days over 25℃.

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

  • thresh (str) – Threshold temperature on which to designate a heatwave.

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

  • freq (str) – Resampling frequency.

Returns

DataArray, [time] – Heat wave index.

xclim.indices.heat_wave_max_length(tasmin: xarray.DataArray, tasmax: xarray.DataArray, thresh_tasmin: str = '22.0 degC', thresh_tasmax: str = '30 degC', window: int = 3, freq: str = 'YS') xarray.DataArray[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 exceeds 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 (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.

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 ([casati2013]).

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

References

casati2013

Casati, B., Yagouti, A., & Chaumont, D. (2013). Regional Climate Projections of Extreme Heat Events in Nine Pilot Canadian Communities for Public Health Planning. Journal of Applied Meteorology and Climatology, 52(12), 2669‑2698. https://doi.org/10.1175/JAMC-D-12-0341.1

robinson2001

Robinson, P. J. (2001). On the Definition of a Heat Wave. Journal of Applied Meteorology and Climatology, 40(4), 762‑775. https://doi.org/10.1175/1520-0450(2001)040<0762:OTDOAH>2.0.CO;2

xclim.indices.heat_wave_total_length(tasmin: xarray.DataArray, tasmax: xarray.DataArray, thresh_tasmin: str = '22.0 degC', thresh_tasmax: str = '30 degC', window: int = 3, freq: str = 'YS') xarray.DataArray[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 exceeds specific thresholds over a minimum number of days. This 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.

Returns

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

Notes

See notes and references of heat_wave_max_length

xclim.indices.heating_degree_days(tas: xarray.DataArray, thresh: str = '17.0 degC', freq: str = 'YS') xarray.DataArray[source]

Heating degree days.

Sum of degree days below the temperature threshold at which spaces are heated.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time][temperature] – Heating degree days index.

Notes

This index intentionally differs from its ECA&D 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.high_precip_low_temp(pr: xarray.DataArray, tas: xarray.DataArray, pr_thresh: str = '0.4 mm/d', tas_thresh: str = '-0.2 degC', freq: str = 'YS') xarray.DataArray[source]

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

Number of days where 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 (str) – Precipitation threshold to exceed.

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

  • freq (str) – Resampling frequency.

Returns

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

Example

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.hot_spell_frequency(tasmax: xarray.DataArray, thresh_tasmax: str = '30 degC', window: int = 3, freq: str = 'YS') xarray.DataArray[source]

Hot spell frequency.

Number of hot spells over a given period. A hot spell is defined as an event where the maximum daily temperature exceeds a specific threshold over a minimum number of days.

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

  • 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.

Returns

xarray.DataArray, [dimensionless] – Number of heatwave at the wanted 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, B., A. Yagouti, and D. Chaumont, 2013: Regional Climate Projections of Extreme Heat Events in Nine Pilot Canadian Communities for Public Health Planning. J. Appl. Meteor. Climatol., 52, 2669–2698, https://doi.org/10.1175/JAMC-D-12-0341.1

Robinson, P.J., 2001: On the Definition of a Heat Wave. J. Appl. Meteor., 40, 762–775, https://doi.org/10.1175/1520-0450(2001)040<0762:OTDOAH>2.0.CO;2

xclim.indices.hot_spell_max_length(tasmax: xarray.DataArray, thresh_tasmax: str = '30 degC', window: int = 1, freq: str = 'YS') xarray.DataArray[source]

Longest hot spell.

Longest spell of high temperatures over a given period.

The longest series of consecutive days with tasmax ≥ 30 °C. Here, there is no minimum threshold for number of days in a row that must be reached or exceeded to count as a spell. A year with zero +30 °C days will return a longest spell value of zero.

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

  • 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.

Returns

xarray.DataArray, [time] – Maximum length of continuous hot days at the wanted 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, B., A. Yagouti, and D. Chaumont, 2013: Regional Climate Projections of Extreme Heat Events in Nine Pilot Canadian Communities for Public Health Planning. J. Appl. Meteor. Climatol., 52, 2669–2698, https://doi.org/10.1175/JAMC-D-12-0341.1

Robinson, P.J., 2001: On the Definition of a Heat Wave. J. Appl. Meteor., 40, 762–775, https://doi.org/10.1175/1520-0450(2001)040<0762:OTDOAH>2.0.CO;2

xclim.indices.huglin_index(tas: xarray.DataArray, tasmax: xarray.DataArray, lat: xarray.DataArray, thresh: str = '10 degC', method: str = 'smoothed', start_date: DayOfYearStr = '04-01', end_date: DayOfYearStr = '10-01', freq: str = 'YS') xarray.DataArray[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 to September (Northern Hemisphere; October to March in Southern Hemisphere). 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.

  • thresh (str) – 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 “AS-JUL”).

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

Huglin heliothermal index originally published in Huglin, P. (1978). Nouveau mode d’évaluation des possibilités héliothermiques d’un milieu viticole. Dans Symposium International sur l’Écologie de la Vigne (p. 89‑98). Ministère de l’Agriculture et de l’Industrie Alimentaire.

Modified day-length for Huglin heliothermal index published in Hall, A., & Jones, G. V. (2010). Spatial analysis of climate in winegrape-growing regions in Australia. Australian Journal of Grape and Wine Research, 16(3), 389‑404. https://doi.org/10.1111/j.1755-0238.2010.00100.x

xclim.indices.humidex(tas: xarray.DataArray, tdps: Optional[xarray.DataArray] = None, hurs: Optional[xarray.DataArray] = None) xarray.DataArray[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) – Air temperature.

  • tdps (xarray.DataArray,) – Dewpoint temperature.

  • hurs (xarray.DataArray) – Relative humidity.

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 [masterton79]:

\[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 ([mekis15]). Alternatively, the term \(e\) can also be computed from the relative humidity h expressed in percent using [sirangelo20]:

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

The humidex comfort scale ([eccc]) 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 vapor pressure, which is used exclusively in the humidex calculation.

References

masterton79

Masterton, J. M., & Richardson, F. A. (1979). HUMIDEX, A method of quantifying human discomfort due to excessive heat and humidity, CLI 1-79. Downsview, Ontario: Environment Canada, Atmospheric Environment Service.

mekis15

Éva Mekis, Lucie A. Vincent, Mark W. Shephard & Xuebin Zhang (2015) Observed Trends in Severe Weather Conditions Based on Humidex, Wind Chill, and Heavy Rainfall Events in Canada for 1953–2012, Atmosphere-Ocean, 53:4, 383-397, DOI: 10.1080/07055900.2015.1086970

sirangelo20

Sirangelo, B., Caloiero, T., Coscarelli, R. et al. Combining stochastic models of air temperature and vapour pressure for the analysis of the bioclimatic comfort through the Humidex. Sci Rep 10, 11395 (2020). https://doi.org/10.1038/s41598-020-68297-4

eccc

https://climate.weather.gc.ca/glossary_e.html

xclim.indices.ice_days(tasmax: xarray.DataArray, thresh: str = '0 degC', freq: str = 'YS') xarray.DataArray[source]

Number of ice/freezing days.

Number of days where daily maximum temperatures are below a threshold.

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

  • thresh (str) – Freezing temperature.

  • freq (str) – Resampling frequency.

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.isothermality(tasmin: xarray.DataArray, tasmax: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Isothermality.

The mean diurnal 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.

Returns

xarray.DataArray, [%] – Isothermality

Notes

According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.jetstream_metric_woollings(ua: xarray.DataArray) xarray.DataArray[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.

Warning

This metric expects eastward wind component (u) to be on a regular grid (i.e. Plate Carree, 1D lat and lon)

Parameters

ua (xarray.DataArray) – Eastward wind component (u) at between 750 and 950 hPa.

Returns

  • xarray.DataArray – Daily time series of latitude of jetstream.

  • xarray.DataArray – Daily time series of strength of jetstream.

References

woollings2010

Woollings, T., Hannachi, A., & Hoskins, B. (2010). Variability of the North Atlantic eddy‐driven jet stream. Quarterly Journal of the Royal Meteorological Society, 136(649), 856-868.

xclim.indices.last_snowfall(prsn: xarray.DataArray, thresh: str = '0.5 mm/day', freq: str = 'AS-JUL') xarray.DataArray[source]

Last day with solid precipitation above a threshold.

Returns the last day of a period where the solid precipitation exceeds a threshold. WARNING: The default freq is valid for the northern hemisphere.

Parameters
  • prsn (xarray.DataArray) – Solid precipitation flux.

  • thresh (str) – Threshold precipitation flux on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – Last day of the year when the solid precipitation is superior to a threshold. If there is no such day, returns np.nan.

References

Climate Projections for the National Capital Region (2020), Volume 1: Results and Interpretation for Key Climate Indices, Report 193600.00, Prepared for Ottawa by CBCL.

xclim.indices.last_spring_frost(tas: xarray.DataArray, thresh: str = '0 degC', before_date: DayOfYearStr = '07-01', window: int = 1, freq: str = 'YS') xarray.DataArray[source]

Last day of temperatures inferior to a threshold temperature.

Returns last day of period where a temperature is inferior to a threshold over a given number of days and limited to a final calendar date.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • 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 threshold needed for evaluation.

  • freq (str) – Resampling frequency.

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.

xclim.indices.latitude_temperature_index(tas: xarray.DataArray, lat: xarray.DataArray, lat_factor: float = 75, freq: str = 'YS') xarray.DataArray[source]

Latitude-Temperature Index.

Mean temperature of the warmest month with a latitude-based scaling factor. Used for categorizing winegrowing regions.

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

  • lat (xarray.DataArray) – Latitude coordinate.

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

  • freq (str) – Resampling frequency.

Returns

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

Notes

The latitude factor of 75 is provided for examining the poleward expansion of winegrowing climates under scenarios of climate change. 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

Indice originally published in Jackson, D. I., & Cherry, N. J. (1988). Prediction of a District’s Grape-Ripening Capacity Using a Latitude-Temperature Index (LTI). American Journal of Enology and Viticulture, 39(1), 19‑28.

Modified latitude factor from Kenny, G. J., & Shao, J. (1992). An assessment of a latitude-temperature index for predicting climate suitability for grapes in Europe. Journal of Horticultural Science, 67(2), 239‑246. https://doi.org/10.1080/00221589.1992.11516243

xclim.indices.liquid_precip_ratio(pr: xarray.DataArray, prsn: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None, thresh: str = '0 degC', freq: str = 'QS-DEC') xarray.DataArray[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 (str) – Threshold temperature under which precipitation is assumed to be solid.

  • freq (str) – Resampling frequency.

Returns

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

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.max_1day_precipitation_amount(pr: xarray.DataArray, freq: str = 'YS') xarray.DataArray[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.

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

>>> from xclim.indices import max_1day_precipitation_amount

# The following would compute for each grid cell the highest 1-day total # at an annual frequency: >>> pr = xr.open_dataset(path_to_pr_file).pr >>> rx1day = max_1day_precipitation_amount(pr, freq=”YS”)

xclim.indices.max_n_day_precipitation_amount(pr: xarray.DataArray, window: int = 1, freq: str = 'YS') xarray.DataArray[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.

Returns

xarray.DataArray, [length] – The highest cumulated n-period precipitation value at the given time frequency.

Examples

>>> from xclim.indices import max_n_day_precipitation_amount

# The following would compute for each grid cell the highest 5-day total precipitation #at an annual frequency: >>> pr = xr.open_dataset(path_to_pr_file).pr >>> out = max_n_day_precipitation_amount(pr, window=5, freq=”YS”)

xclim.indices.max_pr_intensity(pr: xarray.DataArray, window: int = 1, freq: str = 'YS') xarray.DataArray[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.

Returns

xarray.DataArray, [same units as pr] – The highest cumulated n-hour precipitation intensity at the given time frequency.

Examples

>>> from xclim.indices import max_pr_intensity

# The following would compute the maximum 6-hour precipitation intensity. # at an annual frequency: # TODO

xclim.indices.maximum_consecutive_dry_days(pr: xarray.DataArray, thresh: str = '1 mm/day', freq: str = 'YS') xarray.DataArray[source]

Maximum number of consecutive dry days.

Return the maximum number of consecutive days within the period where precipitation is below a certain threshold.

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

  • thresh (str) – Threshold precipitation on which to base evaluation.

  • freq (str) – Resampling frequency.

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 when the temperature 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.maximum_consecutive_frost_days(tasmin: xarray.DataArray, thresh: str = '0.0 degC', freq: str = 'AS-JUL') xarray.DataArray[source]

Maximum number of consecutive frost days (Tn < 0℃).

The maximum number of consecutive days within the period where the temperature is under a certain threshold (default: 0°C). WARNING: The default freq value is valid for the northern hemisphere.

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

  • thresh (str) – Threshold temperature.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – The maximum number of consecutive frost days (tasmin < threshold per period).

Notes

Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a daily minimum 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 when 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.maximum_consecutive_frost_free_days(tasmin: xarray.DataArray, thresh: str = '0 degC', freq: str = 'YS') xarray.DataArray[source]

Maximum number of consecutive frost free days (Tn >= 0℃).

Return the maximum number of consecutive days within the period where the minimum temperature is above or equal to a certain threshold.

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

  • thresh (str) – Threshold temperature.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – The maximum number of consecutive frost free days (tasmin >= threshold per period).

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 when 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.maximum_consecutive_tx_days(tasmax: xarray.DataArray, thresh: str = '25 degC', freq: str = 'YS') xarray.DataArray[source]

Maximum number of consecutive days with tasmax above a threshold (summer days).

Return the maximum number of consecutive days within the period where the maximum temperature is above a certain threshold.

Parameters
  • tasmax (xarray.DataArray) – Max daily temperature.

  • thresh (str) – Threshold temperature.

  • freq (str) – Resampling frequency.

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 when the temperature 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}) [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.maximum_consecutive_wet_days(pr: xarray.DataArray, thresh: str = '1 mm/day', freq: str = 'YS') xarray.DataArray[source]

Consecutive wet days.

Returns the maximum number of consecutive wet days.

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

  • thresh (str) – Threshold precipitation on which to base evaluation.

  • freq (str) – Resampling frequency.

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 when 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.melt_and_precip_max(snw: xarray.DataArray, pr: xarray.DataArray, window: int = 3, freq: str = 'AS-JUL') xarray.DataArray[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.

Returns

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

xclim.indices.multiday_temperature_swing(tasmin: xarray.DataArray, tasmax: xarray.DataArray, thresh_tasmin: str = '0 degC', thresh_tasmax: str = '0 degC', window: int = 1, op: str = 'mean', freq: str = 'YS') xarray.DataArray[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 (str) – The temperature threshold needed to trigger a freeze event.

  • thresh_tasmax (str) – 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.

  • freq (str) – Resampling frequency.

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.potential_evapotranspiration(tasmin: Optional[xarray.DataArray] = None, tasmax: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None, method: str = 'BR65', peta: Optional[float] = 0.00516409319477, petb: Optional[float] = 0.0874972822289) xarray.DataArray[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.

tasminxarray.DataArray

Minimum daily temperature.

tasmaxxarray.DataArray

Maximum daily temperature.

tasxarray.DataArray

Mean daily temperature.

method{“baierrobertson65”, “BR65”, “hargreaves85”, “HG85”, “thornthwaite48”, “TW48”, “mcguinnessbordne05”, “MB05”}

Which method to use, see notes.

petafloat

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

petbfloat

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

xarray.DataArray

Available methods are:

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

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

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

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

The McGuinness-Bordne [McGuinness1972] equation is:

\[PET[mm day^{-1}] = a *\]

rac{S_0}{lambda}T_a + b * rsc{S_0}{lambda}

where \(a\) and \(b\) are empirical parameters; \(S_0\) is the extraterrestrial radiation [MJ m-2 day-1]; \(\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 [Tanguy2018].

baierrobertson65

Baier, W., & Robertson, G. W. (1965). Estimation of latent evaporation from simple weather observations. Canadian journal of plant science, 45(3), 276-284.

hargreaves85

Hargreaves, G. H., & Samani, Z. A. (1985). Reference crop evapotranspiration from temperature. Applied engineering in agriculture, 1(2), 96-99.

tanguy2018(1,2)

Tanguy, M., Prudhomme, C., Smith, K., & Hannaford, J. (2018). Historical gridded reconstruction of potential evapotranspiration for the UK. Earth System Science Data, 10(2), 951-968.

McGuinness1972

McGuinness, J. L., & Bordne, E. F. (1972). A comparison of lysimeter-derived potential evapotranspiration with computed values (No. 1452). US Department of Agriculture.

thornthwaite48

Thornthwaite, C. W. (1948). An approach toward a rational classification of climate. Geographical review, 38(1), 55-94.

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

Accumulated total precipitation.

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.

Returns

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

xclim.indices.prcptot_warmcold_quarter(pr: xarray.DataArray, tas: xarray.DataArray, op: Optional[str] = None, freq: str = 'YS') xarray.DataArray[source]

ANUCLIM 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 are 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’ calculate for the warmest quarter ; ‘coldest’ calculate for the coldest quarter.

  • freq (str) – Resampling frequency.

Returns

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

Notes

According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.prcptot_wetdry_period(pr: xarray.DataArray, *, op: str, freq: str = 'YS') xarray.DataArray[source]

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

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’ calculate the wettest period ; ‘driest’ calculate the driest period.

  • freq (str) – Resampling frequency.

Returns

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

Notes

According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.prcptot_wetdry_quarter(pr: xarray.DataArray, op: Optional[str] = None, freq: str = 'YS') xarray.DataArray[source]

ANUCLIM 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 are 3 months.

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

  • op ({‘wettest’, ‘driest’}) – Operation to perform : ‘wettest’ calculate the wettest quarter ; ‘driest’ calculate the driest quarter.

  • freq (str) – Resampling frequency.

Returns

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

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')

Notes

According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.precip_accumulation(pr: xarray.DataArray, tas: Optional[xarray.DataArray] = None, phase: Optional[str] = None, thresh: str = '0 degC', freq: str = 'YS') xarray.DataArray[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 provided 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 (str) – Threshold of tas over which the precipication is assumed to be liquid rain.

  • freq (str) – Resampling frequency.

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, ie 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.precip_seasonality(pr: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

ANUCLIM 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.

Returns

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

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)

Notes

According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.qian_weighted_mean_average(tas: xarray.DataArray, dim: str = 'time') xarray.DataArray[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.

Returns

xr.DataArray – Binomial smoothed, five-day weighted mean average temperature.

Notes

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

Indice oririginally published in Qian, B., Zhang, X., Chen, K., Feng, Y., & O’Brien, T. (2009). Observed Long-Term Trends for Agroclimatic Conditions in Canada. Journal of Applied Meteorology and Climatology, 49(4), 604‑618. https://doi.org/10.1175/2009JAMC2275.1

Inspired by Bootsma, A., & Gameda and D.W. McKenney, S. (2005). Impacts of potential climate change on selected agroclimatic indices in Atlantic Canada. Canadian Journal of Soil Science, 85(2), 329‑343. https://doi.org/10.4141/S04-019

xclim.indices.rain_approximation(pr: xarray.DataArray, tas: xarray.DataArray, thresh: str = '0 degC', method: str = 'binary') xarray.DataArray[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 (str,) – Threshold temperature, used by method “binary”.

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

Returns

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

Notes

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

xclim.indices.rain_on_frozen_ground_days(pr: xarray.DataArray, tas: xarray.DataArray, thresh: str = '1 mm/d', freq: str = 'YS') xarray.DataArray[source]

Number of rain on frozen ground events.

Number of days with rain above a threshold after a series of seven 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 (str) – Precipitation threshold to consider a day as a rain event.

  • freq (str) – Resampling frequency.

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 ≥ 7\)

xclim.indices.rb_flashiness_index(q: xarray.DataArray, freq: str = 'YS') xarray.DataArray[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; [baker2004]).

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

  • freq (str) – Resampling frequency.

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

baker2004

Baker, D. B., Richards, R. P., Loftus, T. T., & Kramer, J. W. (2004). A New Flashiness Index: Characteristics and Applications to Midwestern Rivers and Streams1. JAWRA Journal of the American Water Resources Association, 40(2), 503‑522. https://doi.org/10.1111/j.1752-1688.2004.tb01046.x

xclim.indices.relative_humidity(tas: xarray.DataArray, tdps: Optional[xarray.DataArray] = None, huss: Optional[xarray.DataArray] = None, ps: Optional[xarray.DataArray] = None, ice_thresh: Optional[str] = None, method: str = 'sonntag90', invalid_values: str = 'clip') xarray.DataArray[source]

Relative humidity.

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

Parameters
  • tas (xr.DataArray) – Temperature array

  • tdps (xr.DataArray) – Dewpoint temperature, if specified, overrides huss and ps.

  • huss (xr.DataArray) – Specific humidity.

  • ps (xr.DataArray) – Air Pressure.

  • ice_thresh (str) – 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.

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 vapor 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 vapor, the relative humidity is computed as:

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

From [BohrenAlbrecht1998], formula taken from [Lawrence2005]. \(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 vapor 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

Lawrence2005

Lawrence, M.G. (2005). The Relationship between Relative Humidity and the Dewpoint Temperature in Moist Air: A Simple Conversion and Applications. Bull. Amer. Meteor. Soc., 86, 225–234, https://doi.org/10.1175/BAMS-86-2-225

BohrenAlbrecht1998

Craig F. Bohren, Bruce A. Albrecht. Atmospheric Thermodynamics. Oxford University Press, 1998.

xclim.indices.rprctot(pr: xarray.DataArray, prc: xarray.DataArray, thresh: str = '1.0 mm/day', freq: str = 'YS') xarray.DataArray[source]

Proportion of accumulated precipitation arising from convective processes.

Return the proportion of total accumulated precipitation due to convection on days with total precipitation exceeding a specified threshold during the given period.

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

  • prc (xarray.DataArray) – Daily convective precipitation.

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

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [dimensionless] – The proportion of the total precipitation accounted for by convective precipitation for each period.

xclim.indices.saturation_vapor_pressure(tas: xarray.DataArray, ice_thresh: Optional[str] = None, method: str = 'sonntag90') xarray.DataArray[source]

Saturation vapor pressure from temperature.

Parameters
  • tas (xr.DataArray) – Temperature array.

  • ice_thresh (str) – 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 ({“dewpoint”, “goffgratch46”, “sonntag90”, “tetens30”, “wmo08”}) – Which method to use, see notes.

Returns

xarray.DataArray, [Pa] – Saturation vapor 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 [goffgratch46], values and equation taken from [voemel].

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

  • “tetens30” or “TE30”, based on [tetens30], values and equation taken from [voemel].

  • “wmo08” or “WMO08”, taken from [wmo08].

References

goffgratch46

Goff, J. A., and S. Gratch (1946) Low-pressure properties of water from -160 to 212 °F, in Transactions of the American Society of Heating and Ventilating Engineers, pp 95-122, presented at the 52nd annual meeting of the American Society of Heating and Ventilating Engineers, New York, 1946.

sonntag90

Sonntag, D. (1990). Important new values of the physical constants of 1986, vapour pressure formulations based on the ITS-90, and psychrometer formulae. Zeitschrift für Meteorologie, 40(5), 340-344.

tetens30

Tetens, O. 1930. Über einige meteorologische Begriffe. Z. Geophys 6: 207-309.

voemel(1,2)

https://cires1.colorado.edu/~voemel/vp.html

wmo08

World Meteorological Organization. (2008). Guide to meteorological instruments and methods of observation. Geneva, Switzerland: World Meteorological Organization. https://www.weather.gov/media/epz/mesonet/CWOP-WMO8.pdf

xclim.indices.sea_ice_area(siconc: xarray.DataArray, areacello: xarray.DataArray, thresh: str = '15 pct') xarray.DataArray[source]

Total sea ice area.

Sea ice area measures the total sea ice covered area where sea ice concentration is above a 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 (str) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.

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

xclim.indices.sea_ice_extent(siconc: xarray.DataArray, areacello: xarray.DataArray, thresh: str = '15 pct') xarray.DataArray[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 threshold usually set to 15%.

Parameters
  • siconc (xarray.DataArray) – Sea ice concentration (area fraction).

  • areacello (xarray.DataArray) – Grid cell area.

  • thresh (str) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.

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

xclim.indices.sfcwind_2_uas_vas(sfcWind: xarray.DataArray, sfcWindfromdir: xarray.DataArray) Tuple[xarray.DataArray, xarray.DataArray][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 stands for North.

Returns

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

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

xclim.indices.snd_max_doy(snd: xarray.DataArray, freq: str = 'AS-JUL') xarray.DataArray[source]

Maximum snow depth day of year.

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.

Returns

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

xclim.indices.snow_cover_duration(snd: xarray.DataArray, thresh: str = '2 cm', freq: str = 'AS-JUL') xarray.DataArray[source]

Number of days with snow depth above a threshold.

Number of days where surface snow depth is greater or equal to given threshold. WARNING: The default freq is valid for the northern hemisphere.

Parameters
  • snd (xarray.DataArray) – Surface snow thickness.

  • thresh (str) – Threshold snow thickness.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days where snow depth is greater or equal to threshold.

xclim.indices.snow_depth(snd: xarray.DataArray, freq: str = 'YS') xarray.DataArray[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.

Returns

xarray.DataArray, [same units as snd] – The mean daily snow depth at the given time frequency

xclim.indices.snow_melt_we_max(snw: xarray.DataArray, window: int = 3, freq: str = 'AS-JUL') xarray.DataArray[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.

Returns

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

xclim.indices.snowfall_approximation(pr: xarray.DataArray, tas: xarray.DataArray, thresh: str = '0 degC', method: str = 'binary') xarray.DataArray[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 (str,) – Threshold temperature, used by method “binary”.

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

Returns

xarray.DataArray, [same units as pr] – Solid precipitation flux.

Notes

The following methods are available to approximate snowfall and are drawn from the Canadian Land Surface Scheme (CLASS, [Verseghy09]).

  • '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

Verseghy09

Diana Verseghy (2009), CLASS – The Canadian Land Surface Scheme (Version 3.4), Technical Documentation (Version 1.1), Environment Canada, Climate Research Division, Science and Technology Branch.

https://gitlab.com/cccma/classic/-/blob/master/src/atmosphericVarsCalc.f90

xclim.indices.snw_max(snw: xarray.DataArray, freq: str = 'AS-JUL') xarray.DataArray[source]

Maximum snow amount.

The maximum daily snow amount.

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

  • freq (str) – Resampling frequency.

Returns

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

xclim.indices.snw_max_doy(snw: xarray.DataArray, freq: str = 'AS-JUL') xarray.DataArray[source]

Maximum snow amount day of year.

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.

Returns

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

xclim.indices.specific_humidity(tas: xarray.DataArray, hurs: xarray.DataArray, ps: xarray.DataArray, ice_thresh: Optional[str] = None, method: str = 'sonntag90', invalid_values: Optional[str] = None) xarray.DataArray[source]

Specific humidity from temperature, relative humidity and pressure.

Parameters
  • tas (xr.DataArray) – Temperature array

  • hurs (xr.DataArray) – Relative Humidity.

  • ps (xr.DataArray) – Air Pressure.

  • ice_thresh (str) – 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.

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 vapor 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 the doc of 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})\]
xclim.indices.tas(tasmin: xarray.DataArray, tasmax: xarray.DataArray) xarray.DataArray[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

Returns

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

xclim.indices.temperature_seasonality(tas: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

ANUCLIM 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.

Returns

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

  • freq (str) – Resampling frequency.

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)

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 https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.tg10p(tas: xarray.DataArray, t10: xarray.DataArray, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[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.

  • t10 (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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

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
>>> t10 = percentile_doy(tas, per=10).sel(percentiles=10)
>>> cold_days = tg10p(tas, t10)
xclim.indices.tg90p(tas: xarray.DataArray, t90: xarray.DataArray, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[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.

  • t90 (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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

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
>>> t90 = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tg90p(tas, t90)
xclim.indices.tg_days_above(tas: xarray.DataArray, thresh: str = '10.0 degC', freq: str = 'YS')[source]

Number of days with tas above a threshold.

Number of days where daily mean temperature exceeds a threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days where tas > threshold.

Notes

Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TG_{ij} > Threshold [℃]\]
xclim.indices.tg_days_below(tas: xarray.DataArray, thresh: str = '10.0 degC', freq: str = 'YS')[source]

Number of days with tas below a threshold.

Number of days where daily mean temperature is below a threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days where tas < threshold.

Notes

Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TG_{ij} < Threshold [℃]\]
xclim.indices.tg_max(tas: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Highest mean temperature.

The maximum of daily mean temperature.

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

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [same units as tas] – Maximum of daily minimum 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.tg_mean(tas: xarray.DataArray, freq: str = 'YS') xarray.DataArray[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.

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, ie 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.tg_mean_warmcold_quarter(tas: xarray.DataArray, op: Optional[str] = None, freq: str = 'YS') xarray.DataArray[source]

ANUCLIM 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 3 months.

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

  • op (str {‘warmest’, ‘coldest’}) – Operation to perform: ‘warmest’ calculate the warmest quarter; ‘coldest’ calculate the coldest quarter.

  • freq (str) – Resampling frequency.

Returns

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

Examples

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

>>> import xclim.indices as xci
>>> t = xr.open_dataset(path_to_tas_file)
>>> t_warm_qrt = xci.tg_mean_warmcold_quarter(tas=t.tas, op='warmest')

Notes

According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.tg_mean_wetdry_quarter(tas: xarray.DataArray, pr: xarray.DataArray, op: Optional[str] = None, freq: str = 'YS') xarray.DataArray[source]

ANUCLIM 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 are 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’ calculate for the wettest quarter; ‘driest’ calculate for the driest quarter.

  • freq (str) – Resampling frequency.

Returns

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

Notes

According to the ANUCLIM user-guide https://fennerschool.anu.edu.au/files/anuclim61.pdf (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.

xclim.indices.tg_min(tas: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Lowest mean temperature.

Minimum of daily mean temperature.

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

  • freq (str) – Resampling frequency.

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.tn10p(tasmin: xarray.DataArray, t10: xarray.DataArray, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[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.

  • t10 (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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

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
>>> t10 = percentile_doy(tas, per=10).sel(percentiles=10)
>>> cold_days = tn10p(tas, t10)
xclim.indices.tn90p(tasmin: xarray.DataArray, t90: xarray.DataArray, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[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.

  • t90 (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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

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
>>> t90 = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tn90p(tas, t90)
xclim.indices.tn_days_above(tasmin: xarray.DataArray, thresh: str = '20.0 degC', freq: str = 'YS')[source]

Number of days with tasmin above a threshold (number of tropical nights).

Number of days where daily minimum temperature exceeds a threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days where tasmin > threshold.

Notes

Let \(TN_{ij}\) be the daily minimum temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} > Threshold [℃]\]
xclim.indices.tn_days_below(tasmin: xarray.DataArray, thresh: str = '-10.0 degC', freq: str = 'YS') xarray.DataArray[source]

Number of days with tasmin below a threshold.

Number of days where daily minimum temperature is below a threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days where tasmin < threshold.

Notes

Let \(TN_{ij}\) be the daily minimum temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} < Threshold [℃]\]
xclim.indices.tn_max(tasmin: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Highest minimum temperature.

The maximum of daily minimum temperature.

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

  • freq (str) – Resampling frequency.

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.tn_mean(tasmin: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Mean minimum temperature.

Mean of daily minimum temperature.

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

  • freq (str) – Resampling frequency.

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.tn_min(tasmin: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Lowest minimum temperature.

Minimum of daily minimum temperature.

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

  • freq (str) – Resampling frequency.

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.tropical_nights(tasmin: xarray.DataArray, thresh: str = '20.0 degC', freq: str = 'YS') xarray.DataArray[source]

Tropical nights.

The number of days with minimum daily temperature above threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days with minimum daily temperature above threshold.

Notes

Let \(TN_{ij}\) be the daily minimum temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} > Threshold [℃]\]

Warning

The tropical_nights indice is being deprecated in favour of tn_days_above with thresh=”20 degC” by default. The indicator reflects this change. This indice will be removed in a future version of xclim.

xclim.indices.tx10p(tasmax: xarray.DataArray, t10: xarray.DataArray, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[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.

  • t10 (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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

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
>>> t10 = percentile_doy(tas, per=10).sel(percentiles=10)
>>> cold_days = tx10p(tas, t10)
xclim.indices.tx90p(tasmax: xarray.DataArray, t90: xarray.DataArray, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[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.

  • t90 (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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

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
>>> t90 = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tx90p(tas, t90)
xclim.indices.tx_days_above(tasmax: xarray.DataArray, thresh: str = '25.0 degC', freq: str = 'YS') xarray.DataArray[source]

Number of days with tasmax above a threshold (number of summer days).

Number of days where daily maximum temperature exceeds a threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days where tasmax > threshold (number of summer days).

Notes

Let \(TX_{ij}\) be the daily maximum temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TX_{ij} > Threshold [℃]\]
xclim.indices.tx_days_below(tasmax: xarray.DataArray, thresh: str = '25.0 degC', freq: str = 'YS')[source]

Number of days with tmax below a threshold.

Number of days where daily maximum temperature is below a threshold.

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days where tasmin < threshold.

Notes

Let \(TN_{ij}\) be the daily minimum temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} < Threshold [℃]\]
xclim.indices.tx_max(tasmax: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Highest max temperature.

The maximum value of daily maximum temperature.

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

  • freq (str) – Resampling frequency.

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.tx_mean(tasmax: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Mean max temperature.

The mean of daily maximum temperature.

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

  • freq (str) – Resampling frequency.

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.tx_min(tasmax: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Lowest max temperature.

The minimum of daily maximum temperature.

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

  • freq (str) – Resampling frequency.

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.tx_tn_days_above(tasmin: xarray.DataArray, tasmax: xarray.DataArray, thresh_tasmin: str = '22 degC', thresh_tasmax: str = '30 degC', freq: str = 'YS') xarray.DataArray[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 (str) – Threshold temperature for tasmin on which to base evaluation.

  • thresh_tasmax (str) – Threshold temperature for tasmax on which to base evaluation.

  • freq (str) – Resampling frequency.

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.uas_vas_2_sfcwind(uas: xarray.DataArray, vas: xarray.DataArray, calm_wind_thresh: str = '0.5 m/s') Tuple[xarray.DataArray, xarray.DataArray][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 (str) – 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.

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°.

xclim.indices.warm_and_dry_days(tas: xarray.DataArray, tas_75: xarray.DataArray, pr: xarray.DataArray, pr_25: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Warm and dry days.

Returns the total number of days where “warm” and “Dry” conditions coincide.

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

  • tas_75 (xarray.DataArray) – Third quartile of daily mean temperature computed by month.

  • pr (xarray.DataArray) – Daily precipitation.

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

    Warning

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

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, – The total number of days where warm and dry conditions coincide.

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 [warm_dry_days].

References

warm_dry_days

Beniston, M. (2009). Trends in joint quantiles of temperature and precipitation in Europe since 1901 and projected for 2100. Geophysical Research Letters, 36(7). https://doi.org/10.1029/2008GL037119

xclim.indices.warm_and_wet_days(tas: xarray.DataArray, tas_75: xarray.DataArray, pr: xarray.DataArray, pr_75: xarray.DataArray, freq: str = 'YS') xarray.DataArray[source]

Warm and wet days.

Returns the total number of days where “warm” and “wet” conditions coincide.

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

  • tas_75 (xarray.DataArray) – Third quartile of daily mean temperature computed by month.

  • pr (xarray.DataArray) – Daily precipitation.

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

    Warning

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

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, – The total number of days where warm and wet conditions coincide.

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 [warm_wet_days].

References

warm_wet_days

Beniston, M. (2009). Trends in joint quantiles of temperature and precipitation in Europe since 1901 and projected for 2100. Geophysical Research Letters, 36(7). https://doi.org/10.1029/2008GL037119

xclim.indices.warm_day_frequency(tasmax: xarray.DataArray, thresh: str = '30 degC', freq: str = 'YS') xarray.DataArray[source]

Frequency of extreme warm days.

Return the number of days with tasmax > thresh per period

Parameters
  • tasmax (xarray.DataArray) – Mean daily temperature.

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days with tasmax > threshold per period.

Notes

Let \(TX_{ij}\) be the daily maximum temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} > Threshold [℃]\]
xclim.indices.warm_night_frequency(tasmin: xarray.DataArray, thresh: str = '22 degC', freq: str = 'YS') xarray.DataArray[source]

Frequency of extreme warm nights.

Return the number of days with tasmin > thresh per period

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

  • thresh (str) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray, [time] – Number of days with tasmin > threshold per period.

xclim.indices.warm_spell_duration_index(tasmax: xarray.DataArray, tx90: xarray.DataArray, window: int = 6, freq: str = 'YS', bootstrap: bool = False) xarray.DataArray[source]

Warm spell duration index.

Number of days inside spells of a minimum number of consecutive days where 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.

  • tx90 (xarray.DataArray) – 90th percentile of daily maximum temperature.

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

  • 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. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

Returns

xarray.DataArray, [time] – Warm spell duration index.

Examples

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

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import warm_spell_duration_index
>>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax.isel(lat=0, lon=0)
>>> tx90 = percentile_doy(tasmax, per=90).sel(percentiles=90)
>>> warm_spell_duration_index(tasmax, tx90)

References

From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI). Used in Alexander, L. V., et al. (2006), Global observed changes in daily climate extremes of temperature and precipitation, J. Geophys. Res., 111, D05109, doi: 10.1029/2005JD006290.

xclim.indices.water_budget(pr: xarray.DataArray, tasmin: Optional[xarray.DataArray] = None, tasmax: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None, method: str = 'BR65') xarray.DataArray[source]

Precipitation minus potential evapotranspiration.

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

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

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

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

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

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

Notes

Available methods are listed in the description of xclim.indicators.atmos.potential_evapotranspiration.

Returns

xarray.DataArray, – Precipitation minus potential evapotranspiration.

xclim.indices.wetdays(pr: xarray.DataArray, thresh: str = '1.0 mm/day', freq: str = 'YS') xarray.DataArray[source]

Wet days.

Return the total number of days during period with precipitation over threshold.

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

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

  • freq (str) – Resampling frequency.

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, ie 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.wetdays_prop(pr: xarray.DataArray, thresh: str = '1.0 mm/day', freq: str = 'YS') xarray.DataArray[source]

Proportion of wet days.

Return the proportion of days during period with precipitation over threshold.

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

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

  • freq (str) – Resampling frequency.

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, ie 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.wind_chill_index(tas: xarray.DataArray, sfcWind: xarray.DataArray, method: str = 'CAN', mask_invalid: bool = 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 ([MVSZ15]), 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.

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. 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).

References

MVSZ15

Éva Mekis, Lucie A. Vincent, Mark W. Shephard & Xuebin Zhang (2015) Observed Trends in Severe Weather Conditions Based on Humidex, Wind Chill, and Heavy Rainfall Events in Canada for 1953–2012, Atmosphere-Ocean, 53:4, 383-397, DOI: 10.1080/07055900.2015.1086970

NWS

Wind Chill Questions, Cold Resources, National Weather Service, retrieved 25-05-21. https://www.weather.gov/safety/cold-faqs

xclim.indices.windy_days(sfcWind: xarray.DataArray, thresh: str = '10.8 m s-1', freq: str = 'MS') xarray.DataArray[source]

Windy days.

The number of days with average near-surface wind speed above threshold.

Parameters
  • sfcWind (xarray.DataArray) – Daily average near-surface wind speed.

  • thresh (str) – Threshold average near-surface wind speed on which to base evaluation.

  • freq (str) – Resampling frequency.

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.winter_rain_ratio(*, pr: xarray.DataArray, prsn: Optional[xarray.DataArray] = None, tas: Optional[xarray.DataArray] = None, freq: str = 'QS-DEC') xarray.DataArray[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.

Returns

xarray.DataArray – Ratio of rainfall to total precipitation during winter months (DJF).

xclim.indices.winter_storm(snd: xarray.DataArray, thresh: str = '25 cm', freq: str = 'AS-JUL') xarray.DataArray[source]

Days with snowfall over threshold.

Number of days with snowfall accumulation greater or equal to threshold.

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

  • thresh (str) – Threshold on snowfall accumulation require to label an event a winter storm.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray – Number of days per period identified as winter storms.

Notes

Snowfall accumulation is estimated by the change in snow depth.

Indices submodules

Fire Weather Indices Submodule

This submodule defines the xclim.indices.fire_season(), xclim.indices.drought_code() and xclim.indices.fire_weather_indexes() indices, which are used by the eponym indicators. Users should read this module’s documentation and the one of fire_weather_ufunc.

First adapted from Matlab code CalcFWITimeSeriesWithStartup.m from GFWED made for using MERRA2 data, which was a translation of FWI.vba of the Canadian Fire Weather Index system. Then, updated and synchronized with the R code of the cffdrs package. When given the correct parameters, the current code has an error below 3% when compared with the [GFWED] data.

Parts of the code and of the documentation in this submodule are directly taken from [cffdrs] which was published with the GPL-2 license.

Fire season

Fire weather indexes are iteratively computed, each day’s value depending on the previous day indexes. Additionally and optionally, the codes are “shut down” (set to NaN) in winter. There are a few ways of computing this shut down and the subsequent spring start-up. The fire_season function allows for full control of that, replicating the fireSeason method in the R package. It produces a mask to be given a season_mask in the indicators. However, the fire_weather_ufunc and the indicators also accept a season_method parameter so the fire season can be computed inside the iterator. Passing season_method=None switches to an “always on” mode replicating the fwi method of the R package.

The fire season determination is based on three consecutive daily maximum temperature thresholds ([WF93] , [LA08]). A “GFWED” method is also implemented. There, the 12h LST temperature is used instead of the daily maximum. The current implementation is slightly different from the description in [GFWED], but it replicates the Matlab code when temp_start_thresh and temp_end_thresh are both set to 6 degC. In xclim, the number of consecutive days, the start and end temperature thresholds and the snow depth threshold can all be modified.

Overwintering

Additionnaly, overwintering of the drought code is also directly implemented in fire_weather_ufunc(). The last drought_code of the season is kept in “winter” (where the fire season mask is False) and the precipitation is accumulated until the start of the next season. The first drought code is computed as a function of these instead of using the default DCStart value. Parameters to _overwintering_drought_code() are listed below. The code for the overwintering is based on [ME19].

Finally, a mechanism for dry spring starts is implemented. For now, it is slightly different from what the GFWED, uses, but seems to agree with the state of the science of the CFS. When activated, the drought code and Duff-moisture codes are started in spring with a value that is function of the number of days since the last significative precipitation event. The conventionnal start value increased by that number of days times a “dry start” factor. Parameters are controlled in the call of the indices and fire_weather_ufunc(). Overwintering of the drought code overrides this mechanism if both are activated. GFWED use a more complex approach with an added check on the previous day’s snow cover for determining “dry” points. Moreover, there, the start values are only the multiplication of a factor to the number of dry days, the conventionnal

Examples

The current litterature seems to agree that climate-oriented series of the fire weather indexes should be computed using only the longest fire season of each year and activatting the overwintering of the drought code and the “dry start” for the duff-moisture code. The following example uses reasonable parameters when computing over all of Canada.

Note: here the example snippets use the _indices_ defined in this very module, but we always recommend using the _indicators_ defined in the xc.atmos module.

>>> ds = open_dataset("ERA5/daily_surface_cancities_1990-1993.nc")
>>> ds = ds.assign(
        hurs=xclim.atmos.relative_humidity_from_dewpoint(ds=ds),
        tas=xclim.core.units.convert_units_to(ds.tas, "degC"),
        pr=xclim.core.units.convert_units_to(ds.pr, "mm/d"),
        sfcWind=xclim.atmos.wind_speed_from_vector(ds=ds)[0]
    )
>>> season_mask = fire_season(
        tas=ds.tas,
        method="WF93",
        freq="YS",
        # Parameters below are at their default values, but listed here for explicitness.
        temp_start_thresh="12 degC",
        temp_end_thresh="5 degC",
        temp_condition_days=3
    )
>>> out_fwi = fire_weather_indexes(
        tas=ds.tas,
        pr=ds.pr,
        hurs=ds.hurs,
        sfcWind=ds.sfcWind,
        lat=ds.lat,
        season_mask=season_mask,
        overwintering=True,
        dry_start="CFS",
        prec_thresh="1.5 mm/d",
        dmc_dry_factor=1.2,
        # Parameters below are at their default values, but listed here for explicitness.
        carry_over_fraction=0.75,
        wetting_efficiency_fraction=0.75,
        dc_start=15,
        dmc_start=6,
        ffmc_start=85
    )

Similarly, the next lines calculate the fire weather indexes, but according to the parameters and options used in NASA’s GFWED datasets. Here, no need to split the fire season mask from the rest of the computation as _all_ seasons are used, even the very short shoulder seasons.

>>> ds = open_dataset("FWI/GFWED_sample_2017.nc")
>>> out_fwi = fire_weather_indexes(
        tas=ds.tas,
        pr=ds.prbc,
        snd=ds.snow_depth,
        hurs=ds.rh,
        sfcWind=ds.sfcwind,
        lat=ds.lat,
        season_method="GFWED",
        overwintering=False,
        dry_start="GFWED",
        temp_start_thresh="6 degC",
        temp_end_thresh="6 degC",
        # Parameters below are at their default values, but listed here for explicitness.
        temp_condition_days=3,
        snow_condition_days=3,
        dc_start=15,
        dmc_start=6,
        ffmc_start=85,
        dmc_dry_factor=2
    )

References

Codes:

Updated source code for calculating fire danger indexes in the Canadian Forest Fire Weather Index System, Y. Wang, K.R. Anderson, and R.M. Suddaby, INFORMATION REPORT NOR-X-424, 2015.

cffdrs

Cantin, A., Wang, X., Parisien M-A., Wotton, M., Anderson, K., Moore, B., Schiks, T., Flannigan, M., Canadian Forest Fire Danger Rating System, R package, CRAN, https://cran.r-project.org/package=cffdrs

https://cwfis.cfs.nrcan.gc.ca/background/dsm/fwi

Matlab code of the GFWED obtained through personal communication.

Fire season determination methods:

WF93

Wotton, B.M. and Flannigan, M.D. (1993). Length of the fire season in a changing climate. ForestryChronicle, 69, 187-192.

LA08

Lawson B.D. and Armitage O.B. 2008. Weather Guide for the Canadian Forest Fire Danger RatingSystem. Natural Resources Canada, Canadian Forest Service, Northern Forestry Centre, Edmonton,Alberta. 84 p.http://cfs.nrcan.gc.ca/pubwarehouse/pdfs/29152.pdf

GFWED(1,2)

Field, R. D., Spessa, A. C., Aziz, N. A., Camia, A., Cantin, A., Carr, R., de Groot, W. J., Dowdy, A. J., Flannigan, M. D., Manomaiphiboon, K., Pappenberger, F., Tanpipat, V., and Wang, X. (2015) Development of a Global Fire Weather Database, Nat. Hazards Earth Syst. Sci., 15, 1407–1423, https://doi.org/10.5194/nhess-15-1407-2015

Drought Code overwintering:

VW85

Van Wagner, C.E. 1985. Drought, timelag and fire danger rating. Pages 178-185 in L.R. Donoghueand R.E. Martin, eds. Proc. 8th Conf. Fire For. Meteorol., 29 Apr.-3 May 1985, Detroit, MI. Soc.Am. For., Bethesda, MD.http://cfs.nrcan.gc.ca/pubwarehouse/pdfs/23550.pdf

ME19

McElhinny, M., Beckers, J. F., Hanes, C., Flannigan, M., and Jain, P.: A high-resolution reanalysis of global fire weather from 1979 to 2018 – overwintering the Drought Code, Earth Syst. Sci. Data, 12, 1823–1833, https://doi.org/10.5194/essd-12-1823-2020, 2020.

xclim.indices.fwi.drought_code(tas: xarray.DataArray, pr: xarray.DataArray, lat: xarray.DataArray, snd: Optional[xarray.DataArray] = None, dc0: Optional[xarray.DataArray] = None, season_mask: Optional[xarray.DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]

Drought code (FWI component).

The drought code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of organic layers.

Parameters
  • tas (xr.DataArray) – Noon temperature.

  • pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.

  • lat (xr.DataArray) – Latitude coordinate

  • snd (xr.DataArray) – Noon snow depth.

  • dc0 (xr.DataArray) – Initial values of the drought code.

  • season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.

  • season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fwi function. Ignored if season_mask is given.

  • overwintering (bool) – Whether to activate DC overwintering or not. If True, either season_method or season_mask must be given.

  • dry_start ({None, “CFS”, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism and which method to use. , see fire_weather_ufunc().

  • initial_start_up (bool) – If True (default), grid points where the fire season is active on the first timestep go through a start_up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.

  • params – Any other keyword parameters as defined in xclim.indices.fwi.fire_weather_ufunc and in default_params.

Returns

xr.DataArray, [dimensionless] – Drought code

Notes

See https://cwfis.cfs.nrcan.gc.ca/background/dsm/fwi, the module’s doc and doc of fire_weather_ufunc() for more information.

References

Updated source code for calculating fire danger indexes in the Canadian Forest Fire Weather Index System, Y. Wang, K.R. Anderson, and R.M. Suddaby, INFORMATION REPORT NOR-X-424, 2015.

xclim.indices.fwi.fire_season(tas: xarray.DataArray, snd: Optional[xarray.DataArray] = None, method: str = 'WF93', freq: Optional[str] = None, temp_start_thresh: str = '12 degC', temp_end_thresh: str = '5 degC', temp_condition_days: int = 3, snow_condition_days: int = 3, snow_thresh: str = '0.01 m')[source]

Fire season mask.

Binary mask of the active fire season, defined by conditions on consecutive daily temperatures and, optionally, snow depths.

Parameters
  • tas (xr.DataArray) – Daily surface temperature, cffdrs recommends using maximum daily temperature.

  • snd (xr.DataArray, optional) – Snow depth, used with method == ‘LA08’.

  • method ({“WF93”, “LA08”, “GFWED”}) – Which method to use. “LA08” and “GFWED” need the snow depth.

  • freq (str, optional) – If given only the longest fire season for each period defined by this frequency, Every “seasons” are returned if None, including the short shoulder seasons.

  • temp_start_thresh (str) – Minimal temperature needed to start the season.

  • temp_end_thresh (str) – Maximal temperature needed to end the season.

  • temp_condition_days (int) – Number of days with temperature above or below the thresholds to trigger a start or an end of the fire season.

  • snow_condition_days (int) – Parameters for the fire season determination. See fire_season(). Temperature is in degC, snow in m. The snow_thresh parameters is also used when dry_start is set to “GFWED”.

  • snow_thresh (str) – Minimal snow depth level to end a fire season, only used with method “LA08”.

Returns

fire_season (xr.DataArray) – Fire season mask

References

Wotton, B.M. and Flannigan, M.D. (1993). Length of the fire season in a changing climate. ForestryChronicle, 69, 187-192. Lawson, B.D. and O.B. Armitage. 2008. Weather guide for the Canadian Forest Fire Danger Rating System. NRCAN, CFS, Edmonton, AB

xclim.indices.fwi.fire_weather_indexes(tas: xarray.DataArray, pr: xarray.DataArray, sfcWind: xarray.DataArray, hurs: xarray.DataArray, lat: xarray.DataArray, snd: Optional[xarray.DataArray] = None, ffmc0: Optional[xarray.DataArray] = None, dmc0: Optional[xarray.DataArray] = None, dc0: Optional[xarray.DataArray] = None, season_mask: Optional[xarray.DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]

Fire weather indexes.

Computes the 6 fire weather indexes as defined by the Canadian Forest Service: the Drought Code, the Duff-Moisture Code, the Fine Fuel Moisture Code, the Initial Spread Index, the Build Up Index and the Fire Weather Index.

Parameters
  • tas (xr.DataArray) – Noon temperature.

  • pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.

  • sfcWind (xr.DataArray) – Noon wind speed.

  • hurs (xr.DataArray) – Noon relative humidity.

  • lat (xr.DataArray) – Latitude coordinate

  • snd (xr.DataArray) – Noon snow depth, only used if season_method=’LA08’ is passed.

  • ffmc0 (xr.DataArray) – Initial values of the fine fuel moisture code.

  • dmc0 (xr.DataArray) – Initial values of the Duff moisture code.

  • dc0 (xr.DataArray) – Initial values of the drought code.

  • season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.

  • season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fwi function. Ignored if season_mask is given.

  • overwintering (bool) – Whether to activate DC overwintering or not. If True, either season_method or season_mask must be given.

  • dry_start ({None, ‘CFS’, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism or not, see fire_weather_ufunc().

  • initial_start_up (bool) – If True (default), gridpoints where the fire season is active on the first timestep go through a start_up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.

  • params – Any other keyword parameters as defined in fire_weather_ufunc() and in default_params.

Returns

  • DC (xr.DataArray, [dimensionless])

  • DMC (xr.DataArray, [dimensionless])

  • FFMC (xr.DataArray, [dimensionless])

  • ISI (xr.DataArray, [dimensionless])

  • BUI (xr.DataArray, [dimensionless])

  • FWI (xr.DataArray, [dimensionless])

Notes

See https://cwfis.cfs.nrcan.gc.ca/background/dsm/fwi, the module’s doc and doc of fire_weather_ufunc() for more information.

References

Updated source code for calculating fire danger indexes in the Canadian Forest Fire Weather Index System, Y. Wang, K.R. Anderson, and R.M. Suddaby, INFORMATION REPORT NOR-X-424, 2015.

xclim.indices.fwi.fire_weather_ufunc(*, tas: xarray.DataArray, pr: xarray.DataArray, hurs: Optional[xarray.DataArray] = None, sfcWind: Optional[xarray.DataArray] = None, snd: Optional[xarray.DataArray] = None, lat: Optional[xarray.DataArray] = None, dc0: Optional[xarray.DataArray] = None, dmc0: Optional[xarray.DataArray] = None, ffmc0: Optional[xarray.DataArray] = None, winter_pr: Optional[xarray.DataArray] = None, season_mask: Optional[xarray.DataArray] = None, start_dates: Optional[Union[str, xarray.DataArray]] = None, indexes: Optional[Sequence[str]] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]

Fire Weather Indexes computation using xarray’s apply_ufunc.

No unit handling. Meant to be used by power users only. Please prefer using the DC and FWI indicators or the drought_code() and fire_weather_indexes() indices defined in the same submodule.

Dask arrays must have only one chunk along the “time” dimension. User can control which indexes are computed with the indexes argument.

Parameters
  • tas (xr.DataArray) – Noon surface temperature in °C

  • pr (xr.DataArray) – Rainfall over previous 24h, at noon in mm/day

  • hurs (xr.DataArray, optional) – Noon surface relative humidity in %, not needed for DC

  • sfcWind (xr.DataArray, optional) – Noon surface wind speed in km/h, not needed for DC, DMC or BUI

  • snd (xr.DataArray, optional) – Noon snow depth in m, only needed if season_method is “LA08”

  • lat (xr.DataArray, optional) – Latitude in °N, not needed for FFMC or ISI

  • dc0 (xr.DataArray, optional) – Previous DC map, see Notes. Defaults to NaN.

  • dmc0 (xr.DataArray, optional) – Previous DMC map, see Notes. Defaults to NaN.

  • ffmc0 (xr.DataArray, optional) – Previous FFMC map, see Notes. Defaults to NaN.

  • winter_pr (xr.DataArray, optional) – Accumulated precipitation since the end of the last season, until the beginning of the current data, mm/day. Only used if overwintering is True, defaults to 0.

  • season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.

  • indexes (Sequence[str], optional) – Which indexes to compute. If intermediate indexes are needed, they will be added to the list and output.

  • season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fwi function. Ignored if season_mask is given.

  • overwintering (bool) – Whether to activate DC overwintering or not. If True, either season_method or season_mask must be given.

  • dry_start ({None, ‘CFS’, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism and which method to use. See Notes. If overwintering is activated, it overrides this parameter : only DMC is handled through the dry start mechanism.

  • initial_start_up (bool) – If True (default), grid points where the fire season is active on the first timestep go through a start-up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.

  • carry_over_fraction (float)

  • wetting_efficiency_fraction (float) – Drought code overwintering parameters, see overwintering_drought_code().

  • temp_start_thresh (float) – Starting temperature threshold.

  • temp_end_thresh (float) – Ending temperature threshold.

  • temp_condition_days (int) – The number of days’ temperature condition to consider.

  • snow_thresh (float)

  • snow_condition_days (int) – Parameters for the fire season determination. See fire_season(). Temperature is in degC, snow in m. The snow_thresh parameters is also used when dry_start is set to “GFWED”, see Notes.

  • dc_start (float)

  • dmc_start (float)

  • ffmc_start (float) – Default starting values for the three base codes.

  • prec_thresh (float) – If the “dry start” is activated, this is the “wet” day precipitation threshold, see Notes. In mm/d.

  • dc_dry_factor (float) – DC’s start-up values for the “dry start” mechanism, see Notes.

  • dmc_dry_factor (float) – DMC’s start-up values for the “dry start” mechanism, see Notes.

  • snow_cover_days (int)

  • snow_min_cover_frac (float)

  • snow_min_mean_depth (float) – Additional parameters for GFWED’s version of the “dry start” mechanism. See Notes. Snow depth is in m.

Returns

dict[str, xarray.DataArray] – Dictionary containing the computed indexes as prescribed in indexes, including the intermediate ones needed, even if they were not explicitly listed in indexes. When overwintering is activated, winter_pr is added. If season_method is not None and season_mask was not given, season_mask is computed on-the-fly and added to the output.

Notes

When overwintering is activated, the argument dc0 is understood as last season’s last DC map and will be used to compute the overwintered DC at the beginning of the next season.

If overwintering is not activated and neither is fire season computation (season_method and season_mask are None), dc0, dmc0 and ffmc0 are understood as the codes on the day before the first day of FWI computation. They will default to their respective start values. This “always on” mode replicates the R “fwi” code.

If the “dry start” mechanism is set to “CFS” (but there is no overwintering), the arguments dc0 and dmc0 are understood as the potential start-up values from last season. With \(DC_{start}\) the conventional start-up value, \(F_{dry-dc}\) the dc_dry_factor and \(N_{dry}\) the number of days since the last significative precipitation event, the start-up value \(DC_0\) is computed as:

\[DC_0 = DC_{start} + F_{dry-dc} * N_{dry}\]

The last significative precipitation event is the last day where precipitation was greater or equal to “prec_thresh”. The same happens for the DMC, with corresponding parameters. If overwintering is activated, this mechanism is only used for the DMC.

Alternatively, dry_start can be set to “GFWED”. In this mode, the start-up values are computed as:

\[DC_0 = F_{dry-dc} * N_{dry}\]

Where the current day is also included in the determination of \(N_{dry}\) (\(DC_0\) can thus be 0). Finally, for this “GFWED” mode, if snow cover is provided, a second check is performed: the dry start procedure is skipped and conventional start-up values are used for cells where the snow cover of the last snow_cover_days was above snow_thresh for at least snow_cover_days * snow_min_cover_frac days and where the mean snow cover over the same period was greater of equal to snow_min_mean_depth.

xclim.indices.fwi.overwintering_drought_code(last_dc: xarray.DataArray, winter_pr: xarray.DataArray, carry_over_fraction: Union[xarray.DataArray, float] = 0.75, wetting_efficiency_fraction: Union[xarray.DataArray, float] = 0.75, min_dc: Union[xarray.DataArray, float] = 15) xarray.DataArray[source]

Compute the season-starting drought code based on the previous season’s last drought code and the total winter precipitation.

This method replicates the “wDC” method of the [cffdrs] R package, with an added control on the “minimum” DC.

Parameters
  • last_dc (xr.DataArray) – The previous season’s last drought code.

  • winter_pr (xr.DataArray) – The accumulated precipitation since the end of the fire season.

  • carry_over_fraction (xr.DataArray or float) – Carry-over fraction of last fall’s moisture

  • wetting_efficiency_fraction (xr.DataArray or float) – Effectiveness of winter precipitation in recharging moisture reserves in spring

  • min_dc (xr.DataArray or float) – Minimum drought code starting value.

Returns

wDC (xr.DataArray) – Overwintered drought code.

Notes

Details taken from the R package documentation ([cffdrs]): Of the three fuel moisture codes (i.e. FFMC, DMC and DC) making up the FWI System, only the DC needs to be considered in terms of its values carrying over from one fire season to the next. In Canada both the FFMC and the DMC are assumed to reach moisture saturation from overwinter precipitation at or before spring melt; this is a reasonable assumption and any error in these assumed starting conditions quickly disappears. If snowfall (or other overwinter precipitation) is not large enough however, the fuel layer tracked by the Drought Code may not fully reach saturation after spring snow melt; because of the long response time in this fuel layer (53 days in standard conditions) a large error in this spring starting condition can affect the DC for a significant portion of the fire season. In areas where overwinter precipitation is 200 mm or more, full moisture recharge occurs and DC overwintering is usually unnecessary. More discussion of overwintering and fuel drying time lag can be found in [LA08] and [VW85].

Carry-over fraction of last fall’s moisture:
  • 1.0, Daily DC calculated up to 1 November; continuous snow cover, or freeze-up, whichever comes first

  • 0.75, Daily DC calculations stopped before any of the above conditions met or the area is subject to occasional winter chinook conditions, leaving the ground bare and subject to moisture depletion

  • 0.5, Forested areas subject to long periods in fall or winter that favor depletion of soil moisture

Effectiveness of winter precipitation in recharging moisture reserves in spring:
  • 0.9, Poorly drained, boggy sites with deep organic layers

  • 0.75, Deep ground frost does not occur until late fall, if at all; moderately drained sites that allow infiltration of most of the melting snowpack

  • 0.5, Chinook-prone areas and areas subject to early and deep ground frost; well-drained soils favoring rapid percolation or topography favoring rapid runoff before melting of ground frost

Source: [LA08] - Table 9.

References

cffdrs

Cantin, A., Wang, X., Parisien M-A., Wotton, M., Anderson, K., Moore, B., Schiks, T., Flannigan, M., Canadian Forest Fire Danger Rating System, R package, CRAN. https://cran.r-project.org/package=cffdrs

LA08

Lawson B.D. and Armitage O.B. 2008. Weather Guide for the Canadian Forest Fire Danger RatingSystem. Natural Resources Canada, Canadian Forest Service, Northern Forestry Centre, Edmonton,Alberta. 84 p. http://cfs.nrcan.gc.ca/pubwarehouse/pdfs/29152.pdf

VW85

Van Wagner, C.E. 1985. Drought, timelag and fire danger rating. Pages 178-185 in L.R. Donoghueand R.E. Martin, eds. Proc. 8th Conf. Fire For. Meteorol., 29 Apr.-3 May 1985, Detroit, MI. Soc.Am. For., Bethesda, MD. http://cfs.nrcan.gc.ca/pubwarehouse/pdfs/23550.pdf

Generic indices submodule

Helper functions for common generic actions done in the computation of indices.

xclim.indices.generic.aggregate_between_dates(data: xarray.DataArray, start: Union[xarray.DataArray, DayOfYearStr], end: Union[xarray.DataArray, DayOfYearStr], op: str = 'sum', freq: Optional[str] = None) xarray.DataArray[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) – Resampling frequency.

Returns

xarray.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.compare(da: xarray.DataArray, op: str, thresh: Union[float, int]) xarray.DataArray[source]

Compare a dataArray to a threshold using given operator.

Parameters
  • da (xr.DataArray) – Input data.

  • op ({“>”, “<”, “>=”, “<=”, “gt”, “lt”, “ge”, “le”}) – Logical operator {>, <, >=, <=, gt, lt, ge, le }. e.g. arr > thresh.

  • thresh (Union[float, int]) – Threshold value.

Returns

xr.DataArray – Boolean mask of the comparison.

xclim.indices.generic.count_level_crossings(low_data: xarray.DataArray, high_data: xarray.DataArray, threshold: str, freq: str) xarray.DataArray[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 (str) – Quantity.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray

xclim.indices.generic.count_occurrences(data: xarray.DataArray, threshold: str, condition: str, freq: str) xarray.DataArray[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)

  • threshold (str) – Quantity.

  • condition ({“>”, “<”, “>=”, “<=”, “==”, “!=”}) – Operator.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray

xclim.indices.generic.day_lengths(dates: xarray.DataArray, lat: xarray.DataArray, obliquity: float = - 0.4091, summer_solstice: DayOfYearStr = '06-21', start_date: Optional[Union[xarray.DataArray, DayOfYearStr]] = None, end_date: Optional[Union[xarray.DataArray, DayOfYearStr]] = None, freq: str = 'YS') xarray.DataArray[source]

Day-lengths according to latitude, obliquity, and day of year.

Parameters
  • dates (xr.DataArray)

  • lat (xarray.DataArray) – Latitude coordinate.

  • obliquity (float) – Obliquity of the elliptic (radians). Default: -0.4091.

  • summer_solstice (DayOfYearStr) – Date of summer solstice in northern hemisphere. Used for approximating solar julian dates.

  • start_date (xarray.DataArray or DayOfYearStr, optional) – Start date to consider for calculating mean day lengths. Default: None.

  • end_date (xarray.DataArray or DayOfYearStr, optional) – End date to consider for calculating mean day lengths. Default: None.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray – If start and end date provided, returns total sum of daylight-hour between dates at provided frequency. If no start and end date provided, returns day-length in hours per individual day.

Notes

Daylight-hours are dependent on latitude, \(lat\), the Julian day (solar day) from the summer solstice in the Northern hemisphere, \(Jday\), and the axial tilt \(Axis\), therefore day-length at any latitude for a given date on Earth, \(dayLength_{lat_{Jday}}\), for a given year in days, \(Year\), can be approximated as follows:

\[dayLength_{lat_{Jday}} = f({lat}, {Jday}) = \frac{\arccos(1-m_{lat_{Jday}})}{\pi} * 24\]

Where:

\[m_{lat_{Jday}} = f({lat}, {Jday}) = 1 - \tan({Lat}) * \tan \left({Axis}*\cos\left[\frac{2*\pi*{Jday}}{||{Year}||} \right] \right)\]

The total sum of daylight hours for a given period between two days (\({Jday} = 0\) -> \(N\)) within a solar year then is:

\[\sum({SeasonDayLength_{lat}}) = \sum_{Jday=1}^{N} dayLength_{lat_{Jday}}\]

References

Modified day-length equations for Huglin heliothermal index published in Hall, A., & Jones, G. V. (2010). Spatial analysis of climate in winegrape-growing regions in Australia. Australian Journal of Grape and Wine Research, 16(3), 389‑404. https://doi.org/10.1111/j.1755-0238.2010.00100.x

Examples available from Glarner, 2006 (http://www.gandraxa.com/length_of_day.xml).

xclim.indices.generic.default_freq(**indexer) str[source]

Return the default frequency.

xclim.indices.generic.degree_days(tas: xarray.DataArray, thresh: str, condition: str) xarray.DataArray[source]

Calculate the degree days below/above the temperature threshold.

Parameters
  • tas (xr.DataArray) – Mean daily temperature.

  • thresh (str) – The temperature threshold.

  • condition ({“<”, “>”}) – Operator.

Returns

xarray.DataArray

xclim.indices.generic.diurnal_temperature_range(low_data: xarray.DataArray, high_data: xarray.DataArray, reducer: str, freq: str) xarray.DataArray[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.

Returns

xarray.DataArray

xclim.indices.generic.domain_count(da: xarray.DataArray, low: float, high: float, freq: str) xarray.DataArray[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
Returns

xr.DataArray – The number of days where value is within [low, high] for each period.

xclim.indices.generic.doymax(da: xarray.DataArray) xarray.DataArray[source]

Return the day of year of the maximum value.

xclim.indices.generic.doymin(da: xarray.DataArray) xarray.DataArray[source]

Return the day of year of the minimum value.

xclim.indices.generic.get_daily_events(da: xarray.DataArray, da_value: float, operator: str) xarray.DataArray[source]

Return a 0/1 mask when a condition is True or False.

Parameters
  • da (xr.DataArray)

  • da_value (float)

  • operator ({“>”, “<”, “>=”, “<=”, “gt”, “lt”, “ge”, “le”}) – Logical operator {>, <, >=, <=, gt, lt, ge, le}. e.g. arr > thresh.

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

Returns

xr.DataArray

xclim.indices.generic.get_op(op: str)[source]

Get python’s comparing function according to its name of representation.

Accepted op string are keys and values of xclim.indices.generic.binary_ops.

xclim.indices.generic.interday_diurnal_temperature_range(low_data: xarray.DataArray, high_data: xarray.DataArray, freq: str) xarray.DataArray[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.

Returns

xarray.DataArray

xclim.indices.generic.last_occurrence(data: xarray.DataArray, threshold: str, condition: str, freq: str) xarray.DataArray[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)

  • threshold (str) – Quantity

  • condition ({“>”, “<”, “>=”, “<=”, “==”, “!=”}) – Operator

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray

xclim.indices.generic.select_resample_op(da: xarray.DataArray, op: str, freq: str = 'YS', **indexer) xarray.DataArray[source]

Apply operation over each period that is part of the index selection.

Parameters
  • da (xr.DataArray) – Input data.

  • op (str {‘min’, ‘max’, ‘mean’, ‘std’, ‘var’, ‘count’, ‘sum’, ‘argmax’, ‘argmin’} or func) – Reduce operation. 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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.

  • 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.

Returns

xarray.DataArray – The maximum value for each period.

xclim.indices.generic.statistics(data: xarray.DataArray, reducer: str, freq: str) xarray.DataArray[source]

Calculate a simple statistic of the data.

Parameters
  • data (xr.DataArray)

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray

xclim.indices.generic.temperature_sum(data: xarray.DataArray, threshold: str, condition: str, freq: str) xarray.DataArray[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)

  • threshold (str) – Quantity

  • condition ({“>”, “<”, “>=”, “<=”, “==”, “!=”}) – Operator

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray

xclim.indices.generic.threshold_count(da: xarray.DataArray, op: str, thresh: Union[float, int, xarray.DataArray], freq: str) xarray.DataArray[source]

Count number of days where value is above or below threshold.

Parameters
Returns

xr.DataArray – The number of days meeting the constraints for each period.

xclim.indices.generic.thresholded_statistics(data: xarray.DataArray, threshold: str, condition: str, reducer: str, freq: str) xarray.DataArray[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)

  • threshold (str) – Quantity.

  • condition ({“>”, “<”, “>=”, “<=”, “==”, “!=”}) – Operator

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency.

Returns

xarray.DataArray

Run length algorithms submodule

Computation of statistics on runs of True values in boolean arrays.

xclim.indices.run_length.first_run(da: xarray.DataArray, window: int, dim: str = 'time', coord: Optional[Union[str, bool]] = False, ufunc_1dim: Union[str, bool] = 'from_context') xarray.DataArray[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’).

  • 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.

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: Sequence[Union[int, float]], window: int) int[source]

Return the index of the first item of a run of at least a given length.

Parameters
  • arr (Sequence[Union[int, float]]) – Input array.

  • window (int) – Minimum duration of consecutive run to accumulate values.

Returns

int – 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: xarray.DataArray, window: int, date: Optional[DayOfYearStr] = '07-01', dim: str = 'time', coord: Optional[Union[str, bool]] = 'dayofyear') xarray.DataArray[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’).

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: Union[xarray.DataArray, Sequence[bool]], window: int, dim: str) xarray.DataArray[source]

Dask-parallel version of first_run_1d, ie: 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.

Returns

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.index_of_date(time: xarray.DataArray, date: Optional[Union[DateStr, DayOfYearStr]], max_idxs: Optional[int] = None, default: int = 0) numpy.ndarray[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.

Raises

ValueError – If there are most instances of date in time than max_idxs.

Returns

numpy.ndarray – 1D array of integers, indexes of date in time.

xclim.indices.run_length.keep_longest_run(da: xarray.DataArray, dim: str = 'time') xarray.DataArray[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.

Returns

xr.DataArray – Boolean array similar to da but with only one run, the (first) longest.

xclim.indices.run_length.last_run(da: xarray.DataArray, window: int, dim: str = 'time', coord: Optional[Union[str, bool]] = False, ufunc_1dim: Union[str, bool] = 'from_context') xarray.DataArray[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’).

  • 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.

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: xarray.DataArray, window: int, date: DayOfYearStr = '07-01', dim: str = 'time', coord: Optional[Union[str, bool]] = 'dayofyear') xarray.DataArray[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’).

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: xarray.DataArray, index: xarray.DataArray, dim: Optional[str] = None) xarray.DataArray[source]

Get values of da at indices index in a NaN-aware and lazy manner.

Two case

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 da is not 1D, all dimensions of index must be in da

  • dim (str, optional) – Dimension along which to index, unused if da is 1D, should not be present in index.

Returns

xr.DataArray – Values of da at indices index.

xclim.indices.run_length.longest_run(da: xarray.DataArray, dim: str = 'time', ufunc_1dim: Union[str, bool] = 'from_context', index: str = 'first') xarray.DataArray[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’.

  • 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.

  • 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.

Returns

xr.DataArray – 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.rle(da: xarray.DataArray, dim: str = 'time', max_chunk: int = 1000000, index: str = 'first') xarray.DataArray[source]

Generate basic run length function.

Parameters
  • da (xr.DataArray) – Input array.

  • dim (str) – Dimension name.

  • max_chunk (int) – Maximum chunk size.

  • 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.

Returns

xr.DataArray – Values are 0 where da is False (out of runs).

xclim.indices.run_length.rle_1d(arr: Union[int, float, bool, Sequence[Union[int, float, bool]]]) Tuple[numpy.array, numpy.array, numpy.array][source]

Return the length, starting position and value of consecutive identical values.

Parameters

arr (Sequence[Union[int, float, bool]]) – Array of values to be parsed.

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: xarray.DataArray, reducer: str = 'max', window: int = 1, dim: str = 'time', ufunc_1dim: Union[str, bool] = 'from_context', index: str = 'first') xarray.DataArray[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’.

  • 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.

  • 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.

Returns

xr.DataArray – 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: xarray.DataArray, dim: str = 'time', coord: Optional[Union[str, bool]] = 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: xarray.DataArray, window: int, date: DayOfYearStr = '07-01', dim: str = 'time', coord: Optional[Union[str, bool]] = 'dayofyear') xarray.DataArray[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’).

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.season(da: xarray.DataArray, window: int, date: Optional[DayOfYearStr] = None, dim: str = 'time', coord: Optional[Union[str, bool]] = False) xarray.Dataset[source]

Return the bounds of a season (along dim).

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, then end as the first subsequent run of window False values. If a date is passed, it must be included in the season.

Parameters
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive values to start and end the season.

  • 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 (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’).

Returns

xr.Dataset – “dim” is reduced to “season_bnds” with 2 elements : season start and season end, both indices of da[dim].

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. Example : 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).

xclim.indices.run_length.season_length(da: xarray.DataArray, window: int, date: Optional[DayOfYearStr] = None, dim: str = 'time') xarray.DataArray[source]

Return the length of the longest semi-consecutive run of True values (optionally including a given date).

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, then end as the first subsequent run of window False values. If a date is passed, it must be included in the season.

Parameters
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive values to start and end the season.

  • 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’).

Returns

xr.DataArray – Length of the longest run of True values along a given dimension (inclusive of a given date) without breaks longer than a given length.

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 end is forced to be later or equal to 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. Example : 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).

xclim.indices.run_length.statistics_run_1d(arr: Sequence[bool], reducer: str, window: int = 1) int[source]

Return statistics on lengths of run of identical values.

Parameters
  • arr (Sequence[bool]) – Input array (bool)

  • reducer ({‘mean’, ‘sum’, ‘min’, ‘max’, ‘std’}) – Reducing function name.

  • window (int) – Minimal length of runs to be included in the statistics

Returns

int – Statistics on length of runs.

xclim.indices.run_length.statistics_run_ufunc(x: Union[xarray.DataArray, Sequence[bool]], reducer: str, window: int = 1, dim: str = 'time') xarray.DataArray[source]

Dask-parallel version of statistics_run_1d, ie: the {reducer} number of consecutive true values in array.

Parameters
  • x (Sequence[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.

Returns

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.suspicious_run(arr: xarray.DataArray, dim: str = 'time', window: int = 10, op: str = '>', thresh: Optional[float] = None) xarray.DataArray[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

  • thresh (float, optional) – Threshold above which values are checked for identical values.

  • op ({“>”, “>=”, “==”, “<”, “<=”, “eq”, “gt”, “lt”, “gteq”, “lteq”}) – Operator for threshold comparison, defaults to “>”.

Returns

xarray.DataArray

xclim.indices.run_length.suspicious_run_1d(arr: numpy.ndarray, window: int = 10, op: str = '>', thresh: Optional[float] = None) numpy.ndarray[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 ({“>”, “>=”, “==”, “<”, “<=”, “eq”, “gt”, “lt”, “gteq”, “lteq”}, optional) – Operator for threshold comparison. Defaults to “>”.

  • thresh (float, optional) – Threshold above which values are checked for identical values.

Returns

numpy.ndarray – Whether or not the data points are part of a run of identical values.

xclim.indices.run_length.use_ufunc(ufunc_1dim: Union[bool, str], da: xarray.DataArray, dim: str = 'time', index: str = 'first') bool[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.

  • 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.

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_run_count(da: xarray.DataArray, window: int, dim: str = 'time', ufunc_1dim: Union[str, bool] = 'from_context', index: str = 'first') xarray.DataArray[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’).

  • 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.

  • 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.

Returns

xr.DataArray – Total number of True values part of a consecutive runs of at least window long.

xclim.indices.run_length.windowed_run_count_1d(arr: Sequence[bool], window: int) int[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.

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: Union[xarray.DataArray, Sequence[bool]], window: int, dim: str) xarray.DataArray[source]

Dask-parallel version of windowed_run_count_1d, ie: 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.

Returns

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.windowed_run_events(da: xarray.DataArray, window: int, dim: str = 'time', ufunc_1dim: Union[str, bool] = 'auto', index: str = 'first') xarray.DataArray[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’).

  • 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.

  • 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.

Returns

xr.DataArray – Number of distinct runs of a minimum length (int).

xclim.indices.run_length.windowed_run_events_1d(arr: Sequence[bool], window: int) xarray.DataArray[source]

Return the number of runs of a minimum length.

Parameters
  • arr (Sequence[bool]) – Input array (bool).

  • window (int) – Minimum run length.

Returns

xr.DataArray – Number of distinct runs of a minimum length.

xclim.indices.run_length.windowed_run_events_ufunc(x: Union[xarray.DataArray, Sequence[bool]], window: int, dim: str) xarray.DataArray[source]

Dask-parallel version of windowed_run_events_1d, ie: 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.

Returns

xr.DataArray – A function operating along the time dimension of a dask-array.