Climate Indices
Indices library
This module contains climate indices functions operating on xarray.DataArray. Most of these functions operate on daily time series, but might accept other sampling frequencies as well. All functions perform units checks to make sure that inputs have the expected dimensions (for example have units of temperature, whether it is celsius, kelvin or fahrenheit), and set the units attribute of the output DataArray.
The calendar, fire, generic, helpers, run_length and stats submodules provide helpers to simplify the implementation of the indices.
Note
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.indicators.Indicator
instances found in the xclim.indicators.atmos
,
xclim.indicators.land
and xclim.indicators.seaIce
modules,
documented in Climate Indicators.
- xclim.indices.base_flow_index(q: DataArray, freq: str = 'YS') DataArray [source]
Base flow index.
Return the base flow index, defined as the minimum 7-day average flow divided by the mean flow.
- Parameters
q (xarray.DataArray) – Rate of river discharge.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [dimensionless] – Base flow index.
Notes
Let \(\mathbf{q}=q_0, q_1, \ldots, q_n\) be the sequence of daily discharge and \(\overline{\mathbf{q}}\) the mean flow over the period. The base flow index is given by:
\[\frac{\min(\mathrm{CMA}_7(\mathbf{q}))}{\overline{\mathbf{q}}}\]where \(\mathrm{CMA}_7\) is the seven days moving average of the daily flow:
\[\mathrm{CMA}_7(q_i) = \frac{\sum_{j=i-3}^{i+3} q_j}{7}\]
- xclim.indices.biologically_effective_degree_days(tasmin: DataArray, tasmax: DataArray, lat: Optional[DataArray] = None, thresh_tasmin: Quantified = '10 degC', method: str = 'gladstones', low_dtr: Quantified = '10 degC', high_dtr: Quantified = '13 degC', max_daily_degree_days: Quantified = '9 degC', start_date: DayOfYearStr = '04-01', end_date: DayOfYearStr = '11-01', freq: str = 'YS') DataArray [source]
Biologically effective growing degree days.
Growing-degree days with a base of 10°C and an upper limit of 19°C and adjusted for latitudes between 40°N and 50°N for April to October (Northern Hemisphere; October to April in Southern Hemisphere). A temperature range adjustment also promotes small and large swings in daily temperature range. Used as a heat-summation metric in viticulture agroclimatology.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
lat (xarray.DataArray, optional) – Latitude coordinate. 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 “AS-JUL”).
- 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
- xclim.indices.blowing_snow(snd: DataArray, sfcWind: DataArray, snd_thresh: Quantified = '5 cm', sfcWind_thresh: Quantified = '15 km/h', window: int = 3, freq: str = 'AS-JUL') DataArray [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.
- Returns
xarray.DataArray – Number of days when snowfall and wind speeds are above respective thresholds.
- xclim.indices.calm_days(sfcWind: DataArray, thresh: Quantified = '2 m s-1', freq: str = 'MS') DataArray [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.
- 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: DataArray, pr: DataArray, sfcWind: DataArray, hurs: DataArray, lat: DataArray, snd: Optional[DataArray] = None, ffmc0: Optional[DataArray] = None, dmc0: Optional[DataArray] = None, dc0: Optional[DataArray] = None, season_mask: Optional[DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = 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 indefault_params
.
- Returns
DC (xr.DataArray, [dimensionless])
DMC (xr.DataArray, [dimensionless])
FFMC (xr.DataArray, [dimensionless])
ISI (xr.DataArray, [dimensionless])
BUI (xr.DataArray, [dimensionless])
FWI (xr.DataArray, [dimensionless])
Notes
See Natural Resources Canada [n.d.], the
xclim.indices.fire
module documentation, and the docstring offire_weather_ufunc()
for more information.References
Wang, Anderson, and Suddaby [2015]
- xclim.indices.clausius_clapeyron_scaled_precipitation(delta_tas: DataArray, pr_baseline: DataArray, cc_scale_factor: float = 1.07) DataArray [source]
Scale precipitation according to the Clausius-Clapeyron relation.
- Parameters
delta_tas (xarray.DataArray) – Difference in temperature between a baseline climatology and another climatology.
pr_baseline (xarray.DataArray) – Baseline precipitation to adjust with Clausius-Clapeyron.
cc_scale_factor (float (default = 1.07)) – Clausius Clapeyron scale factor.
- Returns
DataArray – Baseline precipitation scaled to other climatology using Clausius-Clapeyron relationship.
Notes
The Clausius-Clapeyron equation for water 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: DataArray, pr: DataArray, tas_per: DataArray, pr_per: DataArray, freq: str = 'YS') DataArray [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.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
- 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: DataArray, pr: DataArray, tas_per: DataArray, pr_per: DataArray, freq: str = 'YS') DataArray [source]
Cold and wet days.
Returns the total number of days when “cold” and “wet” conditions coincide.
- Parameters
tas (xarray.DataArray) – Mean daily temperature values
pr (xarray.DataArray) – Daily precipitation.
tas_per (xarray.DataArray) – First quartile of daily mean temperature computed by month.
pr_per (xarray.DataArray) – Third quartile of daily total precipitation computed by month.
freq (str) – Resampling frequency.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
- 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: DataArray, thresh: Quantified = '-10 degC', window: int = 5, freq: str = 'AS-JUL', op: str = '<', resample_before_rl: bool = True) DataArray [source]
Cold spell days.
The number of days that are part of cold spell events, defined as a sequence of consecutive days with mean daily temperature below a threshold (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.
- 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: DataArray, tasmin_per: DataArray, window: int = 6, freq: str = 'YS', resample_before_rl: bool = True, bootstrap: bool = False, op: str = '<') DataArray [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: “<”.
- 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: DataArray, thresh: Quantified = '-10 degC', window: int = 5, freq: str = 'AS-JUL', op: str = '<', resample_before_rl: bool = True) DataArray [source]
Cold spell frequency.
The number of cold spell events, defined as a sequence of consecutive days with mean daily temperature below a threshold (default: -10℃).
- 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
- Returns
xarray.DataArray, [time] – Cold spell frequency.
- xclim.indices.continuous_snow_cover_end(snd: DataArray, thresh: Quantified = '2 cm', window: int = 14, freq: str = 'AS-JUL') DataArray [source]
End date of continuous snow cover.
First day after the start of the continuous snow cover when snow depth is below a threshold (default: 2 cm) for at least N (default: 14) consecutive days.
Warning
The default freq is valid for the northern hemisphere.
- 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.
- Returns
xarray.DataArray, [dimensionless] – First day after the start of the continuous snow cover when the snow depth goes below a threshold for a minimum duration. If there is no such day, returns np.nan.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.indices.continuous_snow_cover_start(snd: DataArray, thresh: Quantified = '2 cm', window: int = 14, freq: str = 'AS-JUL') DataArray [source]
Start date of continuous snow cover.
Day of year when snow depth is above or equal to a threshold (default: 2 cm) for at least N (default: 14) consecutive days.
Warning
The default freq is valid for the northern hemisphere.
- 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.
- Returns
xarray.DataArray, [dimensionless] – First day of the year when the snow depth is superior to a threshold for a minimum duration. If there is no such day, returns np.nan.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.indices.cool_night_index(tasmin: DataArray, lat: Optional[Union[DataArray, str]] = None, freq: str = 'YS') DataArray [source]
Cool Night Index.
Mean minimum temperature for September (northern hemisphere) or March (Southern hemisphere). Used in calculating the Géoviticulture Multicriteria Classification System (Tonietto and Carbonneau [2004]).
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
lat (xarray.DataArray or {“north”, “south”}, optional) – Latitude coordinate as an array, float or string. If None, a CF-conformant “latitude” field must be available within the passed DataArray.
freq (str) – Resampling frequency.
- 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:
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: DataArray, thresh: Quantified = '18 degC', freq: str = 'YS') DataArray [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.
- 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: DataArray, tasmax: DataArray, thresh_tasmin: Quantified = '4.44 degC', thresh_tasmax: Quantified = '10 degC') DataArray [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.
- 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: DataArray, thresh: Quantified = '1 mm/day', freq: str = 'YS') DataArray [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.
- 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: DataArray, tasmax: DataArray, freq: str = 'YS', op: Union[str, Callable] = 'mean') DataArray [source]
Statistics of daily temperature range.
The mean difference between the daily maximum temperature and the daily minimum temperature.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
op ({‘min’, ‘max’, ‘mean’, ‘std’} or func) – Reduce operation. Can either be a DataArray method or a function that can be applied to a DataArray.
- Returns
xarray.DataArray, [same units as tasmin] – The average variation in daily temperature range for the given time period.
Notes
For a default calculation using op=’mean’ :
Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then the mean diurnal temperature range in period \(j\) is:
\[DTR_j = \frac{ \sum_{i=1}^I (TX_{ij} - TN_{ij}) }{I}\]
- xclim.indices.daily_temperature_range_variability(tasmin: DataArray, tasmax: DataArray, freq: str = 'YS') DataArray [source]
Mean absolute day-to-day variation in daily temperature range.
Mean absolute day-to-day variation in daily temperature range.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmin] – The average day-to-day variation in daily temperature range for the given time period.
Notes
Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then calculated is the absolute day-to-day differences in period \(j\) is:
\[vDTR_j = \frac{ \sum_{i=2}^{I} |(TX_{ij}-TN_{ij})-(TX_{i-1,j}-TN_{i-1,j})| }{I}\]
- xclim.indices.days_over_precip_thresh(pr: DataArray, pr_per: DataArray, thresh: Quantified = '1 mm/day', freq: str = 'YS', bootstrap: bool = False, op: str = '>') DataArray [source]
Number of wet days with daily precipitation over a given percentile.
Number of days over period where the precipitation is above a threshold defining wet days and above a given percentile for that day.
- Parameters
pr (xarray.DataArray) – Mean daily precipitation flux.
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: “>”.
- 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: DataArray, low: Quantified = '0 kg m-2 s-1', high: Quantified = '1E6 kg m-2 s-1', freq: str = 'AS-JUL') DataArray [source]
Days with snow.
Return the number of days where snowfall is within low and high thresholds.
- Parameters
prsn (xr.DataArray) – Solid precipitation flux.
low (Quantified) – Minimum threshold solid precipitation flux.
high (Quantified) – Maximum threshold solid precipitation flux.
freq (str) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
- Returns
xarray.DataArray, [time] – Number of days where snowfall is between low and high thresholds.
References
Matthews, Andrey, and Picketts [2017]
- xclim.indices.degree_days_exceedance_date(tas: DataArray, thresh: Quantified = '0 degC', sum_thresh: Quantified = '25 K days', op: str = '>', after_date: Optional[DayOfYearStr] = None, freq: str = 'YS') DataArray [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.
freq (str) – Resampling frequency. If after_date is given, freq should be annual.
- Returns
xarray.DataArray, [dimensionless] – Degree-days exceedance date.
Notes
Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\), \(T\) is the reference threshold and \(ST\) is the sum threshold. Then, starting at day :math:i_0:, the degree days exceedance date is the first day \(k\) such that
\[\begin{split}\begin{cases} ST < \sum_{i=i_0}^{k} \max(TG_{ij} - T, 0) & \text{if $op$ is '>'} \\ ST < \sum_{i=i_0}^{k} \max(T - TG_{ij}, 0) & \text{if $op$ is '<'} \end{cases}\end{split}\]The resulting \(k\) is expressed as a day of year.
Cumulated degree days have numerous applications including plant and insect phenology. See https://en.wikipedia.org/wiki/Growing_degree-day for examples (Wikipedia Contributors [2021]).
- xclim.indices.drought_code(tas: DataArray, pr: DataArray, lat: DataArray, snd: Optional[DataArray] = None, dc0: Optional[DataArray] = None, season_mask: Optional[DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]
Drought code (FWI component).
The drought code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of organic layers.
- Parameters
tas (xr.DataArray) – Noon temperature.
pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.
lat (xr.DataArray) – Latitude coordinate
snd (xr.DataArray) – Noon snow depth.
dc0 (xr.DataArray) – Initial values of the drought code.
season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.
season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R 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
.
- Returns
xr.DataArray, [dimensionless] – Drought code
Notes
See Natural Resources Canada [n.d.], the
xclim.indices.fire
module documentation, and the docstring offire_weather_ufunc()
for more information.References
Wang, Anderson, and Suddaby [2015]
- xclim.indices.dry_days(pr: DataArray, thresh: Quantified = '0.2 mm/d', freq: str = 'YS', op: str = '<') DataArray [source]
Dry days.
The number of days with daily precipitation below threshold.
- Parameters
pr (xarray.DataArray) – Daily precipitation.
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 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: DataArray, thresh: Quantified = '1.0 mm', window: int = 3, freq: str = 'YS', resample_before_rl: bool = True, op: str = 'sum') DataArray [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.
- 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_total_length(pr: DataArray, thresh: Quantified = '1.0 mm', window: int = 3, op: str = 'sum', freq: str = 'YS', resample_before_rl: bool = True, **indexer) DataArray [source]
Total length of dry spells.
Total number of days in dry periods of a minimum length, during which the maximum or accumulated precipitation within a window of the same length is under a threshold.
- Parameters
pr (xarray.DataArray) – Daily precipitation.
thresh (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.
- 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.effective_growing_degree_days(tasmax: DataArray, tasmin: DataArray, *, thresh: Quantified = '5 degC', method: str = 'bootsma', after_date: DayOfYearStr = '07-01', dim: str = 'time', freq: str = 'YS') DataArray [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.
- 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: DataArray, tasmax: DataArray, freq: str = 'YS') DataArray [source]
Extreme intra-period temperature range.
The maximum of max temperature (TXx) minus the minimum of min temperature (TNn) for the given time period.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmin] – Extreme intra-period temperature range for the given time period.
Notes
Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then the extreme temperature range in period \(j\) is:
\[ETR_j = max(TX_{ij}) - min(TN_{ij})\]
- xclim.indices.fire_season(tas: DataArray, snd: Optional[DataArray] = None, method: str = 'WF93', freq: Optional[str] = None, temp_start_thresh: Quantified = '12 degC', temp_end_thresh: Quantified = '5 degC', temp_condition_days: int = 3, snow_condition_days: int = 3, snow_thresh: Quantified = '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.
- Returns
xr.DataArray – Fire season mask
References
- xclim.indices.first_day_temperature_above(tas: DataArray, thresh: Quantified = '0 degC', op: str = '>', after_date: DayOfYearStr = '01-01', window: int = 1, freq: str = 'YS') DataArray [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.
- 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: DataArray, thresh: Quantified = '0 degC', op: str = '<', after_date: DayOfYearStr = '07-01', window: int = 1, freq: str = 'YS') DataArray [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.
- 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: DataArray, thresh: Quantified = '0.5 mm/day', freq: str = 'AS-JUL') DataArray [source]
First day with solid precipitation above a threshold.
Returns the first day of a period where the solid precipitation exceeds a threshold (default: 0.5 mm/day).
Warning
The default freq is valid for the northern hemisphere.
- Parameters
prsn (xarray.DataArray) – Solid precipitation flux.
thresh (Quantified) – Threshold precipitation flux on which to base evaluation.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [dimensionless] – First day of the year when the solid precipitation is superior to a threshold. If there is no such day, returns np.nan.
References
CBCL [2020].
- xclim.indices.fraction_over_precip_thresh(pr: DataArray, pr_per: DataArray, thresh: Quantified = '1 mm/day', freq: str = 'YS', bootstrap: bool = False, op: str = '>') DataArray [source]
Fraction of precipitation due to wet days with daily precipitation over a given percentile.
Percentage of the total precipitation over period occurring in days 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: “>”.
- Returns
xarray.DataArray, [dimensionless] – Fraction of precipitation over threshold during wet days.
- xclim.indices.frost_days(tasmin: DataArray, thresh: Quantified = '0 degC', freq: str = 'YS') DataArray [source]
Frost days index.
Number of days where daily minimum temperatures are below a threshold temperature.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Freezing temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [time] – Frost days index.
Notes
Let \(TN_{ij}\) be the daily minimum temperature at day \(i\) of period \(j\) and :math`TT` the threshold. Then counted is the number of days where:
\[TN_{ij} < TT\]
- xclim.indices.frost_free_season_end(tasmin: DataArray, thresh: Quantified = '0.0 degC', mid_date: DayOfYearStr = '07-01', window: int = 5, freq: str = 'YS') DataArray [source]
End of the frost free season.
Day of the year of the start of a sequence of days with minimum temperatures consistently below a threshold (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.
- 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: DataArray, window: int = 5, mid_date: Optional[DayOfYearStr] = '07-01', thresh: Quantified = '0.0 degC', freq: str = 'YS') DataArray [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.
- Returns
xarray.DataArray, [time] – Frost free season length.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least N consecutive days with:
\[TN_{ij} >= 0 ℃\]and the first subsequent occurrence of at least N consecutive days with:
\[TN_{ij} < 0 ℃\]Examples
>>> from xclim.indices import frost_season_length >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
For the Northern Hemisphere:
>>> ffsl_nh = frost_free_season_length(tasmin, freq="YS")
If working in the Southern Hemisphere, one can use:
>>> ffsl_sh = frost_free_season_length(tasmin, freq="AS-JUL")
- xclim.indices.frost_free_season_start(tasmin: DataArray, thresh: Quantified = '0.0 degC', window: int = 5, freq: str = 'YS') DataArray [source]
Start of the frost free season.
Day of the year of the start of a sequence of days with minimum temperatures consistently above or equal to a threshold (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.
- 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_season_length(tasmin: DataArray, window: int = 5, mid_date: Optional[DayOfYearStr] = '01-01', thresh: Quantified = '0.0 degC', freq: str = 'AS-JUL') DataArray [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.
- Returns
xarray.DataArray, [time] – Frost season length.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least N consecutive days with:
\[TN_{ij} > 0 ℃\]and the first subsequent occurrence of at least N consecutive days with:
\[TN_{ij} < 0 ℃\]Examples
>>> from xclim.indices import frost_season_length >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
For the Northern Hemisphere:
>>> fsl_nh = frost_season_length(tasmin, freq="AS-JUL")
If working in the Southern Hemisphere, one can use:
>>> fsl_sh = frost_season_length(tasmin, freq="YS")
- xclim.indices.griffiths_drought_factor(pr: DataArray, smd: DataArray, limiting_func: str = 'xlim') DataArray [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.
- 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: DataArray, thresh: Quantified = '4.0 degC', freq: str = 'YS') DataArray [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.
- 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: DataArray, thresh: Quantified = '5.0 degC', mid_date: DayOfYearStr = '07-01', window: int = 5, freq: str = 'YS') DataArray [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.
- 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: DataArray, thresh: Quantified = '5.0 degC', window: int = 6, mid_date: DayOfYearStr = '07-01', freq: str = 'YS') DataArray [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.
- Returns
xarray.DataArray, [time] – Growing season length.
Notes
Let \(TG_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least 6 consecutive days with:
\[TG_{ij} > 5 ℃\]and the first occurrence after 1 July of at least 6 consecutive days with:
\[TG_{ij} < 5 ℃\]Examples
>>> from xclim.indices import growing_season_length >>> tas = xr.open_dataset(path_to_tas_file).tas
For the Northern Hemisphere:
>>> gsl_nh = growing_season_length(tas, mid_date="07-01", freq="AS")
If working in the Southern Hemisphere, one can use:
>>> gsl_sh = growing_season_length(tas, mid_date="01-01", freq="AS-JUL")
References
Project team ECA&D and KNMI [2013]
- xclim.indices.growing_season_start(tas: DataArray, thresh: Quantified = '5.0 degC', window: int = 5, freq: str = 'YS') DataArray [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.
- 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.heat_index(tas: DataArray, hurs: DataArray) DataArray [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.
- 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: DataArray, tasmax: DataArray, thresh_tasmin: Quantified = '22.0 degC', thresh_tasmax: Quantified = '30 degC', window: int = 3, freq: str = 'YS', op: str = '>', resample_before_rl: bool = True) DataArray [source]
Heat wave frequency.
Number of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both 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.
- 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
- xclim.indices.heat_wave_index(tasmax: DataArray, thresh: Quantified = '25.0 degC', window: int = 5, freq: str = 'YS', op: str = '>') DataArray [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: “>”.
- Returns
DataArray, [time] – Heat wave index.
- xclim.indices.heat_wave_max_length(tasmin: DataArray, tasmax: DataArray, thresh_tasmin: Quantified = '22.0 degC', thresh_tasmax: Quantified = '30 degC', window: int = 3, freq: str = 'YS', op: str = '>', resample_before_rl: bool = True) DataArray [source]
Heat wave max length.
Maximum length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceeds specific thresholds over a minimum number of days.
By definition heat_wave_max_length must be >= window.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (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.
- 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
- xclim.indices.heat_wave_total_length(tasmin: DataArray, tasmax: DataArray, thresh_tasmin: Quantified = '22.0 degC', thresh_tasmax: Quantified = '30 degC', window: int = 3, freq: str = 'YS', op: str = '>', resample_before_rl: bool = True) DataArray [source]
Heat wave total length.
Total length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceeds specific thresholds over a minimum number of days. This the sum of all days in such events.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (str) – The minimum temperature threshold needed to trigger a heatwave event.
thresh_tasmax (str) – The maximum temperature threshold needed to trigger a heatwave event.
window (int) – Minimum number of days with temperatures above thresholds to qualify as a heatwave.
freq (str) – Resampling frequency.
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.
- 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: DataArray, thresh: Quantified = '17.0 degC', freq: str = 'YS') DataArray [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.
- 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: DataArray, tas: DataArray, pr_thresh: Quantified = '0.4 mm/d', tas_thresh: Quantified = '-0.2 degC', freq: str = 'YS') DataArray [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.
- 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: DataArray, thresh_tasmax: Quantified = '30 degC', window: int = 3, freq: str = 'YS', op: str = '>') DataArray [source]
Hot spell frequency.
Number of hot spells over a given period. A hot spell is defined as an event where the maximum daily temperature exceeds a specific threshold (default: 30℃) over a minimum number of days (default: 3).
- Parameters
tasmax (xarray.DataArray) – Maximum daily temperature.
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: “>”.
- Returns
xarray.DataArray, [dimensionless] – Number of heatwave at the wanted frequency
Notes
The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].
In Robinson [2001], the parameters would be thresh_tasmin=27.22, thresh_tasmax=39.44, window=2 (81F, 103F).
References
- xclim.indices.hot_spell_max_length(tasmax: DataArray, thresh_tasmax: Quantified = '30 degC', window: int = 1, freq: str = 'YS', op: str = '>') DataArray [source]
Longest hot spell.
Longest spell of high temperatures over a given period. The longest series of consecutive days with tasmax at or above 30°C. Here, there is no minimum threshold for number of days in a row that must be reached or exceeded to count as a spell. A year with zero +30°C days will return a longest spell value of zero.
- Parameters
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmax (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: “>”.
- Returns
xarray.DataArray, [time] – Maximum length of continuous hot days at the wanted frequency.
Notes
The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].
In Robinson [2001], the parameters would be thresh_tasmin=27.22, thresh_tasmax=39.44, window=2 (81F, 103F).
References
- xclim.indices.huglin_index(tas: DataArray, tasmax: DataArray, lat: Optional[DataArray] = None, thresh: Quantified = '10 degC', method: str = 'smoothed', start_date: DayOfYearStr = '04-01', end_date: DayOfYearStr = '10-01', freq: str = 'YS') DataArray [source]
Huglin Heliothermal Index.
Growing-degree days with a base of 10°C and adjusted for latitudes between 40°N and 50°N for April-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 “AS-JUL”).
- Returns
xarray.DataArray, [unitless] – Huglin heliothermal index (HI).
Notes
Let \(TX_{i}\) and \(TG_{i}\) be the daily maximum and mean temperature at day \(i\) and \(T_{thresh}\) the base threshold needed for heat summation (typically, 10 degC). A day-length multiplication, \(k\), based on latitude, \(lat\), is also considered. Then the Huglin heliothermal index for dates between 1 April and 30 September is:
\[HI = \sum_{i=\text{April 1}}^{\text{September 30}} \left( \frac{TX_i + TG_i)}{2} - T_{thresh} \right) * k\]For the smoothed method, the day-length multiplication factor, \(k\), is calculated as follows:
\[\begin{split}k = f(lat) = \begin{cases} 1, & \text{if } |lat| <= 40 \\ 1 + ((abs(lat) - 40) / 10) * 0.06, & \text{if } 40 < |lat| <= 50 \\ NaN, & \text{if } |lat| > 50 \\ \end{cases}\end{split}\]For compatibility with ICCLIM, end_date should be set to 11-01, method should be set to icclim. The day-length multiplication factor, \(k\), is calculated as follows:
\[\begin{split}k = f(lat) = \begin{cases} 1.0, & \text{if } |lat| <= 40 \\ 1.02, & \text{if } 40 < |lat| <= 42 \\ 1.03, & \text{if } 42 < |lat| <= 44 \\ 1.04, & \text{if } 44 < |lat| <= 46 \\ 1.05, & \text{if } 46 < |lat| <= 48 \\ 1.06, & \text{if } 48 < |lat| <= 50 \\ NaN, & \text{if } |lat| > 50 \\ \end{cases}\end{split}\]A more robust day-length calculation based on latitude, calendar, day-of-year, and obliquity is available with method=”jones”. See:
xclim.indices.generic.day_lengths()
or Hall and Jones [2010] for more information.References
- xclim.indices.humidex(tas: DataArray, tdps: Optional[DataArray] = None, hurs: Optional[DataArray] = None) DataArray [source]
Humidex index.
The humidex indicates how hot the air feels to an average person, accounting for the effect of humidity. It can be loosely interpreted as the equivalent perceived temperature when the air is dry.
- Parameters
tas (xarray.DataArray) – Air temperature.
tdps (xarray.DataArray,) – Dewpoint temperature.
hurs (xarray.DataArray) – Relative humidity.
- Returns
xarray.DataArray, [temperature] – The humidex index.
Notes
The humidex is usually computed using hourly observations of dry bulb and dewpoint temperatures. It is computed using the formula based on 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: DataArray, thresh: Quantified = '0 degC', freq: str = 'YS') DataArray [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.
- 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: DataArray, tasmax: DataArray, freq: str = 'YS') DataArray [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.
- 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: xarray.DataArray)[source]
Strength and latitude of jetstream.
Identify latitude and strength of maximum smoothed zonal wind speed in the region from 15 to 75°N and -60 to 0°E, 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.
- 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: DataArray, tasmax: DataArray, pr_annual: DataArray, kbdi0: Optional[DataArray] = None) DataArray [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.
- 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: DataArray, thresh: Quantified = '0.5 mm/day', freq: str = 'AS-JUL') DataArray [source]
Last day with solid precipitation above a threshold.
Returns the last day of a period where the solid precipitation exceeds a threshold (default: 0.5 mm/day).
Warning
The default freq is valid for the northern hemisphere.
- Parameters
prsn (xarray.DataArray) – Solid precipitation flux.
thresh (Quantified) – Threshold precipitation flux on which to base evaluation.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [dimensionless] – Last day of the year when the solid precipitation is superior to a threshold. If there is no such day, returns np.nan.
References
CBCL [2020].
- xclim.indices.last_spring_frost(tas: DataArray, thresh: Quantified = '0 degC', before_date: DayOfYearStr = '07-01', window: int = 1, freq: str = 'YS') DataArray [source]
Last day of temperatures inferior to a threshold temperature.
Returns last day of period where a temperature is inferior to a threshold over a given number of days (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
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
before_date (str,) – Date of the year before which to look for the final frost event. Should have the format ‘%m-%d’.
window (int) – Minimum number of days with temperature below threshold needed for evaluation.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [dimensionless] – Day of the year when temperature is inferior to a threshold over a given number of days for the first time. If there is no such day, returns np.nan.
- xclim.indices.latitude_temperature_index(tas: DataArray, lat: Optional[DataArray] = None, lat_factor: float = 75, freq: str = 'YS') DataArray [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.
- 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
- xclim.indices.liquid_precip_ratio(pr: DataArray, prsn: Optional[DataArray] = None, tas: Optional[DataArray] = None, thresh: Quantified = '0 degC', freq: str = 'QS-DEC') DataArray [source]
Ratio of rainfall to total precipitation.
The ratio of total liquid precipitation over the total precipitation. If solid precipitation is not provided, it is approximated with pr, tas and thresh, using the snowfall_approximation function with method ‘binary’.
- Parameters
pr (xarray.DataArray) – Mean daily precipitation flux.
prsn (xarray.DataArray, optional) – Mean daily solid precipitation flux.
tas (xarray.DataArray, optional) – Mean daily temperature.
thresh (Quantified) – Threshold temperature under which precipitation is assumed to be solid.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [dimensionless] – Ratio of rainfall to total precipitation.
Notes
Let \(PR_i\) be the mean daily precipitation of day \(i\), then for a period \(j\) starting at day \(a\) and finishing on day \(b\):
\[ \begin{align}\begin{aligned}PR_{ij} = \sum_{i=a}^{b} PR_i\\PRwet_{ij}\end{aligned}\end{align} \]See also
winter_rain_ratio
- xclim.indices.max_1day_precipitation_amount(pr: DataArray, freq: str = 'YS') DataArray [source]
Highest 1-day precipitation amount for a period (frequency).
Resample the original daily total precipitation temperature series by taking the max over each period.
- Parameters
pr (xarray.DataArray) – Daily precipitation values.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as pr] – The highest 1-period precipitation flux value at the given time frequency.
Notes
Let \(PR_i\) be the mean daily precipitation of day i, then for a period j:
\[PRx_{ij} = max(PR_{ij})\]Examples
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: DataArray, window: int = 1, freq: str = 'YS') DataArray [source]
Highest precipitation amount cumulated over a n-day moving window.
Calculate the n-day rolling sum of the original daily total precipitation series and determine the maximum value over each period.
- Parameters
pr (xarray.DataArray) – Daily precipitation values.
window (int) – Window size in days.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [length] – The highest cumulated n-period precipitation value at the given time frequency.
Examples
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: DataArray, window: int = 1, freq: str = 'YS') DataArray [source]
Highest precipitation intensity over a n-hour moving window.
Calculate the n-hour rolling average of the original hourly total precipitation series and determine the maximum value over each period.
- Parameters
pr (xarray.DataArray) – Hourly precipitation values.
window (int) – Window size in hours.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as pr] – The highest cumulated n-hour precipitation intensity at the given time frequency.
Examples
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: DataArray, thresh: Quantified = '1 mm/day', freq: str = 'YS') DataArray [source]
Maximum number of consecutive dry days.
Return the maximum number of consecutive days within the period where precipitation is below a certain threshold (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.
- 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: DataArray, thresh: Quantified = '0.0 degC', freq: str = 'AS-JUL') DataArray [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.
- 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: DataArray, thresh: Quantified = '0 degC', freq: str = 'YS') DataArray [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.
- 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: DataArray, thresh: Quantified = '25 degC', freq: str = 'YS') DataArray [source]
Maximum number of consecutive days with tasmax above a threshold (summer days).
Return the maximum number of consecutive days within the period where the maximum daily temperature is above a certain threshold (default: 25℃).
- Parameters
tasmax (xarray.DataArray) – Max daily temperature.
thresh (Quantified) – Threshold temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [time] – The maximum number of days with tasmax > thresh per periods (summer days).
Notes
Let \(\mathbf{t}=t_0, t_1, \ldots, t_n\) be a daily maximum temperature series and \(thresh\) the threshold above which a day is considered a summer day. Let \(\mathbf{s}\) be the sorted vector of indices \(i\) where \([t_i < thresh] \neq [t_{i+1} < thresh]\), that is, the days 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: DataArray, thresh: Quantified = '1 mm/day', freq: str = 'YS', resample_before_rl: bool = True) DataArray [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.
- 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: DataArray, tasmax: DataArray, hurs: DataArray, sfcWind: DataArray)[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: DataArray, rsus: DataArray, rlds: DataArray, rlus: DataArray, stat: str = 'average') DataArray [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 ({‘average’, ‘instant’, ‘sunlit’}) – Which statistic to apply. If “average”, the average of the cosine of the solar zenith angle is calculated. 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. If “instant”, the instantaneous cosine of the solar zenith angle is calculated. This is necessary if mrt is not None.
- 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: DataArray, pr: DataArray, window: int = 3, freq: str = 'AS-JUL') DataArray [source]
Maximum snow melt and precipitation.
The maximum snow melt plus precipitation over a given number of days expressed in snow water equivalent.
- Parameters
snw (xarray.DataArray) – Snow amount (mass per area).
pr (xarray.DataArray) – Daily precipitation flux.
window (int) – Number of days during which the water input is accumulated.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray – The maximum snow melt plus precipitation over a given number of days for each period. [mass/area].
- xclim.indices.multiday_temperature_swing(tasmin: DataArray, tasmax: DataArray, thresh_tasmin: Quantified = '0 degC', thresh_tasmax: Quantified = '0 degC', window: int = 1, op: str = 'mean', op_tasmin: str = '<=', op_tasmax: str = '>', freq: str = 'YS', resample_before_rl: bool = True) DataArray [source]
Statistics of consecutive diurnal temperature swing events.
A diurnal swing of max and min temperature event is when Tmax > thresh_tasmax and Tmin <= thresh_tasmin. This indice finds all days that constitute these events and computes statistics over the length and frequency of these events.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (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.
- Returns
xarray.DataArray, [time] – {freq} {op} length of diurnal temperature cycles exceeding thresholds.
Notes
Let \(TX_{i}\) be the maximum temperature at day \(i\) and \(TN_{i}\) be the daily minimum temperature at day \(i\). Then freeze thaw spells during a given period are consecutive days where:
\[TX_{i} > 0℃ \land TN_{i} < 0℃\]This indice returns a given statistic of the found lengths, optionally dropping those shorter than the window argument. For example, window=1 and op=’sum’ returns the same value as
daily_freezethaw_cycles()
.
- xclim.indices.potential_evapotranspiration(tasmin: Optional[DataArray] = None, tasmax: Optional[DataArray] = None, tas: Optional[DataArray] = None, lat: Optional[DataArray] = None, hurs: Optional[DataArray] = None, rsds: Optional[DataArray] = None, rsus: Optional[DataArray] = None, rlds: Optional[DataArray] = None, rlus: Optional[DataArray] = None, sfcWind: Optional[DataArray] = None, method: str = 'BR65', peta: float = 0.00516409319477, petb: float = 0.0874972822289) DataArray [source]
Potential evapotranspiration.
The potential for water evaporation from soil and transpiration by plants if the water supply is sufficient, according to a given method.
- 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.
- 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: DataArray, thresh: Quantified = '0 mm/d', freq: str = 'YS') DataArray [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.
- Returns
xarray.DataArray, [length] – Total {freq} precipitation.
- xclim.indices.prcptot_warmcold_quarter(pr: DataArray, tas: DataArray, op: Optional[str] = None, freq: str = 'YS') DataArray [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.
- 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: DataArray, *, op: str, freq: str = 'YS') DataArray [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.
- 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: DataArray, op: Optional[str] = None, freq: str = 'YS') DataArray [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.
- 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: DataArray, tas: Optional[DataArray] = None, phase: Optional[str] = None, thresh: Quantified = '0 degC', freq: str = 'YS') DataArray [source]
Accumulated total (liquid and/or solid) precipitation.
Resample the original daily mean precipitation flux and accumulate over each period. If a daily temperature is provided, the phase keyword can be used to sum precipitation of a given phase only. When the temperature is under the 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.
- Returns
xarray.DataArray, [length] – The total daily precipitation at the given time frequency for the given phase.
Notes
Let \(PR_i\) be the mean daily precipitation of day \(i\), then for a period \(j\) starting at day \(a\) and finishing on day \(b\):
\[PR_{ij} = \sum_{i=a}^{b} PR_i\]If tas and phase are given, the corresponding phase precipitation is estimated before computing the accumulation, using one of snowfall_approximation or rain_approximation with the binary method.
Examples
The following would compute, for each grid cell of a dataset, the total precipitation at the seasonal frequency, ie DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.indices import precip_accumulation >>> pr_day = xr.open_dataset(path_to_pr_file).pr >>> prcp_tot_seasonal = precip_accumulation(pr_day, freq="QS-DEC")
- xclim.indices.precip_seasonality(pr: DataArray, freq: str = 'YS') DataArray [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.
- 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.qian_weighted_mean_average(tas: DataArray, dim: str = 'time') DataArray [source]
Binomial smoothed, five-day weighted mean average temperature.
Calculates a five-day weighted moving average with emphasis on temperatures closer to day of interest.
- Parameters
tas (xr.DataArray) – Daily mean temperature.
dim (str) – Time dimension.
- Returns
xr.DataArray, [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: DataArray, tas: DataArray, thresh: Quantified = '0 degC', method: str = 'binary') DataArray [source]
Rainfall approximation from total precipitation and temperature.
Liquid precipitation estimated from precipitation and temperature according to a given method. This is a convenience method based on
snowfall_approximation()
, see the latter for details.- Parameters
pr (xarray.DataArray) – Mean daily precipitation flux.
tas (xarray.DataArray, optional) – Mean, maximum, or minimum daily temperature.
thresh (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.
- 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.
See also
snowfall_approximation
- xclim.indices.rain_on_frozen_ground_days(pr: DataArray, tas: DataArray, thresh: Quantified = '1 mm/d', freq: str = 'YS') DataArray [source]
Number of rain on frozen ground events.
Number of days with rain above a threshold after a series of seven days below freezing temperature. Precipitation is assumed to be rain when the temperature is above 0℃.
- Parameters
pr (xarray.DataArray) – Mean daily precipitation flux.
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Precipitation threshold to consider a day as a rain event.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [time] – The number of rain on frozen ground events per period.
Notes
Let \(PR_i\) be the mean daily precipitation and \(TG_i\) be the mean daily temperature of day \(i\). Then for a period \(j\), rain on frozen grounds days are counted where:
\[PR_{i} > Threshold [mm]\]and where
\[TG_{i} ≤ 0℃\]is true for continuous periods where \(i ≥ 7\)
- xclim.indices.rb_flashiness_index(q: DataArray, freq: str = 'YS') DataArray [source]
Richards-Baker flashiness index.
Measures oscillations in flow relative to total flow, quantifying the frequency and rapidity of short term changes in flow, based on Baker et al. [2004].
- Parameters
q (xarray.DataArray) – Rate of river discharge.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [dimensionless] – R-B Index.
Notes
Let \(\mathbf{q}=q_0, q_1, \ldots, q_n\) be the sequence of daily discharge, the R-B Index is given by:
\[\frac{\sum_{i=1}^n |q_i - q_{i-1}|}{\sum_{i=1}^n q_i}\]References
Baker, Richards, Loftus, and Kramer [2004]
- xclim.indices.relative_humidity(tas: DataArray, tdps: Optional[DataArray] = None, huss: Optional[DataArray] = None, ps: Optional[DataArray] = None, ice_thresh: Optional[Quantified] = None, method: str = 'sonntag90', invalid_values: str = 'clip') DataArray [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.
- 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
- xclim.indices.rprctot(pr: DataArray, prc: DataArray, thresh: Quantified = '1.0 mm/day', freq: str = 'YS') DataArray [source]
Proportion of accumulated precipitation arising from convective processes.
Return the proportion of total accumulated precipitation due to convection on days with total precipitation exceeding a 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.
- Returns
xarray.DataArray, [dimensionless] – The proportion of the total precipitation accounted for by convective precipitation for each period.
- xclim.indices.saturation_vapor_pressure(tas: DataArray, ice_thresh: Optional[Quantified] = None, method: str = 'sonntag90') DataArray [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.
- 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: DataArray, areacello: DataArray, thresh: Quantified = '15 pct') DataArray [source]
Total sea ice area.
Sea ice area measures the total sea ice covered area where sea ice concentration is above a threshold, usually set to 15%.
- Parameters
siconc (xarray.DataArray) – Sea ice concentration (area fraction).
areacello (xarray.DataArray) – Grid cell area (usually over the ocean).
thresh (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.
- Returns
xarray.DataArray, [length]^2 – Sea ice area.
Notes
To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.
References
“What is the difference between sea ice area and extent?” - NSIDC [2008]
- xclim.indices.sea_ice_extent(siconc: DataArray, areacello: DataArray, thresh: Quantified = '15 pct') DataArray [source]
Total sea ice extent.
Sea ice extent measures the ice-covered area, where a region is considered ice-covered if its sea ice concentration is above a threshold, usually set to 15%.
- Parameters
siconc (xarray.DataArray) – Sea ice concentration (area fraction).
areacello (xarray.DataArray) – Grid cell area.
thresh (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.
- Returns
xarray.DataArray, [length]^2 – Sea ice extent.
Notes
To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.
References
“What is the difference between sea ice area and extent?” - NSIDC [2008]
- xclim.indices.sfcwind_2_uas_vas(sfcWind: DataArray, sfcWindfromdir: DataArray) tuple[xarray.DataArray, xarray.DataArray] [source]
Eastward and northward wind components from the wind speed and direction.
Compute the eastward and northward wind components from the wind speed and direction.
- Parameters
sfcWind (xr.DataArray) – Wind velocity
sfcWindfromdir (xr.DataArray) – Direction from which the wind blows, following the meteorological convention where 360 stands for North.
- Returns
uas (xr.DataArray, [m s-1]) – Eastward wind velocity.
vas (xr.DataArray, [m s-1]) – Northward wind velocity.
Examples
>>> from xclim.indices import sfcwind_2_uas_vas >>> uas, vas = sfcwind_2_uas_vas( ... sfcWind=sfcWind_dataset, sfcWindfromdir=sfcWindfromdir_dataset ... )
- xclim.indices.snd_max_doy(snd: DataArray, freq: str = 'AS-JUL') DataArray [source]
Maximum snow depth day of year.
Day of year when surface snow reaches its peak value. If snow depth is 0 over entire period, return NaN.
- Parameters
snd (xarray.DataArray) – Surface snow depth.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray – The day of year at which snow depth reaches its maximum value.
- xclim.indices.snow_cover_duration(snd: DataArray, thresh: Quantified = '2 cm', freq: str = 'AS-JUL') DataArray [source]
Number of days with snow depth above a threshold.
Number of days where surface snow depth is greater or equal to given threshold (default: 2 cm).
Warning
The default freq is valid for the northern hemisphere.
- Parameters
snd (xarray.DataArray) – Surface snow thickness.
thresh (Quantified) – Threshold snow thickness.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [time] – Number of days where snow depth is greater than or equal to threshold.
- xclim.indices.snow_depth(snd: DataArray, freq: str = 'YS') DataArray [source]
Mean of daily average snow depth.
Resample the original daily mean snow depth series by taking the mean over each period.
- Parameters
snd (xarray.DataArray) – Mean daily snow depth.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as snd] – The mean daily snow depth at the given time frequency
- xclim.indices.snow_melt_we_max(snw: DataArray, window: int = 3, freq: str = 'AS-JUL') DataArray [source]
Maximum snow melt.
The maximum snow melt over a given number of days expressed in snow water equivalent.
- Parameters
snw (xarray.DataArray) – Snow amount (mass per area).
window (int) – Number of days during which the melt is accumulated.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray – The maximum snow melt over a given number of days for each period. [mass/area].
- xclim.indices.snowfall_approximation(pr: DataArray, tas: DataArray, thresh: Quantified = '0 degC', method: str = 'binary') DataArray [source]
Snowfall approximation from total precipitation and temperature.
Solid precipitation estimated from precipitation and temperature according to a given method.
- Parameters
pr (xarray.DataArray) – Mean daily precipitation flux.
tas (xarray.DataArray, optional) – Mean, maximum, or minimum daily temperature.
thresh (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.
- 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
- xclim.indices.snw_max(snw: DataArray, freq: str = 'AS-JUL') DataArray [source]
Maximum snow amount.
The maximum daily snow amount.
- Parameters
snw (xarray.DataArray) – Snow amount (mass per area).
freq (str) – Resampling frequency.
- Returns
xarray.DataArray – The maximum snow amount over a given number of days for each period. [mass/area].
- xclim.indices.snw_max_doy(snw: DataArray, freq: str = 'AS-JUL') DataArray [source]
Maximum snow amount day of year.
Day of year when surface snow amount reaches its peak value. If snow amount is 0 over entire period, return NaN.
- Parameters
snw (xarray.DataArray) – Surface snow amount.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray – The day of year at which snow amount reaches its maximum value.
- xclim.indices.specific_humidity(tas: DataArray, hurs: DataArray, ps: DataArray, ice_thresh: Optional[Quantified] = None, method: str = 'sonntag90', invalid_values: Optional[str] = None) DataArray [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.
- 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: DataArray, ps: DataArray, method: str = 'sonntag90') DataArray [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.
- 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: DataArray, wb_cal: Quantified, freq: str = 'MS', window: int = 1, dist: str = 'gamma', method: str = 'APP') DataArray [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) – Daily water budget used for calibration.
freq (str) – Resampling frequency. A monthly or daily frequency is expected.
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. Available methods vary with the distribution: ‘gamma’:{‘APP’, ‘ML’}, ‘fisk’:{‘ML’}
- Returns
xarray.DataArray – Standardized Precipitation Evapotranspiration Index.
See also
standardized_precipitation_index
Notes
See Standardized Precipitation Index (SPI) for more details on usage.
- xclim.indices.standardized_precipitation_index(pr: DataArray, pr_cal: Quantified, freq: str = 'MS', window: int = 1, dist: str = 'gamma', method: str = 'APP') DataArray [source]
Standardized Precipitation Index (SPI).
- Parameters
pr (xarray.DataArray) – Daily precipitation.
pr_cal (xarray.DataArray) – Daily precipitation used for calibration. Usually this is a temporal subset of pr over some reference period.
freq (str) – Resampling frequency. A monthly or daily frequency is expected.
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.
- 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”]
Example
>>> from datetime import datetime >>> from xclim.indices import standardized_precipitation_index >>> ds = xr.open_dataset(path_to_pr_file) >>> pr = ds.pr >>> pr_cal = pr.sel(time=slice(datetime(1990, 5, 1), datetime(1990, 8, 31))) >>> spi_3 = standardized_precipitation_index( ... pr, pr_cal, freq="MS", window=3, dist="gamma", method="ML" ... ) # Computing SPI-3 months using a gamma distribution for the fit
References
McKee, Doesken, and Kleist [1993]
- xclim.indices.tas(tasmin: DataArray, tasmax: DataArray) DataArray [source]
Average temperature from minimum and maximum temperatures.
We assume a symmetrical distribution for the temperature and retrieve the average value as Tg = (Tx + Tn) / 2
- Parameters
tasmin (xarray.DataArray) – Minimum (daily) temperature
tasmax (xarray.DataArray) – Maximum (daily) temperature
- Returns
xarray.DataArray – Mean (daily) temperature [same units as tasmin]
Examples
>>> from xclim.indices import tas >>> tas = tas(tasmin_dataset, tasmax_dataset)
- xclim.indices.temperature_seasonality(tas: DataArray, freq: str = 'YS') DataArray [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.
- 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: DataArray, tas_per: DataArray, freq: str = 'YS', bootstrap: bool = False, op: str = '<') DataArray [source]
Number of days with daily mean temperature below the 10th percentile.
Number of days with daily mean temperature below the 10th percentile.
- Parameters
tas (xarray.DataArray) – Mean daily temperature.
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: “<”.
- 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: DataArray, tas_per: DataArray, freq: str = 'YS', bootstrap: bool = False, op: str = '>') DataArray [source]
Number of days with daily mean temperature over the 90th percentile.
Number of days with daily mean temperature over the 90th percentile.
- Parameters
tas (xarray.DataArray) – Mean daily temperature.
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: “>”.
- 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: DataArray, thresh: Quantified = '10.0 degC', freq: str = 'YS', op: str = '>')[source]
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: DataArray, thresh: Quantified = '10.0 degC', freq: str = 'YS', op: str = '<')[source]
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: DataArray, freq: str = 'YS') DataArray [source]
Highest mean temperature.
The maximum of daily mean temperature.
- Parameters
tas (xarray.DataArray) – Mean daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tas] – Maximum of daily minimum temperature.
Notes
Let \(TN_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the maximum daily mean temperature for period \(j\) is:
\[TNx_j = max(TN_{ij})\]
- xclim.indices.tg_mean(tas: DataArray, freq: str = 'YS') DataArray [source]
Mean of daily average temperature.
Resample the original daily mean temperature series by taking the mean over each period.
- Parameters
tas (xarray.DataArray) – Mean daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tas] – The mean daily temperature at the given time frequency
Notes
Let \(TN_i\) be the mean daily temperature of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):
\[TG_p = \frac{\sum_{i=a}^{b} TN_i}{b - a + 1}\]Examples
The following would compute for each grid cell of file tas.day.nc the mean temperature at the seasonal frequency, 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: DataArray, op: Optional[str] = None, freq: str = 'YS') DataArray [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.
- 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: DataArray, pr: DataArray, op: Optional[str] = None, freq: str = 'YS') DataArray [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.
- 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: DataArray, freq: str = 'YS') DataArray [source]
Lowest mean temperature.
Minimum of daily mean temperature.
- Parameters
tas (xarray.DataArray) – Mean daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tas] – Minimum of daily minimum temperature.
Notes
Let \(TG_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the minimum daily mean temperature for period \(j\) is:
\[TGn_j = min(TG_{ij})\]
- xclim.indices.tn10p(tasmin: DataArray, tasmin_per: DataArray, freq: str = 'YS', bootstrap: bool = False, op: str = '<') DataArray [source]
Number of days with daily minimum temperature below the 10th percentile.
Number of days with daily minimum temperature below the 10th percentile.
- Parameters
tasmin (xarray.DataArray) – Mean daily temperature.
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: “<”.
- 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: DataArray, tasmin_per: DataArray, freq: str = 'YS', bootstrap: bool = False, op: str = '>') DataArray [source]
Number of days with daily minimum temperature over the 90th percentile.
Number of days with daily minimum temperature over the 90th percentile.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
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: “>”.
- 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: DataArray, thresh: Quantified = '20.0 degC', freq: str = 'YS', op: str = '>')[source]
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: DataArray, thresh: Quantified = '-10.0 degC', freq: str = 'YS', op: str = '<') DataArray [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: “<”.
- 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: DataArray, freq: str = 'YS') DataArray [source]
Highest minimum temperature.
The maximum of daily minimum temperature.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmin] – Maximum of daily minimum temperature.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then the maximum daily minimum temperature for period \(j\) is:
\[TNx_j = max(TN_{ij})\]
- xclim.indices.tn_mean(tasmin: DataArray, freq: str = 'YS') DataArray [source]
Mean minimum temperature.
Mean of daily minimum temperature.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmin] – Mean of daily minimum temperature.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:
\[TN_{ij} = \frac{ \sum_{i=1}^{I} TN_{ij} }{I}\]
- xclim.indices.tn_min(tasmin: DataArray, freq: str = 'YS') DataArray [source]
Lowest minimum temperature.
Minimum of daily minimum temperature.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmin] – Minimum of daily minimum temperature.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then the minimum daily minimum temperature for period \(j\) is:
\[TNn_j = min(TN_{ij})\]
- xclim.indices.tx10p(tasmax: DataArray, tasmax_per: DataArray, freq: str = 'YS', bootstrap: bool = False, op: str = '<') DataArray [source]
Number of days with daily maximum temperature below the 10th percentile.
Number of days with daily maximum temperature below the 10th percentile.
- Parameters
tasmax (xarray.DataArray) – Maximum daily temperature.
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: “<”.
- 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: DataArray, tasmax_per: DataArray, freq: str = 'YS', bootstrap: bool = False, op: str = '>') DataArray [source]
Number of days with daily maximum temperature over the 90th percentile.
Number of days with daily maximum temperature over the 90th percentile.
- Parameters
tasmax (xarray.DataArray) – Maximum daily temperature.
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: “>”.
- 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: DataArray, thresh: Quantified = '25.0 degC', freq: str = 'YS', op: str = '>') DataArray [source]
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: “>”.
- 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: DataArray, thresh: Quantified = '25.0 degC', freq: str = 'YS', op: str = '<')[source]
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: DataArray, freq: str = 'YS') DataArray [source]
Highest max temperature.
The maximum value of daily maximum temperature.
- Parameters
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmax] – Maximum value of daily maximum temperature.
Notes
Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then the maximum daily maximum temperature for period \(j\) is:
\[TXx_j = max(TX_{ij})\]
- xclim.indices.tx_mean(tasmax: DataArray, freq: str = 'YS') DataArray [source]
Mean max temperature.
The mean of daily maximum temperature.
- Parameters
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmax] – Mean of daily maximum temperature.
Notes
Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:
\[TX_{ij} = \frac{ \sum_{i=1}^{I} TX_{ij} }{I}\]
- xclim.indices.tx_min(tasmax: DataArray, freq: str = 'YS') DataArray [source]
Lowest max temperature.
The minimum of daily maximum temperature.
- Parameters
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray, [same units as tasmax] – Minimum of daily maximum temperature.
Notes
Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then the minimum daily maximum temperature for period \(j\) is:
\[TXn_j = min(TX_{ij})\]
- xclim.indices.tx_tn_days_above(tasmin: DataArray, tasmax: DataArray, thresh_tasmin: Quantified = '22 degC', thresh_tasmax: Quantified = '30 degC', freq: str = 'YS', op: str = '>') DataArray [source]
Number of days with both hot maximum and minimum daily temperatures.
The number of days per period with tasmin above a threshold and tasmax above another threshold.
- Parameters
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (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: “>”.
- 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: DataArray, vas: DataArray, calm_wind_thresh: Quantified = '0.5 m/s') tuple[xarray.DataArray, xarray.DataArray] [source]
Wind speed and direction from the eastward and northward wind components.
Computes the magnitude and angle of the wind vector from its northward and eastward components, following the meteorological convention that sets calm wind to a direction of 0° and northerly wind to 360°.
- Parameters
uas (xr.DataArray) – Eastward wind velocity
vas (xr.DataArray) – Northward wind velocity
calm_wind_thresh (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.
- 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: DataArray, hurs: DataArray, sfcWind: DataArray, mrt: Optional[DataArray] = None, rsds: Optional[DataArray] = None, rsus: Optional[DataArray] = None, rlds: Optional[DataArray] = None, rlus: Optional[DataArray] = None, stat: str = 'average', mask_invalid: bool = True) DataArray [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 ({‘average’, ‘instant’, ‘sunlit’}) – Which statistic to apply. If “average”, the average of the cosine of the solar zenith angle is calculated. 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. If “instant”, the instantaneous cosine of the solar zenith angle is calculated. 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.
- 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], Błażejczyk, Jendritzky, Bröde, Fiala, Havenith, Epstein, Psikuta, and Kampmann [2013]
- xclim.indices.warm_and_dry_days(tas: DataArray, pr: DataArray, tas_per: DataArray, pr_per: DataArray, freq: str = 'YS') DataArray [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.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
- 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: DataArray, pr: DataArray, tas_per: DataArray, pr_per: DataArray, freq: str = 'YS') DataArray [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.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
- 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: DataArray, thresh: Quantified = '30 degC', freq: str = 'YS', op: str = '>') DataArray [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: “>”.
- 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: DataArray, thresh: Quantified = '22 degC', freq: str = 'YS', op: str = '>') DataArray [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: “>”.
- Returns
xarray.DataArray, [time] – Number of days with tasmin {op} threshold per period.
- xclim.indices.warm_spell_duration_index(tasmax: DataArray, tasmax_per: DataArray, window: int = 6, freq: str = 'YS', resample_before_rl: bool = True, bootstrap: bool = False, op: str = '>') DataArray [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: “>”.
- 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.
>>> from xclim.core.calendar import percentile_doy >>> from xclim.indices import warm_spell_duration_index
>>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax.isel(lat=0, lon=0) >>> tasmax_per = percentile_doy(tasmax, per=90).sel(percentiles=90) >>> warm_spell_duration_index(tasmax, tasmax_per)
- xclim.indices.water_budget(pr: DataArray, evspsblpot: Optional[DataArray] = None, tasmin: Optional[DataArray] = None, tasmax: Optional[DataArray] = None, tas: Optional[DataArray] = None, lat: Optional[DataArray] = None, hurs: Optional[DataArray] = None, rsds: Optional[DataArray] = None, rsus: Optional[DataArray] = None, rlds: Optional[DataArray] = None, rlus: Optional[DataArray] = None, sfcWind: Optional[DataArray] = None, method: str = 'BR65') DataArray [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.
See also
xclim.indicators.atmos.potential_evapotranspiration
- Returns
xarray.DataArray – Precipitation minus potential evapotranspiration.
- xclim.indices.wetdays(pr: DataArray, thresh: Quantified = '1.0 mm/day', freq: str = 'YS', op: str = '>=') DataArray [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: “>=”.
- 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: DataArray, thresh: Quantified = '1.0 mm/day', freq: str = 'YS', op: str = '>=') DataArray [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: “>=”.
- 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: DataArray, sfcWind: DataArray, method: str = 'CAN', mask_invalid: bool = True)[source]
Wind chill index.
The Wind Chill Index is an estimation of how cold the weather feels to the average person. It is computed from the air temperature and the 10-m wind. As defined by the Environment and Climate Change Canada (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.
- 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:
National Weather Service FAQ: [US Department of Commerce, n.d.].
The New Wind Chill Equivalent Temperature Chart: [Osczevski and Bluestein, 2005].
References
Mekis, Vincent, Shephard, and Zhang [2015], US Department of Commerce [n.d.]
- xclim.indices.windy_days(sfcWind: DataArray, thresh: Quantified = '10.8 m s-1', freq: str = 'MS') DataArray [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.
- 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: DataArray, prsn: Optional[DataArray] = None, tas: Optional[DataArray] = None, freq: str = 'QS-DEC') DataArray [source]
Ratio of rainfall to total precipitation during winter.
The ratio of total liquid precipitation over the total precipitation over the winter months (DJF). If solid precipitation is not provided, then precipitation is assumed solid if the temperature is below 0°C.
- Parameters
pr (xarray.DataArray) – Mean daily precipitation flux.
prsn (xarray.DataArray, optional) – Mean daily solid precipitation flux.
tas (xarray.DataArray, optional) – Mean daily temperature.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray – Ratio of rainfall to total precipitation during winter months (DJF).
- xclim.indices.winter_storm(snd: DataArray, thresh: Quantified = '25 cm', freq: str = 'AS-JUL') DataArray [source]
Days with snowfall over threshold.
Number of days with snowfall 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 accumulation require to label an event a winter storm.
freq (str) – Resampling frequency.
- Returns
xarray.DataArray – Number of days per period identified as winter storms.
Notes
Snowfall accumulation is estimated by the change in snow depth.
Indices submodules
Generic indices submodule
Helper functions for common generic actions done in the computation of indices.
- xclim.indices.generic.aggregate_between_dates(data: DataArray, start: Union[DataArray, DayOfYearStr], end: Union[DataArray, DayOfYearStr], op: str = 'sum', freq: Optional[str] = None) DataArray [source]
Aggregate the data over a period between start and end dates and apply the operator on the aggregated data.
- Parameters
data (xr.DataArray) – Data to aggregate between start and end dates.
start (xr.DataArray or DayOfYearStr) – Start dates (as day-of-year) for the aggregation periods.
end (xr.DataArray or DayOfYearStr) – End (as day-of-year) dates for the aggregation periods.
op ({‘min’, ‘max’, ‘sum’, ‘mean’, ‘std’}) – Operator.
freq (str, optional) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling. Default: None.
- 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: DataArray, op: str, right: float | int | numpy.ndarray | xarray.DataArray, constrain: Optional[Sequence[str]] = None) DataArray [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.
- Returns
xr.DataArray – Boolean mask of the comparison.
- xclim.indices.generic.count_level_crossings(low_data: DataArray, high_data: DataArray, threshold: Quantified, freq: str, *, op_low: str = '<', op_high: str = '>=') DataArray [source]
Calculate the number of times low_data is below threshold while high_data is above threshold.
First, the threshold is transformed to the same standard_name and units as the input data, then the thresholding is performed, and finally, the number of occurrences is counted.
- Parameters
low_data (xr.DataArray) – Variable that must be under the threshold.
high_data (xr.DataArray) – Variable that must be above the threshold.
threshold (Quantified) – Threshold.
freq (str) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
op_low ({“<”, “<=”, “lt”, “le”}) – Comparison operator for low_data. Default: “<”.
op_high ({“>”, “>=”, “gt”, “ge”}) – Comparison operator for high_data. Default: “>=”.
- Returns
xr.DataArray
- xclim.indices.generic.count_occurrences(data: DataArray, threshold: Quantified, freq: str, op: str, constrain: Optional[Sequence[str]] = None) DataArray [source]
Calculate the number of times some condition is met.
First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, then this counts the number of times data < threshold. Finally, count the number of occurrences when condition is met.
- Parameters
data (xr.DataArray) – An array.
threshold (Quantified) – Threshold.
freq (str) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.
constrain (sequence of str, optional) – Optionally allowed conditions.
- Returns
xr.DataArray
- xclim.indices.generic.cumulative_difference(data: DataArray, threshold: Quantified, op: str, freq: Optional[str] = None) DataArray [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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling. If None, no resampling is performed. Default: None.
- Returns
xr.DataArray
- xclim.indices.generic.default_freq(**indexer) str [source]
Return the default frequency.
- xclim.indices.generic.diurnal_temperature_range(low_data: DataArray, high_data: DataArray, reducer: str, freq: str) DataArray [source]
Calculate the diurnal temperature range and reduce according to a statistic.
- Parameters
low_data (xr.DataArray) – The lowest daily temperature (tasmin).
high_data (xr.DataArray) – The highest daily temperature (tasmax).
reducer ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Reducer.
freq (str) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
- Returns
xr.DataArray
- xclim.indices.generic.domain_count(da: DataArray, low: float | int | xarray.DataArray, high: float | int | xarray.DataArray, freq: str) DataArray [source]
Count number of days where value is within low and high thresholds.
A value is counted if it is larger than low, and smaller or equal to high, i.e. in ]low, high].
- Parameters
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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
- Returns
xr.DataArray – The number of days where value is within [low, high] for each period.
- xclim.indices.generic.doymax(da: DataArray) DataArray [source]
Return the day of year of the maximum value.
- xclim.indices.generic.doymin(da: DataArray) DataArray [source]
Return the day of year of the minimum value.
- xclim.indices.generic.extreme_temperature_range(low_data: DataArray, high_data: DataArray, freq: str) DataArray [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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
- Returns
xr.DataArray
- xclim.indices.generic.first_day_threshold_reached(data: DataArray, *, threshold: Quantified, op: str, after_date: DayOfYearStr, window: int = 1, freq: str = 'YS', constrain: Optional[Sequence[str]] = None) DataArray [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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling. Default: “YS”.
constrain (sequence of str, optional) – Optionally allowed conditions.
- 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: DataArray, threshold: Quantified, freq: str, op: str, constrain: Optional[Sequence[str]] = None) DataArray [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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.
constrain (sequence of str, optional) – Optionally allowed conditions.
- Returns
xr.DataArray
- xclim.indices.generic.get_daily_events(da: DataArray, threshold: float | int | xarray.DataArray, op: str, constrain: Optional[Sequence[str]] = None) DataArray [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.
Notes
The function returns:
1
where operator(da, da_value) isTrue
0
where operator(da, da_value) isFalse
nan
where da isnan
- Returns
xr.DataArray
- xclim.indices.generic.get_op(op: str, constrain: Optional[Sequence[str]] = None) Callable [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.
- xclim.indices.generic.interday_diurnal_temperature_range(low_data: DataArray, high_data: DataArray, freq: str) DataArray [source]
Calculate the average absolute day-to-day difference in diurnal temperature range.
- Parameters
low_data (xr.DataArray) – The lowest daily temperature (tasmin).
high_data (xr.DataArray) – The highest daily temperature (tasmax).
freq (str) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
- Returns
xr.DataArray
- xclim.indices.generic.last_occurrence(data: DataArray, threshold: Quantified, freq: str, op: str, constrain: Optional[Sequence[str]] = None) DataArray [source]
Calculate the last time some condition is met.
First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, locate the last occurrence when condition is met.
- Parameters
data (xr.DataArray) – Input data.
threshold (Quantified) – Threshold.
freq (str) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.
constrain (sequence of str, optional) – Optionally allowed conditions.
- Returns
xr.DataArray
- xclim.indices.generic.select_resample_op(da: DataArray, op: str, freq: str = 'YS', **indexer) DataArray [source]
Apply operation over each period that is part of the index selection.
- Parameters
da (xr.DataArray) – Input data.
op (str {‘min’, ‘max’, ‘mean’, ‘std’, ‘var’, ‘count’, ‘sum’, ‘argmax’, ‘argmin’} or func) – Reduce operation. Can either be a DataArray method or a function that can be applied to a DataArray.
freq (str) – Resampling frequency defining the periods as defined in https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. For example, use season=’DJF’ to select winter values, month=1 to select January, or month=[6,7,8] to select summer months. If not indexer is given, all values are considered.
- Returns
xr.DataArray – The maximum value for each period.
- xclim.indices.generic.spell_length(data: DataArray, threshold: Quantified, reducer: str, freq: str, op: str) DataArray [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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical operator. e.g. arr > thresh.
- Returns
xr.DataArray
- xclim.indices.generic.statistics(data: DataArray, reducer: str, freq: str) DataArray [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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
- Returns
xr.DataArray
- xclim.indices.generic.temperature_sum(data: DataArray, op: str, threshold: Quantified, freq: str) DataArray [source]
Calculate the temperature sum above/below a threshold.
First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, the sum is calculated for those data values that fulfill the condition after subtraction of the threshold value. If the sum is for values below the threshold the result is multiplied by -1.
- Parameters
data (xr.DataArray) – 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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
- Returns
xr.DataArray
- xclim.indices.generic.threshold_count(da: DataArray, op: str, threshold: float | int | xarray.DataArray, freq: str, constrain: Optional[Sequence[str]] = None) DataArray [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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
constrain (sequence of str, optional) – Optionally allowed conditions.
- Returns
xr.DataArray – The number of days meeting the constraints for each period.
- xclim.indices.generic.thresholded_statistics(data: DataArray, op: str, threshold: Quantified, reducer: str, freq: str, constrain: Optional[Sequence[str]] = None) DataArray [source]
Calculate a simple statistic of the data for which some condition is met.
First, the threshold is transformed to the same standard_name and units as the input data. Then the thresholding is performed as condition(data, threshold), i.e. if condition is <, data < threshold. Finally, the statistic is calculated for those data values that fulfill the condition.
- Parameters
data (xr.DataArray) – 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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling.
constrain (sequence of str, optional) – Optionally allowed conditions. Default: None.
- Returns
xr.DataArray
Helper functions submodule
Functions that encapsulate some geophysical logic but could be shared by many indices.
- xclim.indices.helpers.cosine_of_solar_zenith_angle(declination: DataArray, lat: DataArray, lon: Optional[DataArray] = None, time_correction: Optional[DataArray] = None, hours: Optional[DataArray] = None, interval: Optional[int] = None, stat: str = 'integral') DataArray [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 daily statistic of its cosine : its integral from sunrise to sunset or the average over the same period. Based on Kalogirou [2014]. In addition, it computes instantaneous values of its cosine. Based on Di Napoli et al. [2020].
- Parameters
declination (xr.DataArray) – Solar declination. See
solar_declination()
.lat (xr.DataArray) – Latitude.
lon (xr.DataArray, optional) – Longitude. This is necessary if stat is “instant”, “interval” or “sunlit”.
time_correction (xr.DataArray, optional) – Time correction for solar angle. See
time_correction_for_solar_angle()
This is necessary if stat is “instant”.hours (xr.DataArray, optional) – Watch time hours. This is necessary if stat is “instant”, “interval” or “sunlit”.
interval (int, optional) – Time interval between two time steps in hours This is necessary if stat is “interval” or “sunlit”.
stat ({‘integral’, ‘average’, ‘instant’, ‘interval’, ‘sunlit’}) – Which daily statistic to return. If “integral”, this returns the integral of the cosine of the zenith angle from sunrise to sunset. If “average”, the integral is divided by the “duration” from sunrise to sunset. If “instant”, this returns the instantaneous cosine of the zenith angle. If “interval”, this returns the cosine of the zenith angle during each interval. If “sunlit”, this returns the cosine of the zenith angle during the sunlit period of each interval.
- 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
- xclim.indices.helpers.day_lengths(dates: DataArray, lat: DataArray, method: str = 'spencer') DataArray [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()
.
- Returns
xarray.DataArray, [hours] – Day-lengths in hours per individual day.
References
Kalogirou [2014]
- xclim.indices.helpers.distance_from_sun(dates: DataArray) DataArray [source]
Sun-earth distance.
The distance from sun to earth in astronomical units.
- Parameters
dates (xr.DataArray) – Series of dates and time of days.
- 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(day_angle: DataArray, 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
day_angle (xr.DataArray) – 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()
.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
- xclim.indices.helpers.extraterrestrial_solar_radiation(times: DataArray, lat: DataArray, solar_constant: Quantified = '1361 W m-2', method='spencer') DataArray [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()
andeccentricity_correction_factor()
.
- 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(day_angle: DataArray, method='spencer') DataArray [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
day_angle (xr.DataArray) – 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()
.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).
- Returns
xr.DataArray, [rad] – Solar declination angle.
References
Spencer [1971]
- xclim.indices.helpers.time_correction_for_solar_angle(day_angle: DataArray) DataArray [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
day_angle (xr.DataArray) – 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()
.- Returns
xr.DataArray, [rad] – Time correction of solar angle.
References
Di Napoli, Hogan, and Pappenberger [2020]
- xclim.indices.helpers.wind_speed_height_conversion(ua: DataArray, h_source: str, h_target: str, method: str = 'log') DataArray [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
- 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.first_run(da: DataArray, window: int, dim: str = 'time', freq: Optional[str] = None, coord: str | bool | None = False, ufunc_1dim: str | bool = 'from_context') DataArray [source]
Return the index of the first item of the first run of at least a given length.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
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.
- Returns
xr.DataArray – Index (or coordinate if coord is not False) of first item in first valid run. Returns np.nan if there are no valid runs.
- xclim.indices.run_length.first_run_1d(arr: Sequence[int | float], window: int) int | np.nan [source]
Return the index of the first item of a run of at least a given length.
- Parameters
arr (Sequence[Union[int, float]]) – Input array.
window (int) – Minimum duration of consecutive run to accumulate values.
- Returns
int 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: DataArray, window: int, date: Optional[DayOfYearStr] = '07-01', dim: str = 'time', coord: bool | str | None = 'dayofyear') DataArray [source]
Return the index of the first item of the first run after a given date.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values.
date (DayOfYearStr) – The date after which to look for the run.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Returns
xr.DataArray – Index (or coordinate if coord is not False) of first item in the first valid run. Returns np.nan if there are no valid runs.
- xclim.indices.run_length.first_run_ufunc(x: Union[DataArray, Sequence[bool]], window: int, dim: str) DataArray [source]
Dask-parallel version of first_run_1d, ie: the first entry in array of consecutive true values.
- Parameters
x (Union[xr.DataArray, Sequence[bool]]) – Input array (bool).
window (int) – Minimum run length.
dim (str) – The dimension along which the runs are found.
- Returns
xr.DataArray – A function operating along the time dimension of a dask-array.
- xclim.indices.run_length.index_of_date(time: DataArray, date: Optional[Union[DateStr, DayOfYearStr]], max_idxs: Optional[int] = None, default: int = 0) ndarray [source]
Get the index of a date in a time array.
- Parameters
time (xr.DataArray) – An array of datetime values, any calendar.
date (DayOfYearStr or DateStr, optional) – A string in the “yyyy-mm-dd” or “mm-dd” format. If None, returns default.
max_idxs (int, optional) – Maximum number of returned indexes.
default (int) – Index to return if date is None.
- Raises
ValueError – If there are most instances of date in time than max_idxs.
- Returns
numpy.ndarray – 1D array of integers, indexes of date in time.
- xclim.indices.run_length.keep_longest_run(da: DataArray, dim: str = 'time', freq: Optional[str] = None) DataArray [source]
Keep the longest run along a dimension.
- Parameters
da (xr.DataArray) – Boolean array.
dim (str) – Dimension along which to check for the longest run.
freq (str) – Resampling frequency.
- Returns
xr.DataArray, [bool] – Boolean array similar to da but with only one run, the (first) longest.
- xclim.indices.run_length.last_run(da: DataArray, window: int, dim: str = 'time', freq: Optional[str] = None, coord: str | bool | None = False, ufunc_1dim: str | bool = 'from_context') DataArray [source]
Return the index of the last item of the last run of at least a given length.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
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.
- 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: DataArray, window: int, date: DayOfYearStr = '07-01', dim: str = 'time', coord: bool | str | None = 'dayofyear') DataArray [source]
Return the index of the last item of the last run before a given date.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values.
date (DayOfYearStr) – The date before which to look for the last event.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Returns
xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.
- xclim.indices.run_length.lazy_indexing(da: DataArray, index: DataArray, dim: Optional[str] = None) DataArray [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.
- Returns
xr.DataArray – Values of da at indices index.
- xclim.indices.run_length.longest_run(da: DataArray, dim: str = 'time', freq: Optional[str] = None, ufunc_1dim: str | bool = 'from_context', index: str = 'first') DataArray [source]
Return the length of the longest consecutive run of True values.
- Parameters
da (xr.DataArray) – N-dimensional array (boolean).
dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.
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.
- 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: DataArray, resample_before_rl: bool, compute, *args, freq: str, dim: str = 'time', **kwargs) xarray.DataArray | xarray.Dataset [source]
Wrap run length algorithms to control if resampling occurs before or after the algorithms.
If resample_before_rl is ‘from_context’, the parameter is read from xclim’s global (or context) options.
- 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.
- Returns
xr.DataArray – Output of compute resampled according to frequency {freq}.
- xclim.indices.run_length.rle(da: DataArray, dim: str = 'time', index: str = 'first') DataArray [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.
- Returns
xr.DataArray – Values are 0 where da is False (out of runs).
- xclim.indices.run_length.rle_1d(arr: Union[int, float, bool, Sequence[int | float | bool]]) tuple[numpy.array, numpy.array, numpy.array] [source]
Return the length, starting position and value of consecutive identical values.
- Parameters
arr (Sequence[Union[int, float, bool]]) – Array of values to be parsed.
- Returns
values (np.array) – The values taken by arr over each run.
run lengths (np.array) – The length of each run.
start position (np.array) – The starting index of each run.
Examples
>>> from xclim.indices.run_length import rle_1d >>> a = [1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3] >>> rle_1d(a) (array([1, 2, 3]), array([2, 4, 6]), array([0, 2, 6]))
- xclim.indices.run_length.rle_statistics(da: DataArray, reducer: str, window: int, dim: str = 'time', freq: Optional[str] = None, ufunc_1dim: str | bool = 'from_context', index: str = 'first') DataArray [source]
Return the length of consecutive run of True values, according to a reducing operator.
- Parameters
da (xr.DataArray) – N-dimensional array (boolean).
reducer (str) – Name of the reducing function.
window (int) – Minimal length of consecutive runs to be included in the statistics.
dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.
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.
- 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: DataArray, dim: str = 'time', coord: bool | str = 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: DataArray, window: int, date: DayOfYearStr = '07-01', dim: str = 'time', coord: bool | str | None = 'dayofyear') DataArray [source]
Return the index of the first item after the end of a run after a given date.
The run must begin before the date.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values.
date (str) – The date after which to look for the end of a run.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Returns
xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.
- xclim.indices.run_length.season(da: DataArray, window: int, date: Optional[DayOfYearStr] = None, dim: str = 'time', coord: str | bool | None = False) Dataset [source]
Return the bounds of a season (along dim).
A “season” is a run of True values that may include breaks under a given length (window). The start is computed as the first run of window True values, then end as the first subsequent run of window False values. If a date is passed, it must be included in the season.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive values to start and end the season.
date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Returns
xr.Dataset – “dim” is reduced to “season_bnds” with 2 elements : season start and season end, both indices of da[dim].
Notes
The run can include holes of False or NaN values, so long as they do not exceed the window size.
If a date is given, the season start and end are forced to be on each side of this date. This means that even if the “real” season has been over for a long time, this is the date used in the length calculation. Example : Length of the “warm season”, where T > 25°C, with date = 1st August. Let’s say the temperature is over 25 for all June, but July and august have very cold temperatures. Instead of returning 30 days (June), the function will return 61 days (July + June).
- xclim.indices.run_length.season_length(da: DataArray, window: int, date: Optional[DayOfYearStr] = None, dim: str = 'time') DataArray [source]
Return the length of the longest semi-consecutive run of True values (optionally including a given date).
A “season” is a run of True values that may include breaks under a given length (window). The start is computed as the first run of window True values, then end as the first subsequent run of window False values. If a date is passed, it must be included in the season.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive values to start and end the season.
date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
- Returns
xr.DataArray, [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: Sequence[bool], reducer: str, window: int) int [source]
Return statistics on lengths of run of identical values.
- Parameters
arr (Sequence[bool]) – Input array (bool)
reducer ({‘mean’, ‘sum’, ‘min’, ‘max’, ‘std’}) – Reducing function name.
window (int) – Minimal length of runs to be included in the statistics
- Returns
int – Statistics on length of runs.
- xclim.indices.run_length.statistics_run_ufunc(x: Union[DataArray, Sequence[bool]], reducer: str, window: int, dim: str = 'time') DataArray [source]
Dask-parallel version of statistics_run_1d, ie: the {reducer} number of consecutive true values in array.
- Parameters
x (Sequence[bool]) – Input array (bool)
reducer ({‘min’, ‘max’, ‘mean’, ‘sum’, ‘std’}) – Reducing function name.
window (int) – Minimal length of runs.
dim (str) – The dimension along which the runs are found.
- Returns
xr.DataArray – A function operating along the time dimension of a dask-array.
- xclim.indices.run_length.suspicious_run(arr: DataArray, dim: str = 'time', window: int = 10, op: str = '>', thresh: Optional[float] = None) DataArray [source]
Return True where the array contains has runs of identical values, vectorized version.
In opposition to other run length functions, here the output has the same shape as the input.
- Parameters
arr (xr.DataArray) – Array of values to be parsed.
dim (str) – Dimension along which to check for runs (default: “time”).
window (int) – Minimum run length.
op ({“>”, “>=”, “==”, “<”, “<=”, “eq”, “gt”, “lt”, “gteq”, “lteq”}) – Operator for threshold comparison, defaults to “>”.
thresh (float, optional) – Threshold above which values are checked for identical values.
- Returns
xarray.DataArray
- xclim.indices.run_length.suspicious_run_1d(arr: ndarray, window: int = 10, op: str = '>', thresh: Optional[float] = None) ndarray [source]
Return True where the array contains a run of identical values.
- Parameters
arr (numpy.ndarray) – Array of values to be parsed.
window (int) – Minimum run length.
op ({“>”, “>=”, “==”, “<”, “<=”, “eq”, “gt”, “lt”, “gteq”, “lteq”, “ge”, “le”}) – Operator for threshold comparison. Defaults to “>”.
thresh (float, optional) – Threshold compared against which values are checked for identical values.
- Returns
numpy.ndarray – Whether or not the data points are part of a run of identical values.
- xclim.indices.run_length.use_ufunc(ufunc_1dim: bool | str, da: DataArray, dim: str = 'time', freq: Optional[str] = None, index: str = 'first') bool [source]
Return whether the ufunc version of run length algorithms should be used with this DataArray or not.
If ufunc_1dim is ‘from_context’, the parameter is read from xclim’s global (or context) options. If it is ‘auto’, this returns False for dask-backed array and for arrays with more than
npts_opt
points per slice along dim.- Parameters
ufunc_1dim ({‘from_context’, ‘auto’, True, False}) – The method for handling the ufunc parameters.
da (xr.DataArray) – Input array.
dim (str) – The dimension along which to find runs.
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.
- 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: DataArray, window: int, dim: str = 'time', freq: Optional[str] = None, ufunc_1dim: str | bool = 'from_context', index: str = 'first') DataArray [source]
Return the number of consecutive true values in array for runs at least as long as given duration.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
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.
- 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: Sequence[bool], window: int) int [source]
Return the number of consecutive true values in array for runs at least as long as given duration.
- Parameters
arr (Sequence[bool]) – Input array (bool).
window (int) – Minimum duration of consecutive run to accumulate values.
- Returns
int – Total number of true values part of a consecutive run at least window long.
- xclim.indices.run_length.windowed_run_count_ufunc(x: Union[DataArray, Sequence[bool]], window: int, dim: str) DataArray [source]
Dask-parallel version of windowed_run_count_1d, ie: the number of consecutive true values in array for runs at least as long as given duration.
- Parameters
x (Sequence[bool]) – Input array (bool).
window (int) – Minimum duration of consecutive run to accumulate values.
dim (str) – Dimension along which to calculate windowed run.
- Returns
xr.DataArray – A function operating along the time dimension of a dask-array.
- xclim.indices.run_length.windowed_run_events(da: DataArray, window: int, dim: str = 'time', freq: Optional[str] = None, ufunc_1dim: str | bool = 'from_context', index: str = 'first') DataArray [source]
Return the number of runs of a minimum length.
- Parameters
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
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.
- Returns
xr.DataArray, [int] – Number of distinct runs of a minimum length (int).
- xclim.indices.run_length.windowed_run_events_1d(arr: Sequence[bool], window: int) DataArray [source]
Return the number of runs of a minimum length.
- Parameters
arr (Sequence[bool]) – Input array (bool).
window (int) – Minimum run length.
- Returns
xr.DataArray, [int] – Number of distinct runs of a minimum length.
- xclim.indices.run_length.windowed_run_events_ufunc(x: Union[DataArray, Sequence[bool]], window: int, dim: str) DataArray [source]
Dask-parallel version of windowed_run_events_1d, ie: the number of runs at least as long as given duration.
- Parameters
x (Sequence[bool]) – Input array (bool).
window (int) – Minimum run length.
dim (str) – Dimension along which to calculate windowed run.
- Returns
xr.DataArray – A function operating along the time dimension of a dask-array.
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.
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
Additionaly, 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: DataArray, pr: DataArray, sfcWind: DataArray, hurs: DataArray, lat: DataArray, snd: Optional[DataArray] = None, ffmc0: Optional[DataArray] = None, dmc0: Optional[DataArray] = None, dc0: Optional[DataArray] = None, season_mask: Optional[DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = 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 indefault_params
.
- Returns
DC (xr.DataArray, [dimensionless])
DMC (xr.DataArray, [dimensionless])
FFMC (xr.DataArray, [dimensionless])
ISI (xr.DataArray, [dimensionless])
BUI (xr.DataArray, [dimensionless])
FWI (xr.DataArray, [dimensionless])
Notes
See Natural Resources Canada [n.d.], the
xclim.indices.fire
module documentation, and the docstring offire_weather_ufunc()
for more information.References
Wang, Anderson, and Suddaby [2015]
- xclim.indices.fire._cffwis.drought_code(tas: DataArray, pr: DataArray, lat: DataArray, snd: Optional[DataArray] = None, dc0: Optional[DataArray] = None, season_mask: Optional[DataArray] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]
Drought code (FWI component).
The drought code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of organic layers.
- Parameters
tas (xr.DataArray) – Noon temperature.
pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.
lat (xr.DataArray) – Latitude coordinate
snd (xr.DataArray) – Noon snow depth.
dc0 (xr.DataArray) – Initial values of the drought code.
season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.
season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R 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
.
- Returns
xr.DataArray, [dimensionless] – Drought code
Notes
See Natural Resources Canada [n.d.], the
xclim.indices.fire
module documentation, and the docstring offire_weather_ufunc()
for more information.References
Wang, Anderson, and Suddaby [2015]
- xclim.indices.fire._cffwis.fire_season(tas: DataArray, snd: Optional[DataArray] = None, method: str = 'WF93', freq: Optional[str] = None, temp_start_thresh: Quantified = '12 degC', temp_end_thresh: Quantified = '5 degC', temp_condition_days: int = 3, snow_condition_days: int = 3, snow_thresh: Quantified = '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.
- Returns
xr.DataArray – Fire season mask
References
- xclim.indices.fire._cffwis.fire_weather_ufunc(*, tas: DataArray, pr: DataArray, hurs: Optional[DataArray] = None, sfcWind: Optional[DataArray] = None, snd: Optional[DataArray] = None, lat: Optional[DataArray] = None, dc0: Optional[DataArray] = None, dmc0: Optional[DataArray] = None, ffmc0: Optional[DataArray] = None, winter_pr: Optional[DataArray] = None, season_mask: Optional[DataArray] = None, start_dates: Optional[Union[DataArray, str]] = None, indexes: Optional[Sequence[str]] = None, season_method: Optional[str] = None, overwintering: bool = False, dry_start: Optional[str] = None, initial_start_up: bool = True, **params)[source]
Fire Weather Indexes computation using xarray’s apply_ufunc.
No unit handling. Meant to be used by power users only. Please prefer using the
DC
andCFFWIS
indicators or thedrought_code()
andcffwis_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)
wetting_efficiency_fraction (float) – Drought code overwintering parameters, see
overwintering_drought_code()
.temp_start_thresh (float) – Starting temperature threshold.
temp_end_thresh (float) – Ending temperature threshold.
temp_condition_days (int) – The number of days’ temperature condition to consider.
snow_thresh (float)
snow_condition_days (int) – Parameters for the fire season determination. See
fire_season()
. Temperature is in degC, snow in m. The snow_thresh parameters is also used when dry_start is set to “GFWED”, see Notes.dc_start (float)
dmc_start (float)
ffmc_start (float) – Default starting values for the three base codes.
prec_thresh (float) – If the “dry start” is activated, this is the “wet” day precipitation threshold, see Notes. In mm/d.
dc_dry_factor (float) – DC’s start-up values for the “dry start” mechanism, see Notes.
dmc_dry_factor (float) – DMC’s start-up values for the “dry start” mechanism, see Notes.
snow_cover_days (int)
snow_min_cover_frac (float)
snow_min_mean_depth (float) – Additional parameters for GFWED’s version of the “dry start” mechanism. See Notes. Snow depth is in m.
- Returns
dict[str, xarray.DataArray] – Dictionary containing the computed indexes as prescribed in indexes, including the intermediate ones needed, even if they were not explicitly listed in indexes. When overwintering is activated, winter_pr is added. If season_method is not None and season_mask was not given, season_mask is computed on-the-fly and added to the output.
Notes
When overwintering is activated, the argument dc0 is understood as last season’s last DC map and will be used to compute the overwintered DC at the beginning of the next season.
If overwintering is not activated and neither is fire season computation (season_method and season_mask are None), dc0, dmc0 and ffmc0 are understood as the codes on the day before the first day of FWI computation. They will default to their respective start values. This “always on” mode replicates the R “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: DataArray, winter_pr: DataArray, carry_over_fraction: xarray.DataArray | float = 0.75, wetting_efficiency_fraction: xarray.DataArray | float = 0.75, min_dc: xarray.DataArray | float = 15) DataArray [source]
Compute the season-starting drought code based on the previous season’s last drought code and the total winter precipitation.
This method replicates the “wDC” method of the “cffdrs R package [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.
- 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: DataArray, smd: DataArray, limiting_func: str = 'xlim') DataArray [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.
- 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: DataArray, tasmax: DataArray, pr_annual: DataArray, kbdi0: Optional[DataArray] = None) DataArray [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.
- 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: DataArray, tasmax: DataArray, hurs: DataArray, sfcWind: DataArray)[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)
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).
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)
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).