Climate Indices

Note

Climate Indices serve as the driving mechanisms behind Indicators and should be used in cases where default settings for an Indicator may need to be tweaked, metadata completeness is not required, or a user wishes to design a virtual module from existing indices (see: Defining new indicators).

For higher-level and general purpose use, the xclim developers suggest using the Climate Indicators.

Indices Library

Climate indices functions are designed to operate on xarray.DataArray objects. Most of these functions operate on daily time series, but in some cases might accept other sampling frequencies as well. All functions perform units checks to make sure that inputs have the expected dimensions (e.g. handling for units of temperature, whether they are Celsius, kelvin or Fahrenheit), and set the units attribute of the output DataArray.

The xclim.indices.generic, xclim.indices.helpers, xclim.indices.run_length, and xclim.indices.stats submodules provide helper functions to simplify the implementation of indices while functions under xclim.core.calendar can aid with challenges arising from variable calendar types.

Warning

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

Indices module.

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

Base flow index.

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

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

\[\mathrm{CMA}_7(q_i) = \frac{\sum_{j=i-3}^{i+3} q_j}{7}\]
xclim.indices.biologically_effective_degree_days(tasmin, tasmax, lat=None, thresh_tasmin='10 degC', method='gladstones', low_dtr='10 degC', high_dtr='13 degC', max_daily_degree_days='9 degC', start_date='04-01', end_date='11-01', freq='YS')[source]

Biologically effective growing degree days.

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

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

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

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

  • thresh_tasmin (Quantified) – The minimum temperature threshold.

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

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

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

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

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

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

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

Return type:

DataArray

Returns:

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

Warning

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

Notes

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

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

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

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

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

References

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

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

Blowing snow days.

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

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

  • sfcWind (xr.DataArray) – Wind velocity

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

  • sfcWind_thresh (Quantified) – Wind speed threshold.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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

Calm days.

The number of days with average near-surface wind speed below threshold (default: 2 m/s).

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with average near-surface wind speed below 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.cffwis_indices(tas, pr, sfcWind, hurs, lat, snd=None, ffmc0=None, dmc0=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=True, **params)[source]

Canadian Fire Weather Index System indices.

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

Return type:

tuple[DataArray, DataArray, DataArray, DataArray, DataArray, DataArray]

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 Natural Resources Canada [n.d.], the xclim.indices.fire module documentation, and the docstring of fire_weather_ufunc() for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.

References

Wang, Anderson, and Suddaby [2015]

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

Scale precipitation according to the Clausius-Clapeyron relation.

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

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

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

Return type:

DataArray

Returns:

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

Notes

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

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

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

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, pr, tas_per, pr_per, freq='YS')[source]

Cold and dry days.

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

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

  • pr (xarray.DataArray) – Daily precipitation.

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

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

  • freq (str) – Resampling frequency.

Return type:

xarray.DataArray

Warning

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

Return type:

DataArray

Returns:

xarray.DataArray – The total number of days when 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 (Beniston [2009])

References

Beniston [2009]

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

Cold and wet days.

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

Warning

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

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

  • pr (xarray.DataArray) – Daily precipitation.

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

Formula to be written (Beniston [2009])

References

Beniston [2009]

xclim.indices.cold_spell_days(tas, thresh='-10 degC', window=5, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Cold spell days.

The number of days that are part of cold spell events, defined as a sequence of consecutive days with mean daily temperature below a threshold (default: -10°C).

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

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Cold spell days.

Notes

Let \(T_i\) be the mean daily temperature on day \(i\), the number of cold spell days during period \(\phi\) is given by:

\[\sum_{i \in \phi} \prod_{j=i}^{i+5} [T_j < thresh]\]

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

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

Cold spell duration index.

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

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

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

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

  • freq (str) – Resampling frequency.

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

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

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

Return type:

DataArray

Returns:

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

Notes

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

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

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

References

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

Examples

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

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

xclim.indices.cold_spell_frequency(tas, thresh='-10 degC', window=5, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Cold spell frequency.

The number of cold spell events, defined as a sequence of consecutive {window} days with mean daily temperature below a {thresh}.

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

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

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

  • freq (str) – Resampling frequency.

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

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of cold periods of minimum {window} days.

xclim.indices.cold_spell_max_length(tas, thresh='-10 degC', window=1, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Longest cold spell.

Longest spell of low temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or below {thresh}.

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

  • thresh (Quantified) – The temperature threshold needed to trigger a cold spell.

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in cold periods of minimum {window} days.

xclim.indices.cold_spell_total_length(tas, thresh='-10 degC', window=3, freq='YS-JUL', op='<', resample_before_rl=True)[source]

Total length of cold spells.

Total length of spells of low temperatures over a given period. Total length of series of at least {window} consecutive days with temperature at or below {thresh}.

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

  • thresh (Quantified) – The temperature threshold needed to trigger a cold spell.

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} total number of days in cold periods of minimum {window} days.

xclim.indices.cool_night_index(tasmin, lat=None, freq='YS')[source]

Cool Night Index.

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

Warning

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

Examples

>>> from xclim.indices import cool_night_index
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
>>> cni = cool_night_index(tasmin)

References

Tonietto and Carbonneau [2004]

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

Cooling degree days.

Returns the sum of degree days above the temperature threshold at which spaces are cooled (default: 18℃).

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time][temperature] – Cooling degree days.

Notes

Let \(x_i\) be the daily mean temperature at day \(i\). Then the cooling degree days above temperature threshold \(thresh\) over period \(\phi\) is given by:

\[\sum_{i \in \phi} (x_{i}-{thresh} [x_i > thresh]\]

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

xclim.indices.corn_heat_units(tasmin, tasmax, thresh_tasmin='4.44 degC', thresh_tasmax='10 degC')[source]

Corn heat units.

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

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

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

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

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

Return type:

DataArray

Returns:

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

Notes

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

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

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

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

with

\[ \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

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

xclim.indices.daily_pr_intensity(pr, thresh='1 mm/day', freq='YS', op='>=')[source]

Average daily precipitation intensity.

Return the average precipitation over wet days. Wet days are those with precipitation over a given threshold (default: 1 mm/day).

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [precipitation] – The average precipitation over wet days for each period.

Notes

Let \(\mathbf{p} = p_0, p_1, \ldots, p_n\) be the daily precipitation and \(thresh\) be the precipitation threshold defining wet days. Then the daily precipitation intensity is defined as:

\[\frac{\sum_{i=0}^n p_i [p_i \leq thresh]}{\sum_{i=0}^n [p_i \leq thresh]}\]

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

Examples

The following would compute for each grid cell of file pr.day.nc the average precipitation fallen over days with precipitation >= 5 mm at seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import daily_pr_intensity
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> daily_int = daily_pr_intensity(pr, thresh="5 mm/day", freq="QS-DEC")
xclim.indices.daily_temperature_range(tasmin, tasmax, freq='YS', op='mean')[source]

Statistics of daily temperature range.

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

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

Notes

For a default calculation using op=’mean’ :

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

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

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

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

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

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

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Examples

>>> from xclim.indices import days_over_precip_thresh
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> p75 = pr.quantile(0.75, dim="time", keep_attrs=True)
>>> r75p = days_over_precip_thresh(pr, p75)
xclim.indices.days_with_snow(prsn, low='0 kg m-2 s-1', high='1E6 kg m-2 s-1', freq='YS-JUL')[source]

Days with snow.

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

Warning

The default freq is valid for the northern hemisphere.

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux

  • low (Quantified) – Minimum threshold snowfall flux or liquid water equivalent snowfall rate.

  • high (Quantified) – Maximum threshold snowfall flux or liquid water equivalent snowfall rate.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

References

Matthews, Andrey, and Picketts [2017]

Notes

If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.

xclim.indices.degree_days_exceedance_date(tas, thresh='0 degC', sum_thresh='25 K days', op='>', after_date=None, never_reached=None, freq='YS')[source]

Degree-days exceedance date.

Day of year when the sum of degree days exceeds a threshold (default: 25 K days). Degree days are computed above or below a given temperature threshold (default: 0℃).

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

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

  • sum_thresh (Quantified) – Threshold of the degree days sum.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – If equivalent to ‘>’, degree days are computed as tas - thresh and if equivalent to ‘<’, they are computed as thresh - tas.

  • after_date (str, optional) – Date at which to start the cumulative sum. In “MM-DD” format, defaults to the start of the sampling period.

  • never_reached (int, str, optional) – What to do when sum_thresh is never exceeded. If an int, the value to assign as a day-of-year. If a string, must be in “MM-DD” format, the day-of-year of that date is assigned. Default (None) assigns “NaN”.

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

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Degree-days exceedance date.

Notes

Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\), \(T\) is the reference threshold and \(ST\) is the sum threshold. Then, starting at day :math:i_0:, the degree days exceedance date is the first day \(k\) such that

\[\begin{split}\begin{cases} ST < \sum_{i=i_0}^{k} \max(TG_{ij} - T, 0) & \text{if $op$ is '>'} \\ ST < \sum_{i=i_0}^{k} \max(T - TG_{ij}, 0) & \text{if $op$ is '<'} \end{cases}\end{split}\]

The resulting \(k\) is expressed as a day of year.

Cumulated degree days have numerous applications including plant and insect phenology. See https://en.wikipedia.org/wiki/Growing_degree-day for examples (Wikipedia Contributors [2021]).

xclim.indices.drought_code(tas, pr, lat, snd=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=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 fire 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.fire.fire_weather_ufunc and in default_params.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Drought code

Notes

See Natural Resources Canada [n.d.], the xclim.indices.fire module documentation, and the docstring of fire_weather_ufunc() for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.

References

Wang, Anderson, and Suddaby [2015]

xclim.indices.dry_days(pr, thresh='0.2 mm/d', freq='YS', op='<')[source]

Dry days.

The number of days with daily precipitation below threshold.

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with daily precipitation {op} threshold.

Notes

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

\[\sum PR_{ij} < Threshold [mm/day]\]
xclim.indices.dry_spell_frequency(pr, thresh='1.0 mm', window=3, freq='YS', resample_before_rl=True, op='sum')[source]

Return the number of dry periods of n days and more.

Periods during which the accumulated or maximal daily precipitation amount on a window of n days is under threshold.

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

  • thresh (Quantified) – Precipitation amount under which a period is considered dry. The value against which the threshold is compared depends on op .

  • window (int) – Minimum length of the spells.

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of dry periods of minimum {window} days.

Examples

>>> from xclim.indices import dry_spell_frequency
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> dsf = dry_spell_frequency(pr=pr, op="sum")
>>> dsf = dry_spell_frequency(pr=pr, op="max")
xclim.indices.dry_spell_max_length(pr, thresh='1.0 mm', window=1, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Longest dry spell.

Maximum number of consecutive days in a dry period of minimum length, during which the maximum or accumulated precipitation within a window of the same length is under a threshold.

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

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

  • window (int) – Number of days when the maximum or accumulated precipitation is under 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.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell 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 three days is under the threshold. In comparison, a day in the middle of the series is considered part of a dry spell if any of the three 3-day periods of which it is part are considered dry (so a total of five days are included in the computation, compared to only three).

xclim.indices.dry_spell_total_length(pr, thresh='1.0 mm', window=3, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Total length of dry spells.

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 (Quantified) – Accumulated precipitation value under which a period is considered dry.

  • window (int) – Number of days when 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.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – 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 three days is under the threshold. In comparison, a day in the middle of the series is considered part of a dry spell if any of the three 3-day periods of which it is part are considered dry (so a total of five days are included in the computation, compared to only three).

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

Dryness Index.

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

Warning

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

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

  • evspsblpot (xarray.DataArray) – Potential evapotranspiration.

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [mm] – Dryness Index.

Notes

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

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

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

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

or (for the Southern Hemisphere):

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

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

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

and

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

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

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

Examples

>>> from xclim.indices import dryness_index
>>> dryi = dryness_index(pr_dataset, evspsblpot_dataset, wo="200 mm")

References

Riou [1994], Tonietto and Carbonneau [2004]

xclim.indices.duff_moisture_code(tas, pr, hurs, lat, snd=None, dmc0=None, season_mask=None, season_method=None, dry_start=None, initial_start_up=True, **params)[source]

Duff moisture code (FWI component).

The duff moisture code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of loosely compacted organic layers of moderate depth.

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

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

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

  • lat (xr.DataArray) – Latitude coordinate

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

  • dmc0 (xr.DataArray) – Initial values of the duff moisture 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 fire function. Ignored if season_mask is 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.fire.fire_weather_ufunc and in default_params.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Duff moisture code

Notes

See Natural Resources Canada [n.d.], the xclim.indices.fire module documentation, and the docstring of fire_weather_ufunc() for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.

References

Wang, Anderson, and Suddaby [2015]

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

Effective growing degree days.

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

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

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

  • thresh (Quantified) – The minimum temperature threshold.

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

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

  • dim (str) – Time dimension.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

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

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

References

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

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

Extreme intra-period temperature range.

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

\[ETR_j = max(TX_{ij}) - min(TN_{ij})\]
xclim.indices.fire_season(tas, snd=None, method='WF93', freq=None, temp_start_thresh='12 degC', temp_end_thresh='5 degC', temp_condition_days=3, snow_condition_days=3, snow_thresh='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 (Quantified) – Minimal temperature needed to start the season. Must be scalar.

  • temp_end_thresh (Quantified) – Maximal temperature needed to end the season. Must be scalar.

  • 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 (Quantified) – Minimal snow depth level to end a fire season, only used with method “LA08”. Must be scalar.

Return type:

DataArray

Returns:

xr.DataArray – Fire season mask

References

Lawson and Armitage [2008], Wotton and Flannigan [1993]

xclim.indices.first_day_temperature_above(tas, thresh='0 degC', op='>', after_date='01-01', window=1, freq='YS')[source]

First day of temperatures superior to a given temperature threshold.

Returns first day of period where temperature is superior to a threshold over a given number of days (default: 1), limited to a starting calendar date (default: January 1).

Warning

The default freq and after_date parameters are valid for the northern hemisphere.

Parameters:
  • tas (xarray.DataArray) – Daily temperature.

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

Let \(x_i\) be the daily mean|max|min temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The first day above temperature threshold is given by the smallest index \(i\):

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

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

xclim.indices.first_day_temperature_below(tas, thresh='0 degC', op='<', after_date='07-01', window=1, freq='YS')[source]

First day of temperatures inferior to a given temperature threshold.

Returns first day of period where temperature is inferior to a threshold over a given number of days (default: 1), limited to a starting calendar date (default: July 1).

Warning

The default freq and after_date parameters are valid for the northern hemisphere.

Parameters:
  • tas (xarray.DataArray) – Daily temperature.

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

xclim.indices.first_snowfall(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

First day with snowfall rate above a threshold.

Returns the first day of a period where snowfall exceeds a threshold (default: 1 mm/day).

Warning

The default freq is valid for the northern hemisphere.

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate. (default: 1 mm/day)

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Last day of the year where snowfall is superior to a threshold. If there is no such day, returns np.nan.

References

CBCL [2020].

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.

xclim.indices.fraction_over_precip_thresh(pr, pr_per, thresh='1 mm/day', freq='YS', bootstrap=False, op='>')[source]

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

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

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

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

xclim.indices.frost_days(tasmin, thresh='0 degC', freq='YS', **indexer)[source]

Frost days index.

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

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

  • thresh (Quantified) – Freezing temperature.

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Frost days index.

Notes

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

\[TN_{ij} < TT\]
xclim.indices.frost_free_season_end(tasmin, thresh='0.0 degC', mid_date='07-01', window=5, freq='YS')[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 (default: 0℃), after a period of N days (default: 5) with minimum temperatures consistently above the same threshold.

Warning

The default freq and mid_date parameters are valid for the northern hemisphere.

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

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

Return type:

DataArray

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, window=5, mid_date='07-01', thresh='0.0 degC', freq='YS', op='>=')[source]

Frost free season length.

The number of days between the first occurrence of at least N (default: 5) consecutive days with minimum daily temperature above a threshold (default: 0℃) and the first occurrence of at least N 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 parameters 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 (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – 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="YS-JUL")
xclim.indices.frost_free_season_start(tasmin, thresh='0.0 degC', window=5, freq='YS')[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 (default: 0℃), after a period of N days (default: 5) with minimum temperatures consistently above the same threshold.

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

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

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

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_free_spell_max_length(tasmin, thresh='0.0 degC', window=1, freq='YS-JUL', op='>=', resample_before_rl=True)[source]

Longest cold spell.

Longest spell of low temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or below {thresh}.

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

  • thresh (Quantified) – The temperature threshold needed to trigger a cold spell.

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in frost free periods of minimum {window} days.

xclim.indices.frost_season_length(tasmin, window=5, mid_date='01-01', thresh='0.0 degC', freq='YS-JUL', op='<')[source]

Frost season length.

The number of days between the first occurrence of at least N (default: 5) consecutive days with minimum daily temperature under a threshold (default: 0℃) and the first occurrence of at least N consecutive days with minimum daily temperature above the same threshold. A mid-date can be given to limit the earliest day the end of season can take.

Warning

The default freq and mid_date parameters 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 (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

Notes

Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least N consecutive days with:

\[TN_{ij} > 0 ℃\]

and the first subsequent occurrence of at least N consecutive days with:

\[TN_{ij} < 0 ℃\]

Examples

>>> from xclim.indices import frost_season_length
>>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin

For the Northern Hemisphere:

>>> fsl_nh = frost_season_length(tasmin, freq="YS-JUL")

If working in the Southern Hemisphere, one can use:

>>> fsl_sh = frost_season_length(tasmin, freq="YS")
xclim.indices.griffiths_drought_factor(pr, smd, limiting_func='xlim')[source]

Griffiths drought factor based on the soil moisture deficit.

The drought factor is a numeric indicator of the forest fire fuel availability in the deep litter bed. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006].

Parameters:
  • pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].

  • smd (xarray DataArray) – Daily soil moisture deficit (often KBDI) [mm/day].

  • limiting_func ({“xlim”, “discrete”}) – How to limit the values of the drought factor. If “xlim” (default), use equation (14) in Finkele et al. [2006]. If “discrete”, use equation Eq (13) in Finkele et al. [2006], but with the lower limit of each category bound adjusted to match the upper limit of the previous bound.

Return type:

DataArray

Returns:

df (xr.DataArray) – The limited Griffiths drought factor.

Notes

Calculation of the Griffiths drought factor depends on the rainfall over the previous 20 days. Thus, the first non-NaN time point in the drought factor returned by this function corresponds to the 20th day of the input data.

References

Finkele, Mills, Beard, and Jones [2006], Griffiths [1999], Holgate, Van DIjk, Cary, and Yebra [2017]

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

Growing degree-days over threshold temperature value.

The sum of growing degree-days over a given mean daily temperature threshold (default: 4℃).

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

Let \(TG_{ij}\) be the mean daily temperature at day \(i\) of period \(j\). Then the growing degree days are:

\[GD4_j = \sum_{i=1}^I (TG_{ij}-{4} | TG_{ij} > {4}℃)\]
xclim.indices.growing_season_end(tas, thresh='5.0 degC', mid_date='07-01', window=5, freq='YS')[source]

End of the growing season.

Day of the year of the start of a sequence of N (default: 5) days with mean temperatures consistently below a given threshold (default: 5℃), occurring after a given calendar date (default: July 1).

Warning

The default freq and mid_date parameters are valid for the northern hemisphere.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when temperature is inferior to a threshold over a given number of days for the first time. If there is no such day 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.

Notes

Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date of the end of growing season is given by the smallest index \(i\):

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

where \(w\) is the number of days where temperature should be inferior to a given threshold after a given date, and \([P]\) is 1 if \(P\) is true, and 0 if false.

xclim.indices.growing_season_length(tas, thresh='5.0 degC', window=6, mid_date='07-01', freq='YS', op='>=')[source]

Growing season length.

The number of days between the first occurrence of at least N (default: 6) consecutive days with mean daily temperature over a threshold (default: 5℃) and the first occurrence of at least N consecutive days with mean daily temperature below the same threshold after a certain date, usually July 1st (06-01) in the northern emispher and January 1st (01-01) in the southern hemisphere.

Warning

The default freq and mid_date parameters are valid for the northern hemisphere.

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

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

  • window (int) – Minimum number of days with temperature above 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.

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

Return type:

DataArray

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="YS")

If working in the Southern Hemisphere, one can use:

>>> gsl_sh = growing_season_length(tas, mid_date="01-01", freq="YS-JUL")

References

Project team ECA&D and KNMI [2013]

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

Start of the growing season.

Day of the year of the start of a sequence of days with mean daily temperatures consistently above or equal to a given threshold (default: 5℃).

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when temperature is superior to a threshold over a given number of days for the first time. If there is no such day 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\):

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

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.hardiness_zones(tasmin, window=30, method='usda', freq='YS')[source]

Hardiness zones.

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

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

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

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

  • freq (str) – Resampling frequency.

Returns:

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

References

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

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

Heat index.

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

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

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

Return type:

DataArray

Returns:

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

References

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

Notes

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

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

Heat wave frequency.

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

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

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

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

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

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

References

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

xclim.indices.heat_wave_index(tasmax, thresh='25.0 degC', window=5, freq='YS', op='>', resample_before_rl=True)[source]

Heat wave index.

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

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

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

DataArray, [time] – Heat wave index.

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

Heat wave max length.

Maximum length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both 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 (Quantified) – The minimum temperature threshold needed to trigger a heatwave event.

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

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

References

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

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

Heat wave total length.

Total length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both 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.

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

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

Return type:

DataArray

Returns:

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

Notes

See notes and references of heat_wave_max_length

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

Heating degree days.

Sum of degree days below the temperature threshold (default: 17℃) at which spaces are heated.

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

This index intentionally differs from its ECA&D [Project team ECA&D and KNMI, 2013] equivalent: HD17. In HD17, values below zero are not clipped before the sum. The present definition should provide a better representation of the energy demand for heating buildings to the given threshold.

Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\). Then the heating degree days are:

\[HD17_j = \sum_{i=1}^{I} (17℃ - TG_{ij}) | TG_{ij} < 17℃)\]
xclim.indices.high_precip_low_temp(pr, tas, pr_thresh='0.4 mm/d', tas_thresh='-0.2 degC', freq='YS')[source]

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

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

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

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

  • pr_thresh (Quantified) – Precipitation threshold to exceed.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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, thresh='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]

Hot spell frequency.

The number of hot spell events, defined as a sequence of consecutive {window} days with mean daily temperature above a {thresh}.

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

  • thresh (Quantified) – Threshold temperature below which a hot spell begins.

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

  • freq (str) – Resampling frequency.

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

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of hot periods of minimum {window} days.

Notes

The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).

References

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

xclim.indices.hot_spell_max_length(tasmax, thresh='30 degC', window=1, freq='YS', op='>', resample_before_rl=True)[source]

Longest hot spell.

Longest spell of high temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or above {thresh}.

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

  • thresh (Quantified) – The temperature threshold needed to trigger a hot spell.

  • window (int) – Minimum number of days with temperatures below thresholds to qualify as a hot spell.

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in hot periods of minimum {window} days.

Notes

The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).

References

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

xclim.indices.hot_spell_total_length(tasmax, thresh='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]

Total length of hot spells.

Total length of spells of high temperatures over a given period. Total length of series of at least {window} consecutive days with temperature at or above {thresh}.

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

  • thresh (Quantified) – The temperature threshold needed to trigger a hot spell.

  • window (int) – Minimum number of days with temperatures below thresholds to qualify as a hot spell.

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} total number of days in hot periods of minimum {window} days.

Notes

The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].

In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).

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

Huglin Heliothermal Index.

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

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

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

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

  • thresh (Quantified) – The temperature threshold.

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

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

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

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

Return type:

DataArray

Returns:

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

Notes

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

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

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

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

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

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

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

References

Hall and Jones [2010], Huglin [1978]

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

Humidex index.

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

Parameters:
  • tas (xarray.DataArray) – Air temperature.

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [temperature] – The humidex index.

Notes

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

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

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

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

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

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

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

  • 20 to 29 : no discomfort;

  • 30 to 39 : some discomfort;

  • 40 to 45 : great discomfort, avoid exertion;

  • 46 and over : dangerous, possible heat stroke;

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

References

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

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

Number of ice/freezing days.

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

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

  • thresh (Quantified) – Freezing temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of ice/freezing days.

Notes

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

\[TX_{ij} < TT\]
xclim.indices.isothermality(tasmin, tasmax, freq='YS')[source]

Isothermality.

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [%] – Isothermality

Notes

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

References

Xu and Hutchinson [2010]

xclim.indices.jetstream_metric_woollings(ua)[source]

Strength and latitude of jetstream.

Identify latitude and strength of maximum smoothed zonal wind speed in the region from 15 to 75°N and -60 to 0°E, using the formula outlined in [Woollings et al., 2010]. Wind is smoothened using a Lanczos filter approach.

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.

Return type:

tuple[DataArray, DataArray]

Returns:

(xarray.DataArray, xarray.DataArray) – Daily time series of latitude of jetstream and daily time series of strength of jetstream.

References

Woollings, Hannachi, and Hoskins [2010]

xclim.indices.keetch_byram_drought_index(pr, tasmax, pr_annual, kbdi0=None)[source]

Keetch-Byram drought index (KBDI) for soil moisture deficit.

The KBDI indicates the amount of water necessary to bring the soil moisture content back to field capacity. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006] but limits the maximum KBDI to 203.2 mm, rather than 200 mm, in order to align best with the majority of the literature.

Parameters:
  • pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].

  • tasmax (xr.DataArray) – Maximum temperature near the surface over previous 24 hours [degC].

  • pr_annual (xr.DataArray) – Mean (over years) annual accumulated rainfall [mm/year].

  • kbdi0 (xr.DataArray, optional) – Previous KBDI values used to initialise the KBDI calculation [mm/day]. Defaults to 0.

Return type:

DataArray

Returns:

xr.DataArray – Keetch-Byram drought index.

Notes

This method implements the method described in Finkele et al. [2006] (section 2.1.1) for calculating the KBDI with one small difference: in Finkele et al. [2006] the maximum KBDI is limited to 200 mm to represent the maximum field capacity of the soil (8 inches according to Keetch and Byram [1968]). However, it is more common in the literature to limit the KBDI to 203.2 mm which is a more accurate conversion from inches to mm. In this function, the KBDI is limited to 203.2 mm.

References

Dolling, Chu, and Fujioka [2005], Finkele, Mills, Beard, and Jones [2006], Holgate, Van DIjk, Cary, and Yebra [2017], Keetch and Byram [1968]

xclim.indices.last_snowfall(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

Last day with snowfall above a threshold.

Returns the last day of a period where snowfall exceeds a threshold (default: 1 mm/day)

Warning

The default freq is valid for the northern hemisphere.

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Last day of the year where snowfall is superior to a threshold. If there is no such day, returns np.nan.

References

CBCL [2020].

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.

xclim.indices.last_spring_frost(tasmin, thresh='0 degC', op='<', before_date='07-01', window=1, freq='YS')[source]

Last day of temperatures inferior to a threshold temperature.

Returns last day of period where minimum temperature is inferior to a threshold over a given number of days (default: 1) and limited to a final calendar date (default: July 1).

Warning

The default freq and before_date parameters are valid for the northern hemisphere.

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

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

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

  • before_date (str,) – Date of the year before which to look for the final frost event. Should have the format ‘%m-%d’.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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

Latitude-Temperature Index.

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

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

References

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

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

Ratio of rainfall to total precipitation.

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

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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.longwave_upwelling_radiation_from_net_downwelling(rls, rlds)[source]

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

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

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

Return type:

DataArray

Returns:

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

xclim.indices.max_1day_precipitation_amount(pr, freq='YS')[source]

Highest 1-day precipitation amount for a period (frequency).

Resample the original daily total precipitation temperature series by taking the max over each period.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as pr] – The highest 1-period precipitation flux value at the given time frequency.

Notes

Let \(PR_i\) be the mean daily precipitation of day i, then for a period j:

\[PRx_{ij} = max(PR_{ij})\]

Examples

The following would compute for each grid cell the highest 1-day total at an annual frequency:

>>> from xclim.indices import max_1day_precipitation_amount
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> rx1day = max_1day_precipitation_amount(pr, freq="YS")
xclim.indices.max_n_day_precipitation_amount(pr, window=1, freq='YS')[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.

Return type:

DataArray

Returns:

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

Examples

The following would compute for each grid cell the highest 5-day total precipitation at an annual frequency:

>>> from xclim.indices import max_n_day_precipitation_amount
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> out = max_n_day_precipitation_amount(pr, window=5, freq="YS")
xclim.indices.max_pr_intensity(pr, window=1, freq='YS')[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.

Return type:

DataArray

Returns:

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

Examples

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

>>> from xclim.indices import max_pr_intensity
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> out = max_pr_intensity(pr, window=5, freq="YS")
xclim.indices.maximum_consecutive_dry_days(pr, thresh='1 mm/day', freq='YS', resample_before_rl=True)[source]

Maximum number of consecutive dry days.

Return the maximum number of consecutive days within the period where precipitation is below a certain threshold (default: 1 mm/day).

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

Notes

Let \(\mathbf{p}=p_0, p_1, \ldots, p_n\) be a daily precipitation series and \(thresh\) the threshold under which a day is considered dry. Then let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([p_i < thresh] \neq [p_{i+1} < thresh]\), that is, the days where the precipitation crosses the threshold. Then the maximum number of consecutive dry days is given by

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [p_{s_j} < thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices.maximum_consecutive_frost_days(tasmin, thresh='0.0 degC', freq='YS-JUL', resample_before_rl=True)[source]

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

The maximum number of consecutive days within the period where the minimum daily temperature is under a given threshold (default: 0°C).

Warning

The default freq is valid for the northern hemisphere.

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

  • thresh (Quantified) – Threshold temperature.

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

Notes

Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a minimum daily temperature series and \(thresh\) the threshold below which a day is considered a frost day. Let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([t_i < thresh] \neq [t_{i+1} < thresh]\), that is, the days where the temperature crosses the threshold. Then the maximum number of consecutive frost days is given by

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [t_{s_j} < thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices.maximum_consecutive_frost_free_days(tasmin, thresh='0 degC', freq='YS', resample_before_rl=True)[source]

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

Return the maximum number of consecutive days within the period where the minimum daily temperature is above or equal to a certain threshold (default: 0℃).

Warning

The default freq is valid for the northern hemisphere.

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

  • thresh (Quantified) – Threshold temperature.

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

Notes

Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a daily minimum temperature series and \(thresh\) the threshold above or equal to which a day is considered a frost free day. Let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([t_i <= thresh] \neq [t_{i+1} <= thresh]\), that is, the days where the temperature crosses the threshold. Then the maximum number of consecutive frost free days is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [t_{s_j} >= thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices.maximum_consecutive_tx_days(tasmax, thresh='25 degC', freq='YS', resample_before_rl=True)[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 daily temperature is above a certain threshold (default: 25℃).

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

  • thresh (Quantified) – Threshold temperature.

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The maximum number of days with tasmax > thresh per periods (summer days).

Notes

Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a daily maximum temperature series and \(thresh\) the threshold above which a day is considered a summer day. Let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([t_i < thresh] \neq [t_{i+1} < thresh]\), that is, the days where the temperature crosses the threshold. Then the maximum number of consecutive tx_days (summer days) is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [t_{s_j} > thresh]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices.maximum_consecutive_wet_days(pr, thresh='1 mm/day', freq='YS', resample_before_rl=True)[source]

Consecutive wet days.

Returns the maximum number of consecutive days with precipitation above a given threshold (default: 1 mm/day).

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The maximum number of consecutive wet days.

Notes

Let \(\mathbf{x}=x_0, x_1, \ldots, x_n\) be a daily precipitation series and \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([p_i > thresh] \neq [p_{i+1} > thresh]\), that is, the days where the precipitation crosses the wet day threshold. Then the maximum number of consecutive wet days is given by:

\[\max(\mathbf{d}) \quad \mathrm{where} \quad d_j = (s_j - s_{j-1}) [x_{s_j} > 0^\circ C]\]

where \([P]\) is 1 if \(P\) is true, and 0 if false. Note that this formula does not handle sequences at the start and end of the series, but the numerical algorithm does.

xclim.indices.mcarthur_forest_fire_danger_index(drought_factor, tasmax, hurs, sfcWind)[source]

McArthur forest fire danger index (FFDI) Mark 5.

The FFDI is a numeric indicator of the potential danger of a forest fire.

Parameters:
  • drought_factor (xr.DataArray) – The drought factor, often the daily Griffiths drought factor (see griffiths_drought_factor()).

  • tasmax (xr.DataArray) – The daily maximum temperature near the surface, or similar. Different applications have used different inputs here, including the previous/current day’s maximum daily temperature at a height of 2m, and the daily mean temperature at a height of 2m.

  • hurs (xr.DataArray) – The relative humidity near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon relative humidity at a height of 2m, and the daily mean relative humidity at a height of 2m.

  • sfcWind (xr.DataArray) – The wind speed near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon wind speed at a height of 10m, and the daily mean wind speed at a height of 10m.

Returns:

xr.DataArray – The McArthur forest fire danger index.

References

Dowdy [2018], Holgate, Van DIjk, Cary, and Yebra [2017], Noble, Gill, and Bary [1980]

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

Mean radiant temperature.

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

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

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

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

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [K] – Mean radiant temperature

Warning

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

Notes

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

References

Di Napoli, Hogan, and Pappenberger [2020]

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

Maximum snow melt and precipitation.

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

xclim.indices.multiday_temperature_swing(tasmin, tasmax, thresh_tasmin='0 degC', thresh_tasmax='0 degC', window=1, op='mean', op_tasmin='<=', op_tasmax='>', freq='YS', resample_before_rl=True)[source]

Statistics of consecutive diurnal temperature swing events.

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

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

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

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

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

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

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

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

Notes

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

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

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

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

Potential evapotranspiration.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Return type:

DataArray

Returns:

xarray.DataArray

Notes

Available methods are:

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

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

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

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

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

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

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

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

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

References

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

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

Accumulated total precipitation.

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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

Total precipitation of warmest/coldest quarter.

The warmest (or coldest) quarter of the year is determined, and the total precipitation of this period is calculated. If the input data frequency is daily (“D) or weekly (“W”), quarters are defined as 13-week periods, otherwise 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.

Return type:

DataArray

Returns:

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

Notes

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

References

Xu and Hutchinson [2010]

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

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

References

Xu and Hutchinson [2010]

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

Total precipitation of wettest/driest quarter.

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

Return type:

DataArray

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

References

Xu and Hutchinson [2010]

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

Accumulated total (liquid and/or solid) precipitation.

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

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

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

Examples

The following would compute, for each grid cell of a dataset, the total precipitation at the seasonal frequency, 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_average(pr, tas=None, phase=None, thresh='0 degC', freq='YS')[source]

Averaged (liquid and/or solid) precipitation.

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

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

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

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

Examples

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

>>> from xclim.indices import precip_average
>>> pr_day = xr.open_dataset(path_to_pr_file).pr
>>> prcp_tot_seasonal = precip_average(pr_day, freq="QS-DEC")
xclim.indices.precip_seasonality(pr, freq='YS')[source]

Precipitation Seasonality (C of V).

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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

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

References

Xu and Hutchinson [2010]

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

Snowfall rate from snowfall flux and density.

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

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

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

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

Return type:

DataArray

Returns:

xr.DataArray – Snowfall rate.

Notes

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

References

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

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

Snowfall flux from snowfall rate and density.

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

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

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

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

Return type:

DataArray

Returns:

xr.DataArray – Snowfall flux.

Notes

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

References

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

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

Binomial smoothed, five-day weighted mean average temperature.

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

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

  • dim (str) – Time dimension.

Return type:

DataArray

Returns:

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

Notes

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

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

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

References

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

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

Rainfall approximation from total precipitation and temperature.

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

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

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

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

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

Return type:

DataArray

Returns:

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

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, tas, thresh='1 mm/d', freq='YS')[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 (Quantified) – Precipitation threshold to consider a day as a rain event.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

and where

\[TG_{i} ≤ 0℃\]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • freq (str) – Resampling frequency.

Returns:

  • rain_season_start (xr.DataArray, [dimensionless])

  • rain_season_end (xr.DataArray, [dimensionless])

  • rain_season_length (xr.DataArray, [time])

Notes

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

References

Sivakumar [1988]

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

Richards-Baker flashiness index.

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

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

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

References

Baker, Richards, Loftus, and Kramer [2004]

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

Relative humidity.

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

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

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

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

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

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

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

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

Return type:

DataArray

Returns:

xr.DataArray, [%] – Relative humidity.

Notes

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

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

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

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

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

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

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

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

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

Examples

>>> from xclim.indices import relative_humidity
>>> rh = relative_humidity(
...     tas=tas_dataset,
...     tdps=tdps_dataset,
...     huss=huss_dataset,
...     ps=ps_dataset,
...     ice_thresh="0 degC",
...     method="wmo08",
...     invalid_values="clip",
... )

References

Bohren and Albrecht [1998], Lawrence [2005]

xclim.indices.rprctot(pr, prc, thresh='1.0 mm/day', freq='YS', op='>=')[source]

Proportion of accumulated precipitation arising from convective processes.

Return the proportion of total accumulated precipitation due to convection on days with total precipitation greater or equal to a given threshold (default: 1.0 mm/day) during the given period.

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

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

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

Saturation vapour pressure from temperature.

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

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [Pa] – Saturation vapour pressure.

Notes

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

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

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

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

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

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

Examples

>>> from xclim.indices import saturation_vapor_pressure
>>> rh = saturation_vapor_pressure(
...     tas=tas_dataset, ice_thresh="0 degC", method="wmo08"
... )

References

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

xclim.indices.sea_ice_area(siconc, areacello, thresh='15 pct')[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 (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.

Return type:

DataArray

Returns:

xarray.DataArray, [length]^2 – Sea ice area.

Notes

To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.

References

“What is the difference between sea ice area and extent?” - NSIDC [2008]

xclim.indices.sea_ice_extent(siconc, areacello, thresh='15 pct')[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 (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.

Return type:

DataArray

Returns:

xarray.DataArray, [length]^2 – Sea ice extent.

Notes

To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.

References

“What is the difference between sea ice area and extent?” - NSIDC [2008]

xclim.indices.sfcWind_max(sfcWind, freq='YS')[source]

Highest daily mean wind speed.

The maximum of daily mean wind speed.

Parameters:
  • sfcWind (xarray.DataArray) – Mean daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWind] – Maximum of daily mean wind speed.

Notes

Let \(FG_{ij}\) be the mean wind speed at day \(i\) of period \(j\). Then the maximum daily mean wind speed for period \(j\) is:

\[FGx_j = max(FG_{ij})\]

Examples

The following would compute for each grid cell the maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWind_max
>>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind
>>> fg_max = sfcWind_max(fg, freq="QS-DEC")
xclim.indices.sfcWind_mean(sfcWind, freq='YS')[source]

Mean of daily mean wind speed.

Resample the original daily mean wind speed series by taking the mean over each period.

Parameters:
  • sfcWind (xarray.DataArray) – Mean daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWind] – The mean daily wind speed at the given time frequency

Notes

Let \(FG_i\) be the mean wind speed of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):

\[FG_m = \frac{\sum_{i=a}^{b} FG_i}{b - a + 1}\]

Examples

The following would compute for each grid cell the mean wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWind_mean
>>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind
>>> fg_mean = sfcWind_mean(fg, freq="QS-DEC")
xclim.indices.sfcWind_min(sfcWind, freq='YS')[source]

Lowest daily mean wind speed.

The minimum of daily mean wind speed.

Parameters:
  • sfcWind (xarray.DataArray) – Mean daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWind] – Minimum of daily mean wind speed.

Notes

Let \(FG_{ij}\) be the mean wind speed at day \(i\) of period \(j\). Then the minimum daily mean wind speed for period \(j\) is:

\[FGn_j = min(FG_{ij})\]

Examples

The following would compute for each grid cell the minimum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWind_min
>>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind
>>> fg_min = sfcWind_min(fg, freq="QS-DEC")
xclim.indices.sfcWindmax_max(sfcWindmax, freq='YS')[source]

Highest maximum wind speed.

The maximum of daily maximum wind speed.

Parameters:
  • sfcWindmax (xarray.DataArray) – Maximum daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWindmax] – Maximum value of daily maximum wind speed.

Notes

Let \(FX_{ij}\) be the maximum wind speed at day \(i\) of period \(j\). Then the maximum daily maximum wind speed for period \(j\) is:

\[FXx_j = max(FX_{ij})\]

Examples

The following would compute for each grid cell of the dataset the extreme maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWindmax_max
>>> max_sfcWindmax = sfcWindmax_max(sfcWindmax_dataset, freq="QS-DEC")
xclim.indices.sfcWindmax_mean(sfcWindmax, freq='YS')[source]

Mean of daily maximum wind speed.

Resample the original daily maximum wind speed series by taking the mean over each period.

Parameters:
  • sfcWindmax (xarray.DataArray) – Maximum daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWindmax] – The mean daily maximum wind speed at the given time frequency

Notes

Let \(FX_i\) be the maximum wind speed of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):

\[FX_m = \frac{\sum_{i=a}^{b} FX_i}{b - a + 1}\]

Examples

The following would compute for each grid cell of the dataset the mean of maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWindmax_mean
>>> mean_sfcWindmax = sfcWindmax_mean(sfcWindmax_dataset, freq="QS-DEC")
xclim.indices.sfcWindmax_min(sfcWindmax, freq='YS')[source]

Lowest daily maximum wind speed.

The minimum of daily maximum wind speed.

Parameters:
  • sfcWindmax (xarray.DataArray) – Maximum daily wind speed.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as sfcWindmax] – Minimum of daily maximum wind speed.

Notes

Let \(FX_{ij}\) be the maximum wind speed at day \(i\) of period \(j\). Then the minimum daily maximum wind speed for period \(j\) is:

\[FXn_j = min(FX_{ij})\]

Examples

The following would compute for each grid cell of the dataset the minimum of maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import sfcWindmax_min
>>> min_sfcWindmax = sfcWindmax_min(sfcWindmax_dataset, freq="QS-DEC")
xclim.indices.sfcwind_2_uas_vas(sfcWind, sfcWindfromdir)[source]

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

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

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

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

Return type:

tuple[DataArray, DataArray]

Returns:

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

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

Examples

>>> from xclim.indices import sfcwind_2_uas_vas
>>> uas, vas = sfcwind_2_uas_vas(
...     sfcWind=sfcWind_dataset, sfcWindfromdir=sfcWindfromdir_dataset
... )
xclim.indices.shortwave_upwelling_radiation_from_net_downwelling(rss, rsds)[source]

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

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

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

Return type:

DataArray

Returns:

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

xclim.indices.snd_days_above(snd, thresh='2 cm', freq='YS-JUL', op='>=')[source]

The number of days with snow depth above a threshold.

Number of days where surface snow depth is greater or equal to given threshold (default: 2 cm).

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

  • thresh (Quantified) – Threshold snow thickness.

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days where snow depth is greater than or equal to {thresh}.

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

Maximum snow depth.

The maximum daily snow depth.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

xclim.indices.snd_max_doy(snd, freq='YS-JUL')[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.

Return type:

DataArray

Returns:

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

xclim.indices.snd_season_end(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]

Snow cover end date (depth).

First day after the start of the continuous snow depth cover when snow depth is below a threshold for at least window consecutive days.

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

  • thresh (Quantified) – Threshold snow thickness.

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

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day after the start of the continuous snow depth cover.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices.snd_season_length(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]

Snow cover duration (depth).

The season starts when snow depth is above a threshold for at least N consecutive days and stops when it drops below the same threshold for the same number of days.

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

  • thresh (Quantified) – Threshold snow thickness.

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

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – Length of the snow season.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices.snd_season_start(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]

Snow cover start date (depth).

Day of year when snow depth is above or equal to a threshold for at least N consecutive days.

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

  • thresh (Quantified) – Threshold snow thickness.

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

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day of the year when the snow depth is superior to a threshold for a minimum duration.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices.snd_storm_days(snd, thresh='25 cm', freq='YS-JUL')[source]

Days with snowfall over threshold.

Number of days with snowfall depth accumulation greater or equal to threshold (default: 25 cm).

Warning

The default freq is valid for the northern hemisphere.

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

  • thresh (Quantified) – Threshold on snowfall depth accumulation require to label an event a snd storm.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

Snowfall accumulation is estimated by the change in snow depth.

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

Snow amount from snow depth and density.

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

  • snr (Quantified, optional) – Snow density.

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

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

Return type:

DataArray

Returns:

xr.DataArray – Snow amount

Notes

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

References

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

xclim.indices.snow_depth(snd, freq='YS')[source]

Mean of daily average snow depth.

Resample the original daily mean snow depth series by taking the mean over each period.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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

Maximum snow melt.

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

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

Snowfall approximation from total precipitation and temperature.

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

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

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

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

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

Return type:

DataArray

Returns:

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

Notes

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

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

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

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

References

Melton [2019], Verseghy [2009]

xclim.indices.snowfall_frequency(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

Percentage of snow days.

Return the percentage of days where snowfall exceeds a threshold (default: 1 mm/day).

Warning

The default freq is valid for the northern hemisphere.

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [%] – Percentage of days where snowfall exceeds a threshold.

References

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

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.

xclim.indices.snowfall_intensity(prsn, thresh='1 mm/day', freq='YS-JUL')[source]

Mean daily snowfall rate during snow days.

Return mean daily snowfall rate during days where snowfall exceeds a threshold (default: 1 mm/day).

Warning

The default freq is valid for the northern hemisphere.

Parameters:
  • prsn (xarray.DataArray) – Snowfall flux.

  • thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, – Mean daily liquid water equivalent snowfall rate during days where snowfall exceeds a threshold.

References

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

Notes

The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.

If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.

xclim.indices.snw_days_above(snw, thresh='4 kg m-2', freq='YS-JUL', op='>=')[source]

The number of days with snow amount above a threshold.

Number of days where surface snow amount is greater or equal to given threshold.

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

  • thresh (str) – Threshold snow amount.

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days where snow amount is greater than or equal to {thresh}.

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

Maximum snow amount.

The maximum daily snow amount.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

xclim.indices.snw_max_doy(snw, freq='YS-JUL')[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.

Return type:

DataArray

Returns:

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

xclim.indices.snw_season_end(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]

Snow cover end date (amount).

First day after the start of the continuous snow water cover when snow water is below a threshold for at least N consecutive days.

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

  • thresh (str) – Threshold snow amount.

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

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day after the start of the continuous snow amount cover.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices.snw_season_length(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]

Snow cover duration (amount).

The season starts when the snow amount is above a threshold for at least N consecutive days and stops when it drops below the same threshold for the same number of days.

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

  • thresh (Quantified) – Threshold snow amount.

  • window (int) – Minimum number of days with snow amount above and below threshold.

  • freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – Length of the snow season.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices.snw_season_start(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]

Snow cover start date (amount).

Day of year when snow water is above or equal to a threshold for at least N consecutive days.

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

  • thresh (str) – Threshold snow amount.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – First day of the year when the snow amount is superior to a threshold for a minimum duration.

References

Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]

xclim.indices.snw_storm_days(snw, thresh='10 kg m-2', freq='YS-JUL')[source]

Days with snowfall over threshold.

Number of days with snowfall amount accumulation greater or equal to threshold (default: 10 kg m-2).

Warning

The default freq is valid for the northern hemisphere.

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

  • thresh (Quantified) – Threshold on snowfall amount accumulation require to label an event a snw storm.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

Notes

Snowfall accumulation is estimated by the change in snow amount.

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

Snow depth from snow amount and density.

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

  • snr (Quantified, optional) – Snow density.

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

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

Return type:

DataArray

Returns:

xr.DataArray – Snow depth

Notes

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

References

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

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

Specific humidity from temperature, relative humidity and pressure.

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

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

  • hurs (xr.DataArray) – Relative Humidity.

  • ps (xr.DataArray) – Air Pressure.

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

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

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

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Specific humidity.

Notes

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

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

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

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

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

Examples

>>> from xclim.indices import specific_humidity
>>> rh = specific_humidity(
...     tas=tas_dataset,
...     hurs=hurs_dataset,
...     ps=ps_dataset,
...     ice_thresh="0 degC",
...     method="wmo08",
...     invalid_values="mask",
... )

References

World Meteorological Organization [2008]

xclim.indices.specific_humidity_from_dewpoint(tdps, ps, method='sonntag90')[source]

Specific humidity from dewpoint temperature and air pressure.

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

Parameters:
  • tdps (xr.DataArray) – Dewpoint temperature array.

  • ps (xr.DataArray) – Air pressure array.

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

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Specific humidity.

Notes

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

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

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

Examples

>>> from xclim.indices import specific_humidity_from_dewpoint
>>> rh = specific_humidity_from_dewpoint(
...     tdps=tas_dataset,
...     ps=ps_dataset,
...     method="wmo08",
... )

References

World Meteorological Organization [2008]

xclim.indices.standardized_precipitation_evapotranspiration_index(wb, wb_cal=None, freq='MS', window=1, dist='gamma', method='APP', offset='1.000 mm/d', cal_start=None, cal_end=None, params=None, **indexer)[source]

Standardized Precipitation Evapotranspiration Index (SPEI).

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

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

  • wb_cal (xarray.DataArray, optional) – Daily water budget used for calibration. Usually this is a temporal subset of wb over some reference period. This option will be removed in xclim >=0.47.0. Two behaviours will be possible (see below).

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

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

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

  • method ({‘APP’, ‘ML’}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate), or PWM (probability weighted moments). The approximate method uses a deterministic function that doesn’t involve any optimization. Available methods vary with the distribution: ‘gamma’:{‘APP’, ‘ML’, ‘PWM’}, ‘fisk’:{‘APP’, ‘ML’}

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

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

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

  • offset (Quantified) – For distributions bounded by zero (e.g. “gamma”, “fisk”), an offset must be added to the water budget to make sure there are no negative values. Keep the offset as small as possible to minimize its influence on the results. This can be given as a precipitation flux or a rate.

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

Return type:

DataArray

Returns:

xarray.DataArray – Standardized Precipitation Evapotranspiration Index.

Notes

If results include NaNs, check that the offset parameter is larger than the minimum water budget values.

See Standardized Precipitation Index (SPI) for more details on usage.

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

Standardized Precipitation Index (SPI).

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

  • pr_cal (xarray.DataArray, optional) – Daily precipitation used for calibration. Usually this is a temporal subset of pr over some reference period. This option will be removed in xclim >=0.47.0. Two behaviour will be possible (see below)

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

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

  • dist ({“gamma”, “fisk”}) – Name of the univariate distribution. (see scipy.stats).

  • method ({‘APP’, ‘ML’}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that doesn’t involve any optimization.

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

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

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

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

Return type:

DataArray

Returns:

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

Notes

  • The length N of the N-month SPI is determined by choosing the window = N.

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

    a log-logistic distribution

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

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

Example

>>> from datetime import datetime
>>> from xclim.indices import standardized_precipitation_index
>>> ds = xr.open_dataset(path_to_pr_file)
>>> pr = ds.pr
>>> cal_start, cal_end = "1990-05-01", "1990-08-31"
>>> spi_3 = standardized_precipitation_index(
...     pr,
...     freq="MS",
...     window=3,
...     dist="gamma",
...     method="ML",
...     cal_start=cal_start,
...     cal_end=cal_end,
... )  # Computing SPI-3 months using a gamma distribution for the fit
>>> # Fitting parameters can also be obtained ...
>>> from xclim.indices.stats import standardized_index_fit_params
>>> params = standardized_index_fit_params(
...     pr.sel(time=slice(cal_start, cal_end)),
...     freq="MS",
...     window=3,
...     dist="gamma",
...     method="ML",
... )  # First getting params
>>> # ... and used as input
>>> spi_3 = standardized_precipitation_index(pr, params=params)

References

McKee, Doesken, and Kleist [1993]

xclim.indices.tas(tasmin, tasmax)[source]

Average temperature from minimum and maximum temperatures.

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

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

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

Return type:

DataArray

Returns:

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

Examples

>>> from xclim.indices import tas
>>> tas = tas(tasmin_dataset, tasmax_dataset)
xclim.indices.temperature_seasonality(tas, freq='YS')[source]

Temperature seasonality (coefficient of variation).

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

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

  • freq (str) – Resampling frequency.

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

References

Xu and Hutchinson [2010]

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

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

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

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

Examples

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

Number of days with daily mean temperature over the 90th percentile.

Number of days with daily mean temperature over the 90th percentile.

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tg90p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tas_per = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tg90p(tas, tas_per)
xclim.indices.tg_days_above(tas, thresh='10.0 degC', freq='YS', op='>')[source]

The number of days with tas above a threshold.

Number of days where mean daily temperature exceeds a threshold (default: 10℃).

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

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

  • freq (str) – Resampling frequency.

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

Returns:

xarray.DataArray, [time] – Number of days where tas {op} threshold.

Notes

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

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

The number of days with tas below a threshold.

Number of days where mean daily temperature is below a threshold (default: 10℃).

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

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

  • freq (str) – Resampling frequency.

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

Returns:

xarray.DataArray, [time] – Number of days where tas {op} threshold.

Notes

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

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

Highest mean temperature.

The maximum of daily mean temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tas] – Maximum of daily mean temperature.

Notes

Let \(TN_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the maximum daily mean temperature for period \(j\) is:

\[TNx_j = max(TN_{ij})\]
xclim.indices.tg_mean(tas, freq='YS')[source]

Mean of daily average temperature.

Resample the original daily mean temperature series by taking the mean over each period.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tas] – The mean daily temperature at the given time frequency

Notes

Let \(TN_i\) be the mean daily temperature of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):

\[TG_p = \frac{\sum_{i=a}^{b} TN_i}{b - a + 1}\]

Examples

The following would compute for each grid cell of file tas.day.nc the mean temperature at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import tg_mean
>>> t = xr.open_dataset(path_to_tas_file).tas
>>> tg = tg_mean(t, freq="QS-DEC")
xclim.indices.tg_mean_warmcold_quarter(tas, op, freq='YS')[source]

Mean temperature of warmest/coldest quarter.

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

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

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

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 of the warmest quarter mean temperature:

>>> from xclim.indices import tg_mean_warmcold_quarter
>>> t = xr.open_dataset(path_to_tas_file)
>>> t_warm_qrt = tg_mean_warmcold_quarter(tas=t.tas, op="warmest")

Notes

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

References

Xu and Hutchinson [2010]

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

Mean temperature of wettest/driest quarter.

The wettest (or driest) quarter of the year is determined, and the mean temperature of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”), quarters are defined as 13-week periods, otherwise 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.

Return type:

DataArray

Returns:

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

Notes

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

References

Xu and Hutchinson [2010]

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

Lowest mean temperature.

Minimum of daily mean temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tas] – Minimum of daily minimum temperature.

Notes

Let \(TG_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the minimum daily mean temperature for period \(j\) is:

\[TGn_j = min(TG_{ij})\]
xclim.indices.tn10p(tasmin, tasmin_per, freq='YS', bootstrap=False, op='<')[source]

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

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

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

  • tasmin_per (xarray.DataArray) – 10th percentile of daily minimum temperature.

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

Examples

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

Number of days with daily minimum temperature over the 90th percentile.

Number of days with daily minimum temperature over the 90th percentile.

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

  • tasmin_per (xarray.DataArray) – 90th percentile of daily minimum temperature.

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tn90p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tas_per = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tn90p(tas, tas_per)
xclim.indices.tn_days_above(tasmin, thresh='20.0 degC', freq='YS', op='>')[source]

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

Number of days where minimum daily temperature exceeds a threshold (default: 20℃).

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

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

  • freq (str) – Resampling frequency.

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

Returns:

xarray.DataArray, [time] – Number of days where tasmin {op} threshold.

Notes

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

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

Number of days with tasmin below a threshold.

Number of days where minimum daily temperature is below a threshold (default: -10℃).

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days where tasmin {op} threshold.

Notes

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

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

Highest minimum temperature.

The maximum of daily minimum temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – Maximum of daily minimum temperature.

Notes

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

\[TNx_j = max(TN_{ij})\]
xclim.indices.tn_mean(tasmin, freq='YS')[source]

Mean minimum temperature.

Mean of daily minimum temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – Mean of daily minimum temperature.

Notes

Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:

\[TN_{ij} = \frac{ \sum_{i=1}^{I} TN_{ij} }{I}\]
xclim.indices.tn_min(tasmin, freq='YS')[source]

Lowest minimum temperature.

Minimum of daily minimum temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmin] – Minimum of daily minimum temperature.

Notes

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

\[TNn_j = min(TN_{ij})\]
xclim.indices.tx10p(tasmax, tasmax_per, freq='YS', bootstrap=False, op='<')[source]

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

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

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

  • tasmax_per (xarray.DataArray) – 10th percentile of daily maximum temperature.

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tx10p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tasmax_per = percentile_doy(tas, per=10).sel(percentiles=10)
>>> cold_days = tx10p(tas, tasmax_per)
xclim.indices.tx90p(tasmax, tasmax_per, freq='YS', bootstrap=False, op='>')[source]

Number of days with daily maximum temperature over the 90th percentile.

Number of days with daily maximum temperature over the 90th percentile.

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

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

  • freq (str) – Resampling frequency.

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

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

Return type:

DataArray

Returns:

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

Notes

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

Examples

>>> from xclim.core.calendar import percentile_doy
>>> from xclim.indices import tx90p
>>> tas = xr.open_dataset(path_to_tas_file).tas
>>> tasmax_per = percentile_doy(tas, per=90).sel(percentiles=90)
>>> hot_days = tx90p(tas, tasmax_per)
xclim.indices.tx_days_above(tasmax, thresh='25.0 degC', freq='YS', op='>')[source]

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

Number of days where maximum daily temperature exceeds a threshold (default: 25℃).

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

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

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

Notes

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

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

The number of days with tmax below a threshold.

Number of days where maximum daily temperature is below a threshold (default: 25℃).

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

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

  • freq (str) – Resampling frequency.

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

Returns:

xarray.DataArray, [time] – Number of days where tasmin {op} threshold.

Notes

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

\[TX_{ij} < Threshold [℃]\]
xclim.indices.tx_max(tasmax, freq='YS')[source]

Highest max temperature.

The maximum value of daily maximum temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmax] – Maximum value of daily maximum temperature.

Notes

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

\[TXx_j = max(TX_{ij})\]
xclim.indices.tx_mean(tasmax, freq='YS')[source]

Mean max temperature.

The mean of daily maximum temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmax] – Mean of daily maximum temperature.

Notes

Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:

\[TX_{ij} = \frac{ \sum_{i=1}^{I} TX_{ij} }{I}\]
xclim.indices.tx_min(tasmax, freq='YS')[source]

Lowest max temperature.

The minimum of daily maximum temperature.

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

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [same units as tasmax] – Minimum of daily maximum temperature.

Notes

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

\[TXn_j = min(TX_{ij})\]
xclim.indices.tx_tn_days_above(tasmin, tasmax, thresh_tasmin='22 degC', thresh_tasmax='30 degC', freq='YS', op='>')[source]

Number of days with both hot maximum and minimum daily temperatures.

The number of days per period with tasmin above a threshold and tasmax above another threshold.

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

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

  • thresh_tasmin (Quantified) – Threshold temperature for tasmin on which to base evaluation.

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

  • freq (str) – Resampling frequency.

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

Return type:

DataArray

Returns:

xarray.DataArray, [time] – the number of days with tasmin > thresh_tasmin and tasmax > thresh_tasmax per period.

Notes

Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\), \(TN_{ij}\) the daily minimum temperature at day \(i\) of period \(j\), \(TX_{thresh}\) the threshold for maximum daily temperature, and \(TN_{thresh}\) the threshold for minimum daily temperature. Then counted is the number of days where:

\[TX_{ij} > TX_{thresh} [℃]\]

and where:

\[TN_{ij} > TN_{thresh} [℃]\]
xclim.indices.uas_vas_2_sfcwind(uas, vas, calm_wind_thresh='0.5 m/s')[source]

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

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

Parameters:
  • uas (xr.DataArray) – Eastward wind velocity

  • vas (xr.DataArray) – Northward wind velocity

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

Return type:

tuple[DataArray, DataArray]

Returns:

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

  • wind_from_dir (xr.DataArray, [°]) – Direction from which the wind blows, following the meteorological convention where 360 stands for North and 0 for calm winds.

Examples

>>> from xclim.indices import uas_vas_2_sfcwind
>>> sfcWind = uas_vas_2_sfcwind(
...     uas=uas_dataset, vas=vas_dataset, calm_wind_thresh="0.5 m/s"
... )

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.universal_thermal_climate_index(tas, hurs, sfcWind, mrt=None, rsds=None, rsus=None, rlds=None, rlus=None, stat='sunlit', mask_invalid=True, wind_cap_min=False)[source]

Universal thermal climate index (UTCI).

The UTCI is the equivalent temperature for the environment derived from a reference environment and is used to evaluate heat stress in outdoor spaces.

Parameters:
  • tas (xarray.DataArray) – Mean temperature

  • hurs (xarray.DataArray) – Relative Humidity

  • sfcWind (xarray.DataArray) – Wind velocity

  • mrt (xarray.DataArray, optional) – Mean radiant temperature

  • rsds (xr.DataArray, optional) – Surface Downwelling Shortwave Radiation This is necessary if mrt is not None.

  • rsus (xr.DataArray, optional) – Surface Upwelling Shortwave Radiation This is necessary if mrt is not None.

  • rlds (xr.DataArray, optional) – Surface Downwelling Longwave Radiation This is necessary if mrt is not None.

  • rlus (xr.DataArray, optional) – Surface Upwelling Longwave Radiation This is necessary if mrt is not None.

  • stat ({‘instant’, ‘sunlit’}) – Which statistic to apply. If “instant”, the instantaneous cosine of the solar zenith angle is calculated. If “sunlit”, the cosine of the solar zenith angle is calculated during the sunlit period of each interval. This is necessary if mrt is not None.

  • mask_invalid (bool) – If True (default), UTCI values are NaN where any of the inputs are outside their validity ranges : -50°C < tas < 50°C, -30°C < tas - mrt < 30°C and 0.5 m/s < sfcWind < 17.0 m/s.

  • wind_cap_min (bool) – If True, wind velocities are capped to a minimum of 0.5 m/s following Bröde et al. [2012] usage guidalines. This ensures UTCI calculation for low winds. Default value False.

Return type:

DataArray

Returns:

xarray.DataArray – Universal Thermal Climate Index.

Notes

The calculation uses water vapour partial pressure, which is derived from relative humidity and saturation vapour pressure computed according to the ITS-90 equation.

This code was inspired by the pythermalcomfort and thermofeel packages.

Notes

See: http://www.utci.org/utcineu/utcineu.php

References

Bröde [2009], Bröde, Fiala, Błażejczyk, Holmér, Jendritzky, Kampmann, Tinz, and Havenith [2012], Błażejczyk, Jendritzky, Bröde, Fiala, Havenith, Epstein, Psikuta, and Kampmann [2013]

xclim.indices.warm_and_dry_days(tas, pr, tas_per, pr_per, freq='YS')[source]

Warm and dry days.

Returns the total number of days when “warm” and “Dry” conditions coincide.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature values

  • pr (xarray.DataArray) – Daily precipitation.

  • tas_per (xarray.DataArray) – Third quartile of daily mean temperature computed by month.

  • pr_per (xarray.DataArray) – First quartile of daily total precipitation computed by month.

  • freq (str) – Resampling frequency.

Return type:

xarray.DataArray

Warning

Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.

Return type:

DataArray

Returns:

xarray.DataArray, – The total number of days when 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 (Beniston [2009])

References

Beniston [2009]

xclim.indices.warm_and_wet_days(tas, pr, tas_per, pr_per, freq='YS')[source]

Warm and wet days.

Returns the total number of days when “warm” and “wet” conditions coincide.

Parameters:
  • tas (xarray.DataArray) – Mean daily temperature values

  • pr (xarray.DataArray) – Daily precipitation.

  • tas_per (xarray.DataArray) – Third quartile of daily mean temperature computed by month.

  • pr_per (xarray.DataArray) – Third quartile of daily total precipitation computed by month.

  • freq (str) – Resampling frequency.

Return type:

xarray.DataArray

Warning

Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.

Return type:

DataArray

Returns:

xarray.DataArray – The total number of days when 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 (Beniston [2009])

References

Beniston [2009]

xclim.indices.warm_day_frequency(tasmax, thresh='30 degC', freq='YS', op='>')[source]

Frequency of extreme warm days.

Return the number of days with maximum daily temperature exceeding threshold (default: 30℃) per period.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with tasmax {op} threshold per period.

Notes

Let \(TX_{ij}\) be the maximum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:

\[TN_{ij} > Threshold [℃]\]
xclim.indices.warm_night_frequency(tasmin, thresh='22 degC', freq='YS', op='>')[source]

Frequency of extreme warm nights.

Return the number of days with minimum daily temperature exceeding threshold (default: 22℃) per period.

Parameters:
  • tasmin (xarray.DataArray) – Minimum daily temperature.

  • thresh (Quantified) – Threshold temperature on which to base evaluation.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with tasmin {op} threshold per period.

xclim.indices.warm_spell_duration_index(tasmax, tasmax_per, window=6, freq='YS', resample_before_rl=True, bootstrap=False, op='>')[source]

Warm spell duration index.

Number of days inside spells of a minimum number of consecutive days when the daily maximum temperature is above the 90th percentile. The 90th percentile should be computed for a 5-day moving window, centered on each calendar day in the 1961-1990 period.

Parameters:
  • tasmax (xarray.DataArray) – Maximum daily temperature.

  • tasmax_per (xarray.DataArray) – percentile(s) of daily maximum temperature.

  • window (int) – Minimum number of days with temperature above threshold to qualify as a warm spell.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Keep bootstrap to False when there is no common period, it would give wrong results plus, bootstrapping is computationally expensive.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Warm spell duration index.

References

From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI; [Zhang et al., 2011]). Used in Alexander, Zhang, Peterson, Caesar, Gleason, Klein Tank, Haylock, Collins, Trewin, Rahimzadeh, Tagipour, Rupa Kumar, Revadekar, Griffiths, Vincent, Stephenson, Burn, Aguilar, Brunet, Taylor, New, Zhai, Rusticucci, and Vazquez-Aguirre [2006]

Examples

Note that this example does not use a proper 1961-1990 reference period.

>>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax.isel(lat=0, lon=0)
>>> tasmax_per = percentile_doy(tasmax, per=90).sel(percentiles=90)
>>> warm_spell_duration_index(tasmax, tasmax_per)
xclim.indices.water_budget(pr, evspsblpot=None, tasmin=None, tasmax=None, tas=None, lat=None, hurs=None, rsds=None, rsus=None, rlds=None, rlus=None, sfcWind=None, method='BR65')[source]

Precipitation minus potential evapotranspiration.

Precipitation minus potential evapotranspiration as a measure of an approximated surface water budget, where the potential evapotranspiration can be calculated with a given method.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • evspsblpot (xarray.DataArray, optional) – Potential evapotranspiration

  • tasmin (xarray.DataArray, optional) – Minimum daily temperature.

  • tasmax (xarray.DataArray, optional) – Maximum daily temperature.

  • tas (xarray.DataArray, optional) – Mean daily temperature.

  • lat (xarray.DataArray, optional) – Latitude coordinate, needed if evspsblpot is not given. If None, a CF-conformant “latitude” field must be available within the pr DataArray.

  • hurs (xarray.DataArray, optional) – Relative humidity.

  • rsds (xarray.DataArray, optional) – Surface Downwelling Shortwave Radiation

  • rsus (xarray.DataArray, optional) – Surface Upwelling Shortwave Radiation

  • rlds (xarray.DataArray, optional) – Surface Downwelling Longwave Radiation

  • rlus (xarray.DataArray, optional) – Surface Upwelling Longwave Radiation

  • sfcWind (xarray.DataArray, optional) – Surface wind velocity (at 10 m)

  • method (str) – Method to use to calculate the potential evapotranspiration.

Return type:

xarray.DataArray

Return type:

DataArray

Returns:

xarray.DataArray – Precipitation minus potential evapotranspiration.

xclim.indices.wet_spell_frequency(pr, thresh='1.0 mm', window=3, freq='YS', resample_before_rl=True, op='sum')[source]

Return the number of wet periods of n days and more.

Periods during which the accumulated or maximal daily precipitation amount on a window of n days is over threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation amount over which a period is considered dry. The value against which the threshold is compared depends on op .

  • window (int) – Minimum length of the spells.

  • freq (str) – Resampling frequency.

  • resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.

  • op ({“sum”,”max”}) – Operation to perform on the window. Default is “sum”, which checks that the sum of accumulated precipitation over the whole window is more than the threshold. “max” checks that the maximal daily precipitation amount within the window is more than the threshold. This is the same as verifying that each individual day is above the threshold.

Return type:

DataArray

Returns:

xarray.DataArray, [unitless] – The {freq} number of wet periods of minimum {window} days.

Examples

>>> from xclim.indices import wet_spell_frequency
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> dsf = wet_spell_frequency(pr=pr, op="sum")
>>> dsf = wet_spell_frequency(pr=pr, op="max")
xclim.indices.wet_spell_max_length(pr, thresh='1.0 mm', window=1, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Longest wet spell.

Maximum number of consecutive days in a wet period of minimum length, during which the maximum or accumulated precipitation within a window of the same length is over a threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Accumulated precipitation value over which a period is considered dry.

  • window (int) – Number of days when the maximum or accumulated precipitation is over 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.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} longest spell in wet periods of minimum {window} days.

Notes

The algorithm assumes days before and after the timeseries are “dry”, meaning that the condition for being considered part of a wet spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a wet spell only if the accumulated precipitation within the first three days is over the threshold. In comparison, a day in the middle of the series is considered part of a wet spell if any of the three 3-day periods of which it is part are considered wet (so a total of five days are included in the computation, compared to only three).

xclim.indices.wet_spell_total_length(pr, thresh='1.0 mm', window=3, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]

Total length of dry spells.

Total number of days in wet periods of a minimum length, during which the maximum or accumulated precipitation within a window of the same length is over a threshold.

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Accumulated precipitation value over which a period is considered dry.

  • window (int) – Number of days when the maximum or accumulated precipitation is over 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.

Return type:

DataArray

Returns:

xarray.DataArray, [days] – The {freq} total number of days in wet periods of minimum {window} days.

Notes

The algorithm assumes days before and after the timeseries are “dry”, meaning that the condition for being considered part of a wet spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a wet spell only if the accumulated precipitation within the first three days is over the threshold. In comparison, a day in the middle of the series is considered part of a wet spell if any of the three 3-day periods of which it is part are considered wet (so a total of five days are included in the computation, compared to only three).

xclim.indices.wetdays(pr, thresh='1.0 mm/day', freq='YS', op='>=')[source]

Wet days.

Return the total number of days during period with precipitation over threshold (default: 1.0 mm/day).

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The number of wet days for each period [day].

Examples

The following would compute for each grid cell of file pr.day.nc the number days with precipitation over 5 mm at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import wetdays
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> wd = wetdays(pr, thresh="5 mm/day", freq="QS-DEC")
xclim.indices.wetdays_prop(pr, thresh='1.0 mm/day', freq='YS', op='>=')[source]

Proportion of wet days.

Return the proportion of days during period with precipitation over threshold (default: 1.0 mm/day).

Parameters:
  • pr (xarray.DataArray) – Daily precipitation.

  • thresh (Quantified) – Precipitation value over which a day is considered wet.

  • freq (str) – Resampling frequency.

  • op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>=”.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – The proportion of wet days for each period [1].

Examples

The following would compute for each grid cell of file pr.day.nc the proportion of days with precipitation over 5 mm at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:

>>> from xclim.indices import wetdays_prop
>>> pr = xr.open_dataset(path_to_pr_file).pr
>>> wd = wetdays_prop(pr, thresh="5 mm/day", freq="QS-DEC")
xclim.indices.wind_chill_index(tas, sfcWind, method='CAN', mask_invalid=True)[source]

Wind chill index.

The Wind Chill Index is an estimation of how cold the weather feels to the average person. It is computed from the air temperature and the 10-m wind. As defined by the Environment and Climate Change Canada (Mekis, Vincent, Shephard, and Zhang [2015]), two equations exist, the conventional one and one for slow winds (usually < 5 km/h), see Notes.

Parameters:
  • tas (xarray.DataArray) – Surface air temperature.

  • sfcWind (xarray.DataArray) – Surface wind speed (10 m).

  • method ({‘CAN’, ‘US’}) – If “CAN” (default), a “slow wind” equation is used where winds are slower than 5 km/h, see Notes.

  • mask_invalid (bool) – Whether to mask values when the inputs are outside their validity range. or not. If True (default), points where the temperature is above a threshold are masked. The threshold is 0°C for the canadian method and 50°F for the american one. With the latter method, points where sfcWind < 3 mph are also masked.

Return type:

DataArray

Returns:

xarray.DataArray, [degC] – Wind Chill Index.

Notes

Following the calculations of Environment and Climate Change Canada, this function switches from the standardized index to another one for slow winds. The standard index is the same as used by the National Weather Service of the USA [US Department of Commerce, n.d.]. Given a temperature at surface \(T\) (in °C) and 10-m wind speed \(V\) (in km/h), the Wind Chill Index \(W\) (dimensionless) is computed as:

\[W = 13.12 + 0.6125*T - 11.37*V^0.16 + 0.3965*T*V^0.16\]

Under slow winds (\(V < 5\) km/h), and using the canadian method, it becomes:

\[W = T + \frac{-1.59 + 0.1345 * T}{5} * V\]

Both equations are invalid for temperature over 0°C in the canadian method.

The american Wind Chill Temperature index (WCT), as defined by USA’s National Weather Service, is computed when method=’US’. In that case, the maximal valid temperature is 50°F (10 °C) and minimal wind speed is 3 mph (4.8 km/h).

For more information, see:

References

Mekis, Vincent, Shephard, and Zhang [2015], US Department of Commerce [n.d.]

xclim.indices.wind_power_potential(wind_speed, air_density=None, cut_in='3.5 m/s', rated='13 m/s', cut_out='25 m/s')[source]

Wind power potential estimated from an idealized wind power production factor.

The actual power production of a wind farm can be estimated by multiplying its nominal (nameplate) capacity by the wind power potential, which depends on wind speed at the hub height, the turbine specifications and air density.

Parameters:
  • wind_speed (xarray.DataArray) – Wind speed at the hub height. Use the wind_profile function to estimate from the surface wind speed.

  • air_density (xarray.DataArray) – Air density at the hub height. Defaults to 1.225 kg/m³. This is worth changing if applying in cold or mountainous regions with non-standard air density.

  • cut_in (Quantified) – Cut-in wind speed. Default is 3.5 m/s.

  • rated (Quantified) – Rated wind speed. Default is 13 m/s.

  • cut_out (Quantified) – Cut-out wind speed. Default is 25 m/s.

Return type:

DataArray

Returns:

xr.DataArray – The power production factor. Multiply by the nominal capacity to get the actual power production.

See also

wind_profile

Estimate wind speed at the hub height from the surface wind speed.

Notes

This estimate of wind power production is based on an idealized power curve with four wind regimes specified by the cut-in wind speed (\(u_i\)), the rated speed (\(u_r\)) and the cut-out speed (\(u_o\)). Power production is zero for wind speeds below the cut-in speed, increases cubically between the cut-in and rated speed, is constant between the rated and cut-out speed, and is zero for wind speeds above the cut-out speed to avoid damage to the turbine [Tobin et al., 2018]:

\[\begin{split}\begin{cases} 0, & v < u_i \\ (v^3 - u_i^3) / (u_r^3 - u_i^3), & u_i ≤ v < u_r \\ 1, & u_r ≤ v < u_o \\ 0, & v ≥ u_o \end{cases}\end{split}\]

For non-standard air density (\(\rho\)), the wind speed is scaled using \(v_n = v \left( \frac{\rho}{\rho_0} \right)^{1/3}\).

The temporal resolution of wind time series has a significant influence on the results: mean daily wind speeds yield lower values than hourly wind speeds. Note however that percent changes in the wind power potential climate projections are similar across resolutions [Chen, 2020].

To compute the power production, multiply the power production factor by the nominal turbine capacity (e.g. 100), set the units attribute (e.g. “MW”), resample and sum with xclim.indices.generic.select_resample_op(power, op=”sum”, freq=”D”), then convert to the desired units (e.g. “MWh”) using xclim.core.units.convert_units_to.

References

Chen [2020], Tobin, Greuell, Jerez, Ludwig, Vautard, van Vliet, and Bréon [2018].

xclim.indices.wind_profile(wind_speed, h, h_r, method='power_law', **kwds)[source]

Wind speed at a given height estimated from the wind speed at a reference height.

Estimate the wind speed based on a power law profile relating wind speed to height above the surface.

Parameters:
  • wind_speed (xarray.DataArray) – Wind speed at the reference height.

  • h (Quantified) – Height at which to compute the wind speed.

  • h_r (Quantified) – Reference height.

  • method ({“power_law”}) – Method to use. Currently only “power_law” is implemented.

  • kwds (dict) – Additional keyword arguments to pass to the method. For power_law, this is alpha, which takes a default value of 1/7, but is highly variable based on topography, surface cover and atmospheric stability.

Notes

The power law profile is given by

\[v = v_r \left( \frac{h}{h_r} \right)^{\alpha},\]

where \(v_r\) is the wind speed at the reference height, \(h\) is the height at which the wind speed is desired, and \(h_r\) is the reference height.

xclim.indices.windy_days(sfcWind, thresh='10.8 m s-1', freq='MS')[source]

Windy days.

The number of days with average near-surface wind speed above threshold (default: 10.8 m/s).

Parameters:
  • sfcWind (xarray.DataArray) – Daily average near-surface wind speed.

  • thresh (Quantified) – Threshold average near-surface wind speed on which to base evaluation.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray, [time] – Number of days with average near-surface wind speed above threshold.

Notes

Let \(WS_{ij}\) be the windspeed at day \(i\) of period \(j\). Then counted is the number of days where:

\[WS_{ij} >= Threshold [m s-1]\]
xclim.indices.winter_rain_ratio(*, pr, prsn=None, tas=None, freq='QS-DEC')[source]

Ratio of rainfall to total precipitation during winter.

The ratio of total liquid precipitation over the total precipitation over the winter months (DJF). If solid precipitation is not provided, then precipitation is assumed solid if the temperature is below 0°C.

Parameters:
  • pr (xarray.DataArray) – Mean daily precipitation flux.

  • prsn (xarray.DataArray, optional) – Mean daily solid precipitation flux.

  • tas (xarray.DataArray, optional) – Mean daily temperature.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xarray.DataArray – Ratio of rainfall to total precipitation during winter months (DJF).

Indices submodules

Generic Indices Submodule

Helper functions for common generic actions done in the computation of indices.

xclim.indices.generic.aggregate_between_dates(data, start, end, op='sum', freq=None)[source]

Aggregate the data over a period between start and end dates and apply the operator on the aggregated data.

Parameters:
  • data (xr.DataArray) – Data to aggregate between start and end dates.

  • start (xr.DataArray or DayOfYearStr) – Start dates (as day-of-year) for the aggregation periods.

  • end (xr.DataArray or DayOfYearStr) – End (as day-of-year) dates for the aggregation periods.

  • op ({‘min’, ‘max’, ‘sum’, ‘mean’, ‘std’}) – Operator.

  • freq (str, optional) – Resampling frequency defining the periods as defined in Resampling. Default: None.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Aggregated data between the start and end dates. If the end date is before the start date, returns np.nan. If there is no start and/or end date, returns np.nan.

xclim.indices.generic.compare(left, op, right, constrain=None)[source]

Compare a dataArray to a threshold using given operator.

Parameters:
  • left (xr.DataArray) – A DatArray being evaluated against right.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • right (float, int, np.ndarray, or xr.DataArray) – A value or array-like being evaluated against left`.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – Boolean mask of the comparison.

xclim.indices.generic.count_level_crossings(low_data, high_data, threshold, freq, *, op_low='<', op_high='>=')[source]

Calculate the number of times low_data is below threshold while high_data is above threshold.

First, the threshold is transformed to the same standard_name and units as the input data, then the thresholding is performed, and finally, the number of occurrences is counted.

Parameters:
  • low_data (xr.DataArray) – Variable that must be under the threshold.

  • high_data (xr.DataArray) – Variable that must be above the threshold.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op_low ({“<”, “<=”, “lt”, “le”}) – Comparison operator for low_data. Default: “<”.

  • op_high ({“>”, “>=”, “gt”, “ge”}) – Comparison operator for high_data. Default: “>=”.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.count_occurrences(data, threshold, freq, op, constrain=None)[source]

Calculate the number of times some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, then this counts the number of times data < threshold. Finally, count the number of occurrences when condition is met.

Parameters:
  • data (xr.DataArray) – An array.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.cumulative_difference(data, threshold, op, freq=None)[source]

Calculate the cumulative difference below/above a given value threshold.

Parameters:
  • data (xr.DataArray) – Data for which to determine the cumulative difference.

  • threshold (Quantified) – The value threshold.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – Logical operator. e.g. arr > thresh.

  • freq (str, optional) – Resampling frequency defining the periods as defined in Resampling. If None, no resampling is performed. Default: None.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.default_freq(**indexer)[source]

Return the default frequency.

Return type:

str

xclim.indices.generic.detrend(ds, dim='time', deg=1)[source]

Detrend data along a given dimension computing a polynomial trend of a given order.

Parameters:
  • ds (xr.Dataset or xr.DataArray) – The data to detrend. If a Dataset, detrending is done on all data variables.

  • dim (str) – Dimension along which to compute the trend.

  • deg (int) – Degree of the polynomial to fit.

Returns:

detrended (xr.Dataset or xr.DataArray) – Same as ds, but with its trend removed (subtracted).

xclim.indices.generic.diurnal_temperature_range(low_data, high_data, reducer, freq)[source]

Calculate the diurnal temperature range and reduce according to a statistic.

Parameters:
  • low_data (xr.DataArray) – The lowest daily temperature (tasmin).

  • high_data (xr.DataArray) – The highest daily temperature (tasmax).

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.domain_count(da, low, high, freq)[source]

Count number of days where value is within low and high thresholds.

A value is counted if it is larger than low, and smaller or equal to high, i.e. in ]low, high].

Parameters:
  • da (xr.DataArray) – Input data.

  • low (scalar or DataArray) – Minimum threshold value.

  • high (scalar or DataArray) – Maximum threshold value.

  • freq (str) – Resampling frequency defining the periods defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray – The number of days where value is within [low, high] for each period.

xclim.indices.generic.doymax(da)[source]

Return the day of year of the maximum value.

Return type:

DataArray

xclim.indices.generic.doymin(da)[source]

Return the day of year of the minimum value.

Return type:

DataArray

xclim.indices.generic.extreme_temperature_range(low_data, high_data, freq)[source]

Calculate the extreme temperature range as the maximum of daily maximum temperature minus the minimum of daily minimum temperature.

Parameters:
  • low_data (xr.DataArray) – The lowest daily temperature (tasmin).

  • high_data (xr.DataArray) – The highest daily temperature (tasmax).

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.first_day_threshold_reached(data, *, threshold, op, after_date, window=1, freq='YS', constrain=None)[source]

First day of values exceeding threshold.

Returns first day of period where values reach or exceed a threshold over a given number of days, limited to a starting calendar date.

Parameters:
  • data (xarray.DataArray) – Dataset being evaluated.

  • threshold (str) – Threshold on which to base evaluation.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • after_date (str) – Date of the year after which to look for the first event. Should have the format ‘%m-%d’.

  • window (int) – Minimum number of days with values above threshold needed for evaluation. Default: 1.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling. Default: “YS”.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Day of the year when value reaches or exceeds a threshold over a given number of days for the first time. If there is no such day, returns np.nan.

xclim.indices.generic.first_occurrence(data, threshold, freq, op, constrain=None)[source]

Calculate the first time some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, locate the first occurrence when condition is met.

Parameters:
  • data (xr.DataArray) – Input data.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.get_daily_events(da, threshold, op, constrain=None)[source]

Return a 0/1 mask when a condition is True or False.

Parameters:
  • da (xr.DataArray) – Input data.

  • threshold (float) – Threshold value.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

xarray.DataArray

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

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.get_op(op, constrain=None)[source]

Get python’s comparing function according to its name of representation and validate allowed usage.

Accepted op string are keys and values of xclim.indices.generic.binary_ops.

Parameters:
  • op (str) – Operator.

  • constrain (sequence of str, optional) – A tuple of allowed operators.

Return type:

Callable

xclim.indices.generic.get_zones(da, zone_min=None, zone_max=None, zone_step=None, bins=None, exclude_boundary_zones=True, close_last_zone_right_boundary=True)[source]

Divide data into zones and attribute a zone coordinate to each input value.

Divide values into zones corresponding to bins of width zone_step beginning at zone_min and ending at zone_max. Bins are inclusive on the left values and exclusive on the right values.

Parameters:
  • da (xarray.DataArray) – Input data

  • zone_min (Quantity | None) – Left boundary of the first zone

  • zone_max (Quantity | None) – Right boundary of the last zone

  • zone_step (Quantity | None) – Size of zones

  • bins (xr.DataArray | list[Quantity] | None) – Zones to be used, either as a DataArray with appropriate units or a list of Quantity

  • exclude_boundary_zones (Bool) – Determines whether a zone value is attributed for values in ]`-np.inf`, zone_min`[ and [`zone_max, np.inf[.

  • close_last_zone_right_boundary (Bool) – Determines if the right boundary of the last zone is closed.

Return type:

DataArray

Returns:

xarray.DataArray, [dimensionless] – Zone index for each value in da. Zones are returned as an integer range, starting from 0

xclim.indices.generic.interday_diurnal_temperature_range(low_data, high_data, freq)[source]

Calculate the average absolute day-to-day difference in diurnal temperature range.

Parameters:
  • low_data (xr.DataArray) – The lowest daily temperature (tasmin).

  • high_data (xr.DataArray) – The highest daily temperature (tasmax).

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.last_occurrence(data, threshold, freq, op, constrain=None)[source]

Calculate the last time some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, locate the last occurrence when condition is met.

Parameters:
  • data (xr.DataArray) – Input data.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.select_resample_op(da, op, freq='YS', out_units=None, **indexer)[source]

Apply operation over each period that is part of the index selection.

Parameters:
  • da (xr.DataArray) – Input data.

  • op (str {‘min’, ‘max’, ‘mean’, ‘std’, ‘var’, ‘count’, ‘sum’, ‘integral’, ‘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 Resampling.

  • out_units (str, optional) – Output units to assign. Only necessary if op is function not supported by xclim.core.units.to_agg_units().

  • indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. For example, use season=’DJF’ to select winter values, month=1 to select January, or month=[6,7,8] to select summer months. If not indexer is given, all values are considered.

Return type:

DataArray

Returns:

xr.DataArray – The maximum value for each period.

xclim.indices.generic.spell_length(data, threshold, reducer, freq, op)[source]

Calculate statistics on lengths of spells.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Then the spells are determined, and finally the statistics according to the specified reducer are calculated.

Parameters:
  • data (xr.DataArray) – Input data.

  • threshold (Quantified) – Threshold.

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.statistics(data, reducer, freq)[source]

Calculate a simple statistic of the data.

Parameters:
  • data (xr.DataArray) – Input data.

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.temperature_sum(data, op, threshold, freq)[source]

Calculate the temperature sum above/below a threshold.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, the sum is calculated for those data values that fulfill the condition after subtraction of the threshold value. If the sum is for values below the threshold the result is multiplied by -1.

Parameters:
  • data (xr.DataArray) – Input data.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – Logical operator. e.g. arr > thresh.

  • threshold (Quantified) – Threshold.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

Return type:

DataArray

Returns:

xr.DataArray

xclim.indices.generic.threshold_count(da, op, threshold, freq, constrain=None)[source]

Count number of days where value is above or below threshold.

Parameters:
  • da (xr.DataArray) – Input data.

  • op ({“>”, “<”, “>=”, “<=”, “gt”, “lt”, “ge”, “le”}) – Logical operator. e.g. arr > thresh.

  • threshold (Union[float, int]) – Threshold value.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • constrain (sequence of str, optional) – Optionally allowed conditions.

Return type:

DataArray

Returns:

xr.DataArray – The number of days meeting the constraints for each period.

xclim.indices.generic.thresholded_statistics(data, op, threshold, reducer, freq, constrain=None)[source]

Calculate a simple statistic of the data for which some condition is met.

First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, the statistic is calculated for those data values that fulfill the condition.

Parameters:
  • data (xr.DataArray) – Input data.

  • op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.

  • threshold (Quantified) – Threshold.

  • reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.

  • freq (str) – Resampling frequency defining the periods as defined in Resampling.

  • constrain (sequence of str, optional) – Optionally allowed conditions. Default: None.

Return type:

DataArray

Returns:

xr.DataArray

Indices Helper Functions Submodule

Functions that encapsulate some geophysical logic but could be shared by many indices.

xclim.indices.helpers.cosine_of_solar_zenith_angle(time, declination, lat, lon='0 °', time_correction=None, stat='average', sunlit=False, chunks=None)[source]

Cosine of the solar zenith angle.

The solar zenith angle is the angle between a vertical line (perpendicular to the ground) and the sun rays. This function computes a statistic of its cosine : its instantaneous value, the integral from sunrise to sunset or the average over the same period or over a subdaily interval. Based on Kalogirou [2014] and Di Napoli et al. [2020].

Parameters:
  • time (xr.DataArray) – The UTC time. If not daily and stat is “integral” or “average”, the timestamp is taken as the start of interval. If daily, the interval is assumed to be centered on Noon. If fewer than three timesteps are given, a daily frequency is assumed.

  • declination (xr.DataArray) – Solar declination. See solar_declination().

  • lat (Quantified) – Latitude.

  • lon (Quantified) – Longitude. Needed if the input timeseries is subdaily.

  • time_correction (xr.DataArray, optional) – Time correction for solar angle. See time_correction_for_solar_angle() This is necessary if stat is “instant”.

  • stat ({‘average’, ‘integral’, ‘instant’}) – Which daily statistic to return. If “average”, this returns the average of the cosine of the zenith angle If “integral”, this returns the integral of the cosine of the zenith angle If “instant”, this returns the instantaneous cosine of the zenith angle

  • sunlit (bool) – If True, only the sunlit part of the interval is considered in the integral or average. Does nothing if stat is “instant”.

  • chunks (dictionary) – When time, lat and lon originate from coordinates of a large chunked dataset, this dataset’s chunking can be passed here to ensure the computation is also chunked.

Return type:

DataArray

Returns:

xr.DataArray, [rad] or [dimensionless] – Cosine of the solar zenith angle. If stat is “integral”, dimensions can be said to be “time” as the integral is on the hour angle. For seconds, multiply by the number of seconds in a complete day cycle (24*60*60) and divide by 2π.

Notes

This code was inspired by the thermofeel and PyWBGT package.

References

Di Napoli, Hogan, and Pappenberger [2020], Kalogirou [2014]

xclim.indices.helpers.day_angle(time)[source]

Day of year as an angle.

Assuming the earth makes a full circle in a year, this is the angle covered from the beginning of the year up to that timestep. Also called the “julian day fraction”. See datetime_to_decimal_year().

xclim.indices.helpers.day_lengths(dates, lat, method='spencer')[source]

Day-lengths according to latitude and day of year.

See solar_declination() for the approximation used to compute the solar declination angle. Based on Kalogirou [2014].

Parameters:
  • dates (xr.DataArray) – Daily datetime data. This function makes no sense with data of other frequency.

  • lat (xarray.DataArray) – Latitude coordinate.

  • method ({‘spencer’, ‘simple’}) – Which approximation to use when computing the solar declination angle. See solar_declination().

Return type:

DataArray

Returns:

xarray.DataArray, [hours] – Day-lengths in hours per individual day.

References

Kalogirou [2014]

xclim.indices.helpers.distance_from_sun(dates)[source]

Sun-earth distance.

The distance from sun to earth in astronomical units.

Parameters:

dates (xr.DataArray) – Series of dates and time of days.

Return type:

DataArray

Returns:

xr.DataArray, [astronomical units] – Sun-earth distance.

References

# TODO: Find a way to reference this U.S. Naval Observatory:Astronomical Almanac. Washington, D.C.: U.S. Government Printing Office (1985).

xclim.indices.helpers.eccentricity_correction_factor(time, method='spencer')[source]

Eccentricity correction factor of the Earth’s orbit.

The squared ratio of the mean distance Earth-Sun to the distance at a specific moment. As approximated by Spencer [1971].

Parameters:
  • time (xr.DataArray) – Time coordinate

  • method (str) – Which approximation to use. The default (“spencer”) uses the first five terms of the fourier series of the eccentricity, while “simple” approximates with only the first two.

Returns:

xr.DataArray, [dimensionless] – Eccentricity correction factor.

References

Perrin [1975], Spencer [1971]

xclim.indices.helpers.extraterrestrial_solar_radiation(times, lat, solar_constant='1361 W m-2', method='spencer', chunks=None)[source]

Extraterrestrial solar radiation.

This is the daily energy received on a surface parallel to the ground at the mean distance of the earth to the sun. It neglects the effect of the atmosphere. Computation is based on Kalogirou [2014] and the default solar constant is taken from Matthes et al. [2017].

Parameters:
  • times (xr.DataArray) – Daily datetime data. This function makes no sense with data of other frequency.

  • lat (xr.DataArray) – Latitude.

  • solar_constant (str) – The solar constant, the energy received on earth from the sun per surface per time.

  • method ({‘spencer’, ‘simple’}) – Which method to use when computing the solar declination and the eccentricity correction factor. See solar_declination() and eccentricity_correction_factor().

  • chunks (dictionary) – When times and lat originate from coordinates of a large chunked dataset, passing the dataset’s chunks here will ensure the computation is chunked as well.

Return type:

DataArray

Returns:

Extraterrestrial solar radiation, [J m-2 d-1]

References

Kalogirou [2014], Matthes, Funke, Andersson, Barnard, Beer, Charbonneau, Clilverd, Dudok de Wit, Haberreiter, Hendry, Jackman, Kretzschmar, Kruschke, Kunze, Langematz, Marsh, Maycock, Misios, Rodger, Scaife, Seppälä, Shangguan, Sinnhuber, Tourpali, Usoskin, van de Kamp, Verronen, and Versick [2017]

xclim.indices.helpers.solar_declination(time, method='spencer')[source]

Solar declination.

The angle between the sun rays and the earth’s equator, in radians, as approximated by Spencer [1971] or assuming the orbit is a circle.

Parameters:
  • time (xr.DataArray) – Time coordinate.

  • method ({‘spencer’, ‘simple’}) – Which approximation to use. The default (“spencer”) uses the first 7 terms of the Fourier series representing the observed declination, while “simple” assumes the orbit is a circle with a fixed obliquity and that the solstice/equinox happen at fixed angles on the orbit (the exact calendar date changes for leap years).

Return type:

DataArray

Returns:

xr.DataArray, [rad] – Solar declination angle.

References

Spencer [1971]

xclim.indices.helpers.time_correction_for_solar_angle(time)[source]

Time correction for solar angle.

Every 1° of angular rotation on earth is equal to 4 minutes of time. The time correction is needed to adjust local watch time to solar time.

Parameters:

time (xr.DataArray) – Time coordinate.

Return type:

DataArray

Returns:

xr.DataArray, [rad] – Time correction of solar angle.

References

Di Napoli, Hogan, and Pappenberger [2020]

xclim.indices.helpers.wind_speed_height_conversion(ua, h_source, h_target, method='log')[source]

Wind speed at two meters.

Parameters:
  • ua (xarray.DataArray) – Wind speed at height h

  • h_source (str) – Height of the input wind speed ua (e.g. h == “10 m” for a wind speed at 10 meters)

  • h_target (str) – Height of the output wind speed

  • method ({“log”}) – Method used to convert wind speed from one height to another

Return type:

DataArray

Returns:

xarray.DataArray – Wind speed at height h_target

References

Allen, Pereira, Raes, and Smith [1998]

Run-Length Algorithms Submodule

Computation of statistics on runs of True values in boolean arrays.

xclim.indices.run_length.extract_events(da_start, window_start, da_stop, window_stop, dim='time')[source]

Extract events, i.e. runs whose starting and stopping points are defined through run length conditions.

Parameters:
  • da_start (xr.DataArray) – Input array where run sequences are searched to define the start points in the main runs

  • window_start (int,) – Number of True (1) values needed to start a run in da_start

  • da_stop (xr.DataArray) – Input array where run sequences are searched to define the stop points in the main runs

  • window_stop (int,) – Number of True (1) values needed to start a run in da_stop

  • dim (str) – Dimension name.

Return type:

DataArray

Returns:

xr.DataArray – Output array with 1’s when in a run sequence and with 0’s elsewhere.

Notes

A season (as defined in season) could be considered as an event with window_stop == window_start and da_stop == 1 - da_start, although it has more constraints on when to start and stop a run through the date argument.

xclim.indices.run_length.first_run(da, window, dim='time', freq=None, coord=False, ufunc_1dim='from_context')[source]

Return the index of the first item of the first run of at least a given length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of first item in first valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.first_run_1d(arr, window)[source]

Return the index of the first item of a run of at least a given length.

Parameters:
  • arr (Sequence[Union[int, float]]) – Input array.

  • window (int) – Minimum duration of consecutive run to accumulate values.

Return type:

int | np.nan

Returns:

int or np.nan – Index of first item in first valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.first_run_after_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]

Return the index of the first item of the first run after a given date.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • date (DayOfYearStr) – The date after which to look for the run.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of first item in the first valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.first_run_ufunc(x, window, dim)[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.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.index_of_date(time, date, max_idxs=None, default=0)[source]

Get the index of a date in a time array.

Parameters:
  • time (xr.DataArray) – An array of datetime values, any calendar.

  • date (DayOfYearStr or DateStr, optional) – A string in the “yyyy-mm-dd” or “mm-dd” format. If None, returns default.

  • max_idxs (int, optional) – Maximum number of returned indexes.

  • default (int) – Index to return if date is None.

Raises:

ValueError – If there are most instances of date in time than max_idxs.

Return type:

ndarray

Returns:

numpy.ndarray – 1D array of integers, indexes of date in time.

xclim.indices.run_length.keep_longest_run(da, dim='time', freq=None)[source]

Keep the longest run along a dimension.

Parameters:
  • da (xr.DataArray) – Boolean array.

  • dim (str) – Dimension along which to check for the longest run.

  • freq (str) – Resampling frequency.

Return type:

DataArray

Returns:

xr.DataArray, [bool] – Boolean array similar to da but with only one run, the (first) longest.

xclim.indices.run_length.last_run(da, window, dim='time', freq=None, coord=False, ufunc_1dim='from_context')[source]

Return the index of the last item of the last run of at least a given length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for a DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.last_run_before_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]

Return the index of the last item of the last run before a given date.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • date (DayOfYearStr) – The date before which to look for the last event.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.lazy_indexing(da, index, dim=None)[source]

Get values of da at indices index in a NaN-aware and lazy manner.

Parameters:
  • da (xr.DataArray) – Input array. If not 1D, dim must be given and must not appear in index.

  • index (xr.DataArray) – N-d integer indices, if 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.

Return type:

DataArray

Returns:

xr.DataArray – Values of da at indices index.

xclim.indices.run_length.longest_run(da, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the length of the longest consecutive run of True values.

Parameters:
  • da (xr.DataArray) – N-dimensional array (boolean).

  • dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Length of the longest run of True values along dimension (int).

xclim.indices.run_length.npts_opt = 9000

Arrays with less than this number of data points per slice will trigger the use of the ufunc version of run lengths algorithms.

xclim.indices.run_length.resample_and_rl(da, resample_before_rl, compute, *args, freq, dim='time', **kwargs)[source]

Wrap run length algorithms to control if resampling occurs before or after the algorithms.

Parameters:
  • da (xr.DataArray) – N-dimensional array (boolean).

  • resample_before_rl (bool) – Determines whether if input arrays of runs da should be separated in period before or after the run length algorithms are applied.

  • compute – Run length function to apply

  • args – Positional arguments needed in compute.

  • dim (str) – The dimension along which to find runs.

  • freq (str) – Resampling frequency.

  • kwargs – Keyword arguments needed in compute.

Return type:

DataArray | Dataset

Returns:

xr.DataArray – Output of compute resampled according to frequency {freq}.

xclim.indices.run_length.rle(da, dim='time', index='first')[source]

Generate basic run length function.

Parameters:
  • da (xr.DataArray) – Input array.

  • dim (str) – Dimension name.

  • index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray – Values are 0 where da is False (out of runs).

xclim.indices.run_length.rle_1d(arr)[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.

Return type:

tuple[array, array, array]

Returns:

  • values (np.array) – The values taken by arr over each run.

  • run lengths (np.array) – The length of each run.

  • start position (np.array) – The starting index of each run.

Examples

>>> from xclim.indices.run_length import rle_1d
>>> a = [1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3]
>>> rle_1d(a)
(array([1, 2, 3]), array([2, 4, 6]), array([0, 2, 6]))
xclim.indices.run_length.rle_statistics(da, reducer, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the length of consecutive run of True values, according to a reducing operator.

Parameters:
  • da (xr.DataArray) – N-dimensional array (boolean).

  • reducer (str) – Name of the reducing function.

  • window (int) – Minimal length of consecutive runs to be included in the statistics.

  • dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Length of runs of True values along dimension, according to the reducing function (float) If there are no runs (but the data is valid), returns 0.

xclim.indices.run_length.run_bounds(mask, dim='time', coord=True)[source]

Return the start and end dates of boolean runs along a dimension.

Parameters:
  • mask (xr.DataArray) – Boolean array.

  • dim (str) – Dimension along which to look for runs.

  • coord (bool or str) – If True, return values of the coordinate, if a string, returns values from dim.dt.<coord>. If False, return indexes.

Returns:

xr.DataArray – With dim reduced to “events” and “bounds”. The events dim is as long as needed, padded with NaN or NaT.

xclim.indices.run_length.run_end_after_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]

Return the index of the first item after the end of a run after a given date.

The run must begin before the date.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum duration of consecutive run to accumulate values.

  • date (str) – The date after which to look for the end of a run.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).

Return type:

DataArray

Returns:

xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.

xclim.indices.run_length.season(da, window, date=None, dim='time', coord=False)[source]

Calculate the bounds of a season along a dimension.

A “season” is a run of True values that may include breaks under a given length (window). The start is computed as the first run of window True values, 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’).

Return type:

Dataset

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, window, date=None, dim='time')[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’).

Return type:

DataArray

Returns:

xr.DataArray, [int] – 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 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.statistics_run_1d(arr, reducer, window)[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

Return type:

int

Returns:

int – Statistics on length of runs.

xclim.indices.run_length.statistics_run_ufunc(x, reducer, window, dim='time')[source]

Dask-parallel version of statistics_run_1d, 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.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.suspicious_run(arr, dim='time', window=10, op='>', thresh=None)[source]

Return True where the array contains has runs of identical values, vectorized version.

In opposition to other run length functions, here the output has the same shape as the input.

Parameters:
  • arr (xr.DataArray) – Array of values to be parsed.

  • dim (str) – Dimension along which to check for runs (default: “time”).

  • window (int) – Minimum run length.

  • op ({“>”, “>=”, “==”, “<”, “<=”, “eq”, “gt”, “lt”, “gteq”, “lteq”}) – Operator for threshold comparison, defaults to “>”.

  • thresh (float, optional) – Threshold above which values are checked for identical values.

Return type:

DataArray

Returns:

xarray.DataArray

xclim.indices.run_length.suspicious_run_1d(arr, window=10, op='>', thresh=None)[source]

Return True where the array contains a run of identical values.

Parameters:
  • arr (numpy.ndarray) – Array of values to be parsed.

  • window (int) – Minimum run length.

  • op ({“>”, “>=”, “==”, “<”, “<=”, “eq”, “gt”, “lt”, “gteq”, “lteq”, “ge”, “le”}) – Operator for threshold comparison. Defaults to “>”.

  • thresh (float, optional) – Threshold compared against which values are checked for identical values.

Return type:

ndarray

Returns:

numpy.ndarray – Whether or not the data points are part of a run of identical values.

xclim.indices.run_length.use_ufunc(ufunc_1dim, da, dim='time', freq=None, index='first')[source]

Return whether the ufunc version of run length algorithms should be used with this DataArray or not.

If ufunc_1dim is ‘from_context’, the parameter is read from xclim’s global (or context) options. If it is ‘auto’, this returns False for dask-backed array and for arrays with more than npts_opt points per slice along dim.

Parameters:
  • ufunc_1dim ({‘from_context’, ‘auto’, True, False}) – The method for handling the ufunc parameters.

  • da (xr.DataArray) – Input array.

  • dim (str) – The dimension along which to find runs.

  • freq (str) – Resampling frequency.

  • index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

bool

Returns:

bool – If ufunc_1dim is “auto”, returns True if the array is on dask or too large. Otherwise, returns ufunc_1dim.

xclim.indices.run_length.windowed_run_count(da, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the number of consecutive true values in array for runs at least as long as given duration.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Total number of True values part of a consecutive runs of at least window long.

xclim.indices.run_length.windowed_run_count_1d(arr, window)[source]

Return the number of consecutive true values in array for runs at least as long as given duration.

Parameters:
  • arr (Sequence[bool]) – Input array (bool).

  • window (int) – Minimum duration of consecutive run to accumulate values.

Return type:

int

Returns:

int – Total number of true values part of a consecutive run at least window long.

xclim.indices.run_length.windowed_run_count_ufunc(x, window, dim)[source]

Dask-parallel version of windowed_run_count_1d, 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.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

xclim.indices.run_length.windowed_run_events(da, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]

Return the number of runs of a minimum length.

Parameters:
  • da (xr.DataArray) – Input N-dimensional DataArray (boolean).

  • window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.

  • dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).

  • freq (str) – Resampling frequency.

  • ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.

  • index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Number of distinct runs of a minimum length (int).

xclim.indices.run_length.windowed_run_events_1d(arr, window)[source]

Return the number of runs of a minimum length.

Parameters:
  • arr (Sequence[bool]) – Input array (bool).

  • window (int) – Minimum run length.

Return type:

DataArray

Returns:

xr.DataArray, [int] – Number of distinct runs of a minimum length.

xclim.indices.run_length.windowed_run_events_ufunc(x, window, dim)[source]

Dask-parallel version of windowed_run_events_1d, 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.

Return type:

DataArray

Returns:

xr.DataArray – A function operating along the time dimension of a dask-array.

Fire indices submodule

Indices related to fire and fire weather. Currently, submodules exist for calculating indices from the Canadian Forest Fire Weather Index System and the McArthur Forest Fire Danger (Mark 5) System. All fire indices can be accessed from the xclim.indices module.

Canadian Forest Fire Weather Index System

This submodule defines the xclim.indices.fire.fire_season(), xclim.indices.fire.drought_code() and xclim.indices.fire.cffwis_indices() indices, which are used by the eponym indicators. Users should read this module’s documentation and the one of fire_weather_ufunc(). They should also consult the information available at Natural Resources Canada [n.d.].

First adapted from Matlab code CalcFWITimeSeriesWithStartup.m from GFWED [Wang et al., 2015] 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 Field et al. [2015] data. The cffdrs R package is different from the original 1982 implementation, and so is xclim.

Parts of the code and of the documentation in this submodule are directly taken from Cantin et al. [2014] which was published with the GPLv2 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 fire method of the R package.

The fire season determination is based on three consecutive daily maximum temperature thresholds [Lawson and Armitage, 2008, Wotton and Flannigan, 1993]. 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 Field et al. [2015], 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

Additionally, 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 McElhinny et al. [2020], Van Wagner [1985].

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 significant precipitation event. The conventional 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.

Examples

The current literature 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 activating 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 xclim.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 = cffwis_indices(
...     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 = cffwis_indices(
...     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,
... )
xclim.indices.fire._cffwis.cffwis_indices(tas, pr, sfcWind, hurs, lat, snd=None, ffmc0=None, dmc0=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=True, **params)[source]

Canadian Fire Weather Index System indices.

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 fire 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.

Return type:

tuple[DataArray, DataArray, DataArray, DataArray, DataArray, DataArray]

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 Natural Resources Canada [n.d.], the xclim.indices.fire module documentation, and the docstring of fire_weather_ufunc() for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.

References

Wang, Anderson, and Suddaby [2015]

xclim.indices.fire._cffwis.drought_code(tas, pr, lat, snd=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=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 fire 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.fire.fire_weather_ufunc and in default_params.

Return type:

DataArray

Returns:

xr.DataArray, [dimensionless] – Drought code

Notes

See Natural Resources Canada [n.d.], the xclim.indices.fire module documentation, and the docstring of fire_weather_ufunc() for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.

References

Wang, Anderson, and Suddaby [2015]

xclim.indices.fire._cffwis.fire_season(tas, snd=None, method='WF93', freq=None, temp_start_thresh='12 degC', temp_end_thresh='5 degC', temp_condition_days=3, snow_condition_days=3, snow_thresh='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 (Quantified) – Minimal temperature needed to start the season. Must be scalar.

  • temp_end_thresh (Quantified) – Maximal temperature needed to end the season. Must be scalar.

  • 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 (Quantified) – Minimal snow depth level to end a fire season, only used with method “LA08”. Must be scalar.

Return type:

DataArray

Returns:

xr.DataArray – Fire season mask

References

Lawson and Armitage [2008], Wotton and Flannigan [1993]

xclim.indices.fire._cffwis.fire_weather_ufunc(*, tas, pr, hurs=None, sfcWind=None, snd=None, lat=None, dc0=None, dmc0=None, ffmc0=None, winter_pr=None, season_mask=None, start_dates=None, indexes=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=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 CFFWIS indicators or the drought_code() and cffwis_indices() 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 fire 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) – Carry over fraction.

  • 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) – The snow threshold.

  • 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) – DC start.

  • dmc_start (float) – DMC start.

  • 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 cover days.

  • snow_min_cover_frac (float) – Snow minimum cover fraction.

  • snow_min_mean_depth (float) – Additional parameters for GFWED’s version of the “dry start” mechanism. See Notes. Snow depth is in m.

Return type:

dict[str, DataArray]

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 “fire” 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 significant precipitation event, the start-up value \(DC_0\) is computed as:

\[DC_0 = DC_{start} + F_{dry-dc} * N_{dry}\]

The last significant precipitation event is the last day when 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.fire._cffwis.overwintering_drought_code(last_dc, winter_pr, carry_over_fraction=0.75, wetting_efficiency_fraction=0.75, min_dc=15)[source]

Compute season-starting drought code based on previous season’s last drought code and total winter precipitation.

This method replicates the “wDC” method of the “cffdrs R package [Cantin et al., 2014], 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.

Return type:

DataArray

Returns:

wDC (xr.DataArray) – Overwintered drought code.

Notes

Details taken from the “cffdrs” R package documentation [Cantin et al., 2014]: 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 Lawson and Armitage [2008] and Van Wagner [1985].

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: Lawson and Armitage [2008] - Table 9.

References

Cantin et al. [2014], Field et al. [2015], Lawson and Armitage [2008], Van Wagner [1985]

McArthur Forest Fire Danger (Mark 5) System

This submodule defines indices related to the McArthur Forest Fire Danger Index Mark 5. Currently implemented are the xclim.indices.fire.keetch_byram_drought_index(), xclim.indices.fire.griffiths_drought_factor() and xclim.indices.fire.mcarthur_forest_fire_danger_index() indices, which are used by the eponym indicators. The implementation of these indices follows Finkele et al. [2006] and Noble et al. [1980], with any differences described in the documentation for each index. Users are encouraged to read this module’s documentation and consult Finkele et al. [2006] for a full description of the methods used to calculate each index.

xclim.indices.fire._ffdi.griffiths_drought_factor(pr, smd, limiting_func='xlim')[source]

Griffiths drought factor based on the soil moisture deficit.

The drought factor is a numeric indicator of the forest fire fuel availability in the deep litter bed. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006].

Parameters:
  • pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].

  • smd (xarray DataArray) – Daily soil moisture deficit (often KBDI) [mm/day].

  • limiting_func ({“xlim”, “discrete”}) – How to limit the values of the drought factor. If “xlim” (default), use equation (14) in Finkele et al. [2006]. If “discrete”, use equation Eq (13) in Finkele et al. [2006], but with the lower limit of each category bound adjusted to match the upper limit of the previous bound.

Return type:

DataArray

Returns:

df (xr.DataArray) – The limited Griffiths drought factor.

Notes

Calculation of the Griffiths drought factor depends on the rainfall over the previous 20 days. Thus, the first non-NaN time point in the drought factor returned by this function corresponds to the 20th day of the input data.

References

Finkele, Mills, Beard, and Jones [2006], Griffiths [1999], Holgate, Van DIjk, Cary, and Yebra [2017]

xclim.indices.fire._ffdi.keetch_byram_drought_index(pr, tasmax, pr_annual, kbdi0=None)[source]

Keetch-Byram drought index (KBDI) for soil moisture deficit.

The KBDI indicates the amount of water necessary to bring the soil moisture content back to field capacity. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006] but limits the maximum KBDI to 203.2 mm, rather than 200 mm, in order to align best with the majority of the literature.

Parameters:
  • pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].

  • tasmax (xr.DataArray) – Maximum temperature near the surface over previous 24 hours [degC].

  • pr_annual (xr.DataArray) – Mean (over years) annual accumulated rainfall [mm/year].

  • kbdi0 (xr.DataArray, optional) – Previous KBDI values used to initialise the KBDI calculation [mm/day]. Defaults to 0.

Return type:

DataArray

Returns:

xr.DataArray – Keetch-Byram drought index.

Notes

This method implements the method described in Finkele et al. [2006] (section 2.1.1) for calculating the KBDI with one small difference: in Finkele et al. [2006] the maximum KBDI is limited to 200 mm to represent the maximum field capacity of the soil (8 inches according to Keetch and Byram [1968]). However, it is more common in the literature to limit the KBDI to 203.2 mm which is a more accurate conversion from inches to mm. In this function, the KBDI is limited to 203.2 mm.

References

Dolling, Chu, and Fujioka [2005], Finkele, Mills, Beard, and Jones [2006], Holgate, Van DIjk, Cary, and Yebra [2017], Keetch and Byram [1968]

xclim.indices.fire._ffdi.mcarthur_forest_fire_danger_index(drought_factor, tasmax, hurs, sfcWind)[source]

McArthur forest fire danger index (FFDI) Mark 5.

The FFDI is a numeric indicator of the potential danger of a forest fire.

Parameters:
  • drought_factor (xr.DataArray) – The drought factor, often the daily Griffiths drought factor (see griffiths_drought_factor()).

  • tasmax (xr.DataArray) – The daily maximum temperature near the surface, or similar. Different applications have used different inputs here, including the previous/current day’s maximum daily temperature at a height of 2m, and the daily mean temperature at a height of 2m.

  • hurs (xr.DataArray) – The relative humidity near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon relative humidity at a height of 2m, and the daily mean relative humidity at a height of 2m.

  • sfcWind (xr.DataArray) – The wind speed near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon wind speed at a height of 10m, and the daily mean wind speed at a height of 10m.

Returns:

xr.DataArray – The McArthur forest fire danger index.

References

Dowdy [2018], Holgate, Van DIjk, Cary, and Yebra [2017], Noble, Gill, and Bary [1980]

Fire indices footnotes

McArthur Forest Fire Danger Indices methods
[FFDI-dolling_2005] (1,2)

Klaus Dolling, Pao-Shin Chu, and Francis Fujioka. A climatological study of the keetch/byram drought index and fire activity in the hawaiian islands. Agricultural and Forest Meteorology, 133(1-4):17–27, 2005.

[FFDI-dowdy_2018] (1,2)

Andrew J Dowdy. Climatological variability of fire weather in australia. Journal of Applied Meteorology and Climatology, 57(2):221–234, 2018.

[FFDI-finkele_2006] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18)

Klara Finkele, Graham A Mills, Grant Beard, and David A Jones. National gridded drought factors and comparison of two soil moisture deficit formulations used in prediction of forest fire danger index in australia. Australian Meteorological Magazine, 55(3):183–197, 2006.

[FFDI-griffiths_1999] (1,2)

Deryn Griffiths. Improved formula for the drought factor in mcarthur's forest fire danger meter. Australian Forestry, 62(2):202–206, 1999.

[FFDI-holgate_2017] (1,2,3,4,5,6)

Chiara M Holgate, Albert IJM Van DIjk, Geoffrey J Cary, and Marta Yebra. Using alternative soil moisture estimates in the mcarthur forest fire danger index. International Journal of Wildland Fire, 26(9):806–819, 2017.

[FFDI-keetch_1968] (1,2,3,4)

John James Keetch and George Marsden Byram. A drought index for forest fire control. Volume 38. US Department of Agriculture, Forest Service, Southeastern Forest Experiment …, 1968.

[FFDI-noble_1980] (1,2,3)

IR Noble, AM Gill, and GAV Bary. Mcarthur's fire-danger meters expressed as equations. Australian Journal of Ecology, 5(2):201–203, 1980.

Canadian Forest Fire Weather Index System codes

[CODE-cantin_canadian_2014]

Alan Cantin, Xianli Wang, Marc-André Parisien, Mike Wotton, Kerry Anderson, Brett Moore, Tom Schiks, and Mike Flannigan. Canadian Forest Fire Danger Rating System (CFFDRS). 2014. URL: https://r-forge.r-project.org/projects/cffdrs/.

[CODE-natural_resources_canada_data_nodate] (1,2,3,4,5,6)

Natural Resources Canada. Data Sources and Methods for Daily Maps. URL: https://cwfis.cfs.nrcan.gc.ca/background/dsm/fwi (visited on 2022-07-29).

Note

Matlab code of the GFWED obtained through personal communication.

Fire season determination methods

[FIRE-field_development_2015] (1,2)

R. D. Field, A. C. Spessa, N. A. Aziz, A. Camia, A. Cantin, R. Carr, W. J. de Groot, A. J. Dowdy, M. D. Flannigan, K. Manomaiphiboon, F. Pappenberger, V. Tanpipat, and X. Wang. Development of a Global Fire Weather Database. Natural Hazards and Earth System Sciences, 15(6):1407–1423, June 2015. Publisher: Copernicus GmbH. URL: https://nhess.copernicus.org/articles/15/1407/2015/ (visited on 2022-07-29), doi:10.5194/nhess-15-1407-2015.

[FIRE-lawson_weather_2008] (1,2,3)

B. D. Lawson and O. B. Armitage. Weather Guide for the Canadian Forest Fire Danger Rating System. Technical Report C2009-980001-2, Canadian Forest Service, Northern Forestry Centre, 2008. ISSN 0831-8247. URL: https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/29152.pdf (visited on 2022-07-29).

[FIRE-wang_updated_2015] (1,2,3,4,5,6)

Y. Wang, K. R. Anderson, and R. M. Suddaby. Updated source code for calculating fire danger indices in the Canadian Forest Fire Weather Index System. Information Report NOR-X-424, Canadian Forest Service, Northern Forestry Centre, 2015. ISSN: 0831-8247. URL: https://cfs.nrcan.gc.ca/publications?id=36461 (visited on 2022-11-16).

[FIRE-wotton_length_1993] (1,2,3)

B. M. Wotton and M. D. Flannigan. Length of the fire season in a changing climate. The Forestry Chronicle, 69(2):187–192, April 1993. Publisher: Canadian Institute of Forestry. URL: https://pubs.cif-ifc.org/doi/abs/10.5558/tfc69187-2 (visited on 2022-07-29), doi:10.5558/tfc69187-2.

Drought Code overwintering background

[DROUGHT-cantin_canadian_2014] (1,2)

Alan Cantin, Xianli Wang, Marc-André Parisien, Mike Wotton, Kerry Anderson, Brett Moore, Tom Schiks, and Mike Flannigan. Canadian Forest Fire Danger Rating System (CFFDRS). 2014. URL: https://r-forge.r-project.org/projects/cffdrs/.

[DROUGHT-field_development_2015]

R. D. Field, A. C. Spessa, N. A. Aziz, A. Camia, A. Cantin, R. Carr, W. J. de Groot, A. J. Dowdy, M. D. Flannigan, K. Manomaiphiboon, F. Pappenberger, V. Tanpipat, and X. Wang. Development of a Global Fire Weather Database. Natural Hazards and Earth System Sciences, 15(6):1407–1423, June 2015. Publisher: Copernicus GmbH. URL: https://nhess.copernicus.org/articles/15/1407/2015/ (visited on 2022-07-29), doi:10.5194/nhess-15-1407-2015.

[DROUGHT-lawson_weather_2008] (1,2,3)

B. D. Lawson and O. B. Armitage. Weather Guide for the Canadian Forest Fire Danger Rating System. Technical Report C2009-980001-2, Canadian Forest Service, Northern Forestry Centre, 2008. ISSN 0831-8247. URL: https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/29152.pdf (visited on 2022-07-29).

[DROUGHT-mcelhinny_high-resolution_2020]

Megan McElhinny, Justin F. Beckers, Chelene Hanes, Mike Flannigan, and Piyush Jain. A high-resolution reanalysis of global fire weather from 1979 to 2018 – overwintering the Drought Code. Earth System Science Data, 12(3):1823–1833, August 2020. Publisher: Copernicus GmbH. URL: https://essd.copernicus.org/articles/12/1823/2020/ (visited on 2022-07-29), doi:10.5194/essd-12-1823-2020.

[DROUGHT-van_wagner_drought_1985] (1,2,3)

C. E. Van Wagner. Drought, Timelag, and Fire Danger Rating. In Society of American Foresters, 178–185. Detroit, Michigan, May 1985. URL: https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/23550.pdf (visited on 2022-11-16).