API¶
Indicators¶
Indicator collections¶
An indicator collection is a structure holding multiple indicators. It can be created through a yaml configuration file.
YAML file structure¶
Indicator-defining yaml files are structured in the following way. Most entries of the indicators section are
mirroring attributes of the xclim.core.indicator.Indicator, please refer to its documentation for more
details on each.
module: <module name> # Defaults to the file name
realm: <realm> # If given here, applies to all indicators that do not already provide it.
keywords:
- <keyword> # Merged with indicator-specific keywords (appended to the list)
references: <references> # Merged with indicator-specific references (joined with a new line)
base: <base indicator class> # Defaults to "Daily" and applies to all indicators that do not give it.
doc: <module docstring> # Defaults to a minimal header, only valid if the module doesn't already exist.
variables: # Optional section if indicators declared below rely on variables unknown to xclim
# (not in `xclim.core.VARIABLES`)
# The variables are not module-dependent and will overwrite any already existing with the same name.
<varname>:
canonical_units: <units> # required
description: <description> # required
standard_name: <expected standard_name> # optional
cell_methods: <expected cell_methods> # optional
indicators:
<identifier>: # The actual indicator identifier will be prepended by the module name.
# From which Indicator to inherit
base: <base indicator class> # Defaults to module-wide base class
# If the name startswith a '.', the base class is taken from the current module
# (thus an indicator declared _above_).
# Available indicators are listed in `xclim.core.indicator.registry` and
# other base classes in `xclim.core.indicator.base_registry`.
# General metadata, usually parsed from the `compute`s docstring when possible.
realm: <realm> # defaults to module-wide realm. One of "atmos", "land", "seaIce", "ocean".
title: <title>
abstract: <abstract>
keywords:
- <keyword> # merged to module-wide keywords.
references: <references> # newline-seperated, merged to module-wide references.
notes: <notes>
# Other options (not all indicator classes support them)
missing: <missing method name>
missing_options: <missing options mapping>
allowed_periods: [<list>, <of>, <allowed>, <periods>]
context: <context> # A unit context enabled during the conversion of the compute's output to the requested units
# Compute function
compute: <function name> # Referring to a function in `compute` module
# (xclim.compute.generic or xclim.compute)
# Or to a function declared in the mapping passed to the collection constructor.
input: # When "compute" is a generic function, this is a mapping from argument name to the expected variable.
# It will change the expected name of the variable as well as its units/dimensionality.
# Can refer to a variable declared in the `variables` section above or in `xclim.core.VARIABLES`.
<var name in compute> : <variable official name>
...
# Parameters
<param name>: <param data> # Simplest case, to inject parameters in the compute function.
# Kwargs-like parameters like ``indexer`` must be injected as a dictionary here.
<param name>: # To change parameters metadata or to declare units when "compute" is a generic function.
default : <param default>
description: <param description>
name : <param name> # Change the name of the parameter (similar to what `input` does for variables)
kind: <param kind> # Override the parameter kind. This is mostly useful for transforming an
# optional variable into a required one by passing ``kind: 0``.
...
... # and so on.
All fields are optional. Other fields found in the yaml file will trigger errors when validation is activated.
When a module is built from a yaml file, the yaml is first validated against the schema (see xclim/data/schema.yml) using the YAMALE library ([Lopker, 2022]). See the “Extending xclim” notebook for more info.
Inputs¶
As xclim has strict definitions of possible input variables (see xclim.core.VARIABLES),
the mapping of indicators.<identifier>.input simply links an argument name from the function given in “compute”
to one of those official variables.
- class xclim.core.collection.IndicatorCollection(indicators, name=None, doc=None)[source]
A collection of indicators.
- classmethod from_yaml(filename, name=None, computes=None, translations=None, mode='raise', encoding='UTF8', validate=True)[source]
Build an indicator collection from a YAML file.
When given only a base filename (no ‘yml’ extension), this tries to find custom indicators in a module of the same name (.py) and translations in json files (.<lang>.json), see Notes.
Indicator created here will have the name of the module prepended to their identifier (ex: {mod}.{baseId}). The base identifier being the key name within the indicators mapping in the yaml.
- Parameters:
filename (PathLike) – Path to a YAML file or to the stem of all module files. See Notes for behaviour when passing a basename only.
name (str, optional) – The name of the new or existing module, defaults to the basename of the file (e.g: atmos.yml -> atmos).
computes (Mapping of callables or module or path, optional) – A mapping or module of compute functions or a python file declaring such a module. When creating the indicator, the name in the compute field is first sought here, then the indicator class will search in
xclim.compute.genericand finally inxclim.compute.translations (Mapping of dicts or path, optional) – Translated metadata for the new indicators. Keys of the mapping must be two-character language tags. Values can be translations dictionaries as defined in Internationalization. They can also be a path to a JSON file defining the translations.
mode ({‘raise’, ‘warn’, ‘ignore’}) – How to deal with broken indicator definitions.
encoding (str) – The encoding used to open the .yaml and .json files. It defaults to UTF-8, overriding python’s mechanism which is machine dependent.
validate (bool or PathLike) – If True (default), the yaml module is validated against the xclim schema. Can also be the path to a YAML schema against which to validate; Or False, in which case validation is simply skipped.
- Returns:
IndicatorCollection – A collection of indicators.
See also
xclim.core.indicatorIndicator build logic.
Notes
When the given filename has no suffix (usually ‘.yaml’ or ‘.yml’), the function will try to load custom compute functions definitions from a file with the same name but with a .py extension. Similarly, it will try to load translations in *.<lang>.json files, where <lang> is the IETF language tag. Note that the file name can not contain a dot (
.) for this logic to work.For example. a set of custom indicators could be fully described by the following files:
example.yml : defining the indicator’s metadata.
example.py : defining a few compute functions.
example.fr.json : French translations
- iter_indicators()[source]
Iterate over the (name, indicator) pairs in this collection.
Compute functions¶
Note
Index-like compute functions (formerly “Indices”) serve as the scientific logic behind Indicators. End users should usually
not have to use these functions directly, unless creating a new IndicatorCollection.
(see: Defining new indicators).
Otherwise, we suggest using the Climate Indicators.
Compute functions are designed to operate on xarray.DataArray objects.
Most of these functions operate on daily time series, but they usually don’t check this.
All functions perform units checks to make sure that inputs have the expected dimensions
(e.g. handling for units of temperature, whether they are Celsius, kelvin or Fahrenheit), and set the units
attribute of the output DataArray.
Helper submodules¶
The xclim.compute.generic, xclim.compute.helpers, xclim.compute.run_length, and
xclim.compute.stats submodules provide helper functions to simplify the implementation of index-like compute functions
while functions under xclim.core.calendar can aid with challenges arising from variable calendar
types.
Generic Index Submodule¶
A generic index function is a function that computes a resampling indicator without a specific application or input variable. The functions defined here are the building blocks for most xclim indicators.
A generic index function should take in one or multiple variable in the form of xarray.DataArray,
as its first arguments. Almost all functions here should also take a freq argument, defining the resampling period.
A specific vocabulary and annotations are used in this submodule to define arguments as clearly as possible.
The vocabulary is strongly inspired from clix-meta.
data: xr.DataArrayThe first(s) arguments of all index function. When multiple variables are required,an integer suffix is added.
statistic: ReducerThe name of a time-reducing operation, usually a built-in numpy/xarray method or a member ofXCLIM_OPS.
condition: ConditionThe string or symbol of a binary comparison operator. Should usually be a key or valid ofBINARY_OPS.
thresh: QuantifiedA threshold for thresholded index. Usually a string with a value and units (" 0 °C"),index functions should also accept non-temporal DataArrays and pint Quantity objects.
freq: FreqA frequency string referring to a pandasdate offset object. Xclim only officially supports the frequency strings that xarray’s implementation of CFtime supports, so the ones completely independent of a specific calendar.
**indexer: Time selection arguments as implemented byselect_time().
- xclim.compute.generic.bivariate_count_occurrences(data1, data2, condition1, condition2, thresh1, thresh2, freq, var_reducer='all', constrain1=None, constrain2=None, **indexer)[source]
Count number of timesteps where two variables fulfill thresholded conditions.
The output has a temporal dimensionality, it is the total duration of moments where the condition is fulfilled, considering all variables as interval variables.
- Parameters:
data1 (xr.DataArray) – An array.
data2 (xr.DataArray) – An array.
condition1 ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator for data variable 1.
condition2 ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}, optional) – Logical comparison operator for data variable 2. If None,
condition1is used.thresh1 (Quantified) – Threshold for data variable 1.
thresh2 (Quantified, optional) – Threshold for data variable 2. If None,
thresh1is used.freq (str) – Resampling frequency defining the periods as defined in Resampling.
var_reducer ({“all”, “any”}) – The condition must either be fulfilled on all or any variables for the timestep to be considered an occurrence.
constrain1 (sequence of str, optional) – Allowed comparison operators for variable 1, None to allow all.
constrain2 (sequence of str, optional) – Allowed comparison operators for variable 2, None to allow all. If
condition2is None,constrain1is used andconstrain2is ignored.**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray, [time] – Number of timesteps where data1 is {condition1} {thresh1} and data2 is {condition2} {thresh2}.
Notes
Sampling length is derived from data1.
- xclim.compute.generic.bivariate_spell_length_statistics(data1, data2, window, window_statistic, condition, thresh1, thresh2, statistic, freq, min_gap=1, constrain=None, resample_before_rl=True, **indexer)[source]
Statistics of bivariate spells lengths.
A spell is when a running statistic (window_statistic) over a (minimum) number (window) of consecutive timesteps respects a condition (data
conditionthresh). Then this returns a statistic over the spell lengths. Two consecutive spells are merged into a single one.- Parameters:
data1 (xr.DataArray) – Input data.
data2 (xr.DataArray) – Input data.
window (int) – Minimum length of a spell.
window_statistic ({‘min’, ‘max’, ‘sum’, ‘mean’, ‘integral’}) – Reduction along the window length to compute running statistic. Note that this does not matter when window is 1, in which case any occurrence of
data {condition} threshis considered a valid “spell”.condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator. Computed as
rolling_stat {condition} thresh.thresh1 (Quantified) – Threshold to test against for data1.
thresh2 (Quantified) – Threshold to test against for data2.
statistic ({‘max’, ‘sum’, ‘count’} or sequence of str) – Statistic on the spell lengths. If a list, multiple statistics are computed.
freq (str) – Resampling frequency.
min_gap (int) – The shortest possible gap between two spells. Spells closer than this are merged by assigning the gap steps to the merged spell.
constrain (sequence of str, optional) – Allowed conditions. None to allow them all.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Indexing is done after finding the days part of a spell, but before taking the spell statistics.
- Return type:
DataArray|Sequence[DataArray]- Returns:
xr.DataArray or sequence of xr.DataArray – {statistic} of spell lengths. A spell is when the {window}-day {window_statistic} of data1 is {condition} {thresh1} and the one of data2 is {condition} {thresh2}.
See also
spell_length_statisticsThe univariate version.
xclim.indices.helpers.spell_maskThe lower level functions that finds spells.
- xclim.compute.generic.count_domain_occurrences(data, low_bound, high_bound, freq, low_condition='>', high_condition='<=', **indexer)[source]
Count number of timesteps where the data is within two bounds.
The output has a temporal dimensionality, it is the total duration of moments where the condition is fulfilled, considering all variables as interval variables.
- Parameters:
data (xr.DataArray) – Input data.
low_bound (Quantified) – Minimum value.
high_bound (Quantified) – Maximum value.
freq (str) – Resampling frequency defining the periods defined in Resampling.
low_condition ({‘>’, ‘>=’, ‘gt’, ‘ge’}) – The comparison operator to use on the lower bound. Default is “>” which means equality does not fulfill the condition.
high_condition ({‘<’, ‘<=’, ‘lt’, ‘le’}) – The comparison operator to use on the higher bound. Default is “<=” which means equality does fulfill the condition.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray – {The number of days where value is within [low, high] for each period.
- xclim.compute.generic.count_occurrences(data, condition, thresh, freq, constrain=None, **indexer)[source]
Count number of timesteps where the data fulfills a thresholded condition.
The output has a temporal dimensionality, it is the total duration of moments where the condition is fulfilled, considering all variables as interval variables.
- Parameters:
data (xr.DataArray) – Input data.
condition ({“>”, “<”, “>=”, “<=”, “gt”, “lt”, “ge”, “le”}) – Logical comparison operator. Comparison is done as
data {condition} thresh.thresh (Quantified) – Threshold value. Should have the same dimensionality as data.
freq (str) – Resampling frequency defining the periods as defined in Resampling.
constrain (sequence of str, optional) – Allowed conditions, to be used when creating a more specific indicator from this function.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray – Number of timesteps where data {condition} {thresh}.
- xclim.compute.generic.count_percentile_occurrences(data, percentile, condition, reference_period, freq, window=5, bootstrap=False, constrain=None, **indexer)[source]
Count how many times an annually varying percentile-based thresholded condition is fulfilled.
For each day-of-year, the percentile is computed over the reference period with a doy window. Then the number of timesteps where this threshold fulfills the condition is counted for each requested period. The output has a temporal dimensionality, it is the total duration of moments where the condition is fulfilled, considering all variables as interval variables.
- Parameters:
data (xr.DataArray) – An array. Should have a daily step.
percentile (float) – The percentile to compute on the reference period, between 0 and 100.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator. Computed as
data[i] {condition} climatology[doy(i)].reference_period (tuple of two dates) – Start and end of the period used to compute the percentiles. Dates should be given as YYYY-MM-DD.
freq (str) – Resampling frequency defining the periods as defined in Resampling. This function only makes sense with annual frequencies.
window (int) – The number of days on each side of the given day-of-year to include in the climatology.
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 (like here). This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series Note that bootstrapping is computationally expensive.
constrain (sequence of str, optional) – Allowed conditions. None to allow them all.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Subsetting is not done one the data used to compute the climatology, only on the data against which the condition is checked.
- Return type:
DataArray- Returns:
xr.DataArray – Number of timesteps where data is {condition} the {percentile}th percentile computed over {reference_period}.
- xclim.compute.generic.count_thresholded_percentile_occurrences(data, data_condition, thresh, percentile, condition, reference_period, freq, window=5, bootstrap=False, constrain=None, **indexer)[source]
Count how many times an annually-varying percentile condition is fulfilled over data fulfilling another condition.
The data is first filtered to keep only the timesteps where the thresholded
data_conditionis fulfilled. Then, for each day-of-year, the percentile is computed over the reference period with a doy window. Then the number of timesteps where this threshold fulfills the condition is counted for each requested period. The output has a temporal dimensionality, it is the total duration of moments where the condition is fulfilled, considering all variables as interval variables.- Parameters:
data (xr.DataArray) – An array. Should have a daily step.
data_condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator to filter data with threshold.
thresh (Quantified) – Threshold for the
data_condition.percentile (float) – The percentile to compute on the reference period, between 0 and 100.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator to find occurrences. Computed as
data[i] {condition} climatology[doy(i)].reference_period (tuple of two dates) – Start and end of the period used to compute the percentiles. Dates should be given as YYYY-MM-DD.
freq (str) – Resampling frequency defining the periods as defined in Resampling. This function only makes sense with annual frequencies.
window (int) – The number of days on each side of the given day-of-year to include in the climatology.
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 (like here). This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series Note that bootstrapping is computationally expensive.
constrain (sequence of str, optional) – Allowed conditions. None to allow them all.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Subsetting is not done one the data used to compute the climatology, only on the data against which the condition is checked.
- Return type:
DataArray- Returns:
xr.DataArray – Number of timesteps where data is {condition} the {percentile}th percentile computed over {reference_period}. Only data {data_condition} {thresh} is considered.
- xclim.compute.generic.day_threshold_reached(data, condition, thresh, freq, date=None, which='first', window=1, constrain=None, **indexer)[source]
First or last day of values fulfilling a condition.
Returns first or last day of period where values meet a given condition for a minimum number of consecutive days, limited to a starting or ending calendar date.
- Parameters:
data (xr.DataArray) – Data.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator.
thresh (str) – Threshold.
freq (str) – Resampling frequency defining the periods as defined in Resampling.
date (str or None) – Date of the year after which to look for the first event, or before which to look for the last event. Should have the format ‘%m-%d’. None means there is no limit.
which ({‘first’, ‘last’}) – Whether to look for the first or the last event.
window (int) – Minimum number of days with values above thresh needed for evaluation. Default: 1.
constrain (sequence of str, optional) – Optionally allowed conditions.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] – Day-of-year of the {which} time where data {condition} {thresh}.
- xclim.compute.generic.difference_statistics(data1, data2, statistic, freq, absolute=False, **indexer)[source]
Calculate a statistic over the difference between two variables.
The difference is taken as
data2 - data1.- Parameters:
data1 (xr.DataArray) – The lowest variable (ex: tasmin)).
data2 (xr.DataArray) – The highest variable (ex: tasmax).
statistic ({‘max’, ‘min’, ‘mean’, ‘sum’}) – The statistic to compute over the difference between the two variables.
freq (str) – Resampling frequency defining the periods as defined in Resampling.
absolute (bool) – If True, the statistic is computed over the absolute difference.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray, [difference of data1] – {statistic} of the difference between data2 and data1.
- xclim.compute.generic.extreme_range(data1, data2, freq, **indexer)[source]
Calculate the range between extreme values.
The maximum of data2 minus the minimum of data1, for each period.
- Parameters:
data1 (xr.DataArray) – The lowest data.
data2 (xr.DataArray) – The highest data.
freq (str) – Resampling frequency defining the periods as defined in Resampling.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray – The DataArray for the extreme temperature range.
- xclim.compute.generic.integrated_difference(data, condition, thresh, freq, **indexer)[source]
Integrate difference of data below/above a given value threshold, usually used for “degree days” computations.
If
conditionis “>”, then the difference is taken asdata - thresh. The inverse is done for “<”. Values below zero are removed from the integral. “Integral” means summed difference are multiplied by the timestep length.- Parameters:
data (xr.DataArray) – Data.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – Logical comparison operator.
thresh (Quantified) – The value threshold.
freq (str, optional) – Resampling frequency defining the periods as defined in Resampling.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray, [data][time] – Integral of the differences when {data} {condition} {thresh}.
- xclim.compute.generic.interday_difference_statistics(data1, data2, statistic, freq, absolute=True, **indexer)[source]
Calculate a statistic of the day-to-day difference of the difference between two variables.
The difference is taken as
data2 - data1, then it is differentiated along the time dimension before calculating the resampling statistic.- Parameters:
data1 (xr.DataArray) – The lowest data.
data2 (xr.DataArray) – The highest data.
statistic ({‘max’, ‘min’, ‘mean’, ‘sum’}) – Resampling statistic.
freq (str) – Resampling frequency defining the periods as defined in Resampling.
absolute (bool) – If True, the statistic is computed over the absolute value of the differentiated difference.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Subsetting is done after differentiating along time.
- Return type:
DataArray- Returns:
xr.DataArray, [difference of low_data] – {statistic} of the day-to-day difference of the difference between data2 and data1.
- xclim.compute.generic.percentile(data, percentile, freq, **indexer)[source]
Calculate the percentile statistic for each requested period.
- Parameters:
data (xr.DataArray) – An array.
percentile (float) – A percentile (0, 100).
freq (str) – Resampling frequency defining the periods as defined in Resampling.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Returns:
xr.DataArray, [same as data] – {percentile}th percentile of the data.
- xclim.compute.generic.running_statistics(data, window, window_statistic, statistic, freq, window_center=True, out_units=None, **indexer)[source]
Calculate a running statistic over the data and then another statistic for each requested period.
This is an extension of
statistics(), with a rolling aggregation done before the indexing and resampling.- Parameters:
data (xr.DataArray) – Input data.
window (int) – Size of the rolling window.
window_statistic ({“min”, “max”, “mean”, “std”, “var”, “count”, “sum”, “integral”}) – Operation to apply to the rolling window.
statistic ({“min”, “max”, “mean”, “std”, “var”, “count”, “sum”, “integral”, “doymax”, “doymin”} or Callable) – Reducing operation. Can either be a DataArray method or a function that can be applied to a DataArray.
freq (str) – Resampling frequency defining the periods as defined in Resampling. Resampling is done after the running statistic.
window_center (bool) – If True, the window is centered on the date. If False, the window is right-aligned.
out_units (str, optional) – Output units to assign. Only necessary if statistic is a function not supported by
xclim.core.units.to_agg_units().**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Time selection is done after applying the running statistic.
- Return type:
DataArray- Returns:
xr.DataArray – {statistic} of the {window}-day {window_statistic} of the data.
- xclim.compute.generic.season(data, condition, thresh, window, aspect, freq, mid_date=None, constrain=None, **indexer)[source]
Season.
A season starts when a variable fulfills some condition for a consecutive run of
windowdays. It stops when the inverse condition is fulfilled forwindowdays. Seasons with “gaps” where the condition is not met for fewer thanwindowdays are thus allowed. Additionally, a middle date can serve as a latest start date and earliest end date.- Parameters:
data (xr.DataArray) – Variable.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Comparison operation. Computed as
data {condition} thresh.thresh (Quantified) – Threshold for the condition.
window (int) – Minimum number of days that the condition must be met / not met for the start / end of the season.
aspect ({‘start’, ‘end’, ‘length’}, or a list of those) – Which season aspect(s) to return. If a list, this function returns a tuple in the same order as this argument.
freq (str) – Resampling frequency.
mid_date (DayOfYearStr, optional) – An optional middle date. The start must happen before and the end after for the season to be valid.
constrain (Sequence of strings, optional) – A list of acceptable comparison operators. Optional, but indicators wrapping this function should inject it.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] or [time] – {aspect} of the season. The season starts with {window} consecutibe days {condition} {thresh} and ends when the inverse condition is fulfilled for as much consecutive days.
See also
xclim.compute.run_length.season_startThe function that finds the start of the season.
xclim.compute.run_length.season_lengthThe function that finds the length of the season.
xclim.compute.run_length.season_endThe function that finds the end of the season.
Examples
>>> s = season(tas, thresh="0 °C", window=5, condition=">", aspect="start", freq="YS")
Returns the start of the “frost-free” season. The season starts with 5 consecutive days with mean temperature above 0°C and ends with as many days under or equal to 0°C, and end does not need to be found for a start to be valid.
>>> s = season( ... pr, ... condition="<=", ... thresh="2 mm/d", ... window=7, ... mid_date="08-01", ... aspect="length", ... freq="YS", ... )
Returns the length of the “dry” season. The season starts with 7 consecutive days with precipitation under or equal to 2 mm/d and ends with as many days above 2 mm/d. If no start is found before the first of august, the season is invalid. If a start is found but no end, the end is set to the last day of the period (December 31st if the dataset is complete).
- xclim.compute.generic.season_length_from_boundaries(season_start, season_end)[source]
Season length using pre-computed boundaries.
- Parameters:
season_start (xr.DataArray) – Day of year where the season starts.
season_end (xr.DataArray) – Day of year where the season ends.
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] – Length of the season.
Notes
If season_start and season_end are computed with different resampling frequencies, the time of season_start are selected to write the output. This is only useful when season start and end were computed at an annual frequency but with different anchor months. Otherwise, functions in
xclim.compute.run_lengthwill be appropriate. season_start and season_end should be annual indicators with the same length. season_end should be in the same year as season_start or one year later.
- xclim.compute.generic.spell_length_statistics(data, window, window_statistic, condition, thresh, statistic, freq, min_gap=1, constrain=None, resample_before_rl=True, **indexer)[source]
Statistics of spells lengths.
A spell is when a running statistic (window_statistic) over a (minimum) number (window) of consecutive timesteps respects a condition (condition thresh). This returns a statistic over the spell lengths. Two consecutive spells are merged into a single one.
- Parameters:
data (xr.DataArray) – Input data.
window (int) – Minimum length of a spell.
window_statistic ({‘min’, ‘max’, ‘sum’, ‘mean’, ‘integral’}) – Reduction along the window length to compute running statistic. Note that this does not matter when window is 1, in which case any occurrence of
data {condition} threshis considered a valid “spell”.condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator. Computed as
rolling_stat {condition} thresh.thresh (Quantified) – Threshold to test against.
statistic ({‘max’, ‘sum’, ‘count’} or sequence of str) – Statistic on the spell lengths. If a list, multiple statistics are computed.
freq (str) – Resampling frequency.
min_gap (int) – The shortest possible gap between two spells. Spells closer than this are merged by assigning the gap steps to the merged spell.
constrain (sequence of str, optional) – Allowed conditions. None to allow them all.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Indexing is done after finding the days part of a spell, but before taking the spell statistics.
- Return type:
DataArray|Sequence[DataArray]- Returns:
xr.DataArray or sequence of xr.DataArray – {statistic} of spell lengths. A spell is when the {window}-day {window_statistic} is {condition} {thresh}.
See also
xclim.indices.helpers.spell_maskThe lower level functions that finds spells.
bivariate_spell_length_statisticsThe bivariate version of this function.
Examples
>>> sls = spell_length_statistics( ... tas, ... window=7, ... window_statistic="min", ... condition=">", ... thresh="35 °C", ... statistic="sum", ... freq="YS", ... )
Here, a day is part of a spell if it is in any seven (7) day period where the minimum temperature is over 35°C. We then return the annual sum of the spell lengths, so the total number of days in such spells. >>> from xclim.core.units import rate2amount >>> pram = rate2amount(pr, out_units=”mm”) >>> sls = spell_length_statistics( … pram, … window=5, … window_statistic=”sum”, … condition=”>=”, … thresh=”20 mm”, … statistic=”max”, … freq=”YS”, … )
Here, a day is part of a spell if it is in any five (5) day period where the total accumulated precipitation reaches or exceeds 20 mm. We then return the length of the longest of such spells.
- xclim.compute.generic.statistics(data, statistic, freq, out_units=None, **indexer)[source]
Calculate a statistic over the data for each requested period.
- Parameters:
data (xr.DataArray) – Input data.
statistic ({“min”, “max”, “mean”, “std”, “var”, ‘count’, ‘sum’, ‘integral’, ‘doymax’, ‘doymin’} or Callable) – Reducing operation. It can either be a DataArray method or a function that can be applied to a DataArray.
freq (str) – Resampling frequency defining the periods as defined in Resampling.
out_units (str, optional) – Output units to assign (no unit conversion is performed). Only necessary if statistic is function not supported by
xclim.core.units.to_agg_units().**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray – {statistic} of the data.
- xclim.compute.generic.statistics_between_dates(data, start, end, statistic, freq=None)[source]
Calculate a statistic for each requested period but only considering timesteps with a time-varying range.
This is similar to using
statistics()with an indexer but for cases where the start and end bounds of the period of interest are changing along time, i.e, at least one of them is given as a DataArray.startandendmust have aligneable time coordinates and be at the target frequencyfreq.Usually,
startand/orendwill be the output of other indicators likeseason()orday_threshold_reached().- Parameters:
data (xr.DataArray) – Data.
start (xr.DataArray or DayOfYearStr) – Start dates (as day-of-year) for the statistic computation. The start date is included in the statistic.
end (xr.DataArray or DayOfYearStr) – End (as day-of-year) dates for the statistic computation. The end date is not included in the statistic.
statistic ({‘min’, ‘max’, ‘sum’, ‘mean’, ‘std’, ‘integral’}) – Statistic to compute over the selected period.
freq (str, optional) – Resampling frequency defining the periods as defined in Resampling. Default (None) tries to infer the frequency from
startandend.
- Return type:
DataArray- Returns:
xr.DataArray, [time] – {statistic} of data over a time-varying period.
- xclim.compute.generic.thresholded_events(data, condition, thresh, window, condition_stop=None, thresh_stop=None, window_stop=None, freq=None)[source]
Find thresholded events.
Finds all events along the time dimension. An event starts if the start condition is fulfilled for a given number of consecutive time steps. It ends when the end condition is fulfilled for a given number of consecutive time steps.
Conditions are simple comparison of the data with a threshold:
cond = data {condition} thresh. The end conditions defaults to the negation of the start condition.The resulting
eventdimension always has its maximal possible size :data.size / (window + window_stop).- Parameters:
data (xr.DataArray) – Variable.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator for the start condition.
thresh (Quantified) – Threshold defining the event.
window (int) – Number of time steps where the event condition must be true to start an event.
condition_stop ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}, optional) – Logical comparison operator for the end condition. Defaults to the opposite of condition.
thresh_stop (Quantified, optional) – Threshold defining the end of an event. Defaults to thresh.
window_stop (int, optional) – Number of time steps where the end condition must be true to end an event. Defaults to
window.freq (str, optional) – A frequency to divide the data into periods. If absent, the output has not time dimension. If given, the events are searched within in each resample period independently.
- Return type:
Dataset- Returns:
xr.Dataset – Same shape as the data except the time dimension is replaced by an “event” dimension or it is resampled if
freqis given.- The dataset contains the following variables:
event_length: The number of time steps in each event including gaps shorter than
window_stopevent_effective_length: The number of time steps of even event where the start condition is true. event_sum: The sum within each event, only considering the steps where start condition is true. event_start: The datetime of the start of the run.
- xclim.compute.generic.thresholded_percentile(data, condition, thresh, percentile, freq, constrain=None, **indexer)[source]
Calculate a percentile of the data for which some condition is met, for each requested period.
- Parameters:
data (xr.DataArray) – Input data.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator. Calculated as
data {condition} thresh.thresh (Quantified) – Threshold.
percentile (float) – A percentile (0, 100).
freq (str) – Resampling frequency defining the periods as defined in Resampling.
constrain (sequence of str, optional) – Optionally allowed conditions. Default: None.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray – {percentile}th percentile of the data where it is {condition} {thresh}.
- xclim.compute.generic.thresholded_running_statistics(data, condition, thresh, window, window_statistic, statistic, freq, window_center=True, constrain=None, out_units=None, **indexer)[source]
Calculate a running statistic of the data for which some condition is met, then compute a resampling statistic.
This is an extension of
running_statistics()with a threshold.- Parameters:
data (xr.DataArray) – Input data.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator. Comparison is done as
data {condition} thresh.thresh (Quantified) – Threshold, should have the same dimensionality as
data.window (int) – Size of the rolling window.
window_statistic ({“min”, “max”, “mean”, “std”, “var”, “count”, “sum”, “integral”}) – Operation to apply to the rolling window.
statistic ({“min”, “max”, “mean”, “std”, “var”, “count”, “sum”, “integral”, “doymax”, “doymin”} or Callable) – Reducing operation. Can either be a DataArray method or a function that can be applied to a DataArray.
freq (str) – Resampling frequency defining the periods as defined in Resampling. Resampling is done after the running statistic.
window_center (bool) – If True, the window is centered on the date. If False, the window is right-aligned.
constrain (sequence of str, optional) – Allowed conditions, to be used when creating a more specific indicator from this function.
out_units (str, optional) – Output units to assign. Only necessary if statistic is a function not supported by
xclim.core.units.to_agg_units().**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Time selection is done after the running statistic.
- Return type:
DataArray- Returns:
xr.DataArray – {statistic} of the {window}-day {window_statistic} of the data, where it is {condition} {thresh}.
- xclim.compute.generic.thresholded_statistics(data, condition, thresh, statistic, freq, constrain=None, out_units=None, **indexer)[source]
Calculate a statistic over data that fulfills a threshold condition for each requested period.
This is a thresolded extension of
statistics().- Parameters:
data (xr.DataArray) – Input data.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Logical comparison operator. Comparison is done as
data {condition} thresh.thresh (Quantified) – Threshold, should have the same dimensionality as
data.statistic ({“min”, “max”, “mean”, “std”, “var”, “count”, “sum”, “integral”, “doymin”, “doymax”} or Callable) – Reducing operation. Can either be a DataArray method or a function that can be applied to a DataArray.
freq (str) – Resampling frequency defining the periods as defined in Resampling.
constrain (sequence of str, optional) – Allowed conditions, to be used when creating a more specific indicator from this function.
out_units (str, optional) – Output units to assign. Only necessary if statistic is a function not supported by
xclim.core.units.to_agg_units().**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xr.DataArray – {statistic} of data where it is {condition} {thresh}.
Helper Functions Submodule¶
Functions that encapsulate logic and can be shared by many compute functions,
but are not particularly index-like themselves (those should go in the xclim.compute.generic module).
- xclim.compute.helpers.cosine_of_solar_zenith_angle(time, declination, lat, lon='0 °', time_correction=None, stat='average', sunlit=False, chunks=None)[source]
Cosine of the solar zenith angle.
The solar zenith angle is the angle between a vertical line (perpendicular to the ground) and the sun rays. This function computes a statistic of its cosine : its instantaneous value, the integral from sunrise to sunset or the average over the same period or over a subdaily interval. Based on Kalogirou [2014] and Di Napoli et al. [2020].
- Parameters:
time (xr.DataArray) – The UTC time. If not daily and stat is “integral” or “average”, the timestamp is taken as the start of interval. If daily, the interval is assumed to be centered on Noon. If fewer than three timesteps are given, a daily frequency is assumed.
declination (xr.DataArray) – Solar declination. See
solar_declination().lat (Quantified) – Latitude coordinate. Expects units of “degree_north”.
lon (Quantified) – Longitude. Needed if the input timeseries is subdaily.
time_correction (xr.DataArray, optional) – Time correction for solar angle. See
time_correction_for_solar_angle()This is necessary if stat is “instant”.stat ({‘average’, ‘integral’, ‘instant’}) – Which daily statistic to return. If “average”, this returns the average of the cosine of the zenith angle If “integral”, this returns the integral of the cosine of the zenith angle If “instant”, this returns the instantaneous cosine of the zenith angle
sunlit (bool) – If True, only the sunlit part of the interval is considered in the integral or average. Does nothing if stat is “instant”.
chunks (dict) – When time, lat and lon originate from coordinates of a large chunked dataset, this dataset’s chunking can be passed here to ensure the computation is also chunked.
- Return type:
DataArray- Returns:
xr.DataArray, [rad] or [dimensionless] – Cosine of the solar zenith angle. If stat is “integral”, dimensions can be said to be “time” as the integral is on the hour angle. For seconds, multiply by the number of seconds in a complete day cycle (24*60*60) and divide by 2π.
Notes
This code was inspired by the thermofeel and PyWBGT package.
References
- xclim.compute.helpers.day_angle(time)[source]
Day of year as an angle.
Assuming the Earth makes a full circle in a year, this is the angle covered from the beginning of the year up to that timestep. Also called the “julian day fraction”.
- Parameters:
time (xr.DataArray) – Time coordinate.
- Return type:
DataArray- Returns:
xr.DataArray, [rad] – Day angle.
- xclim.compute.helpers.day_lengths(dates, lat, method='spencer', infill_polar_days=False)[source]
Calculate day-length according to latitude and day of the 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 time frequencies.
lat (Quantified or xarray.Dataset or xarray.DataTree) – Latitude coordinate. Expects units of “degree_north”.
method ({‘spencer’, ‘simple’}) – Which approximation to use when computing the solar declination angle. See
xclim.compute.helpers.solar_declination().infill_polar_days (bool) – Whether to use a mask of 24 hours for polar days and 0 hours for polar nights. If False, polar days and nights will be NaN. If True, they will be filled with 24 and 0 hours, respectively, dependent on latitude and solar declination at the given date.
- Return type:
DataArray- Returns:
xarray.DataArray, [hours] – Day-lengths in hours per individual day.
- Raises:
NotImplementedError – If a series of dates provided are not inferrable at a daily time frequency.
Notes
The day length is computed as the time between sunrise and sunset. The infill_polar_days option provides an arbitrary method fill polar days and nights with 24 and 0 hours, respectively. Care should be taken when using this option, as it may not be appropriate for all applications.
References
Kalogirou [2014]
- xclim.compute.helpers.distance_from_sun(dates)[source]
Sun-earth distance.
The distance from sun to earth in astronomical units.
- Parameters:
dates (xr.DataArray) – Series of dates and time of days.
- Return type:
DataArray- Returns:
xr.DataArray, [astronomical units] – Sun-earth distance.
References
# TODO: Find a way to reference this U.S. Naval Observatory:Astronomical Almanac. Washington, D.C.: U.S. Government Printing Office (1985).
- xclim.compute.helpers.eccentricity_correction_factor(time, method='spencer')[source]
Eccentricity correction factor of the Earth’s orbit.
The squared ratio of the mean distance Earth-Sun to the distance at a specific moment. As approximated by Spencer [1971].
- Parameters:
time (xr.DataArray) – Time coordinate.
method ({‘spencer’, ‘simple’}) – Which approximation to use. The default (“spencer”) uses the first five (5) terms of the fourier series of the eccentricity. The “simple” method approximates with only the first two (2).
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] – Eccentricity correction factor.
References
- xclim.compute.helpers.extraterrestrial_solar_radiation(times, lat, solar_constant='1361 W m-2', method='spencer', chunks=None)[source]
Extraterrestrial solar radiation.
This is the daily energy received on a surface parallel to the ground at the mean distance of the earth to the sun. It neglects the effect of the atmosphere. Computation is based on Kalogirou [2014] and the default solar constant is taken from Matthes et al. [2017].
- Parameters:
times (xr.DataArray) – Daily datetime data. This function makes no sense with data of other frequency.
lat (xr.DataArray) – Latitude coordinate. Expects units of “degree_north”.
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().chunks (dict) – When times and lat originate from coordinates of a large chunked dataset, passing the dataset’s chunks here will ensure the computation is chunked as well.
- Return type:
DataArray- Returns:
xr.DataArray, [J m-2 d-1] – Extraterrestrial solar radiation.
References
Kalogirou [2014], Matthes, Funke, Andersson, Barnard, Beer, Charbonneau, Clilverd, Dudok de Wit, Haberreiter, Hendry, Jackman, Kretzschmar, Kruschke, Kunze, Langematz, Marsh, Maycock, Misios, Rodger, Scaife, Seppälä, Shangguan, Sinnhuber, Tourpali, Usoskin, van de Kamp, Verronen, and Versick [2017]
- xclim.compute.helpers.gladstones_day_length_latitude_coefficient(dates, lat, neutral_latitude='40.0 deg', constrain=None, day_length_method='spencer')[source]
Day-length latitude coefficient based on the Gladstones methodology.
This function computes a day-length latitude coefficient as it influences the monthly temperatures of the growing season as compared to the day-length of a neutral reference latitude. Based on Gladstones [1992] and cite:t:gladstones_wine_2011.
- Parameters:
dates (xarray.DataArray) – The dates for which the day length latitude coefficient is computed.
lat (xarray.DataArray or int or float) – Latitude coordinate. Expects units of “degree_north”. If a single value is given, it is converted to an xarray.DataArray.
neutral_latitude (str) – The latitude at which the day length coefficient is 1.0. Latitudes between this value and 0 degrees North will have a coefficient below 1.0 during the growing season, while latitudes above this value will have a coefficient greater than 1.0. This negative absolute value of this latitude is used for calculating coefficients in the Southern Hemisphere.
constrain (str, optional) – The lower latitude limit for applying the latitude coefficient. If a str is given (e.g. ‘25 degree_north`), values below this threshold will be set to ‘1.0’.
day_length_method ({‘simple’, ‘spencer’}) – The method to use for the day length calculation. The “simple” method uses a simple approximation of the day length based on latitude and time of year. The “spencer” method uses a more complex approximation based on the Fourier series of the solar declination.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Coefficient for the day length based on latitude.
- xclim.compute.helpers.huglin_day_length_latitude_coefficient(lat, method, cap_value=nan)[source]
Simple coefficient for the day-length and high latitudes.
This latitude coefficient is used for determining the latitude effect on the day length specific to climate indicators that concern viticulture, such as
xclim.compute.huglin_index()(cite:p:huglin_nouveau_1978). This function is an empirical approximation of the day-length multiplication factor, \(k\), based on latitude.- Parameters:
lat (xarray.DataArray, str) – Latitude coordinate. Expects units of “degree_north”. If provided a string (e.g. “45 degree_north”), it is converted to an xarray.DataArray.
method ({“huglin”, “interpolated”}) – The method to use for the coefficient calculation.
cap_value (float) – For latitudes north of 50° N and south of 50° S, the value for the coefficient.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Coefficient for the day length based on latitude.
Notes
For the original “huglin” implementation [Huglin, 1978], 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 \\ m, & \text{if } | lat | > 50 \\ \end{cases}\end{split}\]An alternative implementation (“interpolated”) uses smoothing to reduce the stepwise behaviour of the “huglin”` method. The day-length multiplication factor (\(k\)) for the “interpolated” method then 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 \\ m, & \text{if } | lat | > 50 \\ \end{cases}\end{split}\]Where \(m\) is the cap value, which is set to np.nan, or other if provided.
References
- xclim.compute.helpers.jones_day_length_latitude_coefficient(dates, lat, method, floor=False, start_date='04-01', end_date='11-01', freq='YS')[source]
Complex day length latitude coefficient.
This function computes a day length latitude coefficient as it influences the entire growing season. Based on cite:t:hall_spatial_2010.
- Parameters:
dates (xarray.DataArray) – The dates for which the day length latitude coefficient is computed.
lat (xr.DataArray or xr.Dataset or xr.DataTree) – Latitude coordinate. Expects units of “degree_north”. If a single value is given, it is converted to an xarray.DataArray.
method ({“gladstones”, “jones”}) – The method to use for the coefficient calculation. The “jones” method . The “gladstones” method uses an approximation of the Gladstones methodology for day length latitude coefficient.
floor (bool, optional) – If True, latitudes where the day length latitude coefficient would be below ‘1.0’, the value is set to ‘1.0’. if False, coefficient can be below ‘1.0’ for latitudes where the day length is less than the reference latitude.
start_date (str or DayOfYearStr) – The start date of the growing season.
end_date (str or DayOfYearStr) – The end date of the growing season. Date is not included in the aggregation.
freq ({“YS”, “YS-JAN”, “YS-JUL”}) – The frequency at which to aggregate the day lengths. Must be an annual frequency, such as “YS” or “YS-JAN” (yearly start in January) or “YS-JUL” (yearly start in July).
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Coefficient for the day length based on latitude, aggregated over the growing season.
- Raises:
ValueError – If all latitudes for every computed growing season have a day length latitude coefficient below 1.0.
Notes
For the “jones” method, A more robust day-length calculation based on latitude, calendar, day-of-year, and obliquity is used. This algorithm requires a calculation of the sum of the day lengths over the growing season at each latitude, \(totalSeasonDayLength_{Lat}\), which is then used to calculate the day length latitude coefficient \(k\):
\[totalSeasonDayLength_{Lat} = \sum_{Jday=\text{103}}^{\text{284}}{dayLength_{Lat_{JDay}}}\]The day length latitude coefficient (\(k\)) using the “jones” method is calculated as follows:
\[k_{Lat} = 2.8311e-4 * totalSeasonDayLength_{Lat} + 0.30834\]The “gladstones” method provided here is a transformation of the “jones” method, based on the relationship detailed in Hall and Jones [2010]:
\[k_{Lat}^{Gladstones} = 1.1135 * k_{Lat}^{Jones} - 0.1352\]For both of these methods, the \(k\) coefficient must be calculated at the growing season frequency (yearly), starting from either January or July, depending on the hemisphere of interest.
- xclim.compute.helpers.make_hourly_temperature(tasmin, tasmax, infill_polar_days=False)[source]
Compute hourly temperatures from tasmin and tasmax.
Based on the Linvill et al. “Calculating Chilling Hours and Chill Units from Daily Maximum and Minimum Temperature Observations”, HortScience, 1990 we assume a sinusoidal temperature profile during daylight and a logarithmic decrease after sunset with tasmin reached at sunsrise and tasmax reached 2h before sunset.
For simplicity and because it’s used for daily aggregation, we assume that sunrise globally happens at midnight and the sunsets after daylength hours computed via the
day_lengths()function.- Parameters:
tasmin (xarray.DataArray) – Daily minimum temperature.
tasmax (xarray.DataArray) – Daily maximum temperature.
infill_polar_days (bool) – Whether to use a mask of 24 hours for polar days and 0 hours for polar nights. If False, polar days and nights will be NaN. If True, they will be filled with 24 and 0 hours, respectively, dependent on latitude and solar declination at the given date.
- Return type:
DataArray- Returns:
xarray.DataArray – Hourly temperature.
- xclim.compute.helpers.resample_map(obj, dim, freq, func, map_blocks='from_context', resample_kwargs=None, map_kwargs=None)[source]
Wrap xarray’s resample(…).map() with a
xarray.map_blocks().Ensures that the chunking is appropriate using flox.
- Parameters:
obj (DataArray or Dataset) – The xarray object to resample.
dim (str) – Dimension over which to resample.
freq (str) – Resampling frequency along dim.
func (callable) – Function to map on each resampled group.
map_blocks (bool or “from_context”) – If True, the resample().map() call is wrapped inside a map_blocks. If False, this does not do anything special. If “from_context”, xclim’s “resample_map_blocks” option is used. If the object is not using dask, this is set to False.
resample_kwargs (dict, optional) – Other arguments to pass to obj.resample().
map_kwargs (dict, optional) – Arguments to pass to map.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray or xr.Dataset – Resampled object.
- xclim.compute.helpers.solar_declination(time, method='spencer')[source]
Solar declination.
The angle between the sun rays and the earth’s equator, in radians, as approximated by Spencer [1971] or assuming the orbit is a circle.
- Parameters:
time (xr.DataArray) – Time coordinate.
method ({‘spencer’, ‘simple’}) – Which approximation to use. The default (“spencer”) uses the first seven (7) terms of the Fourier series representing the observed declination, while “simple” assumes the orbit is a circle with a fixed obliquity and that the solstice/equinox happen at fixed angles on the orbit (the exact calendar date changes for leap years).
- Return type:
DataArray- Returns:
xr.DataArray, [rad] – Solar declination angle.
References
Spencer [1971]
- xclim.compute.helpers.time_correction_for_solar_angle(time)[source]
Time correction for solar angle.
Every 1° of angular rotation on earth is equal to 4 minutes of time. The time correction is needed to adjust local watch time to solar time.
- Parameters:
time (xr.DataArray) – Time coordinate.
- Return type:
DataArray- Returns:
xr.DataArray, [rad] – Time correction of solar angle.
References
Di Napoli, Hogan, and Pappenberger [2020]
- xclim.compute.helpers.wind_speed_height_conversion(ua, h_source, h_target, method='log')[source]
Wind speed at two meters.
- Parameters:
ua (xarray.DataArray) – Wind speed at height h.
h_source (str) – Height of the input wind speed ua (e.g. h == “10 m” for a wind speed at 10 meters).
h_target (str) – Height of the output wind speed.
method ({“log”}) – Method used to convert wind speed from one height to another.
- Return type:
DataArray- Returns:
xarray.DataArray – Wind speed at height h_target.
References
Allen, Pereira, Raes, and Smith [1998]
Run-Length Algorithms Submodule¶
Computation of statistics on runs of True values in boolean arrays.
- xclim.compute.run_length.find_events(condition, window, condition_stop=None, window_stop=1, data=None, freq=None)[source]
Find events (runs).
An event starts with a run of
windowconsecutive True values in the condition and stops withwindow_stopconsecutive True values in the stop condition.This returns a Dataset with each event along an event dimension. It does not perform statistics over the events like other function in this module do.
- Parameters:
condition (DataArray of bool) – The boolean mask, true where the start condition of the event is fulfilled.
window (int) – The number of consecutive True values for an event to start.
condition_stop (DataArray of bool, optional) – The stopping boolean mask, true where the end condition of the event is fulfilled. Defaults to the opposite of condition.
window_stop (int) – The number of consecutive True values in
condition_stopfor an event to end. Defaults to 1.data (DataArray, optional) – The actual data. If present, its sum within each event is added to the output.
freq (str, optional) – A frequency to divide the data into periods. If absent, the output has not time dimension. If given, the events are searched within in each resample period independently.
- Return type:
Dataset- Returns:
xr.Dataset, same shape as the data (and the time dimension is resample or removed, according to
freq). –- The Dataset has the following variables:
event_length: The number of time steps in each event event_effective_length: The number of time steps of even event where the start condition is true. event_start: The datetime of the start of the run. event_sum: The sum within each event, only considering steps where start condition is true (if
data).
- xclim.compute.run_length.first_run(da, window, dim='time', freq=None, coord=False, ufunc_1dim='from_context')[source]
Return the index of the first item of the first run of at least a given length.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
freq (str) – Resampling frequency.
coord (str or bool, optional) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
ufunc_1dim ({“auto”, “from_context”} or bool) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.
- Return type:
DataArray- Returns:
xr.DataArray – Index (or coordinate if coord is not False) of first item in first valid run. Returns np.nan if there are no valid runs.
- xclim.compute.run_length.first_run_1d(arr, window)[source]
Return the index of the first item of a run of at least a given length.
- Parameters:
arr (sequence of int or float) – Input array.
window (int) – Minimum duration of consecutive run to accumulate values.
- Return type:
int|float- Returns:
int or np.nan – Index of first item in first valid run. Returns np.nan if there are no valid runs.
- xclim.compute.run_length.first_run_after_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]
Return the index of the first item of the first run after a given date.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values.
date (DayOfYearStr, optional) – The date after which to look for the run.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (bool or str, optional) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Return type:
DataArray- Returns:
xr.DataArray – Index (or coordinate if coord is not False) of first item in the first valid run. Returns np.nan if there are no valid runs.
- xclim.compute.run_length.first_run_before_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]
Return the index of the first item of the first run before a given date.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values.
date (DayOfYearStr, optional) – The date before which to look for the run.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (bool or str, optional) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (e.g. ‘dayofyear’).
- Return type:
DataArray- Returns:
xr.DataArray – Index (or coordinate if coord is not False) of first item in the first valid run. Returns np.nan if there are no valid runs.
- xclim.compute.run_length.first_run_ufunc(x, window, dim)[source]
Dask-parallel version of first_run_1d.
The first entry in array of consecutive true values.
- Parameters:
x (xr.DataArray or sequence of bool) – Input array (bool).
window (int) – Minimum run length.
dim (str) – The dimension along which the runs are found.
- Return type:
DataArray- Returns:
xr.DataArray – A function operating along the time dimension of a dask-array.
- xclim.compute.run_length.index_of_date(time, date, max_idxs=None, default=0)[source]
Get the index of a date in a time array.
- Parameters:
time (xr.DataArray) – An array of datetime values, any calendar.
date (DayOfYearStr or DateStr, optional) – A string in the “yyyy-mm-dd” or “mm-dd” format. If None, returns default.
max_idxs (int, optional) – Maximum number of returned indexes.
default (int) – Index to return if date is None.
- Return type:
- Returns:
numpy.ndarray – 1D array of integers, indexes of date in time.
- Raises:
ValueError – If there are most instances of date in time than max_idxs.
- xclim.compute.run_length.keep_longest_run(da, dim='time', freq=None)[source]
Keep the longest run along a dimension.
- Parameters:
da (xr.DataArray) – Boolean array.
dim (str) – Dimension along which to check for the longest run.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xr.DataArray, [bool] – Boolean array similar to da but with only one run, the (first) longest.
- xclim.compute.run_length.last_run(da, window, dim='time', freq=None, coord=False, ufunc_1dim='from_context')[source]
Return the index of the last item of the last run of at least a given length.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
freq (str) – Resampling frequency.
coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for a DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.
- Return type:
DataArray- Returns:
xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.
- xclim.compute.run_length.last_run_before_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]
Return the index of the last item of the last run before a given date.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values.
date (DayOfYearStr) – The date before which to look for the last event.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (bool or str, optional) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Return type:
DataArray- Returns:
xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.
- xclim.compute.run_length.longest_run(da, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]
Return the length of the longest consecutive run of True values.
- Parameters:
da (xr.DataArray) – N-dimensional array (boolean).
dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.
freq (str) – Resampling frequency.
ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. It can be modified globally through the “run_length_ufunc” global option.
index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.
- Return type:
DataArray- Returns:
xr.DataArray, [int] – Length of the longest run of True values along dimension (int).
- xclim.compute.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.compute.run_length.resample_and_rl(da, resample_before_rl, compute, *args, freq, dim='time', **kwargs)[source]
Wrap run length algorithms to control if resampling occurs before or after the algorithms.
- Parameters:
da (xr.DataArray) – N-dimensional array (boolean).
resample_before_rl (bool) – Determines whether if input arrays of runs da should be separated in period before or after the run length algorithms are applied.
compute (Callable) – Run length function to apply.
*args (Any) – Positional arguments needed in compute.
freq (str) – Resampling frequency.
dim (str) – The dimension along which to find runs.
**kwargs (Any) – Keyword arguments needed in compute.
- Return type:
DataArray- Returns:
xr.DataArray – Output of compute resampled according to frequency {freq}.
- xclim.compute.run_length.rle(da, dim='time', index='first')[source]
Run length.
Despite its name, this is not an actual run-length encoder : it returns an array of the same shape as the input with 0 where the input was <= 0, nan where the input was > 0, except on the first (or last) element of each run of consecutive > 0 values, where it is set to the sum of the elements within the run. For an actual run length encoder, see
rle_1d().Usually, the input would be a boolean mask and the first element of each run would then be set to the run’s length (thus the name), but the function also accepts int and float inputs.
- Parameters:
da (xr.DataArray) – Input array.
dim (str) – Dimension name.
index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.
- Return type:
DataArray- Returns:
xr.DataArray – The run length array.
- xclim.compute.run_length.rle_1d(arr)[source]
Return the length, starting position and value of consecutive identical values.
In opposition to py:func:rle, this is an actuel run length encoder.
- Parameters:
arr (int or float or bool or Sequence[Union[int, float, bool]] or xr.DataArray) – Array of values to be parsed.
- Return type:
- Returns:
values (np.ndarray) – The values taken by arr over each run.
run_lengths (np.ndarray) – The length of each run.
start_positions (np.ndarray) – The starting index of each run.
Examples
>>> from xclim.compute.run_length import rle_1d >>> a = [1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3] >>> rle_1d(a) RLE_1D(values=array([1, 2, 3]), run_lengths=array([2, 4, 6]), start_positions=array([0, 2, 6]))
- xclim.compute.run_length.rle_statistics(da, statistic, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]
Return the length of consecutive run of True values, according to a reducing operator.
- Parameters:
da (xr.DataArray) – N-dimensional array (boolean).
statistic (str) – Name of the reducing function.
window (int) – Minimal length of consecutive runs to be included in the statistics.
dim (str) – Dimension along which to calculate consecutive run; Default: ‘time’.
freq (str) – Resampling frequency.
ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. It can be modified globally through the “run_length_ufunc” global option.
index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.
- Return type:
DataArray- Returns:
xr.DataArray, [int] – Length of runs of True values along dimension, according to the reducing function (float) If there are no runs (but the data is valid), returns 0.
- xclim.compute.run_length.run_bounds(mask, dim='time', coord=True)[source]
Return the start and end dates of boolean runs along a dimension.
- Parameters:
mask (xr.DataArray) – Boolean array.
dim (str) – Dimension along which to look for runs.
coord (bool or str) – If True, return values of the coordinate. If a str, returns values from dim.dt.<coord>. If False, return indexes.
- Returns:
xr.DataArray – With
dimreduced to “events” and “bounds”. The events dim is as long as needed, padded with NaN or NaT.
- xclim.compute.run_length.run_end_after_date(da, window, date='07-01', dim='time', coord='dayofyear')[source]
Return the index of the first item after the end of a run after a given date.
The run must begin before the date.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive run to accumulate values.
date (str) – The date after which to look for the end of a run.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (Optional[Union[bool, str]]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Return type:
DataArray- Returns:
xr.DataArray – Index (or coordinate if coord is not False) of last item in last valid run. Returns np.nan if there are no valid runs.
- xclim.compute.run_length.runs_with_holes(da_start, window_start, da_stop, window_stop, dim='time')[source]
Extract events, i.e. runs whose starting and stopping points are defined through run length conditions.
- Parameters:
da_start (xr.DataArray) – Input array where run sequences are searched to define the start points in the main runs.
window_start (int) – Number of True (1) values needed to start a run in da_start.
da_stop (xr.DataArray) – Input array where run sequences are searched to define the stop points in the main runs.
window_stop (int) – Number of True (1) values needed to start a run in da_stop.
dim (str) – Dimension name.
- Return type:
DataArray- Returns:
xr.DataArray – Output array with 1’s when in a run sequence and with 0’s elsewhere.
Notes
A season (as defined in
season) could be considered as an event withwindow_stop == window_startandda_stop == 1 - da_start, although it has more constraints on when to start and stop a run through the date argument and only one season can be found.
- xclim.compute.run_length.season(da, window, mid_date=None, dim='time', stat=None, coord=False)[source]
Calculate the bounds of a season along a dimension.
A “season” is a run of True values that may include breaks under a given length (window). The start is computed as the first run of window True values, and the end as the first subsequent run of window False values. The end element is the first element after the season. If a date is given, it must be included in the season (i.e. the start cannot occur later and the end cannot occur earlier).
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive values to start and end the season.
mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
stat (str, optional) – Not currently implemented. If not None, return a statistic of the season. The statistic is calculated on the season’s values.
coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Return type:
Dataset- Returns:
xr.Dataset –
- The Dataset variables:
start : start of the season (index or units depending on
coord) end : end of the season (index or units depending oncoord) length : length of the season (in number of elements alongdim)
See also
season_startStart of a season.
season_endEnd of a season.
season_lengthLength of a season.
Notes
The run can include holes of False or NaN values, so long as they do not exceed the window size.
If a date is given, the season start and end are forced to be on each side of this date. This means that even if the “real” season has been over for a long time, this is the date used in the length calculation. e.g. Length of the “warm season”, where T > 25°C, with date = 1st August. Let’s say the temperature is over 25 for all June, but July and august have very cold temperatures. Instead of returning 30 days (June), the function will return 61 days (July + June).
The season’s length is always the difference between the end and the start. Except if no season end was found before the end of the data. In that case the end is set to last element and the length is set to the data size minus the start index. Thus, for the specific case, \(length = end - start + 1\), because the end falls on the last element of the season instead of the subsequent one.
- xclim.compute.run_length.season_end(da, window, mid_date=None, dim='time', coord=False, _beg=None)[source]
End of a season.
See
season(). Similar tofirst_run_after_date()but here a season must have a start for an end to be valid. Also, if no end is found but a start was found the end is set to the last element of the series.- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive values to start and end the season.
mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
coord (str, optional) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
_beg (xr.DataArray, optional) – If given, the start of the season. This is used to avoid recomputing the start.
- Return type:
DataArray- Returns:
xr.DataArray – End of the season, units depend on coord. If there is a start is found but no end, the end is set to the last element.
See also
seasonCalculate the bounds of a season along a dimension.
season_startStart of a season.
season_lengthLength of a season.
- xclim.compute.run_length.season_length(da, window, mid_date=None, dim='time')[source]
Length of a season.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive values to start and end the season.
mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a run must include to be considered valid.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
- Return type:
DataArray- Returns:
xr.DataArray, [int] – Length of the season, in number of elements along dimension time.
See also
seasonCalculate the bounds of a season along a dimension.
season_startStart of a season.
season_endEnd of a season.
- xclim.compute.run_length.season_start(da, window, mid_date=None, dim='time', coord=False)[source]
Start of a season.
See
season().- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum duration of consecutive values to start and end the season.
mid_date (DayOfYearStr, optional) – The date (in MM-DD format) that a season must include to be considered valid.
dim (str) – Dimension along which to calculate the season (default: ‘time’).
coord (Optional[str]) – If not False, the function returns values along dim instead of indexes. If dim has a datetime dtype, coord can also be a str of the name of the DateTimeAccessor object to use (ex: ‘dayofyear’).
- Return type:
DataArray- Returns:
xr.DataArray – Start of the season, units depend on coord.
See also
seasonCalculate the bounds of a season along a dimension.
season_endEnd of a season.
season_lengthLength of a season.
- xclim.compute.run_length.statistics_run_1d(arr, statistic, window)[source]
Return statistics on lengths of run of identical values.
- Parameters:
arr (Sequence of bool) – Input array (bool).
statistic ({“mean”, “sum”, “min”, “max”, “std”, “count”, “q?”}) –
- Reducing function name. The special name ‘q?’ computes a quantile with the provided value (e.g. ‘q90’ computes
a q=0.90 quantile).
window (int) – Minimal length of runs to be included in the statistics.
- Return type:
int- Returns:
int – Statistics on length of runs.
- xclim.compute.run_length.statistics_run_ufunc(x, statistic, window, dim='time')[source]
Dask-parallel version of statistics_run_1d.
The {statistic} number of consecutive true values in array.
- Parameters:
x (Sequence of bool) – Input array (bool).
statistic ({‘min’, ‘max’, ‘mean’, ‘sum’, ‘std’, ‘q?’}) – Reducing function name. The special name ‘q?’ should be called as e.g. ‘q90’ to compute a q=0.90 quantile.
window (int) – Minimal length of runs.
dim (str) – The dimension along which the runs are found.
- Return type:
DataArray- Returns:
xr.DataArray – A function operating along the time dimension of a dask-array.
- xclim.compute.run_length.suspicious_run(arr, dim='time', window=10, op='>', thresh=None)[source]
Return True where the array contains has runs of identical values, vectorized version.
In opposition to other run length functions, here the output has the same shape as the input.
- Parameters:
arr (xr.DataArray) – Array of values to be parsed.
dim (str) – Dimension along which to check for runs (default: “time”).
window (int) – Minimum run length.
op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Operator for threshold comparison, defaults to “>”.
thresh (float, optional) – Threshold above which values are checked for identical values.
- Return type:
DataArray- Returns:
xarray.DataArray – A boolean array of the same shape as the input, indicating where runs of identical values are found.
- xclim.compute.run_length.suspicious_run_1d(arr, window=10, op='>', thresh=None)[source]
Return True where the array contains a run of identical values.
- Parameters:
arr (numpy.ndarray) – Array of values to be parsed.
window (int) – Minimum run length.
op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Operator for threshold comparison. Defaults to “>”.
thresh (float, optional) – Threshold compared against which values are checked for identical values.
- Return type:
- Returns:
numpy.ndarray – Whether the data points are part of a run of identical values or not.
- xclim.compute.run_length.use_ufunc(ufunc_1dim, da, dim='time', freq=None, index='first')[source]
Return whether the ufunc version of run length algorithms should be used with this DataArray or not.
If ufunc_1dim is ‘from_context’, the parameter is read from xclim’s global (or context) options. If it is ‘auto’, this returns False for dask-backed array and for arrays with more than
npts_optpoints per slice along dim.- Parameters:
ufunc_1dim ({‘from_context’, ‘auto’, True, False}) – The method for handling the ufunc parameters.
da (xr.DataArray) – Input array.
dim (str) – The dimension along which to find runs.
freq (str) – Resampling frequency.
index ({‘first’, ‘last’}) – If ‘first’ (default), the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.
- Return type:
bool- Returns:
bool – If ufunc_1dim is “auto”, returns True if the array is on dask or too large. Otherwise, returns ufunc_1dim.
- xclim.compute.run_length.windowed_max_run_sum(da, window, dim='time', freq=None, index='first')[source]
Return the maximum sum of consecutive float values for runs at least as long as the given window length.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray.
window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
freq (str) – Resampling frequency.
index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.
- Return type:
DataArray- Returns:
xr.DataArray, [float] – Cumulative sum of input values part of a consecutive runs of at least window long.
Notes
The input da is expected to be non-negative, e.g. temperature exceedances (tasmax - thresh).clip(0,None)
- xclim.compute.run_length.windowed_run_count(da, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]
Return the number of consecutive true values in array for runs at least as long as given duration.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
freq (str) – Resampling frequency.
ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.
index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.
- Return type:
DataArray- Returns:
xr.DataArray, [int] – Total number of True values part of a consecutive runs of at least window long.
- xclim.compute.run_length.windowed_run_count_1d(arr, window)[source]
Return the number of consecutive true values in array for runs at least as long as given duration.
- Parameters:
arr (Sequence of bool) – Input array (bool).
window (int) – Minimum duration of consecutive run to accumulate values.
- Return type:
int- Returns:
int – Total number of true values part of a consecutive run at least window long.
- xclim.compute.run_length.windowed_run_count_ufunc(x, window, dim)[source]
Dask-parallel version of windowed_run_count_1d.
The number of consecutive true values in array for runs at least as long as given duration.
- Parameters:
x (xr.DataArray or sequence of bool) – Input array (bool).
window (int) – Minimum duration of consecutive run to accumulate values.
dim (str) – Dimension along which to calculate windowed run.
- Return type:
DataArray- Returns:
xr.DataArray – A function operating along the time dimension of a dask-array.
- xclim.compute.run_length.windowed_run_events(da, window, dim='time', freq=None, ufunc_1dim='from_context', index='first')[source]
Return the number of runs of a minimum length.
- Parameters:
da (xr.DataArray) – Input N-dimensional DataArray (boolean).
window (int) – Minimum run length. When equal to 1, an optimized version of the algorithm is used.
dim (str) – Dimension along which to calculate consecutive run (default: ‘time’).
freq (str) – Resampling frequency.
ufunc_1dim (Union[str, bool]) – Use the 1d ‘ufunc’ version of this function : default (auto) will attempt to select optimal usage based on number of data points. Using 1D_ufunc=True is typically more efficient for DataArray with a small number of grid points. Ignored when window=1. It can be modified globally through the “run_length_ufunc” global option.
index ({‘first’, ‘last’}) – If ‘first’, the run length is indexed with the first element in the run. If ‘last’, with the last element in the run.
- Return type:
DataArray- Returns:
xr.DataArray, [int] – Number of distinct runs of a minimum length (int).
- xclim.compute.run_length.windowed_run_events_1d(arr, window)[source]
Return the number of runs of a minimum length.
- Parameters:
arr (Sequence of bool) – Input array (bool).
window (int) – Minimum run length.
- Return type:
DataArray- Returns:
xr.DataArray, [int] – Number of distinct runs of a minimum length.
- xclim.compute.run_length.windowed_run_events_ufunc(x, window, dim)[source]
Dask-parallel version of windowed_run_events_1d.
The number of runs at least as long as given duration.
- Parameters:
x (xr.DataArray or sequence of bool) – Input array (bool).
window (int) – Minimum run length.
dim (str) – Dimension along which to calculate windowed run.
- Return type:
DataArray- Returns:
xr.DataArray – A function operating along the time dimension of a dask-array.
Statistical functions module¶
Functions to aid in computing various statistical indicators
See the frequency_analysis notebook for working examples.
- xclim.compute.stats.dist_method(function, fit_params, arg=None, dist=None, **kwargs)[source]
Vectorized statistical function for given argument on given distribution initialized with params.
Methods where “*args” are the distribution parameters can be wrapped, except those that reduce dimensions (e.g. nnlf) or create new dimensions (e.g. ‘rvs’ with size != 1, ‘stats’ with more than one moment, ‘interval’, ‘support’).
- Parameters:
function (str) – The name of the function to call.
fit_params (xr.DataArray) – Distribution parameters are along dparams, in the same order as given by
fit().arg (array_like, optional) – The first argument for the requested function if different from fit_params.
dist (str or rv_continuous distribution object, optional) – The distribution name or instance. Defaults to the scipy_dist attribute or fit_params.
**kwargs (dict) – Other parameters to pass to the function call.
- Return type:
DataArray- Returns:
array_like – Same shape as arg.
See also
scipy.stats.rv_continuousFor all available functions and their arguments.
- xclim.compute.stats.fa(da, t, dist='norm', mode='max', method='ML')[source]
Return the value corresponding to the given return period.
- Parameters:
da (xr.DataArray) – Maximized/minimized input data with a time dimension.
t (int or Sequence of int) – Return period. The period depends on the resolution of the input data. If the input array’s resolution is yearly, then the return period is in years.
dist (str or rv_continuous distribution object) – Name of the univariate distribution, such as: beta, expon, genextreme, gamma, gumbel_r, lognorm, norm Or the distribution instance itself.
mode ({‘min’, ‘max}) – Whether we are looking for a probability of exceedance (max) or a probability of non-exceedance (min).
method ({“ML”, “MLE”, “MOM”, “PWM”, “APP”}) – Fitting method, either maximum likelihood (ML or MLE), method of moments (MOM) or approximate method (APP). If dist is an instance from the lmoments3 library, accepts probability weighted moments (PWM; “L-Moments”). The PWM method is usually more robust to outliers.
- Return type:
DataArray- Returns:
xarray.DataArray – An array of values with a 1/t probability of exceedance (if mode==’max’).
See also
scipy.statsFor descriptions of univariate distribution types.
- xclim.compute.stats.fit(da, dist='norm', method='ML', dim='time', **fitkwargs)[source]
Fit an array to a univariate distribution along the time dimension.
- Parameters:
da (xr.DataArray) – Time series to be fitted along the time dimension.
dist (str or rv_continuous distribution object) – Name of the univariate distribution, such as beta, expon, genextreme, gamma, gumbel_r, lognorm, norm (see :py:mod:scipy.stats for full list) or the distribution object itself.
method ({“ML”, “MLE”, “MM”, “PWM”, “APP”, “MSE”, “MPS”}) – Fitting method, either maximum likelihood (ML or MLE), method of moments (MM), maximum product of spacings (MSE or MPS) or approximate method (APP). If dist is an instance from the lmoments3 library, accepts probability weighted moments (PWM; “L-Moments”). The PWM method is usually more robust to outliers. The MSE method is more consistent than the MLE method, although it can be more sensitive to repeated data. For the MSE method, each variable parameter must be given finite bounds (provided with keyword argument bounds={‘param_name’:(min,max),…}).
dim (str) – The dimension upon which to perform the indexing (default: “time”).
**fitkwargs (dict) – Other arguments passed directly to
_fitstart()and to the distribution’s fit.
- Return type:
DataArray- Returns:
xr.DataArray – An array of fitted distribution parameters.
Notes
Coordinates for which all values are NaNs will be dropped before fitting the distribution. If the array still contains NaNs, the distribution parameters will be returned as NaNs.
- xclim.compute.stats.frequency_analysis(da, mode, t, dist, window=1, freq=None, method='ML', **indexer)[source]
Return the value corresponding to a return period.
- Parameters:
da (xarray.DataArray) – Input data.
mode ({‘min’, ‘max’}) – Whether we are looking for a probability of exceedance (high) or a probability of non-exceedance (low).
t (int or sequence) – Return period. The period depends on the resolution of the input data. If the input array’s resolution is yearly, then the return period is in years.
dist (str or rv_continuous distribution object) – Name of the univariate distribution, e.g. beta, expon, genextreme, gamma, gumbel_r, lognorm, norm. Or an instance of the distribution.
window (int) – Averaging window length (days).
freq (str, optional) – Resampling frequency. If None, the frequency is assumed to be ‘YS’ unless the indexer is season=’DJF’, in which case freq would be set to YS-DEC.
method ({“ML”, “MLE”, “MOM”, “PWM”, “APP”}) – Fitting method, either maximum likelihood (ML or MLE), method of moments (MOM) or approximate method (APP). If dist is an instance from the lmoments3 library, accepts probability weighted moments (PWM; “L-Moments”). The PWM method is usually more robust to outliers.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. For example, use season=’DJF’ to select winter values, month=1 to select January, or month=[6,7,8] to select summer months. If indexer is not provided, all values are considered.
- Return type:
DataArray- Returns:
xarray.DataArray – An array of values with a 1/t probability of exceedance or non-exceedance when mode is high or low respectively.
See also
scipy.statsFor descriptions of univariate distribution types.
- xclim.compute.stats.get_dist(dist)[source]
Return a distribution object from scipy.stats.
- Parameters:
dist (str or rv_continuous distribution object) – Name of the univariate distribution, e.g. beta, expon, genextreme, gamma, gumbel_r, lognorm, norm. Or an instance of the distribution.
- Return type:
- Returns:
rv_continuous – A distribution object from scipy.stats.
- xclim.compute.stats.parametric_cdf(p, v, dist=None)[source]
Return the cumulative distribution function corresponding to the given distribution parameters and value.
- Parameters:
p (xr.DataArray) – Distribution parameters returned by the fit function. The array should have dimension dparams storing the distribution parameters, and attribute scipy_dist, storing the name of the distribution.
v (xr.DataArray or float or Sequence of float) – Value to compute the CDF.
dist (str or rv_continuous distribution object, optional) – The distribution name or instance is the scipy_dist attribute is not available on p.
- Return type:
DataArray- Returns:
xarray.DataArray – An array of parametric CDF values estimated from the distribution parameters.
- xclim.compute.stats.parametric_pdf(p, v, dist=None)[source]
Return the probability density function corresponding to the given distribution parameters and value.
- Parameters:
p (xr.DataArray) – Distribution parameters returned by the fit function. The array should have dimension dparams storing the distribution parameters, and attribute scipy_dist, storing the name of the distribution.
v (xr.DataArray or float or Sequence of float) – Value to compute the PDF.
dist (str or rv_continuous distribution object, optional) – The distribution name or instance is the scipy_dist attribute is not available on p.
- Return type:
DataArray- Returns:
xarray.DataArray – An array of probabilities estimated from the distribution parameters.
- xclim.compute.stats.parametric_quantile(p, q, dist=None)[source]
Return the value corresponding to the given distribution parameters and quantile.
- Parameters:
p (xr.DataArray) – Distribution parameters returned by the fit function. The array should have dimension dparams storing the distribution parameters, and attribute scipy_dist, storing the name of the distribution.
q (float or Sequence of float) – Quantile to compute, which must be between 0 and 1, inclusive.
dist (str or rv_continuous distribution object, optional) – The distribution name or instance if the scipy_dist attribute is not available on p.
- Return type:
DataArray- Returns:
xarray.DataArray – An array of parametric quantiles estimated from the distribution parameters.
Notes
When all quantiles are above 0.5, the isf method is used instead of ppf because accuracy is sometimes better.
- xclim.compute.stats.standardized_index(da, freq, window, dist, method, zero_inflated, fitkwargs, cal_start, cal_end, params=None, prob_zero_interpolation='upper', plotting_position_zero='ecdf', **indexer)[source]
Standardized Index (SI).
This computes standardized indices which measure the deviation of variables in the dataset compared to a reference distribution. The reference is a statistical distribution computed with fitting parameters params over a given calibration period of the dataset. Those fitting parameters are obtained with
xclim.standardized_index_fit_params().- Parameters:
da (xarray.DataArray) – Daily input data.
freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.
window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.
dist (str or rv_continuous instance) – Name of the univariate distribution. (see
scipy.stats).method (str) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that doesn’t involve any optimization.
zero_inflated (bool) – If True, the zeroes of da are treated separately.
fitkwargs (dict, optional) – Kwargs passed to
xclim.compute.stats.fit()used to impose values of certains parameters (floc, fscale). If method is PWM, fitkwargs should be empty, except for floc with dist`=`gamma which is allowed.cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.
cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.
params (xarray.DataArray) – Fit parameters. The params can be computed using
xclim.compute.stats.standardized_index_fit_params()in advance. The output can be given here as input, and it overrides other options.prob_zero_interpolation ({“center”, “upper”} or float) – Interpolation method used to assign a probability to zero values (only used if zero_inflated is True). When the data contain multiple zeros, the admissible plotting position interval spans from the first zero rank to the last zero rank. This parameter selects a representative probability within that interval. The default method “upper” assigns the upper bound of the zero-rank interval. The “center” method assigns the midpoint of the zero-rank interval. If a float in [0, 1] is provided, it is used as a linear interpolation factor between the lower (0) and upper (1) zero-rank plotting positions.
plotting_position_zero ({“ecdf”, “weibull”} or tuple[float, float]) – Method used to assign a probability to a rank for the zeros (only used if zero_inflated is True). “ecdf” (default option) is the empirical cumulative distribution and divides the number or zeros by the total number of observations. “weibull” implements the unbiased version, dividing by the total number of observation plus one. A tuple consisting of two coefficients in [0,1] to relate the number of zeros and the total number of observations. “ecdf” corresponds to (0,1) and “weibull” to (0,0). See
scipy.stats.mstats.plotting_positions()**indexer ({dim: indexer, }, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – Standardized Precipitation Index.
See also
standardized_index_fit_paramsStandardized Index Fit Params.
Notes
The standardized index is bounded by ±8.21. 8.21 is the largest standardized index as constrained by the float64 precision in the inversion to the normal distribution.
window,dist,method,zero_inflatedare only optional ifparamsis given. If params is given as input, it overrides the cal_start, cal_end, freq and window, dist and method options.Supported combinations of dist and method are: * Gamma (“gamma”) : “ML”, “APP” * Log-logistic (“fisk”) : “ML”, “APP” * “APP” method only supports two-parameter distributions. Parameter loc will be set to 0 (setting floc=0 in fitkwargs). * Otherwise, generic rv_continuous methods can be used. This includes distributions from lmoments3 which should be used with method=”PWM”.
References
McKee, Doesken, and Kleist [1993].
- xclim.compute.stats.standardized_index_fit_params(da, freq, window, dist, method, zero_inflated=False, fitkwargs=None, **indexer)[source]
Standardized Index fitting parameters.
A standardized index measures the deviation of a variable averaged over a rolling temporal window and fitted with a given distribution dist with respect to a calibration dataset. The comparison is done by porting back results to a normalized distribution. The fitting parameters of the calibration dataset fitted with dist are obtained here.
- Parameters:
da (xarray.DataArray) – Input array.
freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.
window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.
dist ({‘gamma’, ‘fisk’, ‘genextreme’, ‘lognorm’} or rv_continuous distribution object) – Name of the univariate distribution. (see
scipy.stats).method ({‘ML’, ‘APP’, ‘PWM’}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that doesn’t involve any optimization.
zero_inflated (bool) – If True, the zeroes of da are treated separately when fitting a probability density function.
fitkwargs (dict, optional) – Kwargs passed to
xclim.compute.stats.fitused to impose values of certains parameters (floc, fscale).**indexer ({dim: indexer, }, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.core.calendar.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray – Standardized Index fitting parameters.
Notes
Supported combinations of dist and method are: * Gamma (“gamma”) : “ML”, “APP” * Log-logistic (“fisk”) : “ML”, “APP” * Generalized extreme value (“genextreme”) : “ML” * Log-normal (“lognorm”) : “ML”, “APP” * “APP” method only supports two-parameter distributions. Parameter loc must be set to 0 through floc=0 in fitkwargs. * Otherwise, generic rv_continuous methods can be used. This includes distributions from lmoments3 which should be used with method=”PWM”.
When using the zero inflated option, : A probability density function \(\texttt{pdf}_0(X)\) is fitted for \(X \neq 0\) and a supplementary parameter \(\pi\) takes into account the probability of \(X = 0\). The full probability density function is a piecewise function:
\[\texttt{pdf}(X) = \pi \texttt{ if } X=0 \texttt{ else } (1-\pi) \texttt{pdf}_0(X)\]
Function Library¶
When an indicator can’t be simply implemented only using a xclim.compute.generic function, then a custom compute function
is implemented here.
Compute functions and helpers module.
- xclim.compute.antecedent_precipitation_index(pr, window=7, p_exp=0.935)[source]
Antecedent Precipitation Index.
Calculate the running weighted sum of daily precipitation values given a window and weighting exponent. This index serves as an indicator for soil moisture.
- Parameters:
pr (xarray.DataArray) – Daily precipitation data.
window (int) – Window for the days of precipitation data to be weighted and summed, default is 7.
p_exp (float) – Weighting exponent, default is 0.935.
- Return type:
DataArray- Returns:
xarray.DataArray – Antecedent Precipitation Index.
References
Li, Wei, and Li [2021], Schröter, Kunz, Elmer, Mühr, and Merz [2015]
- xclim.compute.aridity_index(pr, evspsblpot, freq='YS')[source]
Aridity index.
The ratio of total precipitation over potential evapotranspiration. Classification based on the Aridity Index (AI).
- Parameters:
pr (array_like) – Precipitation.
evspsblpot (array_like) – Potential evapotranspiration.
freq (str) – Resampling frequency. A monthly or yearly frequency is expected.
- Return type:
DataArray- Returns:
float – Aridity index per time step (Unitless).
Notes
- The range in the aridity index define different environment categories (percentage of global land area covered)
Hyperarid (7.5%): AI < 0.05
Arid (12.1%): 0.05 ≤ AI < 0.20
Semi-Arid (17.7%): 0.20 ≤ AI < 0.50
Dry subhumid (9.9%): 0.50 ≤ AI < 0.65
Humid (52.8%): AI ≥ 0.65
In North America, higher aridity index values can be associated with colder climates due to lower evapotranspiration, even when precipitation is limited or occurring as snow.
References
:cite:cts:’zomer_2022’
- xclim.compute.base_flow_index(q, freq='YS')[source]
Base flow index.
Return the base flow index, defined as the minimum 7-day average flow divided by the mean flow.
- Parameters:
q (xarray.DataArray) – Rate of river discharge.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Base flow index.
Notes
Let \(\mathbf{q}=q_0, q_1, \ldots, q_n\) be the sequence of daily discharge and \(\overline{\mathbf{q}}\) the mean flow over the period. The base flow index is given by:
\[\frac{\min(\mathrm{CMA}_7(\mathbf{q}))}{\overline{\mathbf{q}}}\]where \(\mathrm{CMA}_7\) is the seven days moving average of the daily flow:
\[\mathrm{CMA}_7(q_i) = \frac{\sum_{j=i-3}^{i+3} q_j}{7}\]
- xclim.compute.base_flow_index_seasonal_ratio(q, freq='QS-DEC', numerator='DJF', denominator='JJA')[source]
Seasonal Base flow index (bfi) and ratio of winter to summer base flow index.
Return yearly base flow index per season, defined as the minimum 7-day average flow divided by the mean flow as well as yearly winter to summer bfi ratio.
- Parameters:
q (xarray.DataArray) – Rate of river discharge.
freq (str) – Resampling frequency.
numerator (str) – String indicating the season in the numerator of the ratio.
denominator (str) – String indicating the season in the denominator of the ratio.
- Return type:
tuple[DataArray,DataArray,DataArray,DataArray,DataArray]- Returns:
xarray.DataArray, [dimensionless] – Base flow index with a season coordinate.
xarray.DataArray, [dimensionless] – Base flow index winter to summer ratio.
Notes
It is recommended to have at least 70% of valid data per month in order to compute significant values. The default arguments compute the bfi ratio of the winter (“DJF”) to summer (“JJA”) ratio.
References
Singh, Pahlow, Booker, Shankar, and Chamorro [2019] Jaffrés, Cuff, Cuff, Faichney, Knott, and Rasmussen [2021]
- xclim.compute.biologically_effective_degree_days(tasmin, tasmax, lat=None, thresh_tasmin='10 degC', method='gladstones', cap_value=1.0, low_dtr='10 degC', high_dtr='13 degC', max_daily_degree_days='9 degC', start_date='04-01', end_date='11-01', freq='YS')[source]
Biologically effective growing degree days.
Growing-degree days with a base of 10°C and an upper limit of 19°C and adjusted for latitudes between 40°N and 50°N for April to October (Northern Hemisphere; October to April in Southern Hemisphere). A temperature range adjustment also promotes small and large swings in daily temperature range. Used as a heat-summation metric in viticulture agroclimatology.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
lat (xarray.DataArray, optional) – Latitude coordinate. If None and method is not “icclim”, a CF-conformant “latitude” field must be available within the passed DataArray.
thresh_tasmin (Quantified) – The minimum temperature threshold.
method ({“gladstones”, “huglin”, “icclim”, “interpolated”, “jones”}) – The formula to use for the daily temperature range and latitude coefficient. The “gladstones” method uses a temperature range adjustment and a latitude coefficient based on Gladstones [2011]. End_date should be “11-01” for the Northern Hemisphere. The “huglin” method uses a temperature range adjustment and a stepwise latitude coefficient for values between 40° and 50° based on Huglin [1978]. End_date should be “11-01” for the Northern Hemisphere. The “icclim” method does not implement daily temperature range and nor a latitude coefficient based on Project team ECA&D and KNMI [2013]. End date should be “10-01” for the Northern Hemisphere. The “interpolated” method uses a temperature range adjustment and a smoothed curve latitude coefficient for values between 40° and 50° based on Huglin [1978]. The “jones” method uses a temperature range adjustment and integrates axial tilt, latitude, and day-of-year based on Hall and Jones [2010]. End_date should be “11-01” for the Northern Hemisphere.
cap_value (float) – The value to use for the latitude coefficient for latitudes north of 50°N or south of 50°S. Only applicable for methods “huglin” and “interpolated”.
low_dtr (Quantified) – The lower bound for daily temperature range adjustment.
high_dtr (Quantified) – The higher bound for daily temperature range adjustment.
max_daily_degree_days (Quantified) – The maximum number of biologically effective degrees days that can be summed daily.
start_date (str or DayOfYearStr) – The hemisphere-based start date to consider (north = April, south = October).
end_date (str or DayOfYearStr) – The hemisphere-based start date to consider (north = October, south = April). This date is non-inclusive.
freq (str) – Resampling frequency (For Southern Hemisphere, should be “YS-JUL”).
- Return type:
DataArray- Returns:
xarray.DataArray, [K days] – Biologically effective growing degree days (BEDD).
Warning
- UserWarning
Emitted if latitude is supplied for the “icclim” method, as it is not used in the calculation.
Notes
Lat coordinate must be provided if method is “gladstones”, “gladstones_simple”, or “huglin”; The “icclim” method for BEDD here differs from the approach detailed in the Heliothermal Index of Huglin (HI) by not considering the latitude coefficient.
The tasmax ceiling of 19°C is assumed to be the maximum temperature beyond which no further gains from warmer daily temperatures occur. Index 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)\]An alternative version of the BEDD (method=”icclim”) does not consider \(TR_{adj}\) and \(k\) and employs a different end date (30 September) [Project team ECA&D and KNMI, 2013]. The simplified formula is as follows:
\[BEDD_i = \sum_{i=\text{April 1}}^{ \text{September 30} } min\left( max\left( \frac{TX_i + TN_i)}{2} - 10, 0 \right), degdays_{max} \right)\]References
Gladstones [1992], Hall and Jones [2010], Huglin and Schneider [1998], Project team ECA&D and KNMI [2013]
- xclim.compute.blowing_snow(snd, sfcWind, snd_thresh='5 cm', sfcWind_thresh='15 km/h', window=3, freq='YS-JUL', **indexer)[source]
Blowing snow days.
Number of days when both snowfall over the last days and daily wind speeds are above respective thresholds.
- Parameters:
snd (xarray.DataArray) – Surface snow depth.
sfcWind (xr.DataArray) – Wind velocity.
snd_thresh (Quantified) – Threshold on net snowfall accumulation over the last window days.
sfcWind_thresh (Quantified) – Wind speed threshold.
window (int) – Period over which snow is accumulated before comparing against threshold.
freq (str) – Resampling frequency.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. The subset is taken after summing the snowfall over the window. It accepts the same arguments as
xclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray – Number of days when snowfall and wind speeds are above respective thresholds.
- xclim.compute.calm_days(sfcWind, thresh='2 m s-1', freq='MS')[source]
Calm days.
The number of days with average near-surface wind speed below threshold (default: 2 m/s).
- Parameters:
sfcWind (xarray.DataArray) – Daily windspeed.
thresh (Quantified) – Threshold average near-surface wind speed on which to base evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days with average near-surface wind speed below the threshold.
Notes
Let \(WS_{ij}\) be the windspeed at day \(i\) of period \(j\). Then counted is the number of days where:
\[WS_{ij} < Threshold [m s-1]\]
- xclim.compute.cffwis_indices(tas, pr, sfcWind, hurs, lat, snd=None, ffmc0=None, dmc0=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=True, **params)[source]
Canadian Fire Weather Index System indices.
Computes the six (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 - 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 (dict) – Any other keyword parameters as defined in
fire_weather_ufunc()and indefault_params.
- Return type:
tuple[DataArray,DataArray,DataArray,DataArray,DataArray,DataArray]- Returns:
DC (xr.DataArray, [dimensionless]) – The Drought Code.
DMC (xr.DataArray, [dimensionless]) – The Duff Moisture Code.
FFMC (xr.DataArray, [dimensionless]) – The Fine Fuel Moisture Code.
ISI (xr.DataArray, [dimensionless]) – The Initial Spread Index.
BUI (xr.DataArray, [dimensionless]) – The Build Up Index.
FWI (xr.DataArray, [dimensionless]) – The Fire Weather Index.
Notes
See Natural Resources Canada [n.d.], the
xclim.compute.firemodule documentation, and the docstring offire_weather_ufunc()for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.References
Wang, Anderson, and Suddaby [2015]
- xclim.compute.chill_portions(tas, freq='YS', **indexer)[source]
Chill portion based on the dynamic model.
Chill portions are a measure to estimate the bud breaking potential of different crop. The constants and functions are taken from Luedeling et al. (2009) which formalises the method described in Fishman et al. (1987). The model computes the accumulation of an intermediate product that is transformed to the final product once it exceeds a certain concentration. The intermediate product can be broken down at higher temperatures but the final product is stable even at higher temperature. Thus, the dynamic model is more accurate than the Utah model especially in moderate climates like Israel, California, or Spain.
- Parameters:
tas (xr.DataArray) – Hourly temperature.
freq (str) – Resampling frequency.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xr.DataArray, [unitless] – Chill portions after the Dynamic Model.
Notes
Typically, this indicator is computed for a period of the year. You can use the **indexer arguments of select_time in combination with the freq argument to select e.g. a winter period:
cp = chill_portions(tas, date_bounds=("09-01", "03-30"), freq="YS-JUL")
Note that incomplete periods will lead to NaNs.
References
Fishman, Erez, and Couvillon [1987], Luedeling [2012]
Examples
>>> from xclim.compute import chill_portions >>> from xclim.compute.helpers import make_hourly_temperature >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin >>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax >>> tas_hourly = make_hourly_temperature(tasmin, tasmax) >>> cp = chill_portions(tas_hourly)
- xclim.compute.chill_units(tas, positive_only=False, freq='YS')[source]
Chill units using the Utah model.
Chill units are a measure to estimate the bud breaking potential of different crop based on Richardson et al. [1974]. The Utah model assigns a weight to each hour depending on the temperature recognising that high temperatures can actual decrease, the potential for bud breaking. Providing positive_only=True will ignore days with negative chill units.
- Parameters:
tas (xr.DataArray) – Hourly temperature.
positive_only (bool) – If True, only positive daily chill units are aggregated.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] – Chill units using the Utah model.
References
Richardson, Seeley, and Walker [1974]
Examples
>>> from xclim.compute import chill_units >>> from xclim.compute.helpers import make_hourly_temperature >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin >>> tasmax = xr.open_dataset(path_to_tasmax_file).tasmax >>> tas_hourly = make_hourly_temperature(tasmin, tasmax) >>> cu = chill_units(tasmin)
- xclim.compute.clausius_clapeyron_scaled_precipitation(delta_tas, pr_baseline, cc_scale_factor=1.07)[source]
Scale precipitation according to the Clausius-Clapeyron relation.
- Parameters:
delta_tas (xarray.DataArray) – Difference in temperature between a baseline climatology and another climatology.
pr_baseline (xarray.DataArray) – Baseline precipitation to adjust with Clausius-Clapeyron.
cc_scale_factor (float) – Clausius Clapeyron scale factor. (default = 1.07).
- Return type:
DataArray- Returns:
xarray.DataArray – Baseline precipitation scaled to other climatology using Clausius-Clapeyron relationship.
Warning
Make sure that delta_tas is computed over a baseline compatible with pr_baseline. So for example, if delta_tas is the climatological difference between a baseline and a future period, then pr_baseline should be precipitations over a period within the same baseline.
Notes
The Clausius-Clapeyron equation for water vapour under typical atmospheric conditions states that the saturation water vapour pressure \(e_s\) changes approximately exponentially with temperature
\[\frac{\mathrm{d}e_s(T)}{\mathrm{d}T} \approx 1.07 e_s(T)\]This function assumes that precipitation can be scaled by the same factor.
- xclim.compute.clearness_index(rsds)[source]
Compute the clearness index.
The clearness index is the ratio between the shortwave downwelling radiation and the total extraterrestrial radiation on a given day.
- Parameters:
rsds (xr.DataArray) – Surface downwelling solar radiation.
- Return type:
DataArray- Returns:
xr.DataArray, [unitless] – Clearness index.
Notes
Clearness Index (ci) is defined as:
References
Lauret, Alonso-Suárez, Le Gal La Salle, and David [2022]
- xclim.compute.cold_and_dry_days(tas, pr, tas_per, pr_per, freq='YS')[source]
Cold and dry days.
Returns the total number of days when “Cold” and “Dry” conditions coincide.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature values.
pr (xarray.DataArray) – Daily precipitation.
tas_per (xarray.DataArray) – First quartile of daily mean temperature computed by month.
pr_per (xarray.DataArray) – First quartile of daily total precipitation computed by month.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The total number of days when cold and dry conditions coincide.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
Notes
Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.
Formula to be written (Beniston [2009]).
References
Beniston [2009]
- xclim.compute.cold_and_wet_days(tas, pr, tas_per, pr_per, freq='YS')[source]
Cold and wet days.
Returns the total number of days when “cold” and “wet” conditions coincide.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature values.
pr (xarray.DataArray) – Daily precipitation.
tas_per (xarray.DataArray) – First quartile of daily mean temperature computed by month.
pr_per (xarray.DataArray) – Third quartile of daily total precipitation computed by month.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The total number of days when cold and wet conditions coincide.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
Notes
Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.
Formula to be written (Beniston [2009]).
References
Beniston [2009]
- xclim.compute.cold_spell_days(tas, thresh='-10 degC', window=5, freq='YS-JUL', op='<', resample_before_rl=True)[source]
Cold spell days.
The number of days that are part of cold spell events, defined as a sequence of consecutive days with mean daily temperature below a threshold (default: -10°C).
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature below which a cold spell begins.
window (int) – Minimum number of days with temperature below the threshold to qualify as a cold spell.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Cold spell days.
Notes
Let \(T_i\) be the mean daily temperature on day \(i\), the number of cold spell days during period \(\phi\) is given by:
\[\sum_{i \in \phi} \prod_{j=i}^{i+5} [T_j < thresh]\]where \([P]\) is 1 if \(P\) is true, and 0 if false.
- xclim.compute.cold_spell_duration_index(tasmin, tasmin_per, window=6, freq='YS', resample_before_rl=True, bootstrap=False, condition='<')[source]
Cold spell duration index.
Number of days with at least window consecutive days when the daily minimum temperature is below the tasmin_per percentiles.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmin_per (xarray.DataArray) – The nth percentile of daily minimum temperature with dayofyear coordinate.
window (int) – Minimum number of days with temperature below threshold to qualify as a cold spell.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Keep bootstrap to False when there is no common period, as bootstrapping is computationally expensive, and it might provide the wrong results.
condition ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with at least six consecutive days when the daily minimum temperature is below the 10th percentile.
Notes
Let \(TN_i\) be the minimum daily temperature for the day of the year \(i\) and \(TN10_i\) the 10th percentile of the minimum daily temperature over the 1961-1990 period for day of the year \(i\), the cold spell duration index over period \(\phi\) is defined as:
\[\sum_{i \in \phi} \prod_{j=i}^{i+6} \left[ TN_j < TN10_j \right]\]where \([P]\) is 1 if \(P\) is true, and 0 if false.
References
From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI; [Zhang et al., 2011]).
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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) >>> csdi = cold_spell_duration_index(tasmin, tn10)
Note that this example does not use a proper 1961-1990 reference period.
- xclim.compute.cold_spell_frequency(tas, thresh='-10 degC', window=5, freq='YS-JUL', op='<', resample_before_rl=True)[source]
Cold spell frequency.
The number of cold spell events, defined as a sequence of consecutive {window} days with mean daily temperature below a {thresh}.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature below which a cold spell begins.
window (int) – Minimum number of days with temperature below the threshold to qualify as a cold spell.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run.
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – The {freq} number of cold periods of minimum {window} days.
- xclim.compute.cold_spell_max_length(tas, thresh='-10 degC', window=1, freq='YS-JUL', op='<', resample_before_rl=True)[source]
Longest cold spell.
Longest spell of low temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or below {thresh}.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – The temperature threshold needed to trigger a cold spell.
window (int) – Minimum number of days with temperatures below the threshold to qualify as a cold spell.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} longest spell in cold periods of minimum {window} days.
- xclim.compute.cold_spell_total_length(tas, thresh='-10 degC', window=3, freq='YS-JUL', op='<', resample_before_rl=True)[source]
Total length of cold spells.
Total length of spells of low temperatures over a given period. Total length of series of at least {window} consecutive days with temperature at or below {thresh}.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – The temperature threshold needed to trigger a cold spell.
window (int) – Minimum number of days with temperatures below the threshold to qualify as a cold spell.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} total number of days in cold periods of minimum {window} days.
- xclim.compute.cool_night_index(tasmin, lat=None, freq='YS')[source]
Cool Night Index.
Mean minimum temperature for September (northern hemisphere) or March (Southern hemisphere). Used in calculating the Géoviticulture Multicriteria Classification System (Tonietto and Carbonneau [2004]).
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
lat (xarray.DataArray or {“north”, “south”}, optional) – Latitude coordinate as an array, float or string. If None, a CF-conformant “latitude” field must be available within the passed DataArray.
freq ({“YS”, “YS-JAN”}) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [degC] – Mean of daily minimum temperature for month of interest.
Warning
This index is calculated using minimum temperature resampled to monthly average, and therefore will accept monthly averaged data as inputs.
Notes
Given that this index only examines September and March months, it is possible to send in DataArrays containing only these timesteps. Users should be aware that due to the missing values checks in wrapped Indicators, datasets that are missing several months will be flagged as invalid. This check can be ignored by setting the following context:
with xclim.set_options(check_missing="skip"): cni = cool_night_index(tasmin)
References
Tonietto and Carbonneau [2004]
Examples
>>> from xclim.compute import cool_night_index >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin >>> cni = cool_night_index(tasmin)
- xclim.compute.cooling_degree_days(tas, thresh='18 degC', freq='YS')[source]
Cooling degree days.
Returns the sum of degree days above the temperature threshold at which spaces are cooled (default: 18℃).
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Temperature threshold above which air is cooled.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time][temperature] – Cooling degree days.
Notes
Let \(x_i\) be the daily mean temperature at day \(i\). Then the cooling degree days above temperature threshold \(thresh\) over period \(\phi\) is given by:
\[\sum_{i \in \phi} (x_{i}-{thresh} [x_i > thresh]\]where \([P]\) is 1 if \(P\) is true, and 0 if false.
- xclim.compute.cooling_degree_days_approximation(tasmax, tasmin, tas, thresh='18 degC', freq='YS')[source]
Cooling degree days approximation.
A more robust approximation of cooling degree days as a function of the daily cycle of temperature.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
tasmin (xarray.DataArray) – Minimum daily temperature.
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Temperature threshold above which air is cooled.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Approximation of cooling degree days.
References
Spinoni, Vogt, Barbosa, Dosio, McCormick, Bigano, and Füssel [2018]
- xclim.compute.corn_heat_units(tasmin, tasmax, thresh_tasmin='4.44 degC', thresh_tasmax='10 degC')[source]
Corn heat units.
Temperature-based index used to estimate the development of corn crops. Formula adapted from Bootsma et al. [1999].
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (Quantified) – The minimum temperature threshold needed for corn growth.
thresh_tasmax (Quantified) – The maximum temperature threshold needed for corn growth.
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – Daily corn heat units.
Notes
Formula used in calculating the Corn Heat Units for the Agroclimatic Atlas of Quebec [Audet et al., 2012].
The thresholds of 4.44°C for minimum temperatures and 10°C for maximum temperatures were selected following the assumption that no growth occurs below these values.
Let \(TX_{i}\) and \(TN_{i}\) be the daily maximum and minimum temperature at day \(i\). Then the daily corn heat unit is:
\[CHU_i = \frac{YX_{i} + YN_{i}}{2}\]with
\[\begin{split}\begin{aligned} YX_i &= 3.33(TX_i - 10) - 0.084(TX_i - 10)^2, &\text{if } TX_i > 10^\circ\mathrm{C} \\ YN_i &= 1.8(TN_i - 4.44), &\text{if } TN_i > 4.44^\circ\mathrm{C} \end{aligned}\end{split}\]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.compute.daily_pr_intensity(pr, thresh='1 mm/day', freq='YS', op='>=')[source]
Average daily precipitation intensity.
Return the average precipitation over wet days. Wet days are those with precipitation over a given threshold (default: 1 mm/day).
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Precipitation value over which a day is considered wet.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [precipitation] – The average precipitation over wet days for each period.
Notes
Let \(\mathbf{p} = p_0, p_1, \ldots, p_n\) be the daily precipitation and \(thresh\) be the precipitation threshold defining wet days. Then the daily precipitation intensity is defined as:
\[\frac{\sum_{i=0}^n p_i [p_i \leq thresh]}{\sum_{i=0}^n [p_i \leq thresh]}\]where \([P]\) is 1 if \(P\) is true, and 0 if false.
Examples
The following would compute for each grid cell of file pr.day.nc the average precipitation fallen over days with precipitation >= 5 mm at seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute 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.compute.daily_temperature_range(tasmin, tasmax, freq='YS', op='mean')[source]
Statistics of daily temperature range.
The mean difference between the daily maximum temperature and the daily minimum temperature.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
op ({“min”, “max”, “mean”, “std”} or Callable) – Reduce operation. Can either be a DataArray method or a function that can be applied to a DataArray.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmin] – The average variation in daily temperature range for the given time period.
Notes
For a default calculation using op=’mean’:
Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then the mean diurnal temperature range in period \(j\) is:
\[DTR_j = \frac{ \sum_{i=1}^I (TX_{ij} - TN_{ij}) }{I}\]
- xclim.compute.daily_temperature_range_variability(tasmin, tasmax, freq='YS')[source]
Mean absolute day-to-day variation in daily temperature range.
Mean absolute day-to-day variation in daily temperature range.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmin] – The average day-to-day variation in daily temperature range for the given time period.
Notes
Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then calculated is the absolute day-to-day differences in period \(j\) is:
\[vDTR_j = \frac{ \sum_{i=2}^{I} |(TX_{ij}-TN_{ij})-(TX_{i-1,j}-TN_{i-1,j})| }{I}\]
- xclim.compute.days_over_precip_thresh(pr, pr_per, thresh='1 mm/day', freq='YS', bootstrap=False, condition='>')[source]
Number of wet days with daily precipitation over a given percentile.
Number of days over a period where the precipitation is above a threshold defining wet days and above a given percentile for that day.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
pr_per (xarray.DataArray) – Percentile of wet day precipitation flux. Either computed daily (one value per day of year) or computed over a period (one value per spatial point).
thresh (Quantified) – Precipitation value over which a day is considered wet.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with daily precipitation above the given percentile [days].
Examples
>>> from xclim.compute 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.compute.days_with_snow(prsn, low='0 kg m-2 s-1', high='1E6 kg m-2 s-1', freq='YS-JUL')[source]
Days with snow.
Return the number of days where snowfall is within low and high thresholds.
- Parameters:
prsn (xarray.DataArray) – Snowfall flux.
low (Quantified) – Minimum threshold snowfall flux or liquid water equivalent snowfall rate.
high (Quantified) – Maximum threshold snowfall flux or liquid water equivalent snowfall rate.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – Number of days where snowfall is between low and high thresholds.
Warning
The default freq is valid for the northern hemisphere.
Notes
If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.
References
Matthews, Andrey, and Picketts [2017].
- xclim.compute.degree_days_above_approximation(tasmax, tasmin, tas, thresh, freq)[source]
Degree days for temperature above a given threshold, approximated from daily statistics.
Degree days calculations approximating the daily cycle of temperature through is min, mean and max, see notes.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
tasmin (xarray.DataArray) – Minimum daily temperature.
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Temperature threshold above which degree days are accumulated.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Approximation of degree days above a threshold.
Notes
For each day, the integrated quantity depends on where the threshold lies in relation to the 3 temperature statistics.
thresh > tasmax: 0tasmax >= thresh > tas:(tasmax - thresh) / 4tas >= thresh > tasmin:(tasmax - thresh) / 2 - (thresh - tasmin) / 4,`` tasmin > thresh`` :
(tas - thresh).
References
Spinoni, Vogt, Barbosa, Dosio, McCormick, Bigano, and Füssel [2018]
- xclim.compute.degree_days_below_approximation(tasmax, tasmin, tas, thresh, freq)[source]
Degree days for temperature below a given threshold, approximated from daily statistics.
Degree days calculations approximating the daily cycle of temperature through is min, mean and max, see notes.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
tasmin (xarray.DataArray) – Minimum daily temperature.
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Temperature threshold below which degree days are accumulated.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Approximation of degree days above a threshold.
Notes
For each day, the integrated quantity depends on where the threshold lies in relation to the 3 temperature statistics.
thresh > tasmax: (thresh - tas)tasmax >= thresh > tas:(thresh - tasmin) / 2 - (tasmax - thresh) / 4tas >= thresh > tasmin:(thresh - tasmin) / 4tasmin > thresh: 0.
References
Spinoni, Vogt, Barbosa, Dosio, McCormick, Bigano, and Füssel [2018]
- xclim.compute.degree_days_exceedance_date(tas, thresh='0 degC', sum_thresh='25 K days', condition='>', after_date=None, never_reached=None, freq='YS')[source]
Degree-days exceedance date.
Day of year when the sum of degree days exceeds a threshold (default: 25 K days). Degree days are computed above or below a given temperature threshold (default: 0℃).
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base degree-days evaluation.
sum_thresh (Quantified) – Threshold of the degree days sum.
condition ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”}) – If equivalent to ‘>’, degree days are computed as tas - thresh and if equivalent to ‘<’, they are computed as thresh - tas.
after_date (str, optional) – Date at which to start the cumulative sum. In “MM-DD” format, defaults to the start of the sampling period.
never_reached (int, str, optional) – What to do when sum_thresh is never exceeded. If an int, the value to assign as a day-of-year. If a string, must be in “MM-DD” format, the day-of-year of that date is assigned. Default (None) assigns “NaN”.
freq (str) – Resampling frequency. If after_date is given, freq should be annual.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Degree-days exceedance date.
Notes
Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\), \(T\) is the reference threshold and \(ST\) is the sum threshold. Then, starting at day :math:i_0:, the degree days exceedance date is the first day \(k\) such that:
\[\begin{split}\begin{cases} ST < \sum_{i=i_0}^{k} \max(TG_{ij} - T, 0) & \text{if $condition$ is '>' | '>='} \\ ST < \sum_{i=i_0}^{k} \max(T - TG_{ij}, 0) & \text{if $condition$ 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.compute.dewpoint_from_specific_humidity(huss, ps, method='buck81', variant='water')[source]
Dewpoint temperature computed from specific humidity and pressure.
The temperature at which the current vapour pressure would be the saturation vapour pressure. Only a subset of the
saturation_vapor_pressure()methods are supported.- Parameters:
huss (xr.DataArray) – Specific humidity [kg/kg].
ps (xr.DataArray) – Pressure.
method ({‘tetens30’, ‘wmo08’, ‘aerk96’, ‘buck81’}) – The formula to use for saturation vapour pressure. Only the formulas using the easily invertible August-Roche-Magnus form are available.
variant ({‘water’, ‘ice’}) – Which variant of the saturation vapour pressure formula to take.
- Returns:
xr.DataArray, [temperature] – Dewpoint temperature.
See also
saturation_vapor_pressureComputations of the saturation vapour pressure with more notes.
ESAT_FORMULAS_COEFFICIENTSCoefficients of the August-Roche-Magnus form equation for saturation vapour pressure.
Notes
The calculation is based on the following, using the August-Roche-Magnus form for the saturation vapour pressure formula :
\[ \begin{align}\begin{aligned}e(q, p) = e_{sat}(T_d) = A \mathrm{e}^{B * \frac{T_d - T_0}{T_d + C}}\\T_d = \frac{-T_0 - C\frac{1}{B}\mathrm{ln}\frac{e}{A}}{\frac{1}{B}\mathrm{ln}\frac{e}{A} - 1}\end{aligned}\end{align} \]Where \(e\) is the
vapor_pressure(), \(q\) is the specific humidiy, \(p\) is the pressure, \(e_{sat}\) is thesaturation_vapor_pressure(), \(T_0\) is the freezing temperature 273.16 K and \(T_d\) is the dewpoint temperature. \(A\), \(B\) and \(C\) are method-specific and variant-specific coefficients.To imitate the calculations of ECMWF’s IFS (ERA5, ERA5-Land), use
method='buck81'andreference='water'(the defaults).
- xclim.compute.drought_code(tas, pr, lat, snd=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=True, **params)[source]
Drought code (FWI component).
The drought code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of organic layers.
- Parameters:
tas (xr.DataArray) – Noon temperature.
pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.
lat (xr.DataArray) – Latitude coordinate.
snd (xr.DataArray) – Noon snow depth.
dc0 (xr.DataArray) – Initial values of the drought code.
season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.
season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fire function. Ignored if season_mask is given.
overwintering (bool) – Whether to activate DC overwintering or not. If True, either season_method or season_mask must be given.
dry_start ({None, “CFS”, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism and which method to use. See
fire_weather_ufunc().initial_start_up (bool) – If True (default), grid points where the fire season is active on the first timestep go through a start_up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.
**params (dict) – Any other keyword parameters as defined in xclim.compute.fire.fire_weather_ufunc and in
default_params.
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] – Drought code.
Notes
See Natural Resources Canada [n.d.], the
xclim.compute.firemodule documentation, and the docstring offire_weather_ufunc()for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.References
Wang, Anderson, and Suddaby [2015]
- xclim.compute.dry_days(pr, thresh='0.2 mm/d', freq='YS', op='<')[source]
Dry days.
The number of days with daily precipitation below threshold.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Threshold precipitation on which to base evaluation.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days with daily precipitation {op} threshold.
Notes
Let \(PR_{ij}\) be the daily precipitation at day \(i\) of period \(j\). Then counted is the number of days where:
\[\sum PR_{ij} < Threshold [mm/day]\]
- xclim.compute.dry_spell_frequency(pr, thresh='1.0 mm', window=3, freq='YS', resample_before_rl=True, op='sum', **indexer)[source]
Return the number of dry periods of n days and more.
Periods during which the accumulated or maximal daily precipitation amount within a window of n days is under a given threshold.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Precipitation amount under which a period is considered dry. The value against which the threshold is compared depends on op.
window (int) – Minimum length of the spells.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
op ({“sum”, “max”, “min”, “mean”}) – Operation to perform on the window. Default is “sum”, which checks that the sum of accumulated precipitation over the whole window is less than the threshold. “max” checks that the maximal daily precipitation amount within the window is less than the threshold. This is the same as verifying that each individual day is below the threshold.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time(). Indexing is done after finding the dry days, but before finding the spells.
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – The {freq} number of dry periods of minimum {window} days.
See also
xclim.compute.generic.spell_length_statisticsThe parent function that computes the spell length statistics.
Examples
>>> from xclim.compute import dry_spell_frequency >>> pr = xr.open_dataset(path_to_pr_file).pr >>> dsf_sum = dry_spell_frequency(pr=pr, op="sum") >>> dsf_max = dry_spell_frequency(pr=pr, op="max")
- xclim.compute.dry_spell_max_length(pr, thresh='1.0 mm', window=1, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]
Longest dry spell.
The maximum number of consecutive days in a dry period of minimum length, during which the maximum or accumulated precipitation within a window of the same length is under a threshold.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Accumulated precipitation value under which a period is considered dry.
window (int) – Number of days when the maximum or accumulated precipitation is under the threshold.
op ({“max”, “sum”}) – Reduce operation.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time(). Indexing is done after finding the dry days, but before finding the spells.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} longest spell in dry periods of minimum {window} days.
See also
xclim.compute.generic.spell_length_statisticsThe parent function that computes the spell length statistics.
Notes
The algorithm assumes days before and after the timeseries are “wet”, meaning that the condition for being considered part of a dry spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a dry spell only if the accumulated precipitation within the first three days is under the threshold. In comparison, a day in the middle of the series is considered part of a dry spell if any of the three 3-day periods of which it is part are considered dry (so a total of five days are included in the computation, compared to only three).
- xclim.compute.dry_spell_total_length(pr, thresh='1.0 mm', window=3, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]
Total length of dry spells.
The total number of days in dry periods of a minimum length, during which the maximum or accumulated precipitation within a window of the same length is under a given threshold.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Accumulated precipitation value under which a period is considered dry.
window (int) – Number of days when the maximum or accumulated precipitation is under the threshold.
op ({“sum”, “max”, “min”, “mean”}) – Operation to perform on the window. Default is “sum”, which checks that the sum of accumulated precipitation over the whole window is less than the threshold. “max” checks that the maximal daily precipitation amount within the window is less than the threshold. This is the same as verifying that each individual day is below the threshold.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time(). Indexing is done after finding the dry days, but before finding the spells.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} total number of days in dry periods of minimum {window} days.
See also
xclim.compute.generic.spell_length_statisticsThe parent function that computes the spell length statistics.
Notes
The algorithm assumes days before and after the timeseries are “wet”, meaning that the condition for being considered part of a dry spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a dry spell only if the accumulated precipitation within the first three days is under the threshold. In comparison, a day in the middle of the series is considered part of a dry spell if any of the three 3-day periods of which it is part are considered dry (so a total of five days are included in the computation, compared to only three).
- xclim.compute.dryness_index(pr, evspsblpot, lat=None, wo='200 mm', freq='YS')[source]
Dryness Index.
Approximation of the water balance for the categorizing the winegrowing season. Uses both precipitation and an adjustment of potential evapotranspiration between April and September (Northern Hemisphere) or October and March (Southern hemisphere). Used in calculating the Géoviticulture Multicriteria Classification System (Tonietto and Carbonneau [2004]).
- Parameters:
pr (xarray.DataArray) – Precipitation.
evspsblpot (xarray.DataArray) – Potential evapotranspiration.
lat (xarray.DataArray or {“north”, “south”}, optional) – Latitude coordinate as an array, float or string. If None, a CF-conformant “latitude” field must be available within the passed DataArray.
wo (Quantified) – The initial soil water reserve accessible to root systems [length]. Default: 200 mm.
freq ({“YS”, “YS-JAN”}) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [mm] – Dryness Index.
Warning
Dryness Index expects CF-Convention conformant potential evapotranspiration (positive up). This index is calculated using evapotranspiration and precipitation resampled and converted to monthly total accumulations, and therefore will accept monthly fluxes as inputs.
Notes
Given that this index only examines monthly total accumulations for six-month periods depending on the hemisphere, it is possible to send in DataArrays containing only these timesteps. Users should be aware that due to the missing values checks in wrapped Indicators, datasets that are missing several months will be flagged as invalid. This check can be ignored by setting the following context:
with xclim.set_options(check_missing="skip"): di = dryness_index(pr, evspsblpot)
Let \(Wo\) be the initial useful soil water reserve (typically “200 mm”), \(P\) be precipitation, \(T_{v}\) be the potential transpiration in the vineyard, and \(E_{s}\) be the direct evaporation from the soil. Then the Dryness Index, or the estimate of soil water reserve at the end of a period (1 April to 30 September in the Northern Hemispherere or 1 October to 31 March in the Southern Hemisphere), can be given by the following formulae:
\[W = \sum_{\text{April 1}}^{\text{September 30}} \left( Wo + P - T_{v} - E_{s} \right)\]or (for the Southern Hemisphere):
\[W = \sum_{\text{October 1}}^{\text{March 31}} \left( Wo + P - T_{v} - E_{s} \right)\]Where \(T_{v}\) and \(E_{s}\) are given by the following formulae:
\[T_{v} = ETP * k\]and
\[E_{s} = \frac{ETP}{N}\left( 1 - k \right) * JPm\]Where \(ETP\) is evapotranspiration, \(N\) is the number of days in the given month. \(k\) is the coefficient for radiative absorption given by the vine plant architecture, and \(JPm\) is the number of days of effective evaporation from the soil per month, both provided by the following formulae:
\[\begin{split}k = \begin{cases} 0.1, & \text{if month = April (NH) or October (SH)} \\ 0.3, & \text{if month = May (NH) or November (SH)} \\ 0.5, & \text{if month = June - September (NH) or December - March (SH)} \\ \end{cases}\end{split}\]\[JPm = \max\left( P / 5, N \right)\]References
Riou [1994], Tonietto and Carbonneau [2004]
Examples
>>> from xclim.compute import dryness_index >>> dryi = dryness_index(pr_dataset, evspsblpot_dataset, wo="200 mm")
- xclim.compute.duff_moisture_code(tas, pr, hurs, lat, snd=None, dmc0=None, season_mask=None, season_method=None, dry_start=None, initial_start_up=True, **params)[source]
Duff moisture code (FWI component).
The duff moisture code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of loosely compacted organic layers of moderate depth.
- Parameters:
tas (xr.DataArray) – Noon temperature.
pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.
hurs (xr.DataArray) – Noon relative humidity.
lat (xr.DataArray) – Latitude coordinate.
snd (xr.DataArray) – Noon snow depth.
dmc0 (xr.DataArray) – Initial values of the duff moisture code.
season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.
season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fire function. Ignored if season_mask is given.
dry_start ({None, “CFS”, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism and which method to use. See
fire_weather_ufunc().initial_start_up (bool) – If True (default), grid points where the fire season is active on the first timestep go through a start_up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.
**params (dict) – Any other keyword parameters as defined in xclim.compute.fire.fire_weather_ufunc and in
default_params.
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] – The Duff Moisture Code.
Notes
See Natural Resources Canada [n.d.], the
xclim.compute.firemodule documentation, and the docstring offire_weather_ufunc()for more information. This algorithm follows the official R code released by the Canadian Forestry Service, which contains revisions from the original 1982 Fortran code.References
Wang, Anderson, and Suddaby [2015]
- xclim.compute.effective_growing_degree_days(tasmax, tasmin, *, thresh='5 degC', method='bootsma', after_date='07-01', dim='time', freq='YS')[source]
Effective growing degree days.
Growing degree days based on a dynamic start and end of the growing season, as defined in [Bootsma and Gameda and D.W. McKenney, 2005].
- Parameters:
tasmax (xr.DataArray) – Daily mean temperature.
tasmin (xr.DataArray) – Daily minimum temperature.
thresh (Quantified) – The minimum temperature threshold.
method ({“bootsma”, “qian”}) – The window method used to determine the temperature-based start date. For “bootsma”, the start date is defined as 10 days after the average temperature exceeds a threshold. For “qian”, the start date is based on a weighted 5-day rolling average, based on :py:func`qian_weighted_mean_average`.
after_date (str) – Date of the year after which to look for the first frost event. Should have the format ‘%m-%d’.
dim (str) – Time dimension.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [K days] – Effective growing degree days (EGDD).
Notes
The effective growing degree days for a given year \(EGDD_i\) can be calculated as follows:
\[EGDD_i = \sum_{i=j_{start}}^{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.compute.extreme_temperature_range(tasmin, tasmax, freq='YS')[source]
Extreme intra-period temperature range.
The maximum of max temperature (TXx) minus the minimum of min temperature (TNn) for the given time period.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmin] – Extreme intra-period temperature range for the given time period.
Notes
Let \(TX_{ij}\) and \(TN_{ij}\) be the daily maximum and minimum temperature at day \(i\) of period \(j\). Then the extreme temperature range in period \(j\) is:
\[ETR_j = max(TX_{ij}) - min(TN_{ij})\]
- xclim.compute.fao_allen98(net_radiation, tas, wind, es, ea, delta_svp, gamma, G='0 MJ m-2 day-1')[source]
FAO-56 Penman-Monteith equation.
Estimates reference evapotranspiration from a hypothetical short grass reference surface ( height = 0.12m, surface resistance = 70 s m-1, albedo = 0.23 and a
moderately dry soil surface resulting from about a weekly irrigation frequency). Based on equation 6 in based on Allen et al. [1998].- Parameters:
net_radiation (xarray.DataArray) – Net radiation at crop surface [MJ m-2 day-1].
tas (xarray.DataArray) – Air temperature at 2 m height [degC].
wind (xarray.DataArray) – Wind speed at 2 m height [m s-1].
es (xarray.DataArray) – Saturation vapour pressure [kPa].
ea (xarray.DataArray) – Actual vapour pressure [kPa].
delta_svp (xarray.DataArray) – Slope of saturation vapour pressure curve [kPa degC-1].
gamma (xarray.DataArray or str) – Psychrometric constant [kPa deg C].
G (float, optional) – Soil heat flux (G) [MJ m-2 day-1] (For daily default to 0).
- Returns:
xarray.DataArray – Potential Evapotranspiration from a hypothetical grass reference surface [mm day-1].
References
Allen et al. [1998]
- xclim.compute.fire_season(tas, snd=None, method='WF93', freq=None, temp_start_thresh='12 degC', temp_end_thresh='5 degC', temp_condition_days=3, snow_condition_days=3, snow_thresh='0.01 m')[source]
Fire season mask.
Binary mask of the active fire season, defined by conditions on consecutive daily temperatures and, optionally, snow depths.
- Parameters:
tas (xr.DataArray) – Daily surface temperature, cffdrs recommends using maximum daily temperature.
snd (xr.DataArray, optional) – Snow depth, used with method == ‘LA08’.
method ({“WF93”, “LA08”, “GFWED”}) – Which method to use. “LA08” and “GFWED” need the snow depth.
freq (str, optional) – If given only the longest fire season for each period defined by this frequency, Every “seasons” are returned if None, including the short shoulder seasons.
temp_start_thresh (Quantified) – Minimal temperature needed to start the season. Must be scalar.
temp_end_thresh (Quantified) – Maximal temperature needed to end the season. Must be scalar.
temp_condition_days (int) – Number of days with temperature above or below the thresholds to trigger a start or an end of the fire season.
snow_condition_days (int) – Parameters for the fire season determination. See
fire_season(). Temperature is in degC, snow in m. The snow_thresh parameters is also used when dry_start is set to “GFWED”.snow_thresh (Quantified) – Minimal snow depth level to end a fire season, only used with method “LA08”. Must be scalar.
- Return type:
DataArray- Returns:
xr.DataArray – Fire season mask.
References
- xclim.compute.first_day_temperature_above(tas, thresh='0 degC', op='>', after_date='01-01', window=1, freq='YS')[source]
First day of temperatures superior to a given temperature threshold.
Returns first day of period where temperature is superior to a threshold over a given number of days (default: 1), limited to a starting calendar date (default: January 1st).
- Parameters:
tas (xarray.DataArray) – Daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
after_date (str) – Date of the year after which to look for the first event. Should have the format ‘%m-%d’.
window (int) – Minimum number of days with temperature above the threshold needed for evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Day of the year when temperature is superior to a threshold over a given number of days for the first time. If there is no such day, returns np.nan.
Warning
The default freq and after_date parameters are valid for the northern hemisphere.
Notes
Let \(x_i\) be the daily mean|max|min temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The first day above temperature threshold is given by the smallest index \(i\):
\[\prod_{j=i}^{i+w} [x_j > thresh]\]where \(w\) is the number of days the temperature threshold should be exceeded, and \([P]\) is 1 if \(P\) is true, and 0 if false.
- xclim.compute.first_day_temperature_below(tas, thresh='0 degC', op='<', after_date='07-01', window=1, freq='YS')[source]
First day of temperatures inferior to a given temperature threshold.
Returns first day of period where temperature is inferior to a threshold over a given number of days (default: 1), limited to a starting calendar date (default: July 1st).
- Parameters:
tas (xarray.DataArray) – Daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “>”.
after_date (str) – Date of the year after which to look for the first event. Should have the format ‘%m-%d’.
window (int) – Minimum number of days with temperature below the threshold needed for evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Day of the year when temperature is inferior to a threshold over a given number of days for the first time. If there is no such day, returns np.nan.
Warning
The default freq and after_date parameters are valid for the Northern Hemisphere.
- xclim.compute.first_snowfall(prsn, thresh='1 mm/day', freq='YS-JUL')[source]
First day with snowfall rate above a given threshold.
Returns the first day of a period where snowfall exceeds a threshold (default: 1 mm/day).
- Parameters:
prsn (xarray.DataArray) – Snowfall flux.
thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate. (default: 1 mm/day).
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Last day of the year where snowfall is superior to a threshold. If there is no such day, returns np.nan.
Warning
The default freq is valid for the northern hemisphere.
Notes
The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.
If the threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed, and the threshold is converted using a 1000 kg m-3 density.
References
CBCL [2020].
- xclim.compute.flow_index(q, p=0.95)[source]
Flow index.
Calculate the pth percentile of daily streamflow normalized by the median flow.
- Parameters:
q (xarray.DataArray) – Daily streamflow data.
p (float) – Percentile for calculating the flow index, between 0 and 1. Default of 0.95 is for high flows.
- Return type:
DataArray- Returns:
xarray.DataArray – Normalized Qp, which is the p th percentile of daily streamflow normalized by the median flow.
References
Clausen and Biggs [2000]
- xclim.compute.fraction_over_precip_thresh(pr, pr_per, thresh='1 mm/day', freq='YS', bootstrap=False, condition='>')[source]
Fraction of precipitation due to wet days with daily precipitation over a given percentile.
The percentage of the total precipitation over a period occurring for days when the precipitation is above a threshold defining wet days and above a given percentile for that day.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
pr_per (xarray.DataArray) – Percentile of wet day precipitation flux. Either computed daily (one value per day of year) or computed over a period (one value per spatial point).
thresh (Quantified) – Precipitation value over which a day is considered wet.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Fraction of precipitation over threshold during wet days.
- xclim.compute.frost_days(tasmin, thresh='0 degC', freq='YS')[source]
Frost days index.
Number of days where daily minimum temperatures are below a threshold temperature.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Freezing temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Frost days index.
Notes
Let \(TN_{ij}\) be the daily minimum temperature at day \(i\) of period \(j\) and :math`TT` the threshold. Then counted is the number of days where:
\[TN_{ij} < TT\]
- xclim.compute.frost_free_season_end(tasmin, thresh='0.0 degC', window=5, mid_date='07-01', op='>=', freq='YS')[source]
End of the frost-free season.
The frost-free season starts when a sequence of window consecutive days are above the threshold and ends when a sequence of consecutive days of the same length are under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, the start must occur before and the end after for the season to be valid.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
window (int) – Minimum number of days with temperature above/under the threshold to start/end the season.
mid_date (DayOfYearStr, optional) – A date what must be included in the season. None removes that constraint.
op ({“>”, “gt”, “>=”, “ge”}) – How to compare tasmin and the threshold.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Day of the year when the frost-free season starts.
Notes
Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date is given by the smallest index \(i\):
\[\prod_{k=i}^{i+w} [x_k >= thresh]\]while the end date is given bt the largest index \(j\):
\[\prod_{k=j}^{j+w} [x_k < thresh]\]where \(w\) is the number of days the temperature threshold should be exceeded/subceeded. An end is only valid if a start is also found and the end must happen later than mid_date while the start must happen earlier.
- xclim.compute.frost_free_season_length(tasmin, thresh='0.0 degC', window=5, mid_date='07-01', op='>=', freq='YS')[source]
Length of the frost-free season.
The frost-free season starts when a sequence of window consecutive days are above the threshold and ends when a sequence of consecutive days of the same length are under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, the start must occur before and the end after for the season to be valid.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
window (int) – Minimum number of days with temperature above/under the threshold to start/end the season.
mid_date (DayOfYearStr, optional) – A date what must be included in the season. None removes that constraint.
op ({“>”, “gt”, “>=”, “ge”}) – How to compare tasmin and the threshold.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Length of the frost free season.
Notes
Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date is given by the smallest index \(i\):
\[\prod_{k=i}^{i+w} [x_k >= thresh]\]while the end date is given bt the largest index \(j\):
\[\prod_{k=j}^{j+w} [x_k < thresh]\]where \(w\) is the number of days the temperature threshold should be exceeded/subceeded. An end is only valid if a start is also found and the end must happen later than mid_date while the start must happen earlier.
Examples
>>> from xclim.compute import frost_season_length >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
For the Northern Hemisphere:
>>> ffsl_nh = frost_free_season_length(tasmin, freq="YS")
If working in the Southern Hemisphere, one can use:
>>> ffsl_sh = frost_free_season_length(tasmin, freq="YS-JUL")
- xclim.compute.frost_free_season_start(tasmin, thresh='0.0 degC', window=5, mid_date='07-01', op='>=', freq='YS')[source]
Start of the frost-free season.
The frost-free season starts when a sequence of window consecutive days are above the threshold and ends when a sequence of consecutive days of the same length are under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, the start must occur before and the end after for the season to be valid.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
window (int) – Minimum number of days with temperature above/under the threshold to start/end the season.
mid_date (DayOfYearStr, optional) – A date that must be included in the season. None removes that constraint.
op ({“>”, “gt”, “>=”, “ge”}) – How to compare tasmin and the threshold.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Day of the year when the frost-free season starts.
Notes
Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date of the season is given by the smallest index \(i\):
\[\prod_{j=i}^{i+w} [x_j >= thresh]\]where \(w\) is the number of days the temperature threshold should be met or exceeded, and i must be earlier than mid_date.
- xclim.compute.frost_free_spell_max_length(tasmin, thresh='0.0 degC', window=1, freq='YS-JUL', op='>=', resample_before_rl=True)[source]
Longest frost-free spell.
Longest spell of warm temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or above the threshold.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – The temperature threshold needed to trigger a frost-free spell.
window (int) – Minimum number of days with temperatures above thresholds to qualify as a frost-free day.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} longest spell in frost-free periods of minimum {window} days.
- xclim.compute.frost_season_length(tasmin, window=5, mid_date='01-01', thresh='0.0 degC', freq='YS-JUL', op='<')[source]
Frost season length.
The number of days between the first occurrence of at least N (default: 5) consecutive days with minimum daily temperature under a threshold (default: 0℃) and the first occurrence of at least N consecutive days with minimum daily temperature above the same threshold. A mid-date can be given to limit the earliest day the end of season can take.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
window (int) – Minimum number of days with temperature below threshold to mark the beginning and end of frost season.
mid_date (str, optional) – The date must be included in the season. It is the earliest the end of the season can be.
Noneremoves that constraint.thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Frost season length.
Warning
The default freq and mid_date parameters are valid for the Northern Hemisphere.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least N consecutive days with:
\[TN_{ij} > 0 ℃\]and the first subsequent occurrence of at least N consecutive days with:
\[TN_{ij} < 0 ℃\]Examples
>>> from xclim.compute import frost_season_length >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin
For the Northern Hemisphere:
>>> fsl_nh = frost_season_length(tasmin, freq="YS-JUL")
If working in the Southern Hemisphere, one can use:
>>> fsl_sh = frost_season_length(tasmin, freq="YS")
- xclim.compute.griffiths_drought_factor(pr, smd, limiting_func='xlim')[source]
Griffiths drought factor based on the soil moisture deficit.
The drought factor is a numeric indicator of the forest fire fuel availability in the deep litter bed. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006].
- Parameters:
pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].
smd (xarray DataArray) – Daily soil moisture deficit (often KBDI) [mm/day].
limiting_func ({“xlim”, “discrete”}) – How to limit the values of the drought factor. If “xlim” (default), use equation (14) in Finkele et al. [2006]. If “discrete”, use equation Eq (13) in Finkele et al. [2006], but with the lower limit of each category bound adjusted to match the upper limit of the previous bound.
- Return type:
DataArray- Returns:
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.compute.growing_degree_days(tas, thresh='4.0 degC', freq='YS')[source]
Growing degree-days over threshold temperature value.
The sum of growing degree-days over a given mean daily temperature threshold (default: 4℃).
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time][temperature] – The sum of growing degree-days above a given threshold.
Notes
Let \(TG_{ij}\) be the mean daily temperature at day \(i\) of period \(j\). Then the growing degree days are:
\[GD4_j = \sum_{i=1}^I (TG_{ij}-{4} | TG_{ij} > {4}℃)\]
- xclim.compute.growing_season_end(tas, thresh='5.0 degC', mid_date='07-01', window=5, freq='YS', op='>')[source]
End of the growing season.
The growing season starts with the first sequence of a minimum length of consecutive days above the threshold and ends with the first sequence of the same minimum length of consecutive days under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, a start can’t happen later and an end can’t happen earlier.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
mid_date (str, optional) – Date of the year after which to look for the end of the season. Should have the format ‘%m-%d’.
Noneremoves that constraint.window (int) – Minimum number of days with temperature below threshold needed for evaluation.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”. Note that this comparison is what defines the season. The end of the season happens when the condition is NOT met for window consecutive days.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – End of the growing season.
Warning
The default freq and mid_date parameters are valid for the northern hemisphere.
Notes
Let \(x_i\) be the daily mean temperature at day of the year \(i\) for values of \(i\) going from 1 to 365 or 366. The start date of the end of growing season is given by the smallest index \(i\):
\[\prod_{j=i}^{i+w} [x_j < thresh]\]where \(w\) is the number of days where temperature should be inferior to a given threshold after a given date, and \([P]\) is 1 if \(P\) is true, and 0 if false.
- xclim.compute.growing_season_length(tas, thresh='5.0 degC', window=6, mid_date='07-01', freq='YS', op='>=')[source]
Growing season length.
The growing season starts with the first sequence of a minimum length of consecutive days above the threshold and ends with the first sequence of the same minimum length of consecutive days under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, a start can’t happen later and an end can’t happen earlier. If the season starts but never ends, the length is computed up to the end of the resampling period. If no season start is found, but the data is valid, a length of 0 is returned.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
window (int) – Minimum number of days with temperature above the threshold to mark the beginning and end of growing season.
mid_date (str, optional) – Date of the year before which the season must start and after which it can end. Should have the format ‘%m-%d’. Setting None removes that constraint.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Growing season length.
Warning
The default freq and mid_date parameters are valid for the Northern Hemisphere.
Notes
Let \(TG_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then counted is the number of days between the first occurrence of at least 6 consecutive days with:
\[TG_{ij} >= 5 ℃\]and the first occurrence after 1 July of at least six (6) consecutive days with:
\[TG_{ij} < 5 ℃\]References
Project team ECA&D and KNMI [2013]
Examples
>>> from xclim.compute import growing_season_length >>> tas = xr.open_dataset(path_to_tas_file).tas
For the Northern Hemisphere:
>>> gsl_nh = growing_season_length(tas, mid_date="07-01", freq="YS")
If working in the Southern Hemisphere, one can use:
>>> gsl_sh = growing_season_length(tas, mid_date="01-01", freq="YS-JUL")
- xclim.compute.growing_season_start(tas, thresh='5.0 degC', mid_date='07-01', window=5, freq='YS', op='>=')[source]
Start of the growing season.
The growing season starts with the first sequence of a minimum length of consecutive days above the threshold and ends with the first sequence of the same minimum length of consecutive days under the threshold. Sequences of consecutive days under the threshold shorter than window are allowed within the season. A middle date can be given, a start can’t happen later and an end can’t happen earlier.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
mid_date (str, optional) – Date of the year before which the season must start. Should have the format ‘%m-%d’.
Noneremoves that constraint.window (int) – Minimum number of days with temperature above threshold needed for evaluation.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Start of the growing season.
Warning
The default freq and mid_date parameters are valid for the northern hemisphere.
- xclim.compute.hardiness_zones(tasmin, window=30, method='usda', freq='YS')[source]
Hardiness zones.
Hardiness zones are a categorization of the annual extreme temperature minima, averaged over a certain period. The USDA method defines 14 zones, each divided into two sub-zones, using steps of 5°F, starting at -60°F. The Australian National Botanic Gardens method defines 7 zones, using steps of 5°C, starting at -15°C.
- Parameters:
tasmin (xr.DataArray) – Minimum temperature.
window (int) – The length of the averaging window, in years.
method ({“usda”, “anbg”}) – Whether to return the American (usda) or the Australian (anbg) classification zones.
freq (str) – Resampling frequency.
- Returns:
xr.DataArray, [dimensionless] – {method} hardiness zones. US sub-zones are denoted by using a half step. For example, Zone 4b is given as 4.5. Values are given at the end of the averaging window.
References
- xclim.compute.heat_index(tas, hurs)[source]
Heat index.
Perceived temperature after relative humidity is taken into account [Blazejczyk et al., 2012]. The index is only valid for temperatures above 20°C.
- Parameters:
tas (xr.DataArray) – Mean Temperature. The equation assumes an instantaneous value.
hurs (xr.DataArray) – Relative Humidity. The equation assumes an instantaneous value.
- Return type:
DataArray- Returns:
xr.DataArray, [temperature] – Heat index for moments with temperature above 20°C.
Notes
While both the Humidex and the heat index are calculated using dew point the Humidex uses a dew point of 7 °C (45 °F) as a base, whereas the heat index uses a dew point base of 14 °C (57 °F). Further, the heat index uses heat balance equations which account for many variables other than vapour pressure, which is used exclusively in the Humidex calculation.
References
Blazejczyk, Epstein, Jendritzky, Staiger, and Tinz [2012]
- xclim.compute.heat_wave_frequency(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]
Heat wave frequency.
Number of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceed specific thresholds over a minimum number of days.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (Quantified) – The minimum temperature threshold needed to trigger a heatwave event.
thresh_tasmax (Quantified) – The maximum temperature threshold needed to trigger a heatwave event.
window (int) – Minimum number of days with temperatures above thresholds to qualify as a heatwave.
freq (str) – Resampling frequency.
op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Number of heatwave at the requested frequency.
Notes
The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].
In Robinson [2001], the parameters would be
thresh_tasmin=27.22, thresh_tasmax=39.44, window=2(81F, 103F).References
- xclim.compute.heat_wave_max_length(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]
Heat wave max length.
Maximum length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceed specific thresholds over a minimum number of days.
By definition, heat_wave_max_length must be >= window.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (Quantified) – The minimum temperature threshold needed to trigger a heatwave event.
thresh_tasmax (Quantified) – The maximum temperature threshold needed to trigger a heatwave event.
window (int) – Minimum number of days with temperatures above thresholds to qualify as a heatwave.
freq (str) – Resampling frequency.
op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Maximum length of heatwave at the requested frequency.
Notes
The thresholds of 22° and 25°C for night temperatures and 30° and 35°C for day temperatures were selected by Health Canada professionals, following a temperature–mortality analysis. These absolute temperature thresholds characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].
In Robinson [2001], the parameters would be: thresh_tasmin=27.22, thresh_tasmax=39.44, window=2 (81F, 103F).
References
- xclim.compute.heat_wave_total_length(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]
Heat wave total length.
Total length of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceed specific thresholds over a minimum number of days. This is the sum of all days in such events.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh_tasmin (str) – The minimum temperature threshold needed to trigger a heatwave event.
thresh_tasmax (str) – The maximum temperature threshold needed to trigger a heatwave event.
window (int) – Minimum number of days with temperatures above thresholds to qualify as a heatwave.
freq (str) – Resampling frequency.
op ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Total length of heatwave at the requested frequency.
Notes
See notes and references of heat_wave_max_length
- xclim.compute.heating_degree_days(tas, thresh='17.0 degC', freq='YS')[source]
Heating degree days.
Sum of degree days below the temperature threshold (default: 17℃) at which spaces are heated.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time][temperature] – Heating degree days index.
Notes
This index intentionally differs from its ECA&D [Project team ECA&D and KNMI, 2013] equivalent: HD17. In HD17, values below zero are not clipped before the sum. The present definition should provide a better representation of the energy demand for heating buildings to the given threshold.
Let \(TG_{ij}\) be the daily mean temperature at day \(i\) of period \(j\). Then the heating degree days are:
\[HD17_j = \sum_{i=1}^{I} (17℃ - TG_{ij}) | TG_{ij} < 17℃)\]
- xclim.compute.heating_degree_days_approximation(tasmax, tasmin, tas, thresh='17.0 degC', freq='YS')[source]
Heating degree days approximation.
A more robust approximation of heating degree days as a function of the daily cycle of temperature.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
tasmin (xarray.DataArray) – Minimum daily temperature.
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Approximation of heating degree days.
References
Spinoni, Vogt, Barbosa, Dosio, McCormick, Bigano, and Füssel [2018]
- xclim.compute.high_flow_frequency(q, threshold_factor=9, freq='YS-OCT')[source]
High flow frequency.
Calculate the number of days in a given period with flows greater than a specified threshold, given as a multiple of the median flow. By default, the period is the water year starting on 1st October and ending on 30th September, as commonly defined in North America.
- Parameters:
q (xarray.DataArray) – Daily streamflow data.
threshold_factor (int) – Factor by which the median flow is multiplied to set the high flow threshold, default is 9.
freq (str) – Resampling frequency, default is ‘YS-OCT’ for water year starting in October and ending in September.
- Return type:
DataArray- Returns:
xarray.DataArray – Number of high flow days.
References
Addor, Nearing, Prieto, Newman, Le Vine, and Clark [2018], Clausen and Biggs [2000]
- xclim.compute.high_precip_low_temp(pr, tas, pr_thresh='0.4 mm/d', tas_thresh='-0.2 degC', freq='YS')[source]
Number of days with precipitation above threshold and temperature below threshold.
Number of days when precipitation is greater or equal to some threshold, and temperatures are colder than some threshold. This can be used for example to identify days with the potential for freezing rain or icing conditions.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
tas (xarray.DataArray) – Daily mean, minimum or maximum temperature.
pr_thresh (Quantified) – Precipitation threshold to exceed.
tas_thresh (Quantified) – Temperature threshold not to exceed.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with high precipitation and low temperatures.
Examples
To compute the number of days with intense rainfall while minimum temperatures dip below -0.2C: >>> pr = xr.open_dataset(path_to_pr_file).pr >>> tasmin = xr.open_dataset(path_to_tasmin_file).tasmin >>> hplt = high_precip_low_temp(pr, tas=tasmin, pr_thresh=”10 mm/d”, tas_thresh=”-0.2 degC”)
- xclim.compute.holiday_snow_and_snowfall_days(snd, prsn=None, snd_thresh='20 mm', prsn_thresh='1 mm', snd_condition='>=', prsn_condition='>=', date_start='12-25', date_end=None, freq='YS-JUL')[source]
Perfect Christmas Days.
Whether there is a significant amount of snow on the ground and measurable snowfall occurring on December 25th.
- Parameters:
snd (xarray.DataArray) – Surface snow depth.
prsn (xarray.DataArray) – Snowfall flux.
snd_thresh (Quantified) – Threshold snow amount. Default: 20 mm.
prsn_thresh (Quantified) – Threshold daily snowfall liquid-water equivalent thickness. Default: 1 mm.
snd_condition ({“>”, “gt”, “>=”, “ge”}) – Comparison operation for snow depth. Default: “>=”.
prsn_condition ({“>”, “gt”, “>=”, “ge”}) – Comparison operation for snowfall flux. Default: “>=”.
date_start (str) – Beginning of analysis period. Default: “12-25” (December 25th).
date_end (str, optional) – End of analysis period. If not provided, date_start is used. Default: None.
freq (str) – Resampling frequency. Default: “YS-JUL”. The default value is chosen for the northern hemisphere.
- Return type:
DataArray- Returns:
xarray.DataArray, [int] – The total number of days with snow and snowfall during the holiday.
References
- xclim.compute.holiday_snow_days(snd, snd_thresh='20 mm', condition='>=', date_start='12-25', date_end=None, freq='YS')[source]
Christmas Days.
Whether there is a significant amount of snow on the ground on December 25th (or a given date range).
- Parameters:
snd (xarray.DataArray) – Surface snow depth.
snd_thresh (Quantified) – Threshold snow amount. Default: 20 mm.
condition ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
date_start (str) – Beginning of the analysis period. Default: “12-25” (December 25th).
date_end (str, optional) – End of analysis period. If not provided, date_start is used. Default: None.
freq (str) – Resampling frequency. Default: “YS”. The default value is chosen for the northern hemisphere.
- Return type:
DataArray- Returns:
xarray.DataArray, [bool] – Boolean array of years with Christmas Days.
References
- xclim.compute.hot_days(tasmax, thresh='25 degC', freq='YS')[source]
Hot days index.
Number of days where daily maximum temperatures are above a threshold temperature.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – Threshold temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Hot days index.
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.compute.hot_spell_frequency(tasmax, thresh='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]
Hot spell frequency.
The number of hot spell events, defined as a sequence of consecutive {window} days with mean daily temperature above a {thresh}.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – Threshold temperature below which a hot spell begins.
window (int) – Minimum number of days with temperature above the threshold to qualify as a hot spell.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run.
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – The {freq} number of hot periods of minimum {window} days.
Notes
The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].
In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).
References
- xclim.compute.hot_spell_max_length(tasmax, thresh='30 degC', window=1, freq='YS', op='>', resample_before_rl=True)[source]
Longest hot spell.
Longest spell of high temperatures over a given period. Longest series of at least {window} consecutive days with temperature at or above {thresh}.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – The temperature threshold needed to trigger a hot spell.
window (int) – Minimum number of days with temperatures below thresholds to qualify as a hot spell.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} longest spell in hot periods of minimum {window} days.
Notes
The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterizes the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].
In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).
References
- xclim.compute.hot_spell_max_magnitude(tasmax, thresh='25.0 degC', window=3, freq='YS', resample_before_rl=True)[source]
Hot spell maximum magnitude.
Magnitude of the most intensive heat wave event as the sum of differences between tasmax and the given threshold for Heat Wave days, defined as three or more consecutive days over the threshold.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (xarray.DataArray) – Threshold temperature on which to designate a heatwave.
window (int) – Minimum number of days with temperature above the threshold to qualify as a heatwave.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
DataArray, [time] – Hot spell maximum magnitude.
References
Russo, Dosio, Graversen, Sillmann, Carrao, Dunbar, Singleton, Montagna, Barbola, and Vogt [2014], Zhang, She, Zhang, Wang, Chen, and Hao [2022].
- xclim.compute.hot_spell_total_length(tasmax, thresh='30 degC', window=3, freq='YS', op='>', resample_before_rl=True)[source]
Total length of hot spells.
Total length of spells of high temperatures over a given period. Total length of series of at least {window} consecutive days with temperature at or above {thresh}.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – The temperature threshold needed to trigger a hot spell.
window (int) – Minimum number of days with temperatures below the threshold to qualify as a hot spell.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} total number of days in hot periods of minimum {window} days.
Notes
The threshold on tasmax follows the one used in heat waves. A day temperature threshold between 30° and 35°C was selected by Health Canada professionals, following a temperature–mortality analysis. This absolute temperature threshold characterize the occurrence of hot weather events that can result in adverse health outcomes for Canadian communities [Casati et al., 2013].
In Robinson [2001] where heat waves are also considered, the corresponding parameters would be thresh=39.44, window=2 (103F).
- xclim.compute.huglin_index(tas, tasmax, lat=None, thresh='10 degC', method='huglin', cap_value=1.0, start_date='04-01', end_date='10-01', freq='YS')[source]
Heliothermal Index of Huglin.
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. Default: “10 degC”.
method ({“huglin”, “interpolated”, “jones”}) – The formula to use for the latitude coefficient calculation. The “huglin” method uses a stepwise latitude coefficient for values between 40° and 50° based on Huglin [1978]. The “interpolated” method uses a smoothed curve latitude coefficient for values based on the intervals set in Huglin [1978]. The “jones” method integrates axial tilt, latitude, and day-of-year based on Hall and Jones [2010].
cap_value (float) – The value to use for the latitude coefficient when latitude is above 50°N or below 50°S. Only applicable for methods “huglin” and “interpolated” (default: 1.0).
start_date (str or DayOfYearStr) – The hemisphere-based start date to consider (north = April, south = October).
end_date (str or DayOfYearStr) – The hemisphere-based start date to consider (north = October, south = April). This date is non-inclusive.
freq (str) – Resampling frequency (default: “YS”; For Southern Hemisphere, should be “YS-JUL”).
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – Heliothermal index of Huglin (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 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\]There are a few methods provided for calculating the day-length multiplication factor (\(k\)) based on latitude:
For the “huglin” and “interpolated” methods, values for k increase from 1.0 at 40°N or 40°S to 1.06 at 50°N or 50°S, where the interpolated method uses a smoothed curve and the huglin method uses a stepwise function. Values above 50°N or below 50°S are set via the cap_value variable, with 1.0 set as default. See:
xclim.compute.helpers.huglin_day_length_latitude_coefficient()for more information.For the “jones” method, A more robust day-length calculation based on latitude, calendar, day-of-year, and obliquity is used. The current implementation requires an annual frequency for consistent results. See:
xclim.compute.generic.jones_day_length_coefficient()or Hall and Jones [2010] for more information.
For compatibility with the original ICCLIM implementation [Project team ECA&D and KNMI, 2013], end_date should be set to 11-01 with method=”huglin”.
References
- xclim.compute.humidex(tas, tdps=None, hurs=None)[source]
Humidex Index.
The Humidex indicates how hot the air feels to an average person, accounting for the effect of humidity. It can be loosely interpreted as the equivalent perceived temperature when the air is dry.
- Parameters:
tas (xarray.DataArray) – Mean Temperature.
tdps (xarray.DataArray, optional) – Dewpoint Temperature, used to compute the vapour pressure.
hurs (xarray.DataArray, optional) – Relative Humidity, used as an alternative way to compute the vapour pressure if the dewpoint temperature is not available.
- Return type:
DataArray- Returns:
xarray.DataArray, [temperature] – The Humidex Index.
Notes
The humidex is usually computed using hourly observations of dry bulb and dewpoint temperatures. It is computed using the formula based on Masterton and Richardson [1979]:
\[T + {\frac {5}{9}}\left[e - 10\right]\]where \(T\) is the dry bulb air temperature (°C). The term \(e\) can be computed from the dewpoint temperature \(T_{dewpoint}\) in °K:
\[e = 6.112 \times \exp(5417.7530\left({\frac {1}{273.16}}-{\frac {1}{T_{\text{dewpoint}}}}\right)\]where the constant 5417.753 reflects the molecular weight of water, latent heat of vaporization, and the universal gas constant [Mekis et al., 2015]. Alternatively, the term \(e\) can also be computed from the relative humidity h expressed in percent using Sirangelo et al. [2020]:
\[e = \frac{h}{100} \times 6.112 * 10^{7.5 T/(T + 237.7)}.\]The humidex comfort scale [Canada, 2011] can be interpreted as follows:
20 to 29 : no discomfort;
30 to 39 : some discomfort;
40 to 45 : great discomfort, avoid exertion;
46 and over : dangerous, possible heat stroke;
Please note that while both the humidex and the heat index are calculated using dew point, the humidex uses a dew point of 7 °C (45 °F) as a base, whereas the heat index uses a dew point base of 14 °C (57 °F). Further, the heat index uses heat balance equations which account for many variables other than vapour pressure, which is used exclusively in the humidex calculation.
References
Canada [2011], Masterton and Richardson [1979], Mekis, Vincent, Shephard, and Zhang [2015], Sirangelo, Caloiero, Coscarelli, Ferrari, and Fusto [2020]
- xclim.compute.ice_days(tasmax, thresh='0 degC', freq='YS')[source]
Number of ice/freezing days.
Number of days when daily maximum temperatures are below a threshold.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – Freezing temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of ice/freezing days.
Notes
Let \(TX_{ij}\) be the daily maximum temperature at day \(i\) of period \(j\), and :math`TT` the threshold. Then counted is the number of days where:
\[TX_{ij} < TT\]
- xclim.compute.isothermality(tasmin, tasmax, freq='YS')[source]
Isothermality.
The mean diurnal temperature range divided by the annual temperature range.
- Parameters:
tasmin (xarray.DataArray) – Average daily minimum temperature at daily, weekly, or monthly frequency.
tasmax (xarray.DataArray) – Average daily maximum temperature at daily, weekly, or monthly frequency.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [%] – Isothermality.
Notes
According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.compute 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.compute.jetstream_metric_woollings(ua)[source]
Strength and latitude of jetstream.
Identify latitude and strength of maximum smoothed zonal wind speed in the region from 15 to 75°N and -60 to 0°E, using the formula outlined in [Woollings et al., 2010]. Wind is smoothened using a Lanczos filter approach.
- Parameters:
ua (xarray.DataArray) – Eastward wind component (u) at between 750 and 950 hPa.
- Return type:
tuple[DataArray,DataArray]- Returns:
jetlat (xarray.DataArray, [°]) – Daily time series of latitude of jetstream.
jetstr (xarray.DataArray, [speed]) – Daily time series of strength of jetstream.
Warning
This metric expects eastward wind component (u) to be on a regular grid (i.e. Plate Carree, 1D lat and lon)
References
Woollings, Hannachi, and Hoskins [2010]
- xclim.compute.keetch_byram_drought_index(pr, tasmax, pr_annual, kbdi0=None)[source]
Keetch-Byram drought index (KBDI) for soil moisture deficit.
The KBDI indicates the amount of water necessary to bring the soil moisture content back to field capacity. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006] but limits the maximum KBDI to 203.2 mm, rather than 200 mm, in order to align best with the majority of the literature.
- Parameters:
pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].
tasmax (xr.DataArray) – Maximum temperature near the surface over previous 24 hours [degC].
pr_annual (xr.DataArray) – Mean (over years) annual accumulated rainfall [mm/year].
kbdi0 (xr.DataArray, optional) – Previous KBDI values used to initialise the KBDI calculation [mm/day]. Defaults to 0.
- Return type:
DataArray- Returns:
xr.DataArray – Keetch-Byram drought index.
Notes
This method implements the method described in Finkele et al. [2006] (section 2.1.1) for calculating the KBDI with one small difference: in Finkele et al. [2006] the maximum KBDI is limited to 200 mm to represent the maximum field capacity of the soil (8 inches according to Keetch and Byram [1968]). However, it is more common in the literature to limit the KBDI to 203.2 mm which is a more accurate conversion from inches to mm. In this function, the KBDI is limited to 203.2 mm.
References
Dolling, Chu, and Fujioka [2005], Finkele, Mills, Beard, and Jones [2006], Holgate, Van DIjk, Cary, and Yebra [2017], Keetch and Byram [1968]
- xclim.compute.lag_snowpack_flow_peaks(snw, q, freq='YS-OCT', p=0.9)[source]
Time lag between maximum snowpack and river high flows.
Number of days between the annual maximum snowpack, measured by the surface snow amount, and the mean date when river flow exceeds a percentile threshold during a given year. If the time lag between maximum snowpack and river high flows is ≤ 50 days, the watershed is likely in a nival regime.
- Parameters:
snw (xarray.DataArray) – Surface snow amount.
q (xarray.DataArray) – Streamflow.
freq (str) – Resampling frequency. Defaults to the water year starting on the 1st of October.
p (float) – Percentile for calculating the flow index, between 0 and 1. Default of 0.9 is for high flows.
- Return type:
DataArray- Returns:
xarray.DataArray – Number of days between maximum snowpack and the circular mean date of high flow days.
See also
xclim.compute.rb_flashiness_indexRichards-Baker flashiness index.
Notes
The default
freqis the water year used in the Northern Hemisphere, from October to September.It is recommended to have at least 70% of valid data per water year in order to compute significant values.
Nival regime is characterized by a hydrological response dominated by snowmelt, where maximum flows occur shortly after peak snow cover (Burn et al., 2010).
The 50-day threshold is approximate and depends on the specific responsiveness of each watershed.
A negative value means the high flows occur before the peak snow cover.
References
Burn, Sharif, and Zhang [2010]
- xclim.compute.last_snowfall(prsn, thresh='1 mm/day', freq='YS-JUL')[source]
Last day with snowfall above a given threshold.
Returns the last day of a period where snowfall exceeds a threshold (default: 1 mm/day)
- Parameters:
prsn (xarray.DataArray) – Snowfall flux.
thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Last day of the year where snowfall is superior to a threshold. If there is no such day, returns np.nan.
Warning
The default freq is valid for the Northern Hemisphere.
Notes
The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.
If the threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed, and the threshold is converted using a 1000 kg m-3 density.
References
CBCL [2020].
- xclim.compute.last_spring_frost(tasmin, thresh='0 degC', op='<', before_date='07-01', window=1, freq='YS')[source]
Last day of temperatures inferior to a threshold temperature.
Returns last day of period where minimum temperature is inferior to a threshold over a given number of days (default: 1) and limited to a final calendar date (default: July 1st).
- Parameters:
tasmin (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
before_date (str,) – Date of the year before which to look for the final frost event. Should have the format ‘%m-%d’.
window (int) – Minimum number of days with temperature below the threshold needed for evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Day of the year when temperature is inferior to a threshold over a given number of days for the first time. If there is no such day, returns np.nan.
Warning
The default freq and before_date parameters are valid for the Northern Hemisphere.
- xclim.compute.latitude_temperature_index(tas, lat=None, lat_factor=75, freq='YS')[source]
Latitude-Temperature Index.
Mean temperature of the warmest month with a latitude-based scaling factor [Jackson and Cherry, 1988]. Used for categorizing wine-growing regions.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
lat (xarray.DataArray, optional) – Latitude coordinate. If None, a CF-conformant “latitude” field must be available within the passed DataArray.
lat_factor (float) – Latitude factor. Maximum poleward latitude. Default: 75.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – Latitude Temperature Index.
Notes
The latitude factor of 75 is provided for examining the poleward expansion of wine-growing climates under scenarios of climate change [Kenny and Shao, 1992]. For comparing 20th century/observed historical records, the original scale factor of 60 is more appropriate [Jackson and Cherry, 1988].
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.compute.liquid_precip_ratio(pr, prra=None, prsn=None, tas=None, thresh='0 degC', freq='QS-DEC')[source]
Ratio of rainfall to total precipitation.
The ratio of total liquid precipitation over the total precipitation. If liquid precipitation is not provided, it can be estimated with the solid precipitation, or it is approximated with pr, tas and thresh, using the
rain_approximation()function with method ‘binary’.- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
prra (xarray.DataArray, optional) – Mean daily liquid precipitation flux.
prsn (xarray.DataArray, optional) – Mean daily solid precipitation flux.
tas (xarray.DataArray, optional) – Mean daily temperature.
thresh (Quantified) – Threshold temperature under which precipitation is assumed to be solid.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Ratio of rainfall to total precipitation.
See also
winter_rain_ratioThe ratio of rainfall to total precipitation during winter.
Notes
Let \(PR_i\) be the mean daily precipitation on day \(i\), and \(PRSN_i\) the mean daily solid precipitation. For a period \(j\) starting on day \(a\) and ending on day \(b\):
\[PR_{j} = \sum_{i=a}^{b} PR_i\]\[PR^{\mathrm{liquid}}_{j} = \sum_{i=a}^{b} (PR_i - PRSN_i)\]The liquid precipitation ratio is then:
\[R_j = \frac{PR^{\mathrm{liquid}}_{j}}{PR_j}\]
- xclim.compute.longwave_upwelling_radiation_from_net_downwelling(rls, rlds)[source]
Calculate upwelling thermal radiation from net thermal radiation and downwelling thermal radiation.
- Parameters:
rls (xr.DataArray) – Surface net thermal radiation.
rlds (xr.DataArray) – Surface downwelling thermal radiation.
- Return type:
DataArray- Returns:
xr.DataArray, [same units as rlds] – Surface upwelling thermal radiation (rlus).
- xclim.compute.low_flow_frequency(q, threshold_factor=0.2, freq='YS-OCT')[source]
Low flow frequency.
Calculate the number of days in a given period with flows lower than a specified threshold, given by a fraction of the mean flow. By default, the period is the water year starting on 1st October and ending on 30th September, as commonly defined in North America.
- Parameters:
q (xarray.DataArray) – Daily streamflow data.
threshold_factor (float) – Factor by which the mean flow is multiplied to set the low flow threshold, default is 0.2.
freq (str) – Resampling frequency, default is ‘YS-OCT’ for water year starting in October and ending in September.
- Return type:
DataArray- Returns:
xarray.DataArray – Number of low flow days.
References
Olden and Poff [2003]
- xclim.compute.max_1day_precipitation_amount(pr, freq='YS')[source]
Highest 1-day precipitation amount for a period (frequency).
Resample the original daily total precipitation temperature series by taking the max over each period.
- Parameters:
pr (xarray.DataArray) – Daily precipitation values.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as pr] – The highest 1-period precipitation flux value at the given time frequency.
Notes
Let \(PR_i\) be the mean daily precipitation of day i, then for a period j:
\[PRx_{ij} = max(PR_{ij})\]Examples
The following would compute for each grid cell the highest 1-day total at an annual frequency:
>>> from xclim.compute import max_1day_precipitation_amount >>> pr = xr.open_dataset(path_to_pr_file).pr >>> rx1day = max_1day_precipitation_amount(pr, freq="YS")
- xclim.compute.max_n_day_precipitation_amount(pr, window=1, freq='YS', **indexer)[source]
Highest precipitation amount cumulated over a n-day moving window.
Calculate the n-day rolling sum of the original daily total precipitation series and determine the maximum value over each period.
- Parameters:
pr (xarray.DataArray) – Daily precipitation values.
window (int) – Window size in days.
freq (str) – Resampling frequency.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. The subset is taken after the N-day sum, thus including data from up to
window -1days before the selected period (and none after). It accepts the same arguments asxclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray, [length] – The highest cumulated n-period precipitation value at the given time frequency.
Examples
The following would compute for each grid cell the highest 5-day total precipitation at an annual frequency:
>>> from xclim.compute 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.compute.max_pr_intensity(pr, window=1, freq='YS', **indexer)[source]
Highest precipitation intensity over a n-hour moving window.
Calculate the n-hour rolling average of the original hourly total precipitation series and determine the maximum value over each period.
- Parameters:
pr (xarray.DataArray) – Hourly precipitation values.
window (int) – Window size in hours.
freq (str) – Resampling frequency.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. The subset is taken after the N-hour average, thus including data from up to
window - 1hours before the selected period, and none after. It accepts the same arguments asxclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as pr] – The highest cumulated n-hour precipitation intensity at the given time frequency.
Examples
The following would compute the maximum 6-hour precipitation intensity at an annual frequency:
>>> from xclim.compute import max_pr_intensity >>> pr = xr.open_dataset(path_to_pr_file).pr >>> out = max_pr_intensity(pr, window=5, freq="YS")
- xclim.compute.maximum_consecutive_dry_days(pr, thresh='1 mm/day', op='<', freq='YS', resample_before_rl=True)[source]
Maximum number of consecutive dry days.
Return the longest spell with precipitation under a given threshold.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
thresh (Quantified) – Threshold precipitation on which to base evaluation.
op ({“<”, “<=”}) – Comparison operator to use to find wet days.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – The maximum number of consecutive dry days.
- xclim.compute.maximum_consecutive_wet_days(pr, thresh='1 mm/day', op='>=', freq='YS', resample_before_rl=True)[source]
Maximum number of consecutive wet days.
Returns the longest spell of with precipitation above a given threshold.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
thresh (Quantified) – Threshold precipitation on which to base evaluation.
op ({“>”, “>=”}) – Comparison operator to use to find wet days.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – The maximum number of consecutive wet days.
- xclim.compute.mcarthur_forest_fire_danger_index(drought_factor, tasmax, hurs, sfcWind)[source]
McArthur forest fire danger index (FFDI) Mark 5.
The FFDI is a numeric indicator of the potential danger of a forest fire.
- Parameters:
drought_factor (xr.DataArray) – The drought factor, often the daily Griffiths drought factor (see
griffiths_drought_factor()).tasmax (xr.DataArray) – The daily maximum temperature near the surface, or similar. Different applications have used different inputs here, including the previous/current day’s maximum daily temperature at a height of 2m, and the daily mean temperature at a height of 2m.
hurs (xr.DataArray) – The relative humidity near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon relative humidity at a height of 2m, and the daily mean relative humidity at a height of 2m.
sfcWind (xr.DataArray) – The wind speed near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon wind speed at a height of 10m, and the daily mean wind speed at a height of 10m.
- Returns:
xr.DataArray – The McArthur forest fire danger index.
References
Dowdy [2018], Holgate, Van DIjk, Cary, and Yebra [2017], Noble, Gill, and Bary [1980]
- xclim.compute.mean_radiant_temperature(rsds, rsus, rlds, rlus, stat='sunlit')[source]
Mean radiant temperature.
The mean radiant temperature is the incidence of radiation on the body from all directions.
- Parameters:
rsds (xr.DataArray) – Surface Downwelling Shortwave Radiation.
rsus (xr.DataArray) – Surface Upwelling Shortwave Radiation.
rlds (xr.DataArray) – Surface Downwelling Longwave Radiation.
rlus (xr.DataArray) – Surface Upwelling Longwave Radiation.
stat ({‘instant’, ‘sunlit’}) – Which statistic to apply. If “instant”, the instantaneous cosine of the solar zenith angle is calculated. If “sunlit”, the cosine of the solar zenith angle is calculated during the sunlit period of each interval.
- Return type:
DataArray- Returns:
xarray.DataArray, [K] – Mean Radiant Temperature.
Warning
There are some issues in the calculation of mrt in extreme polar regions.
Notes
This code was inspired by the thermofeel package [Brimicombe et al., 2021].
References
Di Napoli, Hogan, and Pappenberger [2020]
- xclim.compute.melt_and_precip_max(snw, pr, window=3, freq='YS-JUL')[source]
Maximum snow melt and precipitation.
The maximum snow melt plus precipitation over a given number of days expressed in snow water equivalent.
- Parameters:
snw (xarray.DataArray) – Snow amount (mass per area).
pr (xarray.DataArray) – Daily precipitation flux.
window (int) – Number of days during which the water input is accumulated.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The maximum snow melt plus precipitation over a given number of days for each period. [mass/area].
- xclim.compute.multiday_temperature_swing(tasmin, tasmax, thresh_tasmin='0 degC', thresh_tasmax='0 degC', window=1, statistic='mean', condition_tasmin='<=', condition_tasmax='>', freq='YS', resample_before_rl=True, **indexer)[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 index 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.
statistic ({“mean”, “sum”, “max”, “min”, “std”, “count”}) – The statistical operation to use when reducing the list of spell lengths.
condition_tasmin ({“<”, “<=”, “lt”, “le”}) – Comparison operation for tasmin. Default: “<=”.
condition_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.
**indexer ({dim: indexer, }, optional) – Time attribute and values over which to subset the array. See
xclim.core.calendar.select_time(). Subsetting is done after finding the events, but before computing the statistic over them.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – {freq} {condition} 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 function returns a given statistic of the found lengths, optionally dropping those shorter than window. For example, window=1 and statistic=’sum’ returns the same value as
daily_freezethaw_cycles().
- xclim.compute.potential_evapotranspiration(tasmin=None, tasmax=None, tas=None, lat=None, hurs=None, rsds=None, rsus=None, rlds=None, rlus=None, sfcWind=None, pr=None, method='BR65', peta=0.00516409319477, petb=0.0874972822289)[source]
Potential evapotranspiration.
The potential for water evaporation from soil and transpiration by plants if the water supply is sufficient, according to a given method.
- Parameters:
tasmin (xarray.DataArray, optional) – Minimum daily Temperature.
tasmax (xarray.DataArray, optional) – Maximum daily Temperature.
tas (xarray.DataArray, optional) – Mean daily Temperature.
lat (xarray.DataArray, optional) – Latitude. If not provided, it is sought on tasmin or tas using cf-xarray accessors.
hurs (xarray.DataArray, optional) – Relative Humidity.
rsds (xarray.DataArray, optional) – Surface Downwelling Shortwave Radiation.
rsus (xarray.DataArray, optional) – Surface Upwelling Shortwave Radiation.
rlds (xarray.DataArray, optional) – Surface Downwelling Longwave Radiation.
rlus (xarray.DataArray, optional) – Surface Upwelling Longwave Radiation.
sfcWind (xarray.DataArray, optional) – Surface Wind Velocity (at 10 m).
pr (xarray.DataArray) – Mean daily Precipitation Flux.
method ({“baierrobertson65”, “BR65”, “hargreaves85”, “HG85”, “thornthwaite48”, “TW48”, “mcguinnessbordne05”, “MB05”, “allen98”, “FAO_PM98”, “droogersallen02”, “DA02”}) – Which method to use, see Notes.
peta (float) – Used only with method MB05 as \(a\) for calculation of PET, see Notes section. Default value resulted from calibration of PET over the UK.
petb (float) – Used only with method MB05 as \(b\) for calculation of PET, see Notes section. Default value resulted from calibration of PET over the UK.
- Return type:
DataArray- Returns:
xarray.DataArray – Potential Evapotranspiration.
Notes
Available methods are:
“baierrobertson65” or “BR65”, based on Baier and Robertson [1965]. Requires tasmin and tasmax, daily [D] freq.
“hargreaves85” or “HG85”, based on George H. Hargreaves and Zohrab A. Samani [1985]. Requires tasmin and tasmax, daily [D] freq. (optional: tas can be given in addition of tasmin and tasmax).
“mcguinnessbordne05” or “MB05”, based on Tanguy et al. [2018]. Requires tas, daily [D] freq, with latitudes ‘lat’.
“thornthwaite48” or “TW48”, based on Thornthwaite [1948]. Requires tasmin and tasmax, monthly [MS] or daily [D] freq. (optional: tas can be given instead of tasmin and tasmax).
“allen98” or “FAO_PM98”, based on Allen et al. [1998]. Modification of Penman-Monteith method. Requires tasmin and tasmax, relative humidity, radiation flux and wind speed (10 m wind will be converted to 2 m).
“droogersallen02” or “DA02”, based on Droogers and Allen [2002]. Requires tasmin, tasmax and precipitation, monthly [MS] or daily [D] freq. (optional: tas can be given in addition of tasmin and tasmax).
The McGuinness-Bordne [McGuinness and Borone, 1972] equation is:
\[PET[mm day^{-1}] = a * \frac{S_0}{\lambda}T_a + b * \frac{S_0}{\lambda}\]where \(a\) and \(b\) are empirical parameters; \(S_0\) is the extraterrestrial radiation [MJ m-2 day-1], assuming a solar constant of 1367 W m-2; \(\\lambda\) is the latent heat of vaporisation [MJ kg-1] and \(T_a\) is the air temperature [°C]. The equation was originally derived for the USA, with \(a=0.0147\) and \(b=0.07353\). The default parameters used here are calibrated for the UK, using the method described in Tanguy et al. [2018].
Methods “BR65”, “HG85”, “MB05” and “DA02” use an approximation of the extraterrestrial radiation. See
extraterrestrial_solar_radiation().References
Allen, Pereira, Raes, and Smith [1998], Baier and Robertson [1965], Droogers and Allen [2002], McGuinness and Borone [1972], Tanguy, Prudhomme, Smith, and Hannaford [2018], Thornthwaite [1948], George H. Hargreaves and Zohrab A. Samani [1985]
- xclim.compute.prcptot(pr, thresh='0 mm/d', freq='YS')[source]
Accumulated total precipitation.
The total accumulated precipitation from days where precipitation exceeds a given amount. A threshold is provided to allow the option of reducing the impact of days with trace precipitation amounts on period totals.
- Parameters:
pr (xarray.DataArray) – Total precipitation flux [mm d-1], [mm week-1], [mm month-1] or similar.
thresh (str) – Threshold over which precipitation starts being cumulated.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [length] – Total {freq} precipitation.
- xclim.compute.prcptot_warmcold_quarter(pr, tas, op, freq='YS')[source]
Total precipitation of warmest/coldest quarter.
The warmest (or coldest) quarter of the year is determined, and the total precipitation of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”), quarters are defined as 13-week periods, otherwise as three (3) months.
- Parameters:
pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency.
tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.
op ({“warmest”, “coldest”}) – Operation to perform: “warmest” calculates for the warmest quarter; “coldest” calculates for the coldest quarter.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [mm] – Precipitation of {op} quarter.
Notes
According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.compute 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.compute.prcptot_wetdry_period(pr, *, op, freq='YS')[source]
Precipitation of the wettest/driest day, week, or month, depending on the time step.
The wettest (or driest) period is determined, and the total precipitation of this period is calculated.
- Parameters:
pr (xarray.DataArray) – Total precipitation flux [mm d-1], [mm week-1], [mm month-1] or similar.
op ({“wettest”, “driest”}) – Operation to perform: “wettest” calculates the wettest quarter. “driest” calculates the driest quarter.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [length] – Precipitation of {op} period.
Notes
According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.compute 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.compute.prcptot_wetdry_quarter(pr, op, freq='YS')[source]
Total precipitation of wettest/driest quarter.
The wettest (or driest) quarter of the year is determined, and the total precipitation of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”) quarters are defined as 13-week periods, otherwise as three (3) months.
- Parameters:
pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency.
op ({“wettest”, “driest”}) – Operation to perform: ‘wettest’ calculates the wettest quarter. ‘driest’ calculates the driest quarter.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [length] – Precipitation of {op} quarter.
Notes
According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.compute implementation here will calculate the result with input data with daily frequency as well. As such, weekly or monthly input values, if desired, should be calculated before calling the function.
References
Xu and Hutchinson [2010]
Examples
The following would compute for each grid cell of file pr.day.nc the annual wettest quarter total precipitation:
>>> from xclim.compute import prcptot_wetdry_quarter >>> p = xr.open_dataset(path_to_pr_file) >>> pr_warm_qrt = prcptot_wetdry_quarter(pr=p.pr, op="wettest")
- xclim.compute.precip_accumulation(pr, tas=None, phase=None, thresh='0 degC', freq='YS')[source]
Accumulated total (liquid and/or solid) precipitation.
Resample the original daily mean precipitation flux and accumulate over each period. If a daily temperature is provided, the phase keyword can be used to sum precipitation of a given phase only. When the temperature is under the given threshold, precipitation is assumed to be snow, and liquid rain otherwise. This index is agnostic to the type of daily temperature (tas, tasmax or tasmin) given.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
tas (xarray.DataArray, optional) – Mean, maximum or minimum daily temperature.
phase ({None, ‘liquid’, ‘solid’}) – Which phase to consider, “liquid” or “solid”, if None (default), both are considered.
thresh (Quantified) – Threshold of tas over which the precipication is assumed to be liquid rain.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [length] – The total daily precipitation at the given time frequency for the given phase.
Notes
Let \(PR_i\) be the mean daily precipitation of day \(i\), then for a period \(j\) starting at day \(a\) and finishing on day \(b\):
\[PR_{ij} = \sum_{i=a}^{b} PR_i\]If tas and phase are given, the corresponding phase precipitation is estimated before computing the accumulation, using one of snowfall_approximation or rain_approximation with the binary method.
Examples
The following would compute, for each grid cell of a dataset, the total precipitation at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import precip_accumulation >>> pr_day = xr.open_dataset(path_to_pr_file).pr >>> prcp_tot_seasonal = precip_accumulation(pr_day, freq="QS-DEC")
- xclim.compute.precip_average(pr, tas=None, phase=None, thresh='0 degC', freq='YS')[source]
Averaged (liquid and/or solid) precipitation.
Resample the original daily mean precipitation flux and average over each period. If a daily temperature is provided, the phase keyword can be used to average precipitation of a given phase only. When the temperature is under the given threshold, precipitation is assumed to be snow, and liquid rain otherwise. This index is agnostic to the type of daily temperature (tas, tasmax or tasmin) given.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
tas (xarray.DataArray, optional) – Mean, maximum or minimum daily temperature.
phase ({None, ‘liquid’, ‘solid’}) – Which phase to consider, “liquid” or “solid”, if None (default), both are considered.
thresh (Quantified) – Threshold of tas over which the precipication is assumed to be liquid rain.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [length] – The averaged daily precipitation at the given time frequency for the given phase.
Notes
Let \(PR_i\) be the mean daily precipitation of day \(i\), then for a period \(j\) starting at day \(a\) and finishing on day \(b\):
\[PR_{ij} =\frac{ \sum_{i=a}^{b} PR_i }{b - a + 1}\]If tas and phase are given, the corresponding phase precipitation is estimated before computing the accumulation, using one of snowfall_approximation or rain_approximation with the binary method.
Examples
The following would compute, for each grid cell of a dataset, the total precipitation at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import precip_average >>> pr_day = xr.open_dataset(path_to_pr_file).pr >>> prcp_tot_seasonal = precip_average(pr_day, freq="QS-DEC")
- xclim.compute.precip_seasonality(pr, freq='YS')[source]
Precipitation Seasonality (C of V).
The annual precipitation Coefficient of Variation (C of V) expressed in percent. Calculated as the standard deviation of precipitation values for a given year expressed as a percentage of the mean of those values.
- Parameters:
pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency. Units need to be defined as a rate (e.g. mm d-1, mm week-1).
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [%] – Precipitation coefficient of variation.
Notes
According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.compute 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.compute.precipitation_concentration_index(pr, freq='YS', subfreq='MS')[source]
Precipitation Concentration Index.
A measure of the unevenness of precipitation distribution within a period. Computed as the ratio of the sum of squared sub-period totals to the square of the sum of sub-period totals, multiplied by 100 [Oliver, 1980].
- Parameters:
pr (xr.DataArray) – Precipitation flux or rate, with units convertible to a precipitation unit (e.g.
"mm/day").freq (str) – Resampling frequency for the output (main period). Default is
"YS"(yearly).subfreq (str) – Resampling frequency for computing sub-period totals. Default is
"MS"(monthly).
- Return type:
DataArray- Returns:
xr.DataArray, [%] – Precipitation Concentration Index for each period defined by freq.
Notes
The precipitation concentration index (PCI) can be calculated as follows:
\[PCI = \frac{\sum_{i=1}^{n} p_i^2}{\left(\sum_{i=1}^{n} p_i\right)^2} \times 100\]where \(p_i\) is the precipitation total for sub-period \(i\) and \(n\) is the number of sub-periods per main period.
A PCI of 8.3 (i.e. \(100/n\)) indicates perfectly uniform precipitation. Higher values indicate increasing concentration. Values above ~20 indicate a highly irregular or seasonal distribution.
References
Oliver [1980]
- xclim.compute.prsn_to_prsnd(prsn, snr=None, const='100 kg m-3', out_units=None)[source]
Snowfall rate from snowfall flux and density.
- Parameters:
prsn (xr.DataArray) – Snowfall Flux.
snr (xr.DataArray, optional) – Snow Density.
const (Quantified) – Constant snow density. const is only used if snr is None.
out_units (str, optional) – Desired units of the snowfall rate. If None, output units simply follow from snd * snr.
- Return type:
DataArray- Returns:
xr.DataArray – Snowfall Rate.
Notes
The estimated mean snow density value of 100 kg m-3 is taken from Frei, Kotlarski, Liniger, and Schär [2018], CBCL [2020].
References
- xclim.compute.prsnd_to_prsn(prsnd, snr=None, const='100 kg m-3', out_units=None)[source]
Snowfall flux from snowfall rate and density.
- Parameters:
prsnd (xr.DataArray) – Snowfall Rate.
snr (xr.DataArray, optional) – Snow Density.
const (Quantified) – Constant Snow Density. const is only used if snr is None.
out_units (str, optional) – Desired units of the snowfall rate. If None, output units simply follow from snd * snr.
- Return type:
DataArray- Returns:
xr.DataArray – Snowfall Flux.
Notes
The estimated mean snow density value of 100 kg m-3 is taken from Frei, Kotlarski, Liniger, and Schär [2018], CBCL [2020].
References
- xclim.compute.qian_weighted_mean_average(tas, dim='time')[source]
Binomial smoothed, five-day weighted mean average temperature.
Calculates a five-day weighted moving average with emphasis on temperatures closer to day of interest.
- Parameters:
tas (xr.DataArray) – Daily mean temperature.
dim (str) – Time dimension. Default: “time”.
- Return type:
DataArray- Returns:
xr.DataArray, [same as tas] – Binomial smoothed, five-day weighted mean average temperature.
Notes
Qian Modified Weighted Mean index 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.compute.rain_approximation(pr, tas, thresh='0 degC', method='binary', clip_temp=None, landmask=True)[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’. Ignored for the
'dai_*'methods.method ({“binary”, “brown”, “auer”, “dai_annual”, “dai_seasonal”}) – Which method to use when approximating snowfall from total precipitation. See notes.
clip_temp (Quantified) – For methods “dai_annual” and “dai_seasonal”, this is an optional temperature delta at which the snowfall fraction function rescaled to 0 or 1. See notes.
landmask (DataArray or bool) – For methods “dai_annual” and “dai_seasonal”, this is the land mask, a DataArray without a time dimension that is True on land grid points and False on ocean grid points. Can also be True or False to use one or the other coefficients set for all points. Default is to consider all points as land.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as pr] – Liquid precipitation rate.
See also
snowfall_approximationSnowfall approximation from total precipitation and temperature.
Notes
For methods “binary”, “brown” and “auer”, this method computes the snowfall approximation and subtracts it from the total precipitation to estimate the liquid rain precipitation. See
snowfall_approximation`().For the “dai_*”, methods, the rain fraction evolves according to an hyperbolic tangent function that has different parameters for precipitation over land or ocean. The snow and rain fraction do not add to 1. Rather, the remainder can be associated to a “sleet” fraction.
If
clip_tempis given, its value $$T_c$$ (in °C) is used to rescale (and then clip) the rain fraction function $$f(T)$$ as $$(f(T) - f(-T_c))/(f(T_c) - f(-T_c))$$, so that it is 0 when $$T < -T_c$$ and 1 when $$T > T_c$$.The “dai_seasonal” method has different parameters for each season. The “annual” coefficients are taken over ocean in summer. These methods are implemented from [Dai, 2008] (
clip_tempis an addition from the xclim team).References
- xclim.compute.rain_on_frozen_ground_days(pr, tas, thresh='1 mm/d', window=7, freq='YS')[source]
Number of rain on frozen ground events.
Number of days with rain above a threshold after a series of consecutive days below freezing temperature. Precipitation is assumed to be rain when the temperature is above 0℃.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Precipitation threshold to consider a day as a rain event.
window (int) – Minimum number of days below freezing temperature needed to consider the ground frozen.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – The number of rain on frozen ground events per period.
Notes
Let \(PR_i\) be the mean daily precipitation and \(TG_i\) be the mean daily temperature of day \(i\). Then for a period \(j\), rain on frozen grounds days are counted where:
\[PR_{i} > Threshold [mm]\]and where
\[TG_{i} ≤ 0℃\]is true for continuous periods where \(i ≥ window\)
- xclim.compute.rain_season(pr, thresh_wet_start='25.0 mm', window_wet_start=3, window_not_dry_start=30, thresh_dry_start='1.0 mm', window_dry_start=7, method_dry_start='per_day', date_min_start='05-01', date_max_start='12-31', thresh_dry_end='0.0 mm', window_dry_end=20, method_dry_end='per_day', date_min_end='09-01', date_max_end='12-31', freq='YS-JAN')[source]
Find the length of the rain season and the day of year of its start and its end.
The rain season begins when two conditions are met: 1) There must be a number of wet days with precipitations above or equal to a given threshold; 2) There must be another sequence following, where, for a given period in time, there are no dry sequence (i.e. a certain number of days where precipitations are below or equal to a certain threshold). The rain season ends when there is a dry sequence.
- Parameters:
pr (xr.DataArray) – Precipitation data.
thresh_wet_start (Quantified) – Accumulated precipitation threshold associated with window_wet_start.
window_wet_start (int) – Number of days when accumulated precipitation is above thresh_wet_start. Defines the first condition to start the rain season.
window_not_dry_start (int) – Number of days, after window_wet_start days, during which no dry period must be found as a second and last condition to start the rain season. A dry sequence is defined with thresh_dry_start, window_dry_start and method_dry_start.
thresh_dry_start (Quantified) – Threshold length defining a dry day in the sequence related to window_dry_start.
window_dry_start (int) – Number of days used to define a dry sequence in the start of the season. Daily precipitations lower than thresh_dry_start during window_dry_start days are considered a dry sequence. The precipitations must be lower than thresh_dry_start for either every day in the sequence (method_dry_start == “per_day”) or for the total (method_dry_start == “total”).
method_dry_start ({“per_day”, “total”}) – Method used to define a dry sequence associated with window_dry_start. The threshold thresh_dry_start is either compared to every daily precipitation (method_dry_start == “per_day”) or to total precipitations (method_dry_start == “total”) in the sequence window_dry_start days.
date_min_start (DayOfYearStr) – First day of year when season can start (“mm-dd”).
date_max_start (DayOfYearStr) – Last day of year when season can start (“mm-dd”).
thresh_dry_end (str) – Threshold length defining a dry day in the sequence related to window_dry_end.
window_dry_end (int) – Number of days used to define a dry sequence in the end of the season. Daily precipitations lower than thresh_dry_end during window_dry_end days are considered a dry sequence. The precipitations must be lower than thresh_dry_end for either every day in the sequence (method_dry_end == “per_day”) or for the total (method_dry_end == “total”).
method_dry_end ({“per_day”, “total”}) – Method used to define a dry sequence associated with window_dry_end. The threshold thresh_dry_end is either compared to every daily precipitation (method_dry_end == “per_day”) or to total precipitations (method_dry_end == “total”) in the sequence window_dry days.
date_min_end (DayOfYearStr) – First day of year when season can end (“mm-dd”).
date_max_end (DayOfYearStr) – Last day of year when season can end (“mm-dd”).
freq (str) – Resampling frequency.
- Return type:
tuple[DataArray,DataArray,DataArray]- Returns:
rain_season_start (xr.DataArray, [dimensionless]) – The beginning of the rain season.
rain_season_end (xr.DataArray, [dimensionless]) – The end of the rain season.
rain_season_length (xr.DataArray, [time]) – The length of the rain season.
Notes
The rain season starts at the end of a period of raining (a total precipitation of thresh_wet_start over window_wet_start days). This must be directly followed by a period of window_not_dry_start days with no dry sequence. The dry sequence is a period of window_dry_start days where precipitations are below thresh_dry_start (either the total precipitations over the period, or the daily precipitations, depending on method_dry_start). The rain season stops when a dry sequence happens (the dry sequence is defined as in the start sequence, but with parameters window_dry_end, thresh_dry_end and method_dry_end). The dates on which the season can start are constrained by date_min_start`and `date_max_start (and similarly for the end of the season).
References
Sivakumar [1988]
- xclim.compute.rb_flashiness_index(q, freq='YS')[source]
Richards-Baker flashiness index.
Measures oscillations in flow relative to total flow, quantifying the frequency and rapidity of short term changes in flow, based on Baker et al. [2004].
- Parameters:
q (xarray.DataArray) – Rate of river discharge.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – R-B Index.
Notes
Let \(\mathbf{q}=q_0, q_1, \ldots, q_n\) be the sequence of daily discharge, the R-B Index is given by:
\[\frac{\sum_{i=1}^n |q_i - q_{i-1}|}{\sum_{i=1}^n q_i}\]References
Baker, Richards, Loftus, and Kramer [2004]
- xclim.compute.relative_humidity(tas, tdps=None, huss=None, ps=None, ice_thresh=None, method='sonntag90', interp_power=None, water_thresh='0 °C', invalid_values='clip')[source]
Relative humidity.
Compute relative humidity from temperature and either dewpoint temperature or specific humidity and pressure through the saturation vapour pressure.
- Parameters:
tas (xr.DataArray) – Mean Temperature.
tdps (xr.DataArray, optional) – Dewpoint Temperature. If specified, overrides huss and ps.
huss (xr.DataArray, optional) – Specific Humidity. Must be given if tdps is not given.
ps (xr.DataArray, optional) – Air Pressure. Must be given if tdps is not given.
ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water. Does nothing if ‘method’ is “bohren98”.
method ({“bohren98”, “goffgratch46”, “sonntag90”, “tetens30”, “wmo08”, “ecmwf”}) – Which method to use, see notes of this function and of
saturation_vapor_pressure().interp_power (int or None) – Optional interpolation for mixing saturation vapour pressures computed over water and ice. See
saturation_vapor_pressure().water_thresh (Quantified) – When
interp_poweris given, this is the threshold temperature above which the formulas with reference to water are used.invalid_values ({“clip”, “mask”, None}) – What to do with values outside the 0-100 range. If “clip” (default), clips everything to 0 - 100, if “mask”, replaces values outside the range by np.nan, and if None, does nothing.
- Return type:
DataArray- Returns:
xr.DataArray, [%] – Relative Humidity.
Notes
In the following, let \(T\), \(T_d\), \(q\) and \(p\) be the temperature, the dew point temperature, the specific humidity and the air pressure.
For the “bohren98” method : This method does not use the saturation vapour pressure directly, but rather uses an approximation of the ratio of \(\frac{e_{sat}(T_d)}{e_{sat}(T)}\). With \(L\) the enthalpy of vaporization of water and \(R_w\) the gas constant for water vapour, the relative humidity is computed as:
\[RH = e^{\frac{-L (T - T_d)}{R_wTT_d}}\]From Bohren and Albrecht [1998], formula taken from Lawrence [2005]. \(L = 2.5\times 10^{-6}\) J kg-1, exact for \(T = 273.15\) K, is used.
Other methods: With \(w\), \(w_{sat}\), \(e_{sat}\) the mixing ratio, the saturation mixing ratio and the saturation vapour pressure. If the dewpoint temperature is given, relative humidity is computed as:
\[RH = 100\frac{e_{sat}(T_d)}{e_{sat}(T)}\]Otherwise, the specific humidity and the air pressure must be given so relative humidity can be computed as the ratio of actual vapor pressure to saturation vapor pressure:
\[RH = 100\frac{P_w}{P_{wsat}} P_w = \frac{pq}{\epsilon\left(1 + q\left(\frac{1}{\epsilon} - 1\right)\right)} \epsilon = 0.62198\]The methods differ by how \(P_{wsat}\) is computed. See the doc of
saturation_vapor_pressure()andvapor_pressure(). This equation for RH is the same as eq. 4.A.15 of [World Meteorological Organization, 2008] and differs very slightly from MetPy which uses 4.A.16 by computing the mixing ratios first.References
Bohren and Albrecht [1998], Lawrence [2005]
Examples
>>> from xclim.compute import relative_humidity >>> rh = relative_humidity( ... tas=tas_dataset, ... tdps=tdps_dataset, ... huss=huss_dataset, ... ps=ps_dataset, ... ice_thresh="0 degC", ... method="wmo08", ... invalid_values="clip", ... )
- xclim.compute.rprctot(pr, prc, thresh='1.0 mm/day', freq='YS', op='>=')[source]
Proportion of accumulated precipitation arising from convective processes.
Return the proportion of total accumulated precipitation due to convection on days with total precipitation greater or equal to a given threshold (default: 1.0 mm/day) during the given period.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
prc (xarray.DataArray) – Daily convective precipitation.
thresh (Quantified) – Precipitation value over which a day is considered wet.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – The proportion of the total precipitation accounted for by convective precipitation for each period.
- xclim.compute.runoff_ratio(q, pr, area, freq='YS')[source]
Runoff ratio.
Ratio of runoff volume measured at the stream to the total precipitation volume over the watershed.
- Parameters:
q (xarray.DataArray) – Streamflow in discharge units.
pr (xarray.DataArray) – Mean daily precipitation in precipitation units.
area (Quantified) – Watershed area in area units.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Runoff ratio (dimensionless).
Notes
Runoff ratio values are comparable to runoff coefficients.
Values near 0 mean most precipitation infiltrates watershed soil or is lost to evapotranspiration.
Values near 1 mean most precipitation leaves the watershed as runoff. Possible causes are impervious surfaces from urban sprawl, thin soils, steep slopes, etc.
Annual runoff ratios are typically ≤ 1.
Annual runoff ratios are typically higher than summer runoff ratios due to higher levels of evapotranspiration in summer months.
For snow-driven watersheds, spring runoff ratios are typically higher than annual runoff ratios, as snowmelt generates concentrated runoff events.
Temporal analysis: Yearly values computed from seasonal daily data and yearly data, depending on chosen frequency. (e.g., ‘YS’ for yearly starting Jan, or ‘QS-DEC’ for seasons, ‘30YS’ to compute the value over slices of 30 years from the start of the time series).
References
:cite:cts:’knoben_2024’
- xclim.compute.saturation_vapor_pressure(tas, ice_thresh=None, method='sonntag90', interp_power=None, water_thresh='0 °C')[source]
Saturation vapour pressure from temperature.
- Parameters:
tas (xr.DataArray) – Mean Temperature.
ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water. If given, see interp_power for more options.
method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”, “its90”, “buck81”, “aerk96”, “ecmwf”}) – Which saturation vapour pressure formula to use, see notes.
interp_power (int or None) – Interpolation options for mixing saturation over water and over ice. See notes.
water_thresh (Quantified) – When
interp_poweris given, this is the threshold temperature above which the formulas with reference to water are used.
- Return type:
DataArray- Returns:
xarray.DataArray, [Pa] – Saturation Vapour Pressure.
See also
ESAT_FORMULAS_COEFFICIENTSCoefficients for methods “tetens30”, “wmo08”, “aerk96” and “buck81”.
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”, based on Goff and Gratch [1946], values and equation taken from Vömel [2016].
“sonntag90””, taken from SONNTAG [1990].
“tetens30”, based on Tetens [1930], values and equation taken from Vömel [2016].
“wmo08”, taken from World Meteorological Organization [2008].
“its90”, taken from Hardy [1998].
“buck81”, taken from Buck [1981].
“aerk96”, corresponds to formulas AERK and AERKi of Alduchov and Eskridge [1996]
“ecmwf”, taken from ECMWF [2016]. This uses “buck91” for saturation over water and “aerk96” for saturation over ice.
Water vs ice
This function implements 3 cases:
All water. When
interp_poweris None (default) andice_threshis None (default). Formulas use water as a reference. This might lead to relative humidities above 100 % for cold temperatures. This is usually what observational products use (World Meteorological Organization [2008]), and also how the dew point of ERA5 is computed.Binary water-ice transition. When
interp_power is None (default) and ``ice_threshis given. The formulas with reference to water are used for temperatures aboveice_threshand the ones with reference to ice are used for temperatures equal to or underice_thresh. Often used in models, this is what MetPy does.Interpolation between water and ice. When
interp_power,ice_threshandwater_threshare all given, formulas with reference to water are used for temperatures abovewater_thresh, the formulas with reference to ice are used for temperatures belowice_threshand an interpolation is used in between.
\[ \begin{align}\begin{aligned}e_{sat} = \alpha e_{sat(water)}(T) + (1 - \alpha) e_{sat(ice)}(T)\\\alpha = \left(\frac{T - T_i}{T_w - T_i}\right)^{\beta}\end{aligned}\end{align} \]Where \(T_{ice}\) is
ice_thresh, \(T_{w}\) iswater_threshand \(\beta\) isinterp_power.As a note, a computation resembling what ECMWF’s IFS does to compute relative humidity would use:
method = 'ecmwf',ice_thresh = 250.16 K,water_thresh = 273.16 K(default) andinterp_power = 2(ECMWF [2016]). Take note, however, that the 2m dew point temperature given by the IFS (ERA5, ERA5-Land) is computed with reference to water only.References
ECMWF [2016], Goff and Gratch [1946], Hardy [1998], SONNTAG [1990], Tetens [1930] Alduchov and Eskridge [1996], Buck [1981], Vömel [2016], World Meteorological Organization [2008]
Examples
>>> from xclim.compute import saturation_vapor_pressure >>> rh = saturation_vapor_pressure(tas=tas_dataset, ice_thresh="0 degC", method="wmo08")
- xclim.compute.sea_ice_area(siconc, areacello, thresh='15 %')[source]
Total sea ice area.
Sea ice area measures the total sea ice covered area where sea ice concentration is above a given threshold, usually set to 15%.
- Parameters:
siconc (xarray.DataArray) – Sea ice concentration (area fraction).
areacello (xarray.DataArray) – Grid cell area (usually over the ocean).
thresh (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.
- Return type:
DataArray- Returns:
xarray.DataArray, [length]^2 – Sea ice area.
Notes
To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.
References
“What is the difference between sea ice area and extent?” - NSIDC [2008]
- xclim.compute.sea_ice_extent(siconc, areacello, thresh='15 %')[source]
Total sea ice extent.
Sea ice extent measures the ice-covered area, where a region is considered ice-covered if its sea ice concentration is above a given threshold, usually set to 15%.
- Parameters:
siconc (xarray.DataArray) – Sea ice concentration (area fraction).
areacello (xarray.DataArray) – Grid cell area.
thresh (Quantified) – Minimum sea ice concentration for a grid cell to contribute to the sea ice extent.
- Return type:
DataArray- Returns:
xarray.DataArray, [length]^2 – Sea ice extent.
Notes
To compute sea ice area over a subregion, first mask or subset the input sea ice concentration data.
References
“What is the difference between sea ice area and extent?” - NSIDC [2008]
- xclim.compute.sen_slope(q, freq='YS')[source]
Temporal robustness analysis of streamflow.
Computes Theil-Sen slope estimators and performs the Mann-Kendall test for trend evaluation.
- Parameters:
q (xarray.DataArray) – Observed streamflow vector.
freq (str) – Resampling frequency.
- Return type:
tuple[DataArray,DataArray]- Returns:
sen_slope (xarray.DataArray, [dimensionless]) – Sen’s slope estimates.
p_value (xarray.DataArray, [dimensionless]) – Mann-Kendall metric indicating slope tendency.
Notes
If p-value <= 0.05, the trend is statistically significant at the 5% level.
The ratio of observed Sen_slope over simulated Sen_slope is considered acceptable within the range 0.5-2 and is optimal when equal to 1 (Sauquet et al., 2025).
References
Sauquet, Evin, Siauve, Aissat, Arnaud, Bérel, Bonneau, Branger, Caballero, Colléoni, Ducharne, Gailhard, Habets, Hendrickx, Héraut, Hingray, Huang, Jaouen, Jeantet, Lanini, Le Lay, Magand, Mimeau, Monteil, Munier, Perrin, Robelin, Rousset, Soubeyroux, Strohmenger, Thirel, Tocquer, Tramblay, Vergnes, and Vidal [2025]
- xclim.compute.sen_slope_ratio(q, qsim, freq='YS')[source]
Temporal robustness analysis of streamflow.
Computes annual and seasonal Theil-Sen slope estimators and performs the Mann-Kendall test for trend evaluation.
- Parameters:
q (xarray.DataArray) – Observed streamflow vector.
qsim (xarray.DataArray, optional) – Simulated streamflow vector.
freq (str) – Resampling frequency.
- Return type:
tuple[DataArray,DataArray,DataArray,DataArray,DataArray]- Returns:
sen_slope (xarray.DataArray, [dimensionless]) – Sen’s slope estimates.
p_value (xarray.DataArray, [dimensionless]) – Mann-Kendall metric indicating slope tendency.
sen_slope_sim (xarray.DataArray, [dimensionless]) – Sen’s slope estimates of the simulation dataset.
p_value_sim (xarray.DataArray, [dimensionless]) – Mann-Kendall metric indicating slope tendency of the simulation dataset.
ratio (xarray.DataArray, [dimensionless]) – Ratio of the slopes.
Notes
If p-value <= 0.05, the trend is statistically significant at the 5% level.
The ratio of observed Sen_slope over simulated Sen_slope is considered acceptable within the range 0.5-2 and is optimal when equal to 1 (Sauquet et al., 2025).
References
Sauquet, Evin, Siauve, Aissat, Arnaud, Bérel, Bonneau, Branger, Caballero, Colléoni, Ducharne, Gailhard, Habets, Hendrickx, Héraut, Hingray, Huang, Jaouen, Jeantet, Lanini, Le Lay, Magand, Mimeau, Monteil, Munier, Perrin, Robelin, Rousset, Soubeyroux, Strohmenger, Thirel, Tocquer, Tramblay, Vergnes, and Vidal [2025]
- xclim.compute.sfcWind_max(sfcWind, freq='YS')[source]
Highest daily mean wind speed.
The maximum of daily mean wind speed.
- Parameters:
sfcWind (xarray.DataArray) – Mean daily wind speed.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as sfcWind] – Maximum of daily mean wind speed.
Notes
Let \(FG_{ij}\) be the mean wind speed at day \(i\) of period \(j\). Then the maximum daily mean wind speed for period \(j\) is:
\[FGx_j = max(FG_{ij})\]Examples
The following would compute for each grid cell the maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import sfcWind_max >>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind >>> fg_max = sfcWind_max(fg, freq="QS-DEC")
- xclim.compute.sfcWind_mean(sfcWind, freq='YS')[source]
Mean of daily mean wind speed.
Resample the original daily mean wind speed series by taking the mean over each period.
- Parameters:
sfcWind (xarray.DataArray) – Mean daily wind speed.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as sfcWind] – The mean daily wind speed at the given time frequency.
Notes
Let \(FG_i\) be the mean wind speed of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):
\[FG_m = \frac{\sum_{i=a}^{b} FG_i}{b - a + 1}\]Examples
The following would compute for each grid cell the mean wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import sfcWind_mean >>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind >>> fg_mean = sfcWind_mean(fg, freq="QS-DEC")
- xclim.compute.sfcWind_min(sfcWind, freq='YS')[source]
Lowest daily mean wind speed.
The minimum of daily mean wind speed.
- Parameters:
sfcWind (xarray.DataArray) – Mean daily wind speed.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as sfcWind] – Minimum of daily mean wind speed.
Notes
Let \(FG_{ij}\) be the mean wind speed at day \(i\) of period \(j\). Then the minimum daily mean wind speed for period \(j\) is:
\[FGn_j = min(FG_{ij})\]Examples
The following would compute for each grid cell the minimum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import sfcWind_min >>> fg = xr.open_dataset(path_to_sfcWind_file).sfcWind >>> fg_min = sfcWind_min(fg, freq="QS-DEC")
- xclim.compute.sfcWindmax_max(sfcWindmax, freq='YS')[source]
Highest maximum wind speed.
The maximum of daily maximum wind speed.
- Parameters:
sfcWindmax (xarray.DataArray) – Maximum daily wind speed.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as sfcWindmax] – Maximum value of daily maximum wind speed.
Notes
Let \(FX_{ij}\) be the maximum wind speed at day \(i\) of period \(j\). Then the maximum daily maximum wind speed for period \(j\) is:
\[FXx_j = max(FX_{ij})\]Examples
The following would compute for each grid cell of the dataset the extreme maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import sfcWindmax_max >>> max_sfcWindmax = sfcWindmax_max(sfcWindmax_dataset, freq="QS-DEC")
- xclim.compute.sfcWindmax_mean(sfcWindmax, freq='YS')[source]
Mean of daily maximum wind speed.
Resample the original daily maximum wind speed series by taking the mean over each period.
- Parameters:
sfcWindmax (xarray.DataArray) – Maximum daily wind speed.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as sfcWindmax] – The mean daily maximum wind speed at the given time frequency.
Notes
Let \(FX_i\) be the maximum wind speed of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):
\[FX_m = \frac{\sum_{i=a}^{b} FX_i}{b - a + 1}\]Examples
The following would compute for each grid cell of the dataset the mean of maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import sfcWindmax_mean >>> mean_sfcWindmax = sfcWindmax_mean(sfcWindmax_dataset, freq="QS-DEC")
- xclim.compute.sfcWindmax_min(sfcWindmax, freq='YS')[source]
Lowest daily maximum wind speed.
The minimum of daily maximum wind speed.
- Parameters:
sfcWindmax (xarray.DataArray) – Maximum daily wind speed.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as sfcWindmax] – Minimum of daily maximum wind speed.
Notes
Let \(FX_{ij}\) be the maximum wind speed at day \(i\) of period \(j\). Then the minimum daily maximum wind speed for period \(j\) is:
\[FXn_j = min(FX_{ij})\]Examples
The following would compute for each grid cell of the dataset the minimum of maximum wind speed at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import sfcWindmax_min >>> min_sfcWindmax = sfcWindmax_min(sfcWindmax_dataset, freq="QS-DEC")
- xclim.compute.sfcwind_to_uas_vas(sfcWind, sfcWindfromdir)[source]
Eastward and northward wind components from the wind speed and direction.
Compute the eastward and northward wind components from the wind speed and direction.
- Parameters:
sfcWind (xr.DataArray) – Wind Velocity.
sfcWindfromdir (xr.DataArray) – Direction from which the wind blows, following the meteorological convention, where “360” denotes “North”.
- Return type:
tuple[DataArray,DataArray]- Returns:
uas (xr.DataArray, [m s-1]) – Eastward Wind Velocity.
vas (xr.DataArray, [m s-1]) – Northward Wind Velocity.
Examples
>>> from xclim.compute import sfcwind_to_uas_vas >>> uas, vas = sfcwind_to_uas_vas(sfcWind=sfcWind_dataset, sfcWindfromdir=sfcWindfromdir_dataset)
- xclim.compute.shortwave_downwelling_radiation_from_clearness_index(ci)[source]
Compute the surface downwelling solar radiation from clearness index.
- Parameters:
ci (xr.DataArray) – Clearness index.
- Return type:
DataArray- Returns:
xr.DataArray, [unitless] – Surface downwelling solar radiation.
See also
clearness_indexInverse transformation, and definition of the clearness index.
Notes
The conversion from Clearness Index is defined as:
- xclim.compute.shortwave_upwelling_radiation_from_net_downwelling(rss, rsds)[source]
Calculate upwelling solar radiation from net solar radiation and downwelling solar radiation.
- Parameters:
rss (xr.DataArray) – Surface net solar radiation.
rsds (xr.DataArray) – Surface downwelling solar radiation.
- Return type:
DataArray- Returns:
xr.DataArray, [same units as rsds] – Surface upwelling solar radiation (rsus).
- xclim.compute.snd_days_above(snd, thresh='2 cm', freq='YS-JUL', op='>=')[source]
The number of days with snow depth above a threshold.
Number of days where surface snow depth is greater or equal to a given threshold (default: 2 cm).
- Parameters:
snd (xarray.DataArray) – Surface snow thickness.
thresh (Quantified) – Threshold snow thickness.
freq (str) – Resampling frequency. The default value is chosen for the Northern Hemisphere.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days where snow depth is greater than or equal to {thresh}.
- xclim.compute.snd_max(snd, freq='YS-JUL')[source]
Maximum snow depth.
The maximum daily snow depth.
- Parameters:
snd (xarray.DataArray) – Snow depth (mass per area).
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The maximum snow depth over a given number of days for each period. [length].
- xclim.compute.snd_max_doy(snd, freq='YS-JUL')[source]
Day of year of maximum snow depth.
Day of year when surface snow reaches its peak value. If snow depth is 0 over entire period, return NaN.
- Parameters:
snd (xarray.DataArray) – Surface snow depth.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The day of year at which snow depth reaches its maximum value.
- xclim.compute.snd_season_end(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]
Snow cover end date (depth).
First day after the start of the continuous snow depth cover when snow depth is below a threshold for at least window consecutive days.
- Parameters:
snd (xarray.DataArray) – Surface snow thickness.
thresh (Quantified) – Threshold snow thickness.
window (int) – Minimum number of days with snow depth below the threshold.
freq (str) – Resampling frequency. Default: “YS-JUL”. The default value is chosen for the northern hemisphere.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – First day after the start of the continuous snow depth cover.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.compute.snd_season_length(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]
Snow cover duration (depth).
The season starts when snow depth is above a threshold for at least N consecutive days and stops when it drops below the same threshold for the same number of days.
- Parameters:
snd (xarray.DataArray) – Surface snow thickness.
thresh (Quantified) – Threshold snow thickness.
window (int) – Minimum number of days with snow depth above and below threshold.
freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – Length of the snow season.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.compute.snd_season_start(snd, thresh='2 cm', window=14, freq='YS-JUL')[source]
Snow cover start date (depth).
Day of year when snow depth is above or equal to a threshold for at least N consecutive days.
- Parameters:
snd (xarray.DataArray) – Surface snow thickness.
thresh (Quantified) – Threshold snow thickness.
window (int) – Minimum number of days with snow depth above or equal to the threshold.
freq (str) – Resampling frequency. The default value is chosen for the Northern Hemisphere.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – First day of the year when the snow depth is superior to a threshold for a minimum duration.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.compute.snd_storm_days(snd, thresh='25 cm', freq='YS-JUL')[source]
Days with snowfall over threshold.
Number of days with snowfall depth accumulation greater or equal to threshold (default: 25 cm).
- Parameters:
snd (xarray.DataArray) – Surface snow depth.
thresh (Quantified) – Threshold on snowfall depth accumulation require to label an event a snd storm.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Number of days per period identified as winter storms.
Warning
The default freq is valid for the northern hemisphere.
Notes
Snowfall accumulation is estimated by the change in snow depth.
- xclim.compute.snd_to_snw(snd, snr=None, const='312 kg m-3', out_units=None)[source]
Snow amount from snow depth and density.
- Parameters:
snd (xr.DataArray) – Snow Depth.
snr (Quantified, optional) – Snow Density.
const (Quantified) – Constant snow density. const is only used if snr is None.
out_units (str, optional) – Desired units of the snow amount output. If None, output units simply follow from snd * snr.
- Return type:
DataArray- Returns:
xr.DataArray – Snow Amount.
Notes
The estimated mean snow density value of 312 kg m-3 is taken from Sturm et al. [2010].
References
Sturm, Taras, Liston, Derksen, Jonas, and Lea [2010]
- xclim.compute.snow_depth(snd, freq='YS')[source]
Mean of daily average snow depth.
Resample the original daily mean snow depth series by taking the mean over each period.
- Parameters:
snd (xarray.DataArray) – Mean daily snow depth.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as snd] – The mean daily snow depth at the given time frequency.
- xclim.compute.snow_melt_we_max(snw, window=3, freq='YS-JUL')[source]
Maximum snow melt.
The maximum snow melt over a given number of days expressed in snow water equivalent.
- Parameters:
snw (xarray.DataArray) – Snow amount (mass per area).
window (int) – Number of days during which the melt is accumulated.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The maximum snow melt over a given number of days for each period. [mass/area].
- xclim.compute.snowfall_approximation(pr, tas, thresh='0 degC', method='binary', clip_temp=None, landmask=True)[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”. Ignored for the
'dai_*'methods.method ({“binary”, “brown”, “auer”, “dai_annual”, “dai_seasonal”}) – Which method to use when approximating snowfall from total precipitation. See notes.
clip_temp (Quantified) – For methods “dai_annual” and “dai_seasonal”, this is an optional temperature delta at which the snowfall fraction is rescaled to 0 or 1. See notes.
landmask (DataArray or bool) – For methods “dai_annual” and “dai_seasonal”, this is the land mask, a DataArray without a time dimension that is True on land grid points and False on ocean grid points. Can also be True or False to use one or the other coefficients set for all points. Default is to consider all points as land.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as pr] – Solid Precipitation Flux.
See also
rain_approximationRainfall approximation from total precipitation and temperature.
Notes
The following methods are available to approximate snowfall.
'brown'and'auer'are drawn from the Canadian Land Surface Scheme [Melton, 2019, Verseghy, 2009]. The two'dai_*'methods are implemented from [Dai, 2008] (clip_tempis an addition from the xclim team).'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.'dai_annual': The snow fraction evolves according to an hyperbolic tangent function that has different parameters for precipitation over land or ocean. The snow and rain fractions do not add to 1, rather the remainder is denoted as a “sleet” fraction. Ifclip_tempis given, its value $$T_c$$ (in °C) is used to rescale (and then clip) the snowfall fraction function $$f(T)$$ as $$(f(T) - f(T_c))/(f(-T_c) - f(T_c))$$, so that it is 0 when $$T > T_c$$ and 1 when $$T < -T_c$$.'dai_seasonal': Same as'dai_annual', but parameters are different for each season. The “annual” coefficients are taken over ocean in summer (JJA).
References
- xclim.compute.snowfall_frequency(prsn, thresh='1 mm/day', freq='YS-JUL')[source]
Percentage of snow days.
Return the percentage of days where snowfall exceeds a threshold (default: 1 mm/day).
- Parameters:
prsn (xarray.DataArray) – Snowfall flux.
thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [%] – Percentage of days where snowfall exceeds a given threshold.
Warning
The default freq is valid for the Northern Hemisphere.
Notes
The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.
If the threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed, and the threshold is converted using a 1000 kg m-3 density.
References
Frei, Kotlarski, Liniger, and Schär [2018].
- xclim.compute.snowfall_intensity(prsn, thresh='1 mm/day', freq='YS-JUL')[source]
Mean daily snowfall rate during snow days.
Return the mean daily snowfall rate during days where snowfall exceeds a threshold (default: 1 mm/day).
- Parameters:
prsn (xarray.DataArray) – Snowfall flux.
thresh (Quantified) – Threshold snowfall flux or liquid water equivalent snowfall rate (default: 1 mm/day).
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Mean daily liquid water equivalent snowfall rate during days where snowfall exceeds a threshold.
Warning
The default freq is valid for the Northern Hemisphere.
Notes
The 1 mm/day liquid water equivalent snowfall rate threshold in Frei, Kotlarski, Liniger, and Schär [2018] corresponds to the 1 cm/day snowfall rate threshold in CBCL [2020] using a snow density of 100 kg/m**3.
If threshold and prsn differ by a density (i.e. [length/time] vs. [mass/area/time]), a liquid water equivalent snowfall rate is assumed and the threshold is converted using a 1000 kg m-3 density.
References
Frei, Kotlarski, Liniger, and Schär [2018].
- xclim.compute.snw_days_above(snw, thresh='4 kg m-2', freq='YS-JUL', op='>=')[source]
The number of days with snow amount above a given threshold.
Number of days where surface snow amount is greater or equal to a given threshold.
- Parameters:
snw (xarray.DataArray) – Surface snow amount.
thresh (str) – Threshold snow amount.
freq (str) – Resampling frequency. The default value is chosen for the Northern hemisphere.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days where snow amount is greater than or equal to {thresh}.
- xclim.compute.snw_max(snw, freq='YS-JUL')[source]
Maximum snow amount.
The maximum daily snow amount.
- Parameters:
snw (xarray.DataArray) – Snow amount (mass per area).
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The maximum snow amount over a given number of days for each period. [mass/area].
- xclim.compute.snw_max_doy(snw, freq='YS-JUL')[source]
Day of year of maximum snow amount.
Day of year when surface snow amount reaches its peak value. If snow amount is 0 over entire period, return NaN.
- Parameters:
snw (xarray.DataArray) – Surface snow amount.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The day of year at which snow amount reaches its maximum value.
- xclim.compute.snw_season_end(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]
Snow cover end date (amount).
First day after the start of the continuous snow water cover when snow water is below a threshold for at least N consecutive days.
- Parameters:
snw (xarray.DataArray) – Surface snow amount.
thresh (str) – Threshold snow amount.
window (int) – Minimum number of days with snow water below the threshold.
freq (str) – Resampling frequency. The default value is chosen for the Northern Hemisphere.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – First day after the start of the continuous snow amount cover.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.compute.snw_season_length(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]
Snow cover duration (amount).
The season starts when the snow amount is above a threshold for at least N consecutive days and stops when it drops below the same threshold for the same number of days.
- Parameters:
snw (xarray.DataArray) – Surface snow amount.
thresh (Quantified) – Threshold snow amount.
window (int) – Minimum number of days with snow amount above and below threshold.
freq (str) – Resampling frequency. The default value is chosen for the northern hemisphere.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – Length of the snow season.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.compute.snw_season_start(snw, thresh='4 kg m-2', window=14, freq='YS-JUL')[source]
Snow cover start date (amount).
Day of year when snow water is above or equal to a threshold for at least N consecutive days.
- Parameters:
snw (xarray.DataArray) – Surface snow amount.
thresh (str) – Threshold snow amount.
window (int) – Minimum number of days with snow amount above or equal to the threshold.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – First day of the year when the snow amount is superior to a threshold for a minimum duration.
References
Chaumont, Mailhot, Diaconescu, Fournier, and Logan [2017]
- xclim.compute.snw_storm_days(snw, thresh='10 kg m-2', freq='YS-JUL')[source]
Days with snowfall over threshold.
Number of days with snowfall amount accumulation greater or equal to threshold (default: 10 kg m-2).
- Parameters:
snw (xarray.DataArray) – Surface snow amount.
thresh (Quantified) – Threshold on snowfall amount accumulation require to label an event a snw storm.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Number of days per period identified as winter storms.
Warning
The default freq is valid for the northern hemisphere.
Notes
Snowfall accumulation is estimated by the change in snow amount.
- xclim.compute.snw_to_snd(snw, snr=None, const='312 kg m-3', out_units=None)[source]
Snow depth from snow amount and density.
- Parameters:
snw (xr.DataArray) – Snow amount.
snr (Quantified, optional) – Snow density.
const (Quantified) – Constant snow density. const is only used if snr is None.
out_units (str, optional) – Desired units of the snow depth output. If None, output units simply follow from snw / snr.
- Return type:
DataArray- Returns:
xr.DataArray – Snow Depth.
Notes
The estimated mean snow density value of 312 kg m-3 is taken from Sturm et al. [2010].
References
Sturm, Taras, Liston, Derksen, Jonas, and Lea [2010]
- xclim.compute.specific_humidity(tas, hurs, ps, ice_thresh=None, method='sonntag90', interp_power=None, water_thresh='0 °C', invalid_values=None)[source]
Specific humidity from temperature, relative humidity, and pressure.
Specific humidity is the ratio between the mass of water vapour and the mass of moist air [World Meteorological Organization, 2008].
- Parameters:
tas (xr.DataArray) – Mean Temperature.
hurs (xr.DataArray) – Relative Humidity.
ps (xr.DataArray) – Air Pressure.
ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water.
method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”, “ecmwf”}) – Which method to use, see notes of this function and of
saturation_vapor_pressure().interp_power (int or None) – Optional interpolation for mixing saturation vapour pressures computed over water and ice. See
saturation_vapor_pressure().water_thresh (Quantified) – When
interp_poweris given, this is the threshold temperature above which the formulas with reference to water are used.invalid_values ({“clip”, “mask”, None}) – What to do with values larger than the saturation specific humidity and lower than 0. If “clip” (default), clips everything to 0 - q_sat if “mask”, replaces values outside the range by np.nan, if None, does nothing.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Specific Humidity.
Notes
In the following, let \(T\), \(hurs\) (in %) and \(p\) be the temperature, the relative humidity and the air pressure. With \(w\), \(w_{sat}\), \(e_{sat}\) the mixing ratio, the saturation mixing ratio and the saturation vapour pressure, specific humidity \(q\) is computed as:
\[w_{sat} = 0.622\frac{e_{sat}}{P - e_{sat}} w = w_{sat} * hurs / 100 q = w / (1 + w)\]The methods differ by how \(e_{sat}\) is computed. See
xclim.core.utils.saturation_vapor_pressure().If invalid_values is not None, the saturation specific humidity \(q_{sat}\) is computed as:
\[q_{sat} = w_{sat} / (1 + w_{sat})\]References
World Meteorological Organization [2008]
Examples
>>> from xclim.compute import specific_humidity >>> rh = specific_humidity( ... tas=tas_dataset, ... hurs=hurs_dataset, ... ps=ps_dataset, ... ice_thresh="0 degC", ... method="wmo08", ... invalid_values="mask", ... )
- xclim.compute.specific_humidity_from_dewpoint(tdps, ps, ice_thresh=None, method='sonntag90', interp_power=None, water_thresh='0 °C')[source]
Specific humidity from dewpoint temperature and air pressure.
Specific humidity is the ratio between the mass of water vapour and the mass of moist air [World Meteorological Organization, 2008].
- Parameters:
tdps (xr.DataArray) – Dewpoint Temperature.
ps (xr.DataArray) – Air Pressure.
ice_thresh (Quantified, optional) – Threshold temperature under which to switch to saturated vapour pressure equations in reference to ice instead of water. See
saturation_vapor_pressure().method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”, “buck81”, “aerk96”, “ecmwf”}) – Method to compute the saturation vapour pressure.
interp_power (int or None) – Optional interpolation for mixing saturation vapour pressures computed over water and ice. See
saturation_vapor_pressure().water_thresh (Quantified) – When
interp_poweris given, this is the threshold temperature above which the formulas with reference to water are used.
- Return type:
DataArray- Returns:
xarray.DataArray, [dimensionless] – Specific Humidity.
Notes
If \(e\) is the water vapour pressure, and \(p\) the total air pressure, then specific humidity is given by
\[q = m_w e / ( m_a (p - e) + m_w e )\]where \(m_w\) and \(m_a\) are the molecular weights of water and dry air respectively. This formula is often written with \(ε = m_w / m_a\), which simplifies to \(q = ε e / (p - e (1 - ε))\).
References
World Meteorological Organization [2008]
Examples
>>> from xclim.compute import specific_humidity_from_dewpoint >>> rh = specific_humidity_from_dewpoint( ... tdps=tas_dataset, ... ps=ps_dataset, ... method="wmo08", ... )
- xclim.compute.standardized_groundwater_index(gwl, freq='MS', window=1, dist='genextreme', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, **indexer)[source]
Standardized Groundwater Index (SGI).
- Parameters:
gwl (xarray.DataArray) – Groundwater head level.
freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.
window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.
dist ({“gamma”, “genextreme”, “lognorm”} or rv_continuous) – Name of the univariate distribution, or a callable rv_continuous (see
scipy.stats).method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization. PWM should be used with a lmoments3 distribution.
fitkwargs (dict, optional) – Kwargs passed to
xclim.compute.stats.fitused to impose values of certain parameters (floc, fscale).cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.
cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.
params (xarray.DataArray, optional) – Fit parameters. The params can be computed using
xclim.compute.stats.standardized_index_fit_paramsin advance. The output can be given here as input, and it overrides other options.**indexer (Indexer) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – Standardized Groundwater Index.
See also
xclim.compute._agro.standardized_precipitation_indexStandardized Precipitation Index.
xclim.compute.stats.standardized_indexStandardized Index.
xclim.compute.stats.standardized_index_fit_paramsStandardized Index Fit Params.
Notes
N-month SGI / N-day SGI is determined by choosing the window = N and the appropriate frequency freq.
Supported statistical distributions are: [“gamma”, “genextreme”, “lognorm”].
If params is provided, it overrides the cal_start, cal_end, freq, window, dist, method options.
“APP” method only supports two-parameter distributions. Parameter loc needs to be fixed to use method “APP”.
References
Bloomfield and Marchant [2013]
Examples
>>> from datetime import datetime >>> from xclim.compute import standardized_groundwater_index >>> ds = xr.open_dataset(path_to_gwl_file) >>> gwl = ds.gwl >>> cal_start, cal_end = "1980-05-01", "1982-06-01" >>> sgi_3 = standardized_groundwater_index( ... gwl, ... freq="MS", ... window=3, ... dist="gamma", ... method="ML", ... cal_start=cal_start, ... cal_end=cal_end, ... ) # Computing SGI-3 months using a Gamma distribution for the fit >>> # Fitting parameters can also be obtained first, then reused as input. >>> from xclim.compute.stats import standardized_index_fit_params >>> params = standardized_index_fit_params( ... gwl.sel(time=slice(cal_start, cal_end)), ... freq="MS", ... window=3, ... dist="gamma", ... method="ML", ... ) # First getting params >>> sgi_3 = standardized_groundwater_index(gwl, params=params)
- xclim.compute.standardized_precipitation_evapotranspiration_index(wb, freq='MS', window=1, dist='gamma', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, **indexer)[source]
Standardized Precipitation Evapotranspiration Index (SPEI).
Precipitation minus potential evapotranspiration data (PET) fitted to a statistical distribution (dist), transformed to a cdf, and inverted back to a gaussian normal pdf. The potential evapotranspiration is calculated with a given method (method).
- Parameters:
wb (xarray.DataArray) – Daily water budget (pr - pet).
freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.
window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.
dist ({‘gamma’, ‘fisk’, ‘genextreme’, ‘lognorm’} or rv_continuous function) – Name of the univariate distribution, or a callable rv_continuous (see
scipy.stats).method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization, which can be sensitive to noise. PWM should be used with a lmoments3 distribution.
fitkwargs (dict, optional) – Kwargs passed to
xclim.compute.stats.fitused to impose values of certains parameters (floc, fscale). If method is PWM, fitkwargs should be empty, except for floc with dist`=`gamma which is allowed.cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.
cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.
params (xarray.DataArray, optional) – Fit parameters. The params can be computed using
xclim.compute.stats.standardized_index_fit_paramsin advance. The output can be given here as input, and it overrides other options.**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray – Standardized Precipitation Evapotranspiration Index.
See also
standardized_precipitation_indexStandardized Precipitation Index.
xclim.compute.stats.standardized_indexStandardized Index.
xclim.compute.stats.standardized_index_fit_paramsStandardized Index Fit Params.
- xclim.compute.standardized_precipitation_index(pr, freq='MS', window=1, dist='gamma', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, prob_zero_interpolation='upper', plotting_position_zero='ecdf', **indexer)[source]
Standardized Precipitation Index (SPI).
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.
window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.
dist ({‘gamma’, ‘fisk’, ‘genextreme’, ‘lognorm’} or rv_continuous function) – Name of the univariate distribution, or a callable rv_continuous (see
scipy.stats).method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization, which can be sensitive to noise. PWM should be used with a lmoments3 distribution.
fitkwargs (dict, optional) – Kwargs passed to
xclim.compute.stats.fitused to impose values of certains parameters (floc, fscale). If method is PWM, fitkwargs should be empty, except for floc with dist`=`gamma which is allowed.cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.
cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.
params (xarray.DataArray) – Fit parameters. The params can be computed using
xclim.compute.stats.standardized_index_fit_paramsin advance. The output can be given here as input, and it overrides other options.prob_zero_interpolation ({“center”, “upper”} or float) – Interpolation method used to assign a probability to zero values (only used if zero_inflated is True). When the data contain multiple zeros, the admissible plotting position interval spans from the first zero rank to the last zero rank. This parameter selects a representative probability within that interval. The default method “upper” assigns the upper bound of the zero-rank interval. The “center” method assigns the midpoint of the zero-rank interval. If a float in [0, 1] is provided, it is used as a linear interpolation factor between the lower (0) and upper (1) zero-rank plotting positions.
plotting_position_zero ({“ecdf”, “weibull”} or tuple[float, float]) – Method used to assign a probability to a rank for the zeros (only used if zero_inflated is True). “ecdf” (default option) is the empirical cumulative distribution and divides the number or zeros by the total number of observations. “weibull” implements the unbiased version, dividing by the total number of observation plus one. A tuple consisting of two coefficients in [0,1] to relate the number of zeros and the total number of observations. “ecdf” corresponds to (0,1) and “weibull” to (0,0). See
scipy.stats.mstats.plotting_positions()**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – Standardized Precipitation Index.
See also
xclim.compute.stats.standardized_indexStandardized Index.
xclim.compute.stats.standardized_index_fit_paramsStandardized Index Fit Params.
Notes
N-month SPI / N-day SPI is determined by choosing the window = N and the appropriate frequency freq.
Supported statistical distributions are: [“gamma”, “fisk”], where “fisk” is scipy’s implementation of a log-logistic distribution
Supported frequencies are daily (“D”), weekly (“W”), and monthly (“MS”).
Weekly frequency will only work if the input array has a “standard” (non-cftime) calendar.
If params is given as input, it overrides the cal_start, cal_end, freq and window, dist and method options.
“APP” method only supports two-parameter distributions. Parameter loc needs to be fixed to use method APP.
The results from climate_indices library can be reproduced with method = “APP” and fitwkargs = {“floc”: 0}, except for the maximum and minimum values allowed which are greater in xclim ±8.21, . See xclim.compute.stats.standardized_index
References
McKee, Doesken, and Kleist [1993], Stagge, Tallaksen, Gudmundsson, Van Loon, and Stahl [2015]
Examples
>>> from datetime import datetime >>> from xclim.compute import standardized_precipitation_index >>> ds = xr.open_dataset(path_to_pr_file) >>> pr = ds.pr >>> cal_start, cal_end = "1990-05-01", "1990-08-31" >>> spi_3 = standardized_precipitation_index( ... pr, ... freq="MS", ... window=3, ... dist="gamma", ... method="ML", ... cal_start=cal_start, ... cal_end=cal_end, ... ) # Computing SPI-3 months using a gamma distribution for the fit >>> # Fitting parameters can also be obtained first, then reused as input. >>> # To properly reproduce the example, we also need to specify that we use a >>> # (potentially) zero-inflated distribution. For a monthly SPI, this should rarely >>> # make a difference. >>> from xclim.compute.stats import standardized_index_fit_params >>> params = standardized_index_fit_params( ... pr.sel(time=slice(cal_start, cal_end)), ... freq="MS", ... window=3, ... dist="gamma", ... method="ML", ... zero_inflated=True, ... ) # First getting params >>> spi_3_fitted = standardized_precipitation_index(pr, params=params)
- xclim.compute.standardized_streamflow_index(q, freq='MS', window=1, dist='genextreme', method='ML', fitkwargs=None, cal_start=None, cal_end=None, params=None, **indexer)[source]
Standardized Streamflow Index (SSI).
- Parameters:
q (xarray.DataArray) – Rate of river discharge.
freq (str, optional) – Resampling frequency. A monthly or daily frequency is expected. Option None assumes that the desired resampling has already been applied input dataset and will skip the resampling step.
window (int) – Averaging window length relative to the resampling frequency. For example, if freq=”MS”, i.e. a monthly resampling, the window is an integer number of months.
dist ({“genextreme”, “fisk”} or rv_continuous function) – Name of the univariate distribution, or a callable rv_continuous (see
scipy.stats).method ({“APP”, “ML”, “PWM”}) – Name of the fitting method, such as ML (maximum likelihood), APP (approximate). The approximate method uses a deterministic function that does not involve any optimization. PWM should be used with a lmoments3 distribution.
fitkwargs (dict, optional) – Kwargs passed to
xclim.compute.stats.fitused to impose values of certain parameters (floc, fscale).cal_start (DateStr, optional) – Start date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period begins at the start of the input dataset.
cal_end (DateStr, optional) – End date of the calibration period. A DateStr is expected, that is a str in format “YYYY-MM-DD”. Default option None means that the calibration period finishes at the end of the input dataset.
params (xarray.DataArray, optional) – Fit parameters. The params can be computed using
xclim.compute.stats.standardized_index_fit_paramsin advance. The output can be given here as input, and it overrides other options.**indexer (Indexer) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time().
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – Standardized Streamflow Index.
See also
xclim.compute._agro.standardized_precipitation_indexStandardized Precipitation Index.
xclim.compute.stats.standardized_indexStandardized Index.
xclim.compute.stats.standardized_index_fit_paramsStandardized Index Fit Params.
Notes
N-month SSI / N-day SSI is determined by choosing the window = N and the appropriate frequency freq.
- Supported statistical distributions are: [“genextreme”, “fisk”], where “fisk” is scipy’s implementation of
a log-logistic distribution.
If params is provided, it overrides the cal_start, cal_end, freq, window, dist, and method options.
“APP” method only supports two-parameter distributions. Parameter loc needs to be fixed to use method “APP”.
The standardized index is bounded by ±8.21. 8.21 is the largest standardized index as constrained by the float64 precision in the inversion to the normal distribution.
References
Vicente-Serrano, López-Moreno, Beguer\'ıa, Lorenzo-Lacruz, Azorin-Molina, and Morán-Tejeda [2012]
Examples
>>> from datetime import datetime >>> from xclim.compute import standardized_streamflow_index >>> ds = xr.open_dataset(path_to_q_file) >>> q = ds.q_sim >>> cal_start, cal_end = "2006-05-01", "2008-06-01" >>> ssi_3 = standardized_streamflow_index( ... q, ... freq="MS", ... window=3, ... dist="genextreme", ... method="ML", ... cal_start=cal_start, ... cal_end=cal_end, ... ) # Computing SSI-3 months using a GEV distribution for the fit >>> # Fitting parameters can also be obtained first, then reused as input. >>> from xclim.compute.stats import standardized_index_fit_params >>> params = standardized_index_fit_params( ... q.sel(time=slice(cal_start, cal_end)), ... freq="MS", ... window=3, ... dist="genextreme", ... method="ML", ... ) # First getting params >>> ssi_3 = standardized_streamflow_index(q, params=params)
- xclim.compute.tas(*args, **kwargs)[source]
Alias for tas_from_tasmin_tasmax.
This function is deprecated and will be removed in a future release. Use tas_from_tasmin_tasmax instead.
- xclim.compute.tas_from_tasmin_tasmax(tasmin, tasmax)[source]
Average temperature from minimum and maximum temperatures.
We assume a symmetrical distribution for the temperature and retrieve the average value as Tg = (Tx + Tn) / 2.
- Parameters:
tasmin (xarray.DataArray) – Minimum (daily) Temperature.
tasmax (xarray.DataArray) – Maximum (daily) Temperature.
- Return type:
DataArray- Returns:
xarray.DataArray – Mean (daily) Temperature [same units as tasmin].
Examples
>>> from xclim.compute import tas_from_tasmin_tasmax >>> tas = tas_from_tasmin_tasmax(tasmin_dataset, tasmax_dataset)
- xclim.compute.temperature_seasonality(tas, freq='YS')[source]
Temperature seasonality (coefficient of variation).
The annual temperature coefficient of variation expressed in percent. Calculated as the standard deviation of temperature values for a given year expressed as a percentage of the mean of those temperatures.
- Parameters:
tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [%] – Mean temperature coefficient of variation.
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.compute 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.compute.tg10p(tas, tas_per, freq='YS', bootstrap=False, condition='<')[source]
Number of days with daily mean temperature below the 10th percentile.
Number of days with daily mean temperature below the 10th percentile.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
tas_per (xarray.DataArray) – 10th percentile of daily mean temperature.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with daily mean temperature below the 10th percentile [days].
Notes
The 10th percentile should be computed for a 5-day window centered on each calendar day for a reference period.
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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.compute.tg90p(tas, tas_per, freq='YS', bootstrap=False, condition='>')[source]
Number of days with daily mean temperature over the 90th percentile.
Number of days with daily mean temperature over the 90th percentile.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
tas_per (xarray.DataArray) – 90th percentile of daily mean temperature.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with daily mean temperature below the 10th percentile [days].
Notes
The 90th percentile should be computed for a 5-day window centered on each calendar day for a reference period.
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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.compute.tg_days_above(tas, thresh='10.0 degC', freq='YS', op='>')[source]
The number of days with tas above a given threshold.
Number of days where mean daily temperature exceeds a threshold (default: 10℃).
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
- Returns:
xarray.DataArray, [time] – Number of days where tas {op} threshold.
Notes
Let \(TG_{ij}\) be the mean daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:
\[TG_{ij} > Threshold [℃]\]
- xclim.compute.tg_days_below(tas, thresh='10.0 degC', freq='YS', op='<')[source]
The number of days with tas below a given threshold.
Number of days where mean daily temperature is below a given threshold (default: 10℃).
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
- Returns:
xarray.DataArray, [time] – Number of days where tas {op} threshold.
Notes
Let \(TG_{ij}\) be the mean daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:
\[TG_{ij} < Threshold [℃]\]
- xclim.compute.tg_max(tas, freq='YS')[source]
Highest mean temperature.
The maximum of daily mean temperature.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tas] – Maximum of daily mean temperature.
Notes
Let \(TN_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the maximum daily mean temperature for period \(j\) is:
\[TNx_j = max(TN_{ij})\]
- xclim.compute.tg_mean(tas, freq='YS')[source]
Mean of daily average temperature.
Resample the original daily mean temperature series by taking the mean over each period.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tas] – The mean daily temperature at the given time frequency.
Notes
Let \(TN_i\) be the mean daily temperature of day \(i\), then for a period \(p\) starting at day \(a\) and finishing on day \(b\):
\[TG_p = \frac{\sum_{i=a}^{b} TN_i}{b - a + 1}\]Examples
The following would compute for each grid cell of file tas.day.nc the mean temperature at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import tg_mean >>> t = xr.open_dataset(path_to_tas_file).tas >>> tg = tg_mean(t, freq="QS-DEC")
- xclim.compute.tg_mean_warmcold_quarter(tas, op, freq='YS')[source]
Mean temperature of warmest/coldest quarter.
The warmest (or coldest) quarter of the year is determined, and the mean temperature of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”), quarters are defined as 13-week periods, otherwise as three (3) months.
- Parameters:
tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.
op ({‘warmest’, ‘coldest’}) – Operation to perform: ‘warmest’ calculates the warmest quarter. ‘coldest’ calculates the coldest quarter.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same as tas] – Mean temperature of {op} quarter.
Notes
According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.compute implementation here will calculate the result with input data with daily frequency as well. As such weekly or monthly input values, if desired, should be calculated prior to calling the function.
References
Xu and Hutchinson [2010]
Examples
The following would compute for each grid cell of file tas.day.nc the annual temperature of the warmest quarter mean temperature:
>>> from xclim.compute import tg_mean_warmcold_quarter >>> t = xr.open_dataset(path_to_tas_file) >>> t_warm_qrt = tg_mean_warmcold_quarter(tas=t.tas, op="warmest")
- xclim.compute.tg_mean_wetdry_quarter(tas, pr, op, freq='YS')[source]
Mean temperature of wettest/driest quarter.
The wettest (or driest) quarter of the year is determined, and the mean temperature of this period is calculated. If the input data frequency is daily (“D”) or weekly (“W”), quarters are defined as 13-week periods, otherwise as three (3) months.
- Parameters:
tas (xarray.DataArray) – Mean temperature at daily, weekly, or monthly frequency.
pr (xarray.DataArray) – Total precipitation rate at daily, weekly, or monthly frequency.
op ({“wettest”, “driest”}) – Operation to perform: ‘wettest’ calculates the wettest quarter. ‘driest’ calculates the driest quarter.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same as tas] – Mean temperature of {op} quarter.
Notes
According to the ANUCLIM user-guide (Xu and Hutchinson [2010], ch. 6), input values should be at a weekly (or monthly) frequency. However, the xclim.compute implementation here will calculate the result with input data with daily frequency as well. As such, weekly or monthly input values, if desired, should be calculated before calling the function.
References
Xu and Hutchinson [2010]
- xclim.compute.tg_min(tas, freq='YS')[source]
Lowest mean temperature.
Minimum of daily mean temperature.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tas] – Minimum of daily minimum temperature.
Notes
Let \(TG_{ij}\) be the mean temperature at day \(i\) of period \(j\). Then the minimum daily mean temperature for period \(j\) is:
\[TGn_j = min(TG_{ij})\]
- xclim.compute.tn10p(tasmin, tasmin_per, freq='YS', bootstrap=False, condition='<')[source]
Number of days with daily minimum temperature below the 10th percentile.
Number of days with daily minimum temperature below the 10th percentile.
- Parameters:
tasmin (xarray.DataArray) – Mean daily temperature.
tasmin_per (xarray.DataArray) – 10th percentile of daily minimum temperature.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with daily minimum temperature below the 10th percentile [days].
Notes
The 10th percentile should be computed for a 5-day window centered on each calendar day for a reference period.
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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.compute.tn90p(tasmin, tasmin_per, freq='YS', bootstrap=False, condition='>')[source]
Number of days with daily minimum temperature over the 90th percentile.
Number of days with daily minimum temperature over the 90th percentile.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
tasmin_per (xarray.DataArray) – 90th percentile of daily minimum temperature.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with daily minimum temperature below the 10th percentile [days].
Notes
The 90th percentile should be computed for a 5-day window centered on each calendar day for a reference period.
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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.compute.tn_days_above(tasmin, thresh='20.0 degC', freq='YS', op='>')[source]
The number of days with tasmin above a threshold (number of tropical nights).
Number of days where minimum daily temperature exceeds a threshold (default: 20℃).
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
- Returns:
xarray.DataArray, [time] – Number of days where tasmin {op} threshold.
Notes
Let \(TN_{ij}\) be the minimum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:
\[TN_{ij} > Threshold [℃]\]
- xclim.compute.tn_days_below(tasmin, thresh='-10.0 degC', freq='YS', op='<')[source]
Number of days with tasmin below a given threshold.
Number of days where minimum daily temperature is below a given threshold (default: -10℃).
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days where tasmin {op} threshold.
Notes
Let \(TN_{ij}\) be the minimum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:
\[TN_{ij} < Threshold [℃]\]
- xclim.compute.tn_max(tasmin, freq='YS')[source]
Highest minimum temperature.
The maximum of daily minimum temperature.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmin] – Maximum of daily minimum temperature.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then the maximum daily minimum temperature for period \(j\) is:
\[TNx_j = max(TN_{ij})\]
- xclim.compute.tn_mean(tasmin, freq='YS')[source]
Mean minimum temperature.
Mean of daily minimum temperature.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmin] – Mean of daily minimum temperature.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:
\[TN_{ij} = \frac{ \sum_{i=1}^{I} TN_{ij} }{I}\]
- xclim.compute.tn_min(tasmin, freq='YS')[source]
Lowest minimum temperature.
Minimum of daily minimum temperature.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmin] – Minimum of daily minimum temperature.
Notes
Let \(TN_{ij}\) be the minimum temperature at day \(i\) of period \(j\). Then the minimum daily minimum temperature for period \(j\) is:
\[TNn_j = min(TN_{ij})\]
- xclim.compute.tx10p(tasmax, tasmax_per, freq='YS', bootstrap=False, condition='<')[source]
Number of days with daily maximum temperature below the 10th percentile.
Number of days with daily maximum temperature below the 10th percentile.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
tasmax_per (xarray.DataArray) – 10th percentile of daily maximum temperature.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“<”, “<=”, “lt”, “le”}) – Comparison operation. Default: “<”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with daily maximum temperature below the 10th percentile [days].
Notes
The 10th percentile should be computed for a 5-day window centered on each calendar day for a reference period.
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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.compute.tx90p(tasmax, tasmax_per, freq='YS', bootstrap=False, condition='>')[source]
Number of days with daily maximum temperature over the 90th percentile.
Number of days with daily maximum temperature over the 90th percentile.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
tasmax_per (xarray.DataArray) – 90th percentile of daily maximum temperature.
freq (str) – Resampling frequency.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Count of days with daily maximum temperature below the 10th percentile [days].
Notes
The 90th percentile should be computed for a 5-day window centered on each calendar day for a reference period.
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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.compute.tx_days_above(tasmax, thresh='25.0 degC', freq='YS', op='>')[source]
The number of days with tasmax above a given threshold (number of summer days).
Number of days where maximum daily temperature exceeds a given threshold (default: 25℃).
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days where tasmax {op} threshold (number of summer days).
Notes
Let \(TX_{ij}\) be the maximum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:
\[TX_{ij} > Threshold [℃]\]
- xclim.compute.tx_days_below(tasmax, thresh='25.0 degC', freq='YS', op='<')[source]
The number of days with tasmax below a given threshold.
Number of days where maximum daily temperature is below a given threshold (default: 25℃).
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“<”, “lt”, “<=”, “le”}) – Comparison operation. Default: “<”.
- Returns:
xarray.DataArray, [time] – Number of days where tasmin {op} threshold.
Notes
Let \(TX_{ij}\) be the maximum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:
\[TX_{ij} < Threshold [℃]\]
- xclim.compute.tx_max(tasmax, freq='YS')[source]
Highest max temperature.
The maximum value of daily maximum temperature.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmax] – Maximum value of daily maximum temperature.
Notes
Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then the maximum daily maximum temperature for period \(j\) is:
\[TXx_j = max(TX_{ij})\]
- xclim.compute.tx_mean(tasmax, freq='YS')[source]
Mean max temperature.
The mean of daily maximum temperature.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmax] – Mean of daily maximum temperature.
Notes
Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then mean values in period \(j\) are given by:
\[TX_{ij} = \frac{ \sum_{i=1}^{I} TX_{ij} }{I}\]
- xclim.compute.tx_min(tasmax, freq='YS')[source]
Lowest max temperature.
The minimum of daily maximum temperature.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [same units as tasmax] – Minimum of daily maximum temperature.
Notes
Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\). Then the minimum daily maximum temperature for period \(j\) is:
\[TXn_j = min(TX_{ij})\]
- xclim.compute.tx_tn_days_above(tasmin, tasmax, thresh_tasmin='22 degC', thresh_tasmax='30 degC', freq='YS', condition='>')[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.
condition ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – The number of days with tasmin > thresh_tasmin and tasmax > thresh_tasmax per period.
Notes
Let \(TX_{ij}\) be the maximum temperature at day \(i\) of period \(j\), \(TN_{ij}\) the daily minimum temperature at day \(i\) of period \(j\), \(TX_{thresh}\) the threshold for maximum daily temperature, and \(TN_{thresh}\) the threshold for minimum daily temperature. Then counted is the number of days where:
\[TX_{ij} > TX_{thresh} [℃]\]and where:
\[TN_{ij} > TN_{thresh} [℃]\]
- xclim.compute.uas_vas_to_sfcwind(uas, vas, calm_wind_thresh='0.5 m/s')[source]
Wind speed and direction from the eastward and northward wind components.
Computes the magnitude and angle of the wind vector from its northward and eastward components, following the meteorological convention that sets calm wind to a direction of 0° and northerly wind to 360°.
- Parameters:
uas (xr.DataArray) – Eastward Wind Velocity.
vas (xr.DataArray) – Northward Wind Velocity.
calm_wind_thresh (Quantified) – The threshold under which winds are considered “calm” and for which the direction is set to 0. On the Beaufort scale, calm winds are defined as < 0.5 m/s.
- Return type:
tuple[DataArray,DataArray]- Returns:
wind (xr.DataArray, [m s-1]) – Wind Velocity.
wind_from_dir (xr.DataArray, [°]) – Direction from which the wind blows, following the meteorological convention where 360 stands for North and 0 for calm winds.
Notes
Winds with a velocity less than calm_wind_thresh are given a wind direction of 0°, while stronger northerly winds are set to 360°.
Examples
>>> from xclim.compute import uas_vas_to_sfcwind >>> sfcWind = uas_vas_to_sfcwind(uas=uas_dataset, vas=vas_dataset, calm_wind_thresh="0.5 m/s")
- xclim.compute.universal_thermal_climate_index(tas, hurs, sfcWind, mrt=None, rsds=None, rsus=None, rlds=None, rlus=None, stat='sunlit', mask_invalid=True, wind_cap_min=False)[source]
Universal thermal climate index (UTCI).
The UTCI is the equivalent temperature for the environment derived from a reference environment and is used to evaluate heat stress in outdoor spaces.
- Parameters:
tas (xarray.DataArray) – Mean Temperature.
hurs (xarray.DataArray) – Relative Humidity.
sfcWind (xarray.DataArray) – Wind Velocity.
mrt (xarray.DataArray, optional) – Mean Radiant Temperature.
rsds (xr.DataArray, optional) – Surface Downwelling Shortwave Radiation. This is necessary if mrt is not None.
rsus (xr.DataArray, optional) – Surface Upwelling Shortwave Radiation. This is necessary if mrt is not None.
rlds (xr.DataArray, optional) – Surface Downwelling Longwave Radiation. This is necessary if mrt is not None.
rlus (xr.DataArray, optional) – Surface Upwelling Longwave Radiation. This is necessary if mrt is not None.
stat ({‘instant’, ‘sunlit’}) – Which statistic to apply. If “instant”, the instantaneous cosine of the solar zenith angle is calculated. If “sunlit”, the cosine of the solar zenith angle is calculated during the sunlit period of each interval. This is necessary if mrt is not None.
mask_invalid (bool) – If True (default), UTCI values are NaN where any of the inputs are outside their validity ranges: - -50°C < tas < 50°C. - -30°C < tas - mrt < 30°C. - 0.5 m/s < sfcWind < 17.0 m/s.
wind_cap_min (bool) – If True, wind velocities are capped to a minimum of 0.5 m/s following Bröde et al. [2012] usage guidelines. This ensures UTCI calculation for low winds. Default value False.
- Return type:
DataArray- Returns:
xarray.DataArray – Universal Thermal Climate Index.
Notes
The calculation uses water vapour partial pressure, which is derived from relative humidity and saturation vapour pressure computed according to the ITS-90 equation.
This code was inspired by the pythermalcomfort and thermofeel packages.
For more information: https://www.utci.org/
References
Błażejczyk, Jendritzky, Bröde, Fiala, Havenith, Epstein, Psikuta, and Kampmann [2013], Bröde [2009], Bröde, Fiala, Błażejczyk, Holmér, Jendritzky, Kampmann, Tinz, and Havenith [2012]
- xclim.compute.vapor_pressure(huss, ps)[source]
Vapour pressure.
Computes the water vapour partial pressure in Pa from the specific humidity and the total pressure.
- Parameters:
huss (xr.DataArray) – Specific humidity [kg/kg].
ps (xr.DataArray) – Pressure.
- Returns:
xr.DataArray, [pressure] – Water vapour partial pressure.
Notes
The vapour pressure \(\epsilon\) is computed with:
\[e = \frac{pq}{\epsilon + (1 - \epsilon)q}\]Where \(p\) is the pressure, \(q\) is the specific humidity and \(\epsilon\) us the ratio of the dry air gas constant to the water vapor gas constant : \(\frac{R_{dry}}{R_{vapor}} = 0.62198\).
- xclim.compute.vapor_pressure_deficit(tas, hurs, ice_thresh=None, method='sonntag90', interp_power=None, water_thresh='0 °C')[source]
Vapour pressure deficit.
The measure of the moisture deficit of the air, computed from temperature and relative humidity.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature.
hurs (xarray.DataArray) – Relative humidity.
ice_thresh (Quantified, optional) – Threshold temperature under which to switch to equations in reference to ice instead of water. If None (default) everything is computed with reference to water.
method ({“goffgratch46”, “sonntag90”, “tetens30”, “wmo08”, “its90”, “ecmwf”}) – Method used to calculate saturation vapour pressure, see notes of
saturation_vapor_pressure(). Default is “sonntag90”.interp_power (int or None) – Optional interpolation for mixing saturation vapour pressures computed over water and ice. See
saturation_vapor_pressure().water_thresh (Quantified) – When
interp_poweris given, this is the threshold temperature above which the formulas with reference to water are used.
- Return type:
DataArray- Returns:
xarray.DataArray, [Pa] – Vapour pressure deficit.
See also
saturation_vapor_pressureVapour pressure at saturation.
- xclim.compute.warm_and_dry_days(tas, pr, tas_per, pr_per, freq='YS')[source]
Warm and dry days.
Returns the total number of days when “warm” and “Dry” conditions coincide.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature values.
pr (xarray.DataArray) – Daily precipitation.
tas_per (xarray.DataArray) – Third quartile of daily mean temperature computed by month.
pr_per (xarray.DataArray) – First quartile of daily total precipitation computed by month.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The total number of days when warm and dry conditions coincide.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
Notes
Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.
Formula to be written (Beniston [2009]).
References
Beniston [2009]
- xclim.compute.warm_and_wet_days(tas, pr, tas_per, pr_per, freq='YS')[source]
Warm and wet days.
Returns the total number of days when “warm” and “wet” conditions coincide.
- Parameters:
tas (xarray.DataArray) – Mean daily temperature values.
pr (xarray.DataArray) – Daily precipitation.
tas_per (xarray.DataArray) – Third quartile of daily mean temperature computed by month.
pr_per (xarray.DataArray) – Third quartile of daily total precipitation computed by month.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The total number of days when warm and wet conditions coincide.
Warning
Before computing the percentiles, all the precipitation below 1mm must be filtered out! Otherwise, the percentiles will include non-wet days.
Notes
Bootstrapping is not available for quartiles because it would make no significant difference to bootstrap percentiles so far from the extremes.
Formula to be written (Beniston [2009]).
References
Beniston [2009]
- xclim.compute.warm_day_frequency(tasmax, thresh='30 degC', freq='YS', op='>')[source]
Frequency of extreme warm days.
Return the number of days with maximum daily temperature exceeding a given threshold (default: 30℃) per period.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days with tasmax {op} threshold per period.
Notes
Let \(TX_{ij}\) be the maximum daily temperature at day \(i\) of period \(j\). Then counted is the number of days where:
\[TN_{ij} > Threshold [℃]\]
- xclim.compute.warm_night_frequency(tasmin, thresh='22 degC', freq='YS', op='>')[source]
Frequency of extreme warm nights.
Return the number of days with minimum daily temperatures exceeding a given threshold (default: 22℃) per period.
- Parameters:
tasmin (xarray.DataArray) – Minimum daily temperature.
thresh (Quantified) – Threshold temperature on which to base evaluation.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days with tasmin {op} threshold per period.
- xclim.compute.warm_spell_duration_index(tasmax, tasmax_per, window=6, freq='YS', resample_before_rl=True, bootstrap=False, condition='>')[source]
Warm spell duration index.
Number of days inside spells of a minimum number of consecutive days when the daily maximum temperature is above the 90th percentile. The 90th percentile should be computed for a 5-day moving window, centered on each calendar day in the 1961-1990 period.
- Parameters:
tasmax (xarray.DataArray) – Maximum daily temperature.
tasmax_per (xarray.DataArray) – Percentile(s) of daily maximum temperature.
window (int) – Minimum number of days with temperature above threshold to qualify as a warm spell.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
bootstrap (bool) – Flag to run bootstrapping of percentiles. Used by percentile_bootstrap decorator. Bootstrapping is only useful when the percentiles are computed on a part of the studied sample. This period, common to percentiles and the sample must be bootstrapped to avoid inhomogeneities with the rest of the time series. Do not enable bootstrap when there is no common period, otherwise it will provide the wrong results. Note that bootstrapping is computationally expensive.
condition ({“>”, “>=”, “gt”, “ge”}) – Comparison operation. Default: “>”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Warm spell duration index.
References
From the Expert Team on Climate Change Detection, Monitoring and Indices (ETCCDMI; [Zhang et al., 2011]). Used in Alexander, Zhang, Peterson, Caesar, Gleason, Klein Tank, Haylock, Collins, Trewin, Rahimzadeh, Tagipour, Rupa Kumar, Revadekar, Griffiths, Vincent, Stephenson, Burn, Aguilar, Brunet, Taylor, New, Zhai, Rusticucci, and Vazquez-Aguirre [2006]
Examples
Note that this example does not use a proper 1961-1990 reference period.
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute 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) >>> wsdi = warm_spell_duration_index(tasmax, tasmax_per)
- xclim.compute.water_budget(pr, evspsblpot=None, tasmin=None, tasmax=None, tas=None, lat=None, hurs=None, rsds=None, rsus=None, rlds=None, rlus=None, sfcWind=None, method='BR65')[source]
Precipitation minus potential evapotranspiration.
Precipitation minus potential evapotranspiration as a measure of an approximated surface water budget, where the potential evapotranspiration can be calculated with a given method.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
evspsblpot (xarray.DataArray, optional) – Potential evapotranspiration.
tasmin (xarray.DataArray, optional) – Minimum daily temperature.
tasmax (xarray.DataArray, optional) – Maximum daily temperature.
tas (xarray.DataArray, optional) – Mean daily temperature.
lat (xarray.DataArray, optional) – Latitude coordinate, needed if evspsblpot is not given. If None, a CF-conformant “latitude” field must be available within the pr DataArray.
hurs (xarray.DataArray, optional) – Relative humidity.
rsds (xarray.DataArray, optional) – Surface Downwelling Shortwave Radiation.
rsus (xarray.DataArray, optional) – Surface Upwelling Shortwave Radiation.
rlds (xarray.DataArray, optional) – Surface Downwelling Longwave Radiation.
rlus (xarray.DataArray, optional) – Surface Upwelling Longwave Radiation.
sfcWind (xarray.DataArray, optional) – Surface wind velocity (at 10 m).
method (str) – Method to use to calculate the potential evapotranspiration.
- Return type:
DataArray- Returns:
xarray.DataArray – Precipitation minus potential evapotranspiration.
See also
xclim.indicators.atmos.potential_evapotranspirationPotential evapotranspiration calculation.
- xclim.compute.water_cycle_intensity(pr, evspsbl, freq='YS')[source]
Water cycle intensity.
The sum of precipitation and actual evapotranspiration.
- Parameters:
pr (xarray.DataArray) – Precipitation flux.
evspsbl (xarray.DataArray) – Actual evapotranspiration flux.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – The sum of precipitation and actual evapotranspiration for each period.
References
Huntington, Weiskel, Wolock, and McCabe [2018]
- xclim.compute.wet_spell_frequency(pr, thresh='1.0 mm', window=3, freq='YS', resample_before_rl=True, op='sum', **indexer)[source]
Return the number of wet periods of n days and more.
Periods during which the accumulated, minimal, or maximal daily precipitation amount within a window of n days is over a given threshold.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Precipitation amount over which a period is considered dry. The value against which the threshold is compared depends on op.
window (int) – Minimum length of the spells.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
op ({“sum”, “min”, “max”, “mean”}) – Operation to perform on the window. Default is “sum”, which checks that the sum of accumulated precipitation over the whole window is more than the threshold. “min” checks that the maximal daily precipitation amount within the window is more than the threshold. This is the same as verifying that each individual day is above the threshold.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time(). Indexing is done after finding the wet days, but before finding the spells.
- Return type:
DataArray- Returns:
xarray.DataArray, [unitless] – The {freq} number of wet periods of minimum {window} days.
See also
xclim.compute.generic.spell_length_statisticsThe parent function that computes the spell length statistics.
Examples
>>> from xclim.compute import wet_spell_frequency >>> pr = xr.open_dataset(path_to_pr_file).pr >>> dsf_sum = wet_spell_frequency(pr=pr, op="sum") >>> dsf_min = wet_spell_frequency(pr=pr, op="min")
- xclim.compute.wet_spell_max_length(pr, thresh='1.0 mm', window=1, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]
Longest wet spell.
The maximum number of consecutive days in a wet period of minimum length, during which the minimum or accumulated precipitation within a window of the same length is over a threshold.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Accumulated precipitation value over which a period is considered wet.
window (int) – Number of days when the maximum or accumulated precipitation is over threshold.
op ({“min”, “sum”, “max”, “mean”}) – Reduce operation. min means that all days within the minimum window must exceed the threshold. sum means that the accumulated precipitation within the window must exceed the threshold. In all cases, the whole window is marked a part of a wet spell.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time(). Indexing is done after finding the wet days, but before finding the spells.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} longest spell in wet periods of minimum {window} days.
See also
xclim.compute.generic.spell_length_statisticsThe parent function that computes the spell length statistics.
Notes
The algorithm assumes days before and after the timeseries are “dry”, meaning that the condition for being considered part of a wet spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a wet spell only if the accumulated precipitation within the first three days is over the threshold. In comparison, a day in the middle of the series is considered part of a wet spell if any of the three 3-day periods of which it is part are considered wet (so a total of five days are included in the computation, compared to only three).
- xclim.compute.wet_spell_total_length(pr, thresh='1.0 mm', window=3, op='sum', freq='YS', resample_before_rl=True, **indexer)[source]
Total length of wet spells.
Total number of days in wet periods of a minimum length, during which the minimum or accumulated precipitation within a window of the same length is over a threshold.
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Accumulated precipitation value over which a period is considered wet.
window (int) – Number of days when the maximum or accumulated precipitation is over the threshold.
op ({“min”, “sum”, “max”, “mean”}) – Reduce operation. min means that all days within the minimum window must exceed the threshold. sum means that the accumulated precipitation within the window must exceed the threshold. In all cases, the whole window is marked a part of a wet spell.
freq (str) – Resampling frequency.
resample_before_rl (bool) – Determines if the resampling should take place before or after the run length encoding (or a similar algorithm) is applied to runs.
**indexer ({dim: indexer}, optional) – Indexing parameters to compute the indicator on a temporal subset of the data. It accepts the same arguments as
xclim.compute.generic.select_time(). Indexing is done after finding the wet days, but before finding the spells.
- Return type:
DataArray- Returns:
xarray.DataArray, [days] – The {freq} total number of days in wet periods of minimum {window} days.
See also
xclim.compute.generic.spell_length_statisticsThe parent function that computes the spell length statistics.
Notes
The algorithm assumes days before and after the timeseries are “dry”, meaning that the condition for being considered part of a wet spell is stricter on the edges. For example, with window=3 and op=’sum’, the first day of the series is considered part of a wet spell only if the accumulated precipitation within the first three days is over the threshold. In comparison, a day in the middle of the series is considered part of a wet spell if any of the three 3-day periods of which it is part are considered wet (so a total of five days are included in the computation, compared to only three).
- xclim.compute.wetdays(pr, thresh='1.0 mm/day', freq='YS', op='>=')[source]
Wet days.
Return the total number of days during period with precipitations over a given threshold (default: 1.0 mm/day).
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Precipitation value over which a day is considered wet.
freq (str) – Resampling frequency.
op ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – The number of wet days for each period [day].
Examples
The following would compute for each grid cell of file pr.day.nc the number days with precipitation over 5 mm at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import wetdays >>> pr = xr.open_dataset(path_to_pr_file).pr >>> wd = wetdays(pr, thresh="5 mm/day", freq="QS-DEC")
- xclim.compute.wetdays_prop(pr, thresh='1.0 mm/day', freq='YS', condition='>=')[source]
Proportion of wet days.
Return the proportion of days during period with precipitations over a given threshold (default: 1.0 mm/day).
- Parameters:
pr (xarray.DataArray) – Daily precipitation.
thresh (Quantified) – Precipitation value over which a day is considered wet.
freq (str) – Resampling frequency.
condition ({“>”, “gt”, “>=”, “ge”}) – Comparison operation. Default: “>=”.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – The proportion of wet days for each period [1].
Examples
The following would compute for each grid cell of file pr.day.nc the proportion of days with precipitation over 5 mm at the seasonal frequency, i.e. DJF, MAM, JJA, SON, DJF, etc.:
>>> from xclim.compute import wetdays_prop >>> pr = xr.open_dataset(path_to_pr_file).pr >>> wd = wetdays_prop(pr, thresh="5 mm/day", freq="QS-DEC")
- xclim.compute.wind_chill_index(tas, sfcWind, method='CAN', mask_invalid=True)[source]
Wind chill index.
The Wind Chill Index is an estimation of how cold the weather feels to the average person. It is computed from the air temperature and the 10-m wind. As defined by the Environment and Climate Change Canada (Mekis, Vincent, Shephard, and Zhang [2015]), two equations exist, the conventional one and one for slow winds (usually < 5 km/h), see Notes.
- Parameters:
tas (xarray.DataArray) – Surface air temperature.
sfcWind (xarray.DataArray) – Surface wind speed (10 m).
method ({‘CAN’, ‘US’}) – If “CAN” (default), a “slow wind” equation is used where winds are slower than 5 km/h, see Notes.
mask_invalid (bool) – Whether to mask values when the inputs are outside their validity range. or not. If True (default), points where the temperature is above a threshold are masked. The threshold is 0°C for the canadian method and 50°F for the american one. With the latter method, points where sfcWind < 3 mph are also masked.
- Return type:
DataArray- Returns:
xarray.DataArray, [degC] – Wind Chill Index.
Notes
Following the calculations of Environment and Climate Change Canada, this function switches from the standardized index to another one for slow winds. The standard index is the same as used by the National Weather Service of the USA [US Department of Commerce, n.d.]. Given a temperature at surface \(T\) (in °C) and 10-m wind speed \(V\) (in km/h), the Wind Chill Index \(W\) (dimensionless) is computed as:
\[W = 13.12 + 0.6125*T - 11.37*V^0.16 + 0.3965*T*V^0.16\]Under slow winds (\(V < 5\) km/h), and using the canadian method, it becomes:
\[W = T + \frac{-1.59 + 0.1345 * T}{5} * V\]Both equations are invalid for temperature over 0°C in the canadian method.
The american Wind Chill Temperature index (WCT), as defined by USA’s National Weather Service, is computed when method=’US’. In that case, the maximal valid temperature is 50°F (10 °C) and minimal wind speed is 3 mph (4.8 km/h).
For more information, see:
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.compute.wind_power_potential(wind_speed, air_density=None, cut_in='3.5 m/s', rated='13 m/s', cut_out='25 m/s')[source]
Wind power potential estimated from an idealized wind power production factor.
The actual power production of a wind farm can be estimated by multiplying its nominal (nameplate) capacity by the wind power potential, which depends on wind speed at the hub height, the turbine specifications and air density.
- Parameters:
wind_speed (xarray.DataArray) – Wind Speed at the hub height. Use the wind_profile function to estimate from the surface wind speed.
air_density (xarray.DataArray) – Air Density at the hub height. Defaults to 1.225 kg/m³. This is worth changing if applying in cold or mountainous regions with non-standard air density.
cut_in (Quantified) – Cut-in wind speed. Default is 3.5 m/s.
rated (Quantified) – Rated wind speed. Default is 13 m/s.
cut_out (Quantified) – Cut-out wind speed. Default is 25 m/s.
- Return type:
DataArray- Returns:
xr.DataArray – The power production factor. Multiply by the nominal capacity to get the actual power production.
See also
wind_profileEstimate wind speed at the hub height from the surface wind speed.
Notes
This estimate of wind power production is based on an idealized power curve with four wind regimes specified by the cut-in wind speed (\(u_i\)), the rated speed (\(u_r\)) and the cut-out speed (\(u_o\)). Power production is zero for wind speeds below the cut-in speed, increases cubically between the cut-in and rated speed, is constant between the rated and cut-out speed, and is zero for wind speeds above the cut-out speed to avoid damage to the turbine [Tobin et al., 2018]:
\[\begin{split}\begin{cases} 0, & v < u_i \\ (v^3 - u_i^3) / (u_r^3 - u_i^3), & u_i ≤ v < u_r \\ 1, & u_r ≤ v < u_o \\ 0, & v ≥ u_o \end{cases}\end{split}\]For non-standard air density (\(\rho\)), the wind speed is scaled using \(v_n = v \left( \frac{\rho}{\rho_0} \right)^{1/3}\).
The temporal resolution of wind time series has a significant influence on the results: mean daily wind speeds yield lower values than hourly wind speeds. Note however that percent changes in the wind power potential climate projections are similar across resolutions [Chen, 2020].
To compute the power production, multiply the power production factor by the nominal turbine capacity (e.g. 100), set the units attribute (e.g. “MW”), resample and sum with xclim.compute.generic.select_resample_op(power, op=”sum”, freq=”D”), then convert to the desired units (e.g. “MWh”) using xclim.core.units.convert_units_to.
References
Chen [2020], Tobin, Greuell, Jerez, Ludwig, Vautard, van Vliet, and Bréon [2018].
- xclim.compute.wind_profile(wind_speed, h, h_r, method='power_law', **kwds)[source]
Wind speed at a given height estimated from the wind speed at a reference height.
Estimate the wind speed based on a power law profile relating wind speed to height above the surface.
- Parameters:
wind_speed (xarray.DataArray) – Wind Speed at the reference height.
h (Quantified) – Height at which to compute the Wind Speed.
h_r (Quantified) – Reference height.
method ({“power_law”}) – Method to use. Currently only “power_law” is implemented.
**kwds (dict) – Additional keyword arguments to pass to the method.For power_law, this is alpha, which takes a default value of 1/7, but is highly variable based on topography, surface cover and atmospheric stability.
- Return type:
DataArray- Returns:
xarray.DataArray – Wind Speed at the desired height.
Notes
The power law profile is given by:
\[v = v_r \left( \frac{h}{h_r} \right)^{\alpha},\]where \(v_r\) is the wind speed at the reference height, \(h\) is the height at which the wind speed is desired, and \(h_r\) is the reference height.
- xclim.compute.windy_days(sfcWind, thresh='10.8 m s-1', freq='MS')[source]
Windy days.
The number of days with average near-surface wind speed above a given threshold (default: 10.8 m/s).
- Parameters:
sfcWind (xarray.DataArray) – Daily average near-surface wind speed.
thresh (Quantified) – Threshold average near-surface wind speed on which to base evaluation.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray, [time] – Number of days with average near-surface wind speed above threshold.
Notes
Let \(WS_{ij}\) be the windspeed at day \(i\) of period \(j\). Then counted is the number of days where:
\[WS_{ij} >= Threshold [m s-1]\]
- xclim.compute.winter_rain_ratio(*, pr, prsn=None, tas=None, freq='QS-DEC')[source]
Ratio of rainfall to total precipitation during winter.
The ratio of total liquid precipitation over the total precipitation over the winter months (DJF). If solid precipitation is not provided, then precipitation is assumed solid if the temperature is below 0°C.
- Parameters:
pr (xarray.DataArray) – Mean daily precipitation flux.
prsn (xarray.DataArray, optional) – Mean daily solid precipitation flux.
tas (xarray.DataArray, optional) – Mean daily temperature.
freq (str) – Resampling frequency.
- Return type:
DataArray- Returns:
xarray.DataArray – Ratio of rainfall to total precipitation during winter months (DJF).
Fire indices submodule¶
Compute functions 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.
Canadian Forest Fire Weather Index System¶
This submodule defines the xclim.compute.fire.fire_season(), xclim.compute.fire.drought_code() and
xclim.compute.fire.cffwis_indices() compute functions, which are used by the eponym indicators.
Users should read this module’s documentation and the one of fire_weather_ufunc(). They should also consult the
information available at Natural Resources Canada [n.d.].
First adapted from Matlab code CalcFWITimeSeriesWithStartup.m from GFWED [Wang et al., 2015] made for using MERRA2 data, which was a translation of FWI.vba of the Canadian Fire Weather Index system. Then, updated and synchronized with the R code of the cffdrs package. When given the correct parameters, the current code has an error below 3% when compared with the Field et al. [2015] data. The cffdrs R package is different from the original 1982 implementation, and so is xclim.
Parts of the code and of the documentation in this submodule are directly taken from Cantin et al. [2014] which was published with the GPLv2 license.
Fire season¶
Fire weather indexes are iteratively computed, each day’s value depending on the previous day indexes. Additionally and optionally, the codes are “shut down” (set to NaN) in winter. There are a few ways of computing this shut down and the subsequent spring start-up. The fire_season function allows for full control of that, replicating the fireSeason method in the R package. It produces a mask to be given a season_mask in the indicators. However, the fire_weather_ufunc and the indicators also accept a season_method parameter so the fire season can be computed inside the iterator. Passing season_method=None switches to an “always on” mode replicating the fire method of the R package.
The fire season determination is based on three consecutive daily maximum temperature thresholds [Lawson and Armitage, 2008, Wotton and Flannigan, 1993]. A “GFWED” method is also implemented. There, the 12h LST temperature is used instead of the daily maximum. The current implementation is slightly different from the description in Field et al. [2015], but it replicates the Matlab code when temp_start_thresh and temp_end_thresh are both set to 6 degC. In xclim, the number of consecutive days, the start and end temperature thresholds and the snow depth threshold can all be modified.
Overwintering¶
Additionally, overwintering of the drought code is also directly implemented in fire_weather_ufunc().
The last drought_code of the season is kept in “winter” (where the fire season mask is False) and the precipitation
is accumulated until the start of the next season. The first drought code is computed as a function of these instead
of using the default DCStart value. Parameters to _overwintering_drought_code() are listed below.
The code for the overwintering is based on
McElhinny et al. [2020], Van Wagner [1985].
Finally, a mechanism for dry spring starts is implemented. For now, it is slightly different from what the GFWED, uses,
but seems to agree with the state of the science of the CFS. When activated, the drought code and Duff-moisture codes
are started in spring with a value that is function of the number of days since the last significant precipitation
event. The conventional start value increased by that number of days times a “dry start” factor. Parameters are
controlled in the call of the compute functions 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 functions defined in this very module, but we always recommend using the
_indicators_ defined in the xclim.atmos module.
>>> ds = xr.open_dataset("ERA5/daily_surface_cancities_1990-1993.nc")
>>> ds = ds.assign(
... hurs=xclim.convert.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.convert.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 = xr.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.compute.fire._cffwis.cffwis_indices(tas, pr, sfcWind, hurs, lat, snd=None, ffmc0=None, dmc0=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=True, **params)[source]
Canadian Fire Weather Index System indices.
Computes the six (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 - 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 (dict) – Any other keyword parameters as defined in
fire_weather_ufunc()and indefault_params.
- Return type:
tuple[DataArray,DataArray,DataArray,DataArray,DataArray,DataArray]- Returns:
DC (xr.DataArray, [dimensionless]) – The Drought Code.
DMC (xr.DataArray, [dimensionless]) – The Duff Moisture Code.
FFMC (xr.DataArray, [dimensionless]) – The Fine Fuel Moisture Code.
ISI (xr.DataArray, [dimensionless]) – The Initial Spread Index.
BUI (xr.DataArray, [dimensionless]) – The Build Up Index.
FWI (xr.DataArray, [dimensionless]) – The Fire Weather Index.
Notes
See Natural Resources Canada [n.d.], the
xclim.compute.firemodule documentation, and the docstring offire_weather_ufunc()for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.References
Wang, Anderson, and Suddaby [2015]
- xclim.compute.fire._cffwis.drought_code(tas, pr, lat, snd=None, dc0=None, season_mask=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=True, **params)[source]
Drought code (FWI component).
The drought code is part of the Canadian Forest Fire Weather Index System. It is a numeric rating of the average moisture content of organic layers.
- Parameters:
tas (xr.DataArray) – Noon temperature.
pr (xr.DataArray) – Rain fall in open over previous 24 hours, at noon.
lat (xr.DataArray) – Latitude coordinate.
snd (xr.DataArray) – Noon snow depth.
dc0 (xr.DataArray) – Initial values of the drought code.
season_mask (xr.DataArray, optional) – Boolean mask, True where/when the fire season is active.
season_method ({None, “WF93”, “LA08”, “GFWED”}) – How to compute the start-up and shutdown of the fire season. If “None”, no start-ups or shutdowns are computed, similar to the R fire function. Ignored if season_mask is given.
overwintering (bool) – Whether to activate DC overwintering or not. If True, either season_method or season_mask must be given.
dry_start ({None, “CFS”, ‘GFWED’}) – Whether to activate the DC and DMC “dry start” mechanism and which method to use. See
fire_weather_ufunc().initial_start_up (bool) – If True (default), grid points where the fire season is active on the first timestep go through a start_up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.
**params (dict) – Any other keyword parameters as defined in xclim.compute.fire.fire_weather_ufunc and in
default_params.
- Return type:
DataArray- Returns:
xr.DataArray, [dimensionless] – Drought code.
Notes
See Natural Resources Canada [n.d.], the
xclim.compute.firemodule documentation, and the docstring offire_weather_ufunc()for more information. This algorithm follows the official R code released by the CFS, which contains revisions from the original 1982 Fortran code.References
Wang, Anderson, and Suddaby [2015]
- xclim.compute.fire._cffwis.fire_season(tas, snd=None, method='WF93', freq=None, temp_start_thresh='12 degC', temp_end_thresh='5 degC', temp_condition_days=3, snow_condition_days=3, snow_thresh='0.01 m')[source]
Fire season mask.
Binary mask of the active fire season, defined by conditions on consecutive daily temperatures and, optionally, snow depths.
- Parameters:
tas (xr.DataArray) – Daily surface temperature, cffdrs recommends using maximum daily temperature.
snd (xr.DataArray, optional) – Snow depth, used with method == ‘LA08’.
method ({“WF93”, “LA08”, “GFWED”}) – Which method to use. “LA08” and “GFWED” need the snow depth.
freq (str, optional) – If given only the longest fire season for each period defined by this frequency, Every “seasons” are returned if None, including the short shoulder seasons.
temp_start_thresh (Quantified) – Minimal temperature needed to start the season. Must be scalar.
temp_end_thresh (Quantified) – Maximal temperature needed to end the season. Must be scalar.
temp_condition_days (int) – Number of days with temperature above or below the thresholds to trigger a start or an end of the fire season.
snow_condition_days (int) – Parameters for the fire season determination. See
fire_season(). Temperature is in degC, snow in m. The snow_thresh parameters is also used when dry_start is set to “GFWED”.snow_thresh (Quantified) – Minimal snow depth level to end a fire season, only used with method “LA08”. Must be scalar.
- Return type:
DataArray- Returns:
xr.DataArray – Fire season mask.
References
- xclim.compute.fire._cffwis.fire_weather_ufunc(*, tas, pr, hurs=None, sfcWind=None, snd=None, lat=None, dc0=None, dmc0=None, ffmc0=None, winter_pr=None, season_mask=None, start_dates=None, indexes=None, season_method=None, overwintering=False, dry_start=None, initial_start_up=True, **params)[source]
Fire Weather Indexes computation using xarray’s apply_ufunc.
No unit handling. Meant to be used by power users only. Please prefer using the
DCandCFFWISindicators or thedrought_code()andcffwis_indices()functions 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. If season_mask is not given or dry start is on but overwintering is off, NaNs are filled with dc_start. If overwintering is off, missing values will have the first start up use dc_start.
dmc0 (xr.DataArray, optional) – Previous DMC map, see Notes. Defaults to NaN. If dry_start is on or season_mask is not given, NaNs are filled with dmc_start.
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 and only DMC is handled through the dry start mechanism.
initial_start_up (bool) – If True (default), grid points where the fire season is active on the first timestep go through a start-up phase for that time step. Otherwise, previous codes must be given as a continuing fire season is assumed for those points.
carry_over_fraction (float) – Carry over fraction.
wetting_efficiency_fraction (float) – Drought code overwintering parameters, see
overwintering_drought_code().temp_start_thresh (float) – Starting temperature threshold.
temp_end_thresh (float) – Ending temperature threshold.
temp_condition_days (int) – The number of days’ temperature condition to consider.
snow_thresh (float) – The snow threshold.
snow_condition_days (int) – Parameters for the fire season determination. See
fire_season(). Temperature is in degC, snow in m. The snow_thresh parameters is also used when dry_start is set to “GFWED”, see Notes.dc_start (float) – DC start.
dmc_start (float) – DMC start.
ffmc_start (float) – Default starting values for the three base codes.
prec_thresh (float) – If the “dry start” is activated, this is the “wet” day precipitation threshold, see Notes. In mm/d.
dc_dry_factor (float) – DC’s start-up values for the “dry start” mechanism, see Notes.
dmc_dry_factor (float) – DMC’s start-up values for the “dry start” mechanism, see Notes.
snow_cover_days (int) – Snow cover days.
snow_min_cover_frac (float) – Snow minimum cover fraction.
snow_min_mean_depth (float) – Additional parameters for GFWED’s version of the “dry start” mechanism. See Notes. Snow depth is in m.
- Return type:
dict[str,DataArray]- Returns:
dict[str, xarray.DataArray] – Dictionary containing the computed indexes as prescribed in indexes, including the intermediate ones needed, even if they were not explicitly listed in indexes. When overwintering is activated, winter_pr is added. If season_method is not None and season_mask was not given, season_mask is computed on-the-fly and added to the output.
Notes
When overwintering is activated, the argument dc0 is understood as last season’s last DC map and will be used to compute the overwintered DC at the beginning of the next season. Missing values will have no overwintering computation and the first start up will use dc_start.
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” and 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.
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.
When dry start is activated, dc0 and dmc0 default to dc_start and dmc_start respectively. If overwintering is activated, this mechanism is only used for the DMC. See above for how DC is handled in this case.
- xclim.compute.fire._cffwis.overwintering_drought_code(last_dc, winter_pr, carry_over_fraction=0.75, wetting_efficiency_fraction=0.75, min_dc=15)[source]
Compute season-starting drought code based on previous season’s last drought code and total winter precipitation.
This method replicates the “wDC” method of the “cffdrs R package [Cantin et al., 2014], with an added control on the “minimum” DC.
- Parameters:
last_dc (xr.DataArray) – The previous season’s last drought code.
winter_pr (xr.DataArray) – The accumulated precipitation since the end of the fire season.
carry_over_fraction (xr.DataArray or float) – Carry-over fraction of last fall’s moisture.
wetting_efficiency_fraction (xr.DataArray or float) – Effectiveness of winter precipitation in recharging moisture reserves in spring.
min_dc (xr.DataArray or float) – Minimum drought code starting value.
- Return type:
DataArray- Returns:
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 functions related to the McArthur Forest Fire Danger Index Mark 5.
Currently implemented are the xclim.compute.fire.keetch_byram_drought_index(),
xclim.compute.fire.griffiths_drought_factor() and
xclim.compute.fire.mcarthur_forest_fire_danger_index() compute functions, which are used by the eponym
indicators.
The implementation of these functions 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 the documentation of
this module and consult Finkele et al. [2006] for a full description of the methods used to calculate each
index.
- xclim.compute.fire._ffdi.griffiths_drought_factor(pr, smd, limiting_func='xlim')[source]
Griffiths drought factor based on the soil moisture deficit.
The drought factor is a numeric indicator of the forest fire fuel availability in the deep litter bed. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006].
- Parameters:
pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].
smd (xarray DataArray) – Daily soil moisture deficit (often KBDI) [mm/day].
limiting_func ({“xlim”, “discrete”}) – How to limit the values of the drought factor. If “xlim” (default), use equation (14) in Finkele et al. [2006]. If “discrete”, use equation Eq (13) in Finkele et al. [2006], but with the lower limit of each category bound adjusted to match the upper limit of the previous bound.
- Return type:
DataArray- Returns:
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.compute.fire._ffdi.keetch_byram_drought_index(pr, tasmax, pr_annual, kbdi0=None)[source]
Keetch-Byram drought index (KBDI) for soil moisture deficit.
The KBDI indicates the amount of water necessary to bring the soil moisture content back to field capacity. It is often used in the calculation of the McArthur Forest Fire Danger Index. The method implemented here follows Finkele et al. [2006] but limits the maximum KBDI to 203.2 mm, rather than 200 mm, in order to align best with the majority of the literature.
- Parameters:
pr (xr.DataArray) – Total rainfall over previous 24 hours [mm/day].
tasmax (xr.DataArray) – Maximum temperature near the surface over previous 24 hours [degC].
pr_annual (xr.DataArray) – Mean (over years) annual accumulated rainfall [mm/year].
kbdi0 (xr.DataArray, optional) – Previous KBDI values used to initialise the KBDI calculation [mm/day]. Defaults to 0.
- Return type:
DataArray- Returns:
xr.DataArray – Keetch-Byram drought index.
Notes
This method implements the method described in Finkele et al. [2006] (section 2.1.1) for calculating the KBDI with one small difference: in Finkele et al. [2006] the maximum KBDI is limited to 200 mm to represent the maximum field capacity of the soil (8 inches according to Keetch and Byram [1968]). However, it is more common in the literature to limit the KBDI to 203.2 mm which is a more accurate conversion from inches to mm. In this function, the KBDI is limited to 203.2 mm.
References
Dolling, Chu, and Fujioka [2005], Finkele, Mills, Beard, and Jones [2006], Holgate, Van DIjk, Cary, and Yebra [2017], Keetch and Byram [1968]
- xclim.compute.fire._ffdi.mcarthur_forest_fire_danger_index(drought_factor, tasmax, hurs, sfcWind)[source]
McArthur forest fire danger index (FFDI) Mark 5.
The FFDI is a numeric indicator of the potential danger of a forest fire.
- Parameters:
drought_factor (xr.DataArray) – The drought factor, often the daily Griffiths drought factor (see
griffiths_drought_factor()).tasmax (xr.DataArray) – The daily maximum temperature near the surface, or similar. Different applications have used different inputs here, including the previous/current day’s maximum daily temperature at a height of 2m, and the daily mean temperature at a height of 2m.
hurs (xr.DataArray) – The relative humidity near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon relative humidity at a height of 2m, and the daily mean relative humidity at a height of 2m.
sfcWind (xr.DataArray) – The wind speed near the surface and near the time of the maximum daily temperature, or similar. Different applications have used different inputs here, including the mid-afternoon wind speed at a height of 10m, and the daily mean wind speed at a height of 10m.
- Returns:
xr.DataArray – The McArthur forest fire danger index.
References
Dowdy [2018], Holgate, Van DIjk, Cary, and Yebra [2017], Noble, Gill, and Bary [1980]
Fire indices footnotes¶
McArthur Forest Fire Danger Indices methods¶
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.
Andrew J Dowdy. Climatological variability of fire weather in australia. Journal of Applied Meteorology and Climatology, 57(2):221–234, 2018.
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.
Deryn Griffiths. Improved formula for the drought factor in mcarthur's forest fire danger meter. Australian Forestry, 62(2):202–206, 1999.
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.
Canadian Forest Fire Weather Index System codes¶
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/.
Note
MATLAB code of the GFWED obtained through personal communication, reimplemented in Python.
Fire season determination methods¶
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, jun 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.
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).
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).
B. M. Wotton and M. D. Flannigan. Length of the fire season in a changing climate. The Forestry Chronicle, 69(2):187–192, apr 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¶
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/.
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, jun 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.
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).
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, aug 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.
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).
Health Checks¶
See: Health Checks
Translation Tools¶
See: Internationalization
Ensembles Module¶
Ensemble tools¶
This submodule defines some useful methods for dealing with ensembles of climate simulations. In xclim, an “ensemble” is a Dataset or a DataArray where multiple climate realizations or models are concatenated along the realization dimension.
- xclim.ensembles.create_ensemble(datasets, multifile=False, resample_freq=None, calendar=None, realizations=None, cal_kwargs=None, **xr_kwargs)[source]
Create an xarray dataset of an ensemble of climate simulation from a list of netcdf files.
Input data is concatenated along a newly created data dimension (‘realization’). Returns an xarray dataset object containing input data from the list of netcdf files concatenated along a new dimension (name:’realization’). In the case where input files have unequal time dimensions, the output ensemble Dataset is created for maximum time-step interval of all input files. Before concatenation, datasets not covering the entire time span have their data padded with NaN values. Dataset and variable attributes of the first dataset are copied to the resulting dataset.
- Parameters:
datasets (list or dict or str) – List of netcdf file paths or xarray Dataset/DataArray objects . If multifile is True, ncfiles should be a list of lists where each sublist contains input .nc files of an xarray multifile Dataset. If DataArray objects are passed, they should have a name in order to be transformed into Datasets. A dictionary can be passed instead of a list, in which case the keys are used as coordinates along the new realization axis. If a string is passed, it is assumed to be a glob pattern for finding datasets.
multifile (bool) – If True, climate simulations are treated as xarray multifile Datasets before concatenation. Only applicable when “datasets” is sequence of list of file paths. Default: False.
resample_freq (Optional[str]) – If the members of the ensemble have the same frequency but not the same offset, they cannot be properly aligned. If resample_freq is set, the time coordinate of each member will be modified to fit this frequency.
calendar (str, optional) – The calendar of the time coordinate of the ensemble. By default, the biggest calendar (in number of days by year) is chosen. For example, a mixed input of “noleap” and “360_day” will default to “noleap”. ‘default’ is the standard calendar using np.datetime64 objects (xarray’s “standard” with use_cftime=False).
realizations (sequence, optional) – The coordinate values for the new realization axis. If None (default), the new axis has a simple integer coordinate. This argument shouldn’t be used if datasets is a glob pattern as the dataset order is random.
cal_kwargs (dict, optional) – Additional arguments to pass to py:func:xclim.core.calendar.convert_calendar. For conversions involving ‘360_day’, the align_on=’date’ option is used by default.
**xr_kwargs (dict) – Any keyword arguments to be given to xr.open_dataset when opening the files (or to xr.open_mfdataset if multifile is True).
- Return type:
Dataset- Returns:
xr.Dataset – A Dataset containing concatenated data from all input files.
Notes
Input netcdf files require equal spatial dimension size (e.g. lon, lat dimensions). If input data contains multiple cftime calendar types they must be at monthly or coarser frequency.
Examples
from pathlib import Path from xclim.ensembles import create_ensemble ens = create_ensemble(temperature_datasets) # Using multifile datasets, through glob patterns. # Simulation 1 is a list of .nc files (e.g. separated by time): datasets = list(Path("/dir").glob("*.nc")) # Simulation 2 is also a list of .nc files: datasets.extend(Path("/dir2").glob("*.nc")) ens = create_ensemble(datasets, multifile=True)
- xclim.ensembles.ensemble_mean_std_max_min(ens, min_members=1, weights=None)[source]
Calculate ensemble statistics between a results from an ensemble of climate simulations.
Returns an xarray Dataset containing ensemble mean, standard-deviation, minimum and maximum for input climate simulations.
- Parameters:
ens (xr.Dataset) – Ensemble dataset (see xclim.ensembles.create_ensemble).
min_members (int, optional) – The minimum number of valid ensemble members for a statistic to be valid. Passing None is equivalent to setting min_members to the size of the realization dimension. The default (1) essentially skips this check.
weights (xr.DataArray, optional) – Weights to apply along the ‘realization’ dimension. This array cannot contain missing values.
- Return type:
Dataset- Returns:
xr.Dataset – Dataset with data variables of ensemble statistics.
Examples
from xclim.ensembles import create_ensemble, ensemble_mean_std_max_min # Create the ensemble dataset: ens = create_ensemble(temperature_datasets) # Calculate ensemble statistics: ens_mean_std = ensemble_mean_std_max_min(ens)
- xclim.ensembles.ensemble_percentiles(ens, values=None, keep_chunk_size=None, min_members=1, weights=None, split=True, method='linear')[source]
Calculate ensemble statistics between a results from an ensemble of climate simulations.
Returns a Dataset containing ensemble percentiles for input climate simulations.
- Parameters:
ens (xr.Dataset or xr.DataArray) – Ensemble Dataset or DataArray (see xclim.ensembles.create_ensemble).
values (Sequence[int], optional) – Percentile values to calculate. Default: (10, 50, 90).
keep_chunk_size (bool, optional) – For ensembles using dask arrays, all chunks along the ‘realization’ axis are merged. If True, the dataset is rechunked along the dimension with the largest chunks, so that the chunks keep the same size (approximately). If False, no shrinking is performed, resulting in much larger chunks. If not defined, the function decides which is best.
min_members (int, optional) – The minimum number of valid ensemble members for a statistic to be valid. Passing None is equivalent to setting min_members to the size of the realization dimension. The default (1) essentially skips this check.
weights (xr.DataArray, optional) – Weights to apply along the ‘realization’ dimension. This array cannot contain missing values. When given, the function uses xarray’s quantile method which is slower than xclim’s NaN-optimized algorithm, and does not support method values other than linear.
split (bool) – Whether to split each percentile into a new variable or concatenate the output along a new “percentiles” dimension.
method ({“linear”, “interpolated_inverted_cdf”, “hazen”, “weibull”, “median_unbiased”, “normal_unbiased”}) – Method to use for estimating the percentile, see the numpy.percentile documentation for more information.
- Return type:
DataArray|Dataset- Returns:
xr.Dataset or xr.DataArray – If split is True, same type as ens; Otherwise, a dataset containing data variable(s) of requested ensemble statistics.
Examples
from xclim.ensembles import create_ensemble, ensemble_percentiles # Create ensemble dataset: ens = create_ensemble(temperature_datasets) # Calculate default ensemble percentiles: ens_percs = ensemble_percentiles(ens) # Calculate non-default percentiles (25th and 75th) ens_percs = ensemble_percentiles(ens, values=(25, 50, 75)) # If the original array has many small chunks, it might be more efficient to do: ens_percs = ensemble_percentiles(ens, keep_chunk_size=False)
Ensemble Reduction¶
Ensemble reduction is the process of selecting a subset of members from an ensemble in order to reduce the volume of computation needed while still covering a good portion of the simulated climate variability.
- xclim.ensembles.kkz_reduce_ensemble(data, num_select, *, dist_method='euclidean', standardize=True, **cdist_kwargs)[source]
Return a sample of ensemble members using KKZ selection.
The algorithm selects num_select ensemble members spanning the overall range of the ensemble. The selection is ordered, smaller groups are always subsets of larger ones for given criteria. The first selected member is the one nearest to the centroid of the ensemble, all subsequent members are selected in a way maximizing the phase-space coverage of the group. Algorithm taken from Cannon [2015].
- Parameters:
data (xr.DataArray) – Selection criteria data : 2-D xr.DataArray with dimensions ‘realization’ (N) and ‘criteria’ (P). These are the values used for clustering. Realizations represent the individual original ensemble members and criteria the variables/indicators used in the grouping algorithm.
num_select (int) – The number of members to select.
dist_method (str) – Any distance metric name accepted by scipy.spatial.distance.cdist.
standardize (bool) – Whether to standardize the input before running the selection or not. Standardization consists in translation as to have a zero mean and scaling as to have a unit standard deviation.
**cdist_kwargs (Any) – All extra arguments are passed as-is to scipy.spatial.distance.cdist, see its docs for more information.
- Return type:
list- Returns:
list – Selected model indices along the realization dimension.
References
- xclim.ensembles.kmeans_reduce_ensemble(data, *, method=None, make_graph=True, max_clusters=None, variable_weights=None, model_weights=None, sample_weights=None, random_state=None)[source]
Return a sample of ensemble members using k-means clustering.
The algorithm attempts to reduce the total number of ensemble members while maintaining adequate coverage of the ensemble uncertainty in an N-dimensional data space. K-Means clustering is carried out on the input selection criteria data-array in order to group individual ensemble members into a reduced number of similar groups. Subsequently, a single representative simulation is retained from each group.
- Parameters:
data (xr.DataArray) – Selection criteria data : 2-D xr.DataArray with dimensions ‘realization’ (N) and ‘criteria’ (P). These are the values used for clustering. Realizations represent the individual original ensemble members and criteria the variables/indicators used in the grouping algorithm.
method (dict, optional) – Dictionary defining selection method and associated value when required. See Notes.
make_graph (bool) – Output a dictionary of input for displays a plot of R² vs. the number of clusters. Defaults to True if matplotlib is installed in the runtime environment.
max_clusters (int, optional) – Maximum number of members to include in the output ensemble selection. When using ‘rsq_optimize’ or ‘rsq_cutoff’ methods, limit the final selection to a maximum number even if method results indicate a higher value. Defaults to N.
variable_weights (np.ndarray, optional) – An array of size P. This weighting can be used to influence of weight of the climate indices (criteria dimension) on the clustering itself.
model_weights (np.ndarray, optional) – An array of size N. This weighting can be used to influence which realization is selected from within each cluster. This parameter has no influence on the clustering itself.
sample_weights (np.ndarray, optional) – An array of size N. sklearn.cluster.KMeans() sample_weights parameter. This weighting can be used to influence of weight of simulations on the clustering itself. See: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html.
random_state (int or np.random.RandomState, optional) – A sklearn.cluster.KMeans() random_state parameter. Determines random number generation for centroid initialization. Use to make the randomness deterministic. See: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html.
- Return type:
tuple[list,ndarray,dict]- Returns:
list – Selected model indexes (positions).
np.ndarray – KMeans clustering results.
dict – Dictionary of input data for creating R² profile plot. ‘None’ when make_graph=False.
Notes
Parameters for method in call must follow these conventions:
- rsq_optimize
Calculate coefficient of variation (R²) of cluster results for n = 1 to N clusters and determine an optimal number of clusters that balances cost/benefit tradeoffs. This is the default setting. See supporting information S2 text in Casajus et al. [2016].
method={‘rsq_optimize’:None}
- rsq_cutoff
Calculate Coefficient of variation (R²) of cluster results for n = 1 to N clusters and determine the minimum numbers of clusters needed for R² > val.
val : float between 0 and 1. R² value that must be exceeded by clustering results.
method={‘rsq_cutoff’: val}
- n_clusters
Create a user determined number of clusters.
val : integer between 1 and N
method={‘n_clusters’: val}
References
Casajus, Périé, Logan, Lambert, Blois, and Berteaux [2016]
Examples
import xclim from xclim.ensembles import create_ensemble, kmeans_reduce_ensemble from xclim.compute import hot_spell_frequency # Start with ensemble datasets for temperature: ensTas = create_ensemble(temperature_datasets) # Calculate selection criteria -- Use annual climate change Δ fields between 2071-2100 and 1981-2010 normals. # First, average annual temperature: tg = xclim.atmos.tg_mean(tas=ensTas.tas) his_tg = tg.sel(time=slice("1990", "2019")).mean(dim="time") fut_tg = tg.sel(time=slice("2020", "2050")).mean(dim="time") dtg = fut_tg - his_tg # Then, hot spell frequency as second indicator: hs = hot_spell_frequency(tasmax=ensTas.tas, window=2, thresh_tasmax="10 degC") his_hs = hs.sel(time=slice("1990", "2019")).mean(dim="time") fut_hs = hs.sel(time=slice("2020", "2050")).mean(dim="time") dhs = fut_hs - his_hs # Create a selection criteria xr.DataArray: from xarray import concat crit = concat((dtg, dhs), dim="criteria") # Finally, create clusters and select realization ids of reduced ensemble: ids, cluster, fig_data = kmeans_reduce_ensemble( data=crit, method={"rsq_cutoff": 0.9}, random_state=42, make_graph=False ) ids, cluster, fig_data = kmeans_reduce_ensemble( data=crit, method={"rsq_optimize": None}, random_state=42, make_graph=True )
- xclim.ensembles.plot_rsqprofile(fig_data)[source]
Create an R² profile plot using kmeans_reduce_ensemble output.
The R² plot allows evaluation of the proportion of total uncertainty in the original ensemble that is provided by the reduced selected.
- Parameters:
fig_data (dict) – Dictionary of input data for creating R² profile plot.
- Return type:
None
Examples
>>> from xclim.ensembles import kmeans_reduce_ensemble, plot_rsqprofile >>> is_matplotlib_installed() >>> crit = xr.open_dataset(path_to_ensemble_file).data >>> ids, cluster, fig_data = kmeans_reduce_ensemble( ... data=crit, method={"rsq_cutoff": 0.9}, random_state=42, make_graph=True ... ) >>> plot_rsqprofile(fig_data)
Ensemble Robustness Metrics¶
Robustness metrics are used to estimate the confidence of the climate change signal of an ensemble. This submodule is inspired by and tries to follow the guidelines of the IPCC, more specifically [Collins et al., 2013] (AR5) and On Climate Change (IPCC) [2023] (AR6).
- xclim.ensembles.robustness_fractions(fut, ref=None, test=None, weights=None, invalid=None, strict_sign=True, **kwargs)[source]
Calculate robustness statistics.
The metric for qualifying how members of an ensemble agree on the existence of change and on its sign.
- Parameters:
fut (xr.DataArray) – Future period values along ‘realization’ and ‘time’ (…, nr, nt1) or if ref is None, Delta values along realization (…, nr).
ref (xr.DataArray, optional) – Reference period values along realization’ and ‘time’ (…, nr, nt2). The size of the ‘time’ axis does not need to match the one of fut. But their ‘realization’ axes must be identical and the other coordinates should be the same. If None (default), values of fut are assumed to be deltas instead of a distribution across the future period.
test ({ttest, welch-ttest, mannwhitney-utest, brownforsythe-test, ipcc-ar6-c, threshold}, optional) – Name of the statistical test used to determine if there was significant change. See notes.
weights (xr.DataArray) – Weights to apply along the ‘realization’ dimension. This array cannot contain missing values.
invalid (xc.core.missing.MissingBase instance) – A Missing class from
xclim.core.missingto use to flag points what are invalid. Invalid points are not included in the fractions. Default is MissingAny, which means any nan along the “time” dimension means the timeseries is invalid. Not used if only deltas are passed as fut.strict_sign (bool) – Whether to include zeros When determining the sign of change. True (default) does not include them, the comparison is done with > and <, while false uses >=, <=. When True, the “agree” fraction is the largest of three : positive, negative, zero change. When False, it is the largest of two : zero-or-positive, zero-or-negative.
**kwargs (dict) – Other arguments specific to the statistical test. See notes.
- Return type:
Dataset- Returns:
xr.Dataset – Same coordinates as fut and ref, but no time and no realization. Values are zero if all members were invalid. Variables returned are:
- changed
The weighted fraction of valid members showing significant change. Passing test=None yields change_frac = 1 everywhere. Same type as fut.
- positive
The weighted fraction of valid members showing positive change, no matter if it is significant or not. If strict_sign=True, only strictly positive change is included.
- changed_positive
The weighted fraction of valid members showing significant and positive change.
- negative
The weighted fraction of valid members showing negative change, no matter if it is significant or not. If strict_sign=True, only strictly negative change is included.
- changed_negative
The weighted fraction of valid members showing significant and negative change.
- agree
The weighted fraction of valid members agreeing on the sign of change. If strict_sign=True, it is the maximum between positive, negative and the zero change. Otherwise, it is the maximum between positive and negative (both including zero change).
- valid
The weighted fraction of valid members. By default, a member is valid if there are no NaNs along the time axes of fut and ref.
- pvals
The p-values estimated by the significance tests. Only returned if the test uses pvals. Has the realization dimension.
Notes
The table below shows the coefficient needed to retrieve the number of members that have the indicated characteristics, by multiplying it by the total number of members (fut.realization.size) and by valid_frac, assuming uniform weights. For compactness, we rename the outputs cf, pf, cpf, nf and cnf.
Significant change
Non-significant change
Any change
Any direction
cf
1 - cf
1
Positive change
cpf
pf - cpf
pf
Negative change
cnf
nf - cnf
nf
And members showing absolutely no change are
1 - nf - pf.Available statistical tests are:
- ttest
Single sample T-test. Same test as used by Tebaldi et al. [2011].
The future values are compared against the reference mean (over ‘time’).
Accepts argument p_change (float, default : 0.05) the p-value threshold for rejecting the hypothesis of no significant change.
- welch-ttest
Two-sided T-test, without assuming equal population variance.
Same significance criterion and argument as ‘ttest’.
- mannwhitney-utest
Two-sided Mann-Whiney U-test.
Same significance criterion and argument as ‘ttest’.
- brownforsythe-test
Brown-Forsythe test assuming skewed, non-normal distributions.
Same significance criterion and argument as ‘ttest’.
- ipcc-ar6-c
The advanced approach used in the IPCC Atlas chapter (on Climate Change (IPCC) [2023]).
Change is considered significant if the delta exceeds a threshold related to the internal variability. If pre-industrial data is given in argument ref_pi, the threshold is defined as \(\sqrt{2}*1.645*\sigma_{20yr}\), where \(\sigma_{20yr}\) is the standard deviation of 20-year means computed from non-overlapping periods after detrending with a quadratic fit. Otherwise, when such pre-industrial control data is not available, the threshold is defined in relation to the historical data (ref) as \(\sqrt{\frac{2}{20}}*1.645*\sigma_{1yr}, where :math:\)sigma_{1yr}` is the inter-annual standard deviation measured after linearly detrending the data. See notebook Ensembles for more details.
- threshold
Change is considered significant when it exceeds an absolute or relative threshold. Accepts one argument, either “abs_thresh” or “rel_thresh”.
- None
Significant change is not tested. The changed fraction is always 1.
References
On Climate Change (IPCC) [2023], Tebaldi, Arblaster, and Knutti [2011].
Examples
This example computes the mean temperature in an ensemble and compares two time periods, qualifying significant change through a single sample T-test.
>>> from xclim import ensembles >>> ens = ensembles.create_ensemble(temperature_datasets) >>> tgmean = xclim.atmos.tg_mean(tas=ens.tas, freq="YS") >>> fut = tgmean.sel(time=slice("2020", "2050")) >>> ref = tgmean.sel(time=slice("1990", "2020")) >>> fractions = ensembles.robustness_fractions(fut, ref, test="ttest")
- xclim.ensembles.robustness_categories(changed_or_fractions, agree=None, valid=None, *, categories=None, ops=None, thresholds=None)[source]
Create a categorical robustness map for mapping hatching patterns.
Each robustness category is defined by a double threshold, one on the fraction of members showing significant change (change_frac) and one on the fraction of member agreeing on the sign of change (agree_frac). When the two thresholds are fulfilled, the point is assigned to the given category. The default values for the comparisons are the ones suggested by the IPCC for its “Advanced approach” described in the Cross-Chapter Box 1 of the Atlas of the AR6 WGI report (on Climate Change (IPCC) [2023]).
- Parameters:
changed_or_fractions (xr.Dataset or xr.DataArray) – Either the fraction of members showing significant change as an array or directly the output of
robustness_fractions().agree (xr.DataArray, optional) – The fraction of members agreeing on the sign of change. Can also be passed as a variable of the first argument.
valid (xr.DataArray, optional) – The fraction of members that were valid for the robustness calculation. Can also be passed as a variable of the first argument.
categories (list of str, optional) – The label of each robustness categories. They are stored in the semicolon separated flag_descriptions attribute as well as in a compressed form in the flag_meanings attribute. If a point is mapped to two categories, priority is given to the first one in this list.
ops (list of tuples of str, optional) – For each category, the comparison operators for change_frac and agree_frac. None or an empty string means the variable is not needed for this category.
thresholds (list of tuples of float, optional) – For each category, the threshold to be used with the corresponding operator. All should be between 0 and 1.
- Return type:
DataArray- Returns:
xr.DataArray – Categorical (int) array following the flag variables CF conventions. 99 is used as a fill value for points that do not fall in any category.
- xclim.ensembles.robustness_coefficient(fut, ref)[source]
Calculate the robustness coefficient quantifying the robustness of a climate change signal in an ensemble.
Taken from Knutti and Sedláček [2013].
The robustness metric is defined as R = 1 − A1 / A2 , where A1 is defined as the integral of the squared area between two cumulative density functions characterizing the individual model projections and the multimodel mean projection and A2 is the integral of the squared area between two cumulative density functions characterizing the multimodel mean projection and the historical climate. Description taken from Knutti and Sedláček [2013].
A value of R equal to one implies perfect model agreement. Higher model spread or smaller signal decreases the value of R.
- Parameters:
fut (xr.DataArray or xr.Dataset) – Future ensemble values along ‘realization’ and ‘time’ (nr, nt). Can be a dataset, in which case the coefficient is computed on each variable.
ref (xr.DataArray or xr.Dataset) – Reference period values along ‘time’ (nt). Same type as fut.
- Return type:
DataArray|Dataset- Returns:
xr.DataArray or xr.Dataset – The robustness coefficient, ]-inf, 1], float. Same type as fut or ref.
References
Knutti and Sedláček [2013]
Uncertainty Partitioning¶
This module implements methods and tools meant to partition climate projection uncertainties into different components.
- xclim.ensembles.hawkins_sutton(da, sm=None, weights=None, baseline=('1971', '2000'), kind='+')[source]
Return the mean and partitioned variance of an ensemble based on method from Hawkins & Sutton (2009).
- Parameters:
da (xr.DataArray) – Time series with dimensions ‘time’, ‘scenario’ and ‘model’.
sm (xr.DataArray, optional) – Smoothed time series over time, with the same dimensions as da. By default, this is estimated using a 4th-order polynomial. Results are sensitive to the choice of smoothing function, use this to set another polynomial order, or a LOESS curve.
weights (xr.DataArray, optional) – Weights to be applied to individual models. Should have model dimension.
baseline ((str, str)) – Start and end year of the reference period.
kind ({‘+’, ‘’}*) – Whether the mean over the reference period should be subtracted (+) or divided by (*).
- Return type:
tuple[DataArray,DataArray]- Returns:
(xr.DataArray, xr.DataArray) – The mean relative to the baseline, and the components of variance of the ensemble. These components are coordinates along the uncertainty dimension: variability, model, scenario, and total.
Notes
To prepare input data, make sure da has dimensions time, scenario and model, e.g. da.rename({“scen”: “scenario”}).
- To reproduce results from Hawkins and Sutton [2009], input data should meet the following requirements:
annual time series starting in 1950 and ending in 2100;
the same models are available for all scenarios.
To get the fraction of the total variance instead of the variance itself, call fractional_uncertainty on the output.
References
- xclim.ensembles.lafferty_sriver(da, sm=None, bb13=False)[source]
Return the mean and partitioned variance of an ensemble based on method from Lafferty and Sriver (2023).
- Parameters:
da (xr.DataArray) – Time series with dimensions ‘time’, ‘scenario’, ‘downscaling’ and ‘model’.
sm (xr.DataArray) – Smoothed time series over time, with the same dimensions as da. By default, this is estimated using a 4th-order polynomial. Results are sensitive to the choice of smoothing function, use this to set another polynomial order, or a LOESS curve.
bb13 (bool) – Whether to apply the Brekke and Barsugli (2013) method to estimate scenario uncertainty, where the variance over scenarios is computed before taking the mean over models and downscaling methods.
- Return type:
tuple[DataArray,DataArray]- Returns:
xr.DataArray, xr.DataArray – The mean relative to the baseline, and the components of variance of the ensemble. These components are coordinates along the uncertainty dimension: variability, model, scenario, downscaling and total.
Notes
To prepare input data, make sure da has dimensions time, scenario, downscaling and model, e.g. da.rename({“experiment”: “scenario”}).
To get the fraction of the total variance instead of the variance itself, call fractional_uncertainty on the output.
References
Lafferty and Sriver [2023]
Units Handling Submodule¶
Units Handling Submodule¶
xclim’s pint-based unit registry is an extension of the registry defined in cf-xarray. This module defines most unit handling methods.
- xclim.core.units.amount2lwethickness(amount, out_units=None)[source]
Convert a liquid water amount (mass over area) to its equivalent area-averaged thickness (length).
This will simply divide the amount by the density of liquid water, 1000 kg/m³. This is equivalent to using the “hydro” context of
xclim.core.units.units.- Parameters:
amount (xr.DataArray) – A DataArray storing a liquid water amount quantity.
out_units (str, optional) – Specific output units, if needed.
- Return type:
Union[DataArray,TypeVar(Quantified,DataArray,str,Quantity)]- Returns:
xr.DataArray or Quantified – The standard_name of amount is modified if a conversion is found (see
xclim.core.units.cf_conversion()), it is removed otherwise. Other attributes are left untouched.
See also
lwethickness2amountConvert a liquid water equivalent thickness to an amount.
- xclim.core.units.amount2rate(amount, dim='time', sampling_rate_from_coord=False, out_units=None)[source]
Convert an amount variable to a rate by dividing by the sampling period length.
If the sampling period length cannot be inferred, the amount values are divided by the duration between their time coordinate and the next one. The last period is estimated with the duration of the one just before.
This is the inverse operation of
xclim.core.units.rate2amount().- Parameters:
amount (xr.DataArray or pint.Quantity or str) – “amount” variable. Ex: Precipitation amount in “mm”.
dim (str or xr.DataArray) – The name of the time dimension or the time coordinate itself.
sampling_rate_from_coord (bool) – For data with irregular time coordinates. If True, the diff of the time coordinate will be used as the sampling rate, meaning each data point will be assumed to span the interval ending at the next point. See notes of
xclim.core.units.rate2amount(). Defaults to False, which raises an error if the time coordinate is irregular.out_units (str, optional) – Specific output units, if needed.
- Return type:
DataArray- Returns:
xr.DataArray or Quantity – The converted variable. The standard_name of amount is modified if a conversion is found.
- Raises:
ValueError – If the time coordinate is irregular and sampling_rate_from_coord is False (default).
See also
rate2amountConvert a rate to an amount.
is_temporal_rateDetermine if a variable is a rate based on its CF attributes.
- xclim.core.units.cf_conversion(standard_name, conversion, direction)[source]
Get the standard name of the specific conversion for the given standard name.
- Parameters:
standard_name (str) – Standard name of the input.
conversion ({‘amount2rate’, ‘amount2lwethickness’}) – Type of conversion. Available conversions are the keys of the conversions entry in xclim/data/variables.yml. See
xclim.core.units.CF_CONVERSIONS. They also correspond to functions in this module.direction ({‘to’, ‘from’}) – The direction of the requested conversion. “to” means the conversion as given by the conversion name, while “from” means the reverse operation. For example conversion=”amount2rate” and direction=”from” will search for a conversion from a rate or flux to an amount or thickness for the given standard name.
- Return type:
str|None- Returns:
str or None – If a string, this means the conversion is possible and the result should have this standard name. If None, the conversion is not possible within the CF standards.
- xclim.core.units.check_units(val, dim=None)[source]
Check that units are compatible with dimensions, otherwise raise a ValidationError.
- Parameters:
val (str or xr.DataArray, optional) – Value to check.
dim (str or xr.DataArray, optional) – Expected dimension, e.g. [temperature]. If a quantity or DataArray is given, the dimensionality is extracted.
- Return type:
None
- xclim.core.units.convert_units_to(source, target, context=None)[source]
Convert a mathematical expression into a value with the same units as a DataArray.
If the dimensionalities of source and target units differ, automatic CF conversions will be applied when possible. See
xclim.core.units.cf_conversion().- Parameters:
source (str or xr.DataArray or units.Quantity or xr.Dataset or xr.DataTree) – The value to be converted, e.g. ‘4C’ or ‘1 mm/d’. If a Dataset, target must also be a mapping from variable name to target units. If a DataTree, this function will be applied over nodes with
xarray.DataTree.map_over_datasets().target (str or xr.DataArray or units.Quantity or units.Unit or dict) – Target array of values to which units must conform. If source is a Dataset, it must be mapping from variable name to target units.
context ({“infer”, “hydro”, “none”}, optional) – The unit definition context. Default: None. If “infer”, it will be inferred with
xclim.core.units.infer_context()using the standard name from the source or, if none is found, from the target. This means that the “hydro” context could be activated if any one of the standard names allows it.
- Return type:
DataArray|float|Dataset- Returns:
xr.DataArray or float or xr.Dataset – The source value converted to target’s units. The outputted type is always similar to source initial type. Attributes are preserved unless an automatic CF conversion is performed, in which case only the new standard_name appears in the result.
See also
cf_conversionGet the standard name of the specific conversion for the given standard name.
amount2rateConvert an amount to a rate.
rate2amountConvert a rate to an amount.
amount2lwethicknessConvert an amount to a liquid water equivalent thickness.
lwethickness2amountConvert a liquid water equivalent thickness to an amount.
- xclim.core.units.declare_relative_units(**units_by_name)[source]
Function decorator checking the units of arguments.
The decorator checks that input values have units that are compatible with each other. It also stores the input units as a ‘relative_units’ attribute.
- Parameters:
**units_by_name (str) – Mapping from the input parameter names to dimensions relative to other parameters. The dimensions can be a single parameter name as <other_var> or more complex expressions, such as <other_var> * [time].
- Return type:
Callable- Returns:
Callable – The decorated function.
See also
declare_unitsA decorator to check units of function arguments.
Examples
In the following function definition:
@declare_relative_units(thresh="<da>", thresh2="<da> / [time]") def func(da, thresh, thresh2): ...
The decorator will check that thresh has units compatible with those of da and that thresh2 has units compatible with the time derivative of da.
Usually, the function would be decorated further by
declare_units()to create a unit-aware index:temperature_func = declare_units(da="[temperature]")(func)
This call will replace the “<da>” by “[temperature]” everywhere needed.
- xclim.core.units.declare_units(**units_by_name)[source]
Create a decorator to check units of function arguments.
The decorator checks that input and output values have units that are compatible with expected dimensions. It also stores the input units as an ‘in_units’ attribute.
- Parameters:
**units_by_name (str) – Mapping from the input parameter names to their units or dimensionality (“[…]”). If this decorates a function previously decorated with
declare_relative_units(), the relative unit declarations are made absolute with the information passed here.- Return type:
Callable- Returns:
Callable – The decorated function.
See also
declare_relative_unitsA decorator to check for relative units of function arguments.
Examples
In the following function definition:
@declare_units(tas="[temperature]") def func(tas): ...
The decorator will check that tas has units of temperature (C, K, F).
- xclim.core.units.ensure_absolute_temperature(units)[source]
Convert temperature units to their absolute counterpart, assuming they represented a difference (delta).
Celsius becomes Kelvin, Fahrenheit becomes Rankine. Does nothing for other units.
- Parameters:
units (str) – Units to transform.
- Return type:
str- Returns:
str – The transformed units.
See also
ensure_deltaEnsure a unit is a delta unit.
- xclim.core.units.ensure_cf_units(ustr)[source]
Ensure the passed unit string is CF-compliant.
The string will be parsed to pint then recast to a string by
xclim.core.units.pint2cfunits().- Parameters:
ustr (str) – A unit string.
- Return type:
str- Returns:
str – The unit string in CF-compliant form.
- xclim.core.units.ensure_delta(unit)[source]
Return delta units for temperature.
For dimensions where delta exist in pint (Temperature), it replaces the temperature unit by delta_degC or delta_degF based on the input unit. For other dimensionality, it just gives back the input units.
- Parameters:
unit (str) – Unit to transform in delta (or not).
- Return type:
str- Returns:
str – The transformed units.
- xclim.core.units.flux2rate(flux, density, out_units=None)[source]
Convert a flux variable to a rate by dividing with a density.
This is the inverse operation of
xclim.core.units.rate2flux().- Parameters:
flux (xr.DataArray) – “flux” variable, e.g. Snowfall flux in “kg m-2 s-1”.
density (Quantified) – Density used to convert from a flux to a rate, e.g. Snowfall density “312 kg m-3”. Density can also be an array with the same shape as flux.
out_units (str, optional) – Specific output units, if needed.
- Return type:
DataArray- Returns:
xr.DataArray – The converted rate value.
See also
rate2fluxConvert a rate to a flux.
Examples
The following converts an array of snowfall flux in kg m-2 s-1 to snowfall flux in mm/s, assuming a density of 100 kg m-3:
>>> time = xr.date_range("2001-01-01", freq="D", periods=365) >>> prsn = xr.DataArray( ... [0.1] * 365, ... dims=("time",), ... coords={"time": time}, ... attrs={"units": "kg m-2 s-1"}, ... ) >>> prsnd = flux2rate(prsn, density="100 kg m-3", out_units="mm/s") >>> prsnd.units 'mm s-1' >>> float(prsnd[0]) 1.0
- xclim.core.units.infer_context(standard_name=None, dimension=None)[source]
Return units context based on either the variable’s standard name or the pint dimension.
Valid standard names for the hydro context are those including the terms “rainfall”, “lwe” (liquid water equivalent) and “precipitation”. The latter is technically incorrect, as any phase of precipitation could be referenced. Standard names for evapotranspiration, evaporation and canopy water amounts are also associated with the hydro context.
- Parameters:
standard_name (str, optional) – CF-Convention standard name.
dimension (str, optional) – Pint dimension, e.g. ‘[time]’.
- Return type:
str- Returns:
str – “hydro” if variable refers to liquid water or to a mass of water in any phase, otherwise “none”.
- xclim.core.units.infer_sampling_units(da, deffreq=None, dim='time')[source]
Infer a multiplier and the units corresponding to one sampling period.
- Parameters:
da (xr.DataArray) – A DataArray from which to take coordinate dim.
deffreq (str, optional) – If no frequency is inferred from da[dim], take this one.
dim (str) – Dimension from which to infer the frequency.
- Return type:
tuple[int,str]- Returns:
int – The magnitude (number of base periods per period).
str – Units as a string, understandable by pint.
- Raises:
ValueError – If the frequency has no corresponding units.
- xclim.core.units.lwethickness2amount(thickness, out_units=None)[source]
Convert a liquid water thickness (length) to its equivalent amount (mass over area).
This will simply multiply the thickness by the density of liquid water, 1000 kg/m³. This is equivalent to using the “hydro” context of
xclim.core.units.units.- Parameters:
thickness (xr.DataArray) – A DataArray storing a liquid water thickness quantity.
out_units (str, optional) – Specific output units, if needed.
- Return type:
Union[DataArray,TypeVar(Quantified,DataArray,str,Quantity)]- Returns:
xr.DataArray or Quantified – The standard_name of amount is modified if a conversion is found (see
xclim.core.units.cf_conversion()), it is removed otherwise. Other attributes are left untouched.
See also
amount2lwethicknessConvert an amount to a liquid water equivalent thickness.
- xclim.core.units.pint2cfattrs(value, is_difference=None)[source]
Return CF-compliant units attributes from a pint unit.
- Parameters:
value (pint.Unit) – Input unit.
is_difference (bool) – Whether the value represent a difference in temperature, which is ambiguous in the case of absolute temperature scales like Kelvin or Rankine. It will automatically be set to True if units are “delta_*” units.
- Return type:
dict[str,str]- Returns:
dict – Units following CF-Convention, using symbols.
- xclim.core.units.pint2cfunits(value)[source]
Return a CF-compliant unit string from a pint unit.
- Parameters:
value (pint.Unit) – Input unit.
- Return type:
str- Returns:
str – Units following CF-Convention, using symbols.
- xclim.core.units.pint_multiply(da, q, out_units=None)[source]
Multiply xarray.DataArray by pint.Quantity.
- Parameters:
da (xr.DataArray) – Input array.
q (pint.Quantity) – Multiplicative factor.
out_units (str, optional) – Units the output array should be converted into.
- Return type:
DataArray- Returns:
xr.DataArray – The product DataArray.
- xclim.core.units.rate2amount(rate, dim='time', sampling_rate_from_coord=False, out_units=None)[source]
Convert a rate variable to an amount by multiplying by the sampling period length.
If the sampling period length cannot be inferred, the rate values are multiplied by the duration between their time coordinate and the next one. The last period is estimated with the duration of the one just before.
This is the inverse operation of
xclim.core.units.amount2rate().- Parameters:
rate (xr.DataArray or pint.Quantity or str) – “Rate” variable, with units of “amount” per time. Ex: Precipitation in “mm / d”.
dim (str or DataArray) – The name of time dimension or the coordinate itself.
sampling_rate_from_coord (bool) – For data with irregular time coordinates. If True, the diff of the time coordinate will be used as the sampling rate, meaning each data point will be assumed to apply for the interval ending at the next point. See notes. Defaults to False, which raises an error if the time coordinate is irregular.
out_units (str, optional) – Specific output units, if needed.
- Return type:
DataArray- Returns:
xr.DataArray or Quantity – The converted variable. The standard_name of rate is modified if a conversion is found.
- Raises:
ValueError – If the time coordinate is irregular and sampling_rate_from_coord is False (default).
See also
amount2rateConvert an amount to a rate.
is_temporal_rateDetermine if a variable is a rate based on its CF attributes.
Notes
Floating-point precision can have surprising results. For example, a daily series of 1 mm/d precipitation rates might not convert to exactly 1 mm daily amounts. This is because a float multiplication is still happening in the background and the time step duration might have been stored in [nano]seconds at one point.
Examples
The following converts a daily array of precipitation in mm/h to the daily amounts in mm:
>>> time = xr.date_range("2001-01-01", freq="D", periods=365) >>> pr = xr.DataArray([1] * 365, dims=("time",), coords={"time": time}, attrs={"units": "mm/h"}) >>> pram = rate2amount(pr) >>> pram.units 'mm' >>> float(pram[0]) 24.0
Also works if the time axis is irregular : the rates are assumed constant for the whole period starting on the values timestamp to the next timestamp. This option is activated with sampling_rate_from_coord=True.
>>> time = time[[0, 9, 30]] # The time axis is Jan 1st, Jan 10th, Jan 31st >>> pr = xr.DataArray([1] * 3, dims=("time",), coords={"time": time}, attrs={"units": "mm/h"}) >>> pram = rate2amount(pr, sampling_rate_from_coord=True) >>> pram.values array([216., 504., 504.])
Finally, we can force output units:
>>> pram = rate2amount(pr, out_units="pc") # Get rain amount in parsecs. Why not. >>> pram.values array([7.00008327e-18, 1.63335276e-17, 1.63335276e-17])
- xclim.core.units.rate2flux(rate, density, out_units=None)[source]
Convert a rate variable to a flux by multiplying with a density.
This is the inverse operation of
xclim.core.units.flux2rate().- Parameters:
rate (xr.DataArray) – “Rate” variable, e.g. Snowfall rate in “mm / d”.
density (Quantified) – Density used to convert from a rate to a flux, e.g. Snowfall density “312 kg m-3”. Density can also be an array with the same shape as rate.
out_units (str, optional) – Specific output units, if needed.
- Return type:
DataArray- Returns:
xr.DataArray – The converted flux value.
See also
flux2rateConvert a flux to a rate.
Examples
The following converts an array of snowfall rate in mm/s to snowfall flux in kg m-2 s-1, assuming a density of 100 kg m-3:
>>> time = xr.date_range("2001-01-01", freq="D", periods=365) >>> prsnd = xr.DataArray([1] * 365, dims=("time",), coords={"time": time}, attrs={"units": "mm/s"}) >>> prsn = rate2flux(prsnd, density="100 kg m-3", out_units="kg m-2 s-1") >>> prsn.units 'kg m-2 s-1' >>> float(prsn[0]) 0.1
- xclim.core.units.str2pint(val)[source]
Convert a string to a pint.Quantity, splitting the magnitude and the units.
- Parameters:
val (str) – A quantity in the form “[{magnitude} ]{units}”, where magnitude can be cast to a float and units is understood by
xclim.core.units.units2pint().- Return type:
Quantity- Returns:
pint.Quantity – Magnitude is 1 if no magnitude was present in the string.
- xclim.core.units.to_agg_units(out, orig, statistic, dim='time', deffreq='D')[source]
Set and convert units of an array after an aggregation operation along the sampling dimension (time).
- Parameters:
out (xr.DataArray) – The output array of the aggregation operation, no units operation done yet.
orig (xr.DataArray) – The original array before the aggregation operation, used to infer the sampling units and get the variable units.
statistic ({‘min’, ‘max’, ‘mean’, ‘std’, ‘var’, ‘doymin’, ‘doymax’, ‘count’, ‘integral’, ‘sum’} or Callable) – The type of aggregation operation performed. “integral” is mathematically equivalent to “sum”, but the units are multiplied by the timestep of the data (requires an inferrable frequency).
dim (str) – The time dimension along which the aggregation was performed.
deffreq (str, optional) – For operations count and integral, this gives the default source frequency to assume, if it can’t be inferred from
out[dim].
- Return type:
DataArray- Returns:
xr.DataArray – The DataArray with aggregated values. Depending on configurations, units may also be converted or simplified.
Examples
Take a daily array of temperature and count number of days above a threshold. to_agg_units will infer the units from the sampling rate along “time”, so we ensure the final units are correct:
>>> time = xr.date_range("2001-01-01", freq="D", periods=365) >>> tas = xr.DataArray( ... np.arange(365), ... dims=("time",), ... coords={"time": time}, ... attrs={"units": "degC"}, ... ) >>> cond = tas > 100 # Which days are boiling >>> Ndays = cond.sum("time") # Number of boiling days
# Note: older xarray drops units while modern xarray preserves them >>> Ndays.attrs.get(“units”) # doctest: +SKIP ‘degC’ >>> Ndays = to_agg_units(Ndays, tas, “count”) >>> Ndays.units ‘d’
Similarly, here we compute the total heating degree-days, but we have weekly data:
>>> time = xr.date_range("2001-01-01", freq="7D", periods=52) >>> tas = xr.DataArray( ... np.arange(52) + 10, ... dims=("time",), ... coords={"time": time}, ... ) >>> dt = (tas - 16).assign_attrs(units="degC", units_metadata="temperature: difference") >>> degdays = dt.clip(0).sum("time") # Integral of temperature above a threshold >>> degdays = to_agg_units(degdays, dt, statistic="integral") >>> degdays.units 'degC week'
Which we can always convert to the more common “K days”:
>>> degdays = convert_units_to(degdays, "K days") >>> degdays.units 'd K'
- xclim.core.units.units2pint(value)[source]
Return the pint Unit for the DataArray units.
- Parameters:
value (xr.DataArray or pint.Unit or pint.Quantity or dict or str) – Input data array or string representing a unit (with no magnitude).
- Return type:
Unit- Returns:
pint.Unit – Units of the data array.
Notes
To avoid ambiguity related to differences in temperature vs absolute temperatures, set the units_metadata attribute to “temperature: difference” or “temperature: on_scale” on the DataArray.
Spatial Analogues Module¶
- class xclim.analog.spatial_analogs(target, candidates, dist_dim='time', method='kldiv', **kwargs)[source]
Compute dissimilarity statistics between target points and candidate points.
Spatial analogues based on the comparison of climate indicators. The algorithm compares the distribution of the reference indicators with the distribution of spatially distributed candidate indicators and returns a value measuring the dissimilarity between both distributions over the candidate grid.
- Parameters:
target (xr.Dataset) – Dataset of the target indicators. Only indicator variables should be included in the dataset’s data_vars. They should have only the dimension(s) dist_dim `in common with `candidates.
candidates (xr.Dataset) – Dataset of the candidate indicators. Only indicator variables should be included in the dataset’s data_vars.
dist_dim (str) – The dimension over which the distributions are constructed. This can be a multi-index dimension.
method ({“seuclidean”, “nearest_neighbor”, “zech_aslan”, “kolmogorov_smirnov”, “friedman_rafsky”, “kldiv”}) – Which method to use when computing the dissimilarity statistic.
**kwargs (dict) – Any other parameter passed directly to the dissimilarity method.
- Returns:
xr.DataArray – The dissimilarity statistic over the union of candidates’ and target’s dimensions. The range depends on the method.
- xclim.analog.friedman_rafsky(x, y)[source]
Compute a dissimilarity metric based on the Friedman-Rafsky runs statistics.
The algorithm builds a minimal spanning tree (the subset of edges connecting all points that minimizes the total edge length) then counts the edges linking points from the same distribution. This method is scale-dependent.
- Parameters:
x (np.ndarray (n,d)) – Reference sample.
y (np.ndarray (m,d)) – Candidate sample.
- Return type:
float- Returns:
float – Friedman-Rafsky dissimilarity metric ranging from 0 to (m+n-1)/(m+n).
References
Friedman and Rafsky [1979]
- xclim.analog.kldiv(x, y, *, k=1)[source]
Compute the Kullback-Leibler divergence between two multivariate samples.
The formula to compute the K-L divergence from samples is given by:
\[D(P||Q) = \frac{d}{n} \sum_i^n \log\left\{\frac{r_k(x_i)}{s_k(x_i)}\right\} + \log\left\{\frac{m}{n-1}\right\}\]where \(r_k(x_i)\) and \(s_k(x_i)\) are, respectively, the Euclidean distance to the kth neighbour of \(x_i\) in the x array (excepting \(x_i\)) and in the y array. This method is scale-dependent.
- Parameters:
x (np.ndarray (n,d)) – Samples from distribution P, which typically represents the true distribution (reference).
y (np.ndarray (m,d)) – Samples from distribution Q, which typically represents the approximate distribution (candidate).
k (int or sequence) – The kth neighbours to look for when estimating the density of the distributions. Defaults to 1, which can be noisy.
- Return type:
float|Sequence[float]- Returns:
float or sequence – The estimated Kullback-Leibler divergence D(P||Q) computed from the distances to the kth neighbour.
Notes
In information theory, the Kullback–Leibler divergence [Perez-Cruz, 2008] is a non-symmetric measure of the difference between two probability distributions P and Q, where P is the “true” distribution and Q an approximation. This nuance is important because \(D(P||Q)\) is not equal to \(D(Q||P)\).
For probability distributions P and Q of a continuous random variable, the K–L divergence is defined as:
\[D_{KL}(P||Q) = \int p(x) \log\left(\frac{p(x)}{q(x)}\right) dx\]This formula assumes we have a representation of the probability densities \(p(x)\) and \(q(x)\). In many cases, we only have samples from the distribution, and most methods first estimate the densities from the samples and then proceed to compute the K-L divergence. In Perez-Cruz [2008], the author proposes an algorithm to estimate the K-L divergence directly from the sample using an empirical CDF. Even though the CDFs do not converge to their true values, the paper proves that the K-L divergence almost surely does converge to its true value.
References
Perez-Cruz [2008]
- xclim.analog.kolmogorov_smirnov(x, y)[source]
Compute the Kolmogorov-Smirnov statistic applied to two multivariate samples as described by Fasano and Franceschini.
This method is scale-dependent.
- Parameters:
x (np.ndarray (n,d)) – Reference sample.
y (np.ndarray (m,d)) – Candidate sample.
- Return type:
float- Returns:
float – Kolmogorov-Smirnov dissimilarity metric ranging from 0 to 1.
References
Fasano and Franceschini [1987]
- xclim.analog.nearest_neighbor(x, y)[source]
Compute a dissimilarity metric based on the number of points in the pooled sample whose nearest neighbor belongs to the same distribution.
This method is scale-invariant.
- Parameters:
x (np.ndarray (n,d)) – Reference sample.
y (np.ndarray (m,d)) – Candidate sample.
- Return type:
- Returns:
float – Nearest-Neighbor dissimilarity metric ranging from 0 to 1.
References
Henze [1988]
- xclim.analog.seuclidean(x, y)[source]
Compute the Euclidean distance between the mean of a multivariate candidate sample with respect to the mean of a reference sample.
This method is scale-invariant.
- Parameters:
x (np.ndarray (n,d)) – Reference sample.
y (np.ndarray (m,d)) – Candidate sample.
- Return type:
float- Returns:
float – Standardized Euclidean Distance between the mean of the samples ranging from 0 to infinity.
Notes
This metric considers neither the information from individual points nor the standard deviation of the candidate distribution.
References
Veloz, Williams, Lorenz, Notaro, Vavrus, and Vimont [2012]
- xclim.analog.szekely_rizzo(x, y, *, standardize=True)[source]
Compute the Székely-Rizzo energy distance dissimilarity metric based on an analogy with Newton’s gravitational potential energy.
This method is scale-invariant when standardize=True (default), scale-dependent otherwise.
- Parameters:
x (ndarray (n,d)) – Reference sample.
y (ndarray (m,d)) – Candidate sample.
standardize (bool) – If True (default), the standardized Euclidean norm is used, instead of the conventional one.
- Return type:
float- Returns:
float – Székely-Rizzo’s energy distance dissimilarity metric ranging from 0 to infinity.
Notes
The e-distance between two variables \(X\), \(Y\) (target and candidates) of sizes \(n,d\) and \(m,d\) proposed by Szekely and Rizzo [2004] is defined by:
\[e(X, Y) = \frac{n m}{n + m} \left[2\phi_{xy} − \phi_{xx} − \phi_{yy} \right]\]where
\[\begin{split}\phi_{xy} &= \frac{1}{n m} \sum_{i = 1}^n \sum_{j = 1}^m \left\Vert X_i − Y_j \right\Vert \\ \phi_{xx} &= \frac{1}{n^2} \sum_{i = 1}^n \sum_{j = 1}^n \left\Vert X_i − X_j \right\Vert \\ \phi_{yy} &= \frac{1}{m^2} \sum_{i = 1}^m \sum_{j = 1}^m \left\Vert X_i − Y_j \right\Vert \\\end{split}\]and where \(\Vert\cdot\Vert\) denotes the Euclidean norm, \(X_i\) denotes the i-th observation of \(X\). When standardized=False, this corresponds to the \(T\) test of Rizzo and Székely [2016] (p. 28) and to the
eqdist.efunction of the energy R package (with two samples). The standardization was added following the logic of [Grenier et al., 2013] to make the metric scale-invariant.References
Grenier, Parent, Huard, Anctil, and Chaumont [2013], Rizzo and Székely [2016], Szekely and Rizzo [2004]
- xclim.analog.zech_aslan(x, y, *, dmin=1e-12)[source]
Compute a modified Zech-Aslan energy distance dissimilarity metric based on an analogy with the energy of a cloud of electrical charges.
This method is scale-invariant.
- Parameters:
x (np.ndarray (n,d)) – Reference sample.
y (np.ndarray (m,d)) – Candidate sample.
dmin (float) – The cut-off for low distances to avoid singularities on identical points.
- Return type:
float- Returns:
float – Zech-Aslan dissimilarity metric ranging from -infinity to infinity.
Notes
The energy measure between two variables \(X\), \(Y\) (target and candidates) of sizes \(n,d\) and \(m,d\) proposed by Aslan and Zech [2003] is defined by:
\[\begin{split}e(X, Y) &= \left[\phi_{xx} + \phi_{yy} - \phi_{xy}\right] \\ \phi_{xy} &= \frac{1}{n m} \sum_{i = 1}^n \sum_{j = 1}^m R\left[SED(X_i, Y_j)\right] \\ \phi_{xx} &= \frac{1}{n^2} \sum_{i = 1}^n \sum_{j = i + 1}^n R\left[SED(X_i, X_j)\right] \\ \phi_{yy} &= \frac{1}{m^2} \sum_{i = 1}^m \sum_{j = i + 1}^m R\left[SED(X_i, Y_j)\right] \\\end{split}\]where \(X_i\) denotes the i-th observation of \(X\). \(R\) is a weight function and \(SED(A, B)\) denotes the standardized Euclidean distance.
\[\begin{split}R(r) &= \left\{\begin{array}{r l} -\ln r & \text{for } r > d_{min} \\ -\ln d_{min} & \text{for } r \leq d_{min} \end{array}\right. \\ SED(X_i, Y_j) &= \sqrt{\sum_{k=1}^d \frac{\left(X_i(k) - Y_i(k)\right)^2}{\sigma_x(k)\sigma_y(k)}}\end{split}\]where \(k\) is a counter over dimensions (indicators in the case of spatial analogs) and \(\sigma_x(k)\) is the standard deviation of \(X\) in dimension \(k\). Finally, \(d_{min}\) is a cut-off to avoid poles when \(r \to 0\), it is controllable through the dmin parameter.
This version corresponds the \(D_{ZAE}\) test of Grenier et al. [2013] (eq. 7), which is a version of \(\phi_{NM}\) from Aslan and Zech [2003], modified by using the standardized Euclidean distance, the log weight function and choosing \(d_{min} = 10^{-12}\).
References
Aslan and Zech [2003], Grenier, Parent, Huard, Anctil, and Chaumont [2013], Zech and Aslan [2003]
- xclim.analog.mahalanobis(x, y, *, VI=None)[source]
Compute the Mahalanobis distance.
This method is scale-invariant.
- Parameters:
x (np.ndarray) – Reference sample (n,d).
y (np.ndarray) – Candidate sample (m,d).
VI (np.ndarray, optional) – Inverse of the covariance matrix used in the Mahalanobis Distance (d,d). Optional.
- Return type:
- Returns:
numpy.float64 – Mahalanobis Distance between the mean of the samples.
Notes
With no Inverse of the covariance matrix provided, the covariance matrix of the set of observation vectors of the reference sample is used. The pseudoinverse is used if the covariance matrix is singular.
References
Deza and Deza [2016]
Other Utilities¶
Calendar Handling Utilities¶
Helper function to handle dates, times and different calendars with xarray.
- xclim.core.calendar.add_season_coord(ds, freq)[source]
Add a season coordinates on a resampled dataset.
- Parameters:
ds (xr.Dataset or xr.DataArray) – The xarray object with a “time” coordinate. Only supports daily or coarser frequencies (excluding weekly). The time axis must be complete and regular (xr.infer_freq(ds.time) doesn’t fail).
freq (str) – Resampling frequency. Must be between “MS” and “YS” and divide a year evenly.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray or xr.Dataset – Input dataset with season coordinate.
- xclim.core.calendar.adjust_doy_calendar(source, target)[source]
Interpolate from one set of dayofyear range to another calendar.
Interpolate an array defined over a dayofyear range (say 1 to 360) to another dayofyear range (say 1 to 365).
- Parameters:
source (xr.DataArray or xr.Dataset) – Array with dayofyear coordinate.
target (xr.DataArray or xr.Dataset) – Array with time coordinate.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray or xr.Dataset – Interpolated source array over coordinates spanning the target dayofyear range.
- xclim.core.calendar.build_climatology_bounds(da)[source]
Build the climatology_bounds property with the start and end dates of input data.
- Parameters:
da (xr.DataArray) – The input data. Must have a time dimension.
- Return type:
list[str]- Returns:
list of str – The climatology bounds.
- xclim.core.calendar.climatological_mean_doy(arr, window=5)[source]
Calculate the climatological mean and standard deviation for each day of the year.
- Parameters:
arr (xarray.DataArray) – Input array.
window (int) – Window size in days.
- Return type:
tuple[DataArray,DataArray]- Returns:
xarray.DataArray, xarray.DataArray – Mean and standard deviation.
- xclim.core.calendar.common_calendar(calendars, join='outer')[source]
Return a calendar common to all calendars from a list.
Uses the hierarchy: 360_day < noleap < standard < all_leap.
- Parameters:
calendars (Sequence of str) – List of calendar names.
join ({‘inner’, ‘outer’}) –
- The criterion for the common calendar.
- ‘outer’: the common calendar is the biggest calendar (in number of days by year) that will include all the
dates of the other calendars. When converting the data to this calendar, no timeseries will lose elements, but some might be missing (gaps or NaNs in the series).
- ‘inner’: the common calendar is the smallest calendar of the list.
When converting the data to this calendar, no timeseries will have missing elements (no gaps or NaNs), but some might be dropped.
- Return type:
str- Returns:
str – Returns “default” only if all calendars are “default”.
Examples
>>> common_calendar(["360_day", "noleap", "default"], join="outer") 'standard' >>> common_calendar(["360_day", "noleap", "default"], join="inner") '360_day'
- xclim.core.calendar.compare_offsets(freqA, op, freqB)[source]
Compare offsets string based on their approximate length, according to a given operator.
Offsets are compared based on their length approximated for a period starting after 1970-01-01 00:00:00. If the offsets are from the same category (same first letter), only the multiplier prefix is compared (QS-DEC == QS-JAN, MS < 2MS). “Business” offsets are not implemented.
- Parameters:
freqA (str) – RHS Date offset string (‘YS’, ‘1D’, ‘QS-DEC’, …).
op ({“>”, “gt”, “<”, “lt”, “>=”, “ge”, “<=”, “le”, “==”, “eq”, “!=”, “ne”}) – Operator to use.
freqB (str) – LHS Date offset string (‘YS’, ‘1D’, ‘QS-DEC’, …).
- Return type:
bool- Returns:
bool – The result of freqA op freqB.
- xclim.core.calendar.construct_offset(mult, base, start_anchored, anchor)[source]
Reconstruct an offset string from its parts.
- Parameters:
mult (int) – The period multiplier (>= 1).
base (str) – The base period string (one char).
start_anchored (bool) – If True and base in [Y, Q, M], adds the “S” flag, False add “E”.
anchor (str, optional) – The month anchor of the offset. Defaults to JAN for bases YS and QS and to DEC for bases YE and QE.
- Returns:
str – An offset string, conformant to pandas-like naming conventions.
Notes
This provides the mirror opposite functionality of
parse_offset().
- xclim.core.calendar.convert_doy(source, target_cal, source_cal=None, align_on='year', missing=nan, dim='time')[source]
Convert the calendar of day of year (doy) data.
- Parameters:
source (xr.DataArray or xr.Dataset) – Day of year data (range [1, 366], max depending on the calendar). If a Dataset, the function is mapped to each variable with attribute is_day_of_year == 1.
target_cal (str) – Name of the calendar to convert to.
source_cal (str, optional) – Calendar the doys are in. If not given, will use the “calendar” attribute of source or, if absent, the calendar of its dim axis.
align_on ({‘date’, ‘year’}) – If ‘year’ (default), the doy is seen as a “percentage” of the year and is simply rescaled onto the new doy range. This always results in floating point data, changing the decimal part of the value. If ‘date’, the doy is seen as a specific date. See notes. This never changes the decimal part of the value.
missing (Any) – If align_on is “date” and the new doy doesn’t exist in the new calendar, this value is used.
dim (str) – Name of the temporal dimension.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray or xr.Dataset – The converted doy data.
- xclim.core.calendar.days_since_to_doy(da, start=None, calendar=None)[source]
Reverse the conversion made by
doy_to_days_since().Converts data given in days since a specific date to day-of-year.
- Parameters:
da (xr.DataArray) – The result of
doy_to_days_since().start (DateOfYearStr, optional) – da is considered as days since that start date (in the year of the time index). If None (default), it is read from the attributes.
calendar (str, optional) – Calendar the “days since” were computed in. If None (default), it is read from the attributes.
- Return type:
DataArray- Returns:
xr.DataArray – Same shape as da, values as day of year.
Examples
>>> time = xr.date_range("2020-07-01", "2021-07-01", freq="YS-JUL") >>> da = xr.DataArray( ... [-86, 92], ... dims=("time",), ... coords={"time": time}, ... attrs={"units": "days since 10-02"}, ... ) >>> days_since_to_doy(da).values array([190, 2])
- xclim.core.calendar.doy_from_string(doy, year, calendar)[source]
Return the day-of-year corresponding to an “MM-DD” string for a given year and calendar.
- Parameters:
doy (str) – The day of year in the format “MM-DD”.
year (int) – The year.
calendar (str) – The calendar name.
- Return type:
int- Returns:
int – The day of year.
- xclim.core.calendar.doy_to_days_since(da, start=None, calendar=None)[source]
Convert day-of-year data to days since a given date.
This is useful for computing meaningful statistics on doy data.
- Parameters:
da (xr.DataArray) – Array of “day-of-year”, usually int dtype, must have a time dimension. Sampling frequency should be finer or similar to yearly and coarser than daily.
start (date of year str, optional) – A date in “MM-DD” format, the base day of the new array. If None (default), the time axis is used. Passing start only makes sense if da has a yearly sampling frequency.
calendar (str, optional) – The calendar to use when computing the new interval. If None (default), the calendar attribute of the data or of its time axis is used. All time coordinates of da must exist in this calendar. No check is done to ensure doy values exist in this calendar.
- Return type:
DataArray- Returns:
xr.DataArray – Same shape as da, int dtype, day-of-year data translated to a number of days since a given date. If start is not None, there might be negative values.
Notes
The time coordinates of da are considered as the START of the period. For example, a doy value of 350 with a timestamp of ‘2020-12-31’ is understood as ‘2021-12-16’ (the 350th day of 2021). Passing start=None, will use the time coordinate as the base, so in this case the converted value will be 350 “days since time coordinate”.
Examples
>>> time = xr.date_range("2020-07-01", "2021-07-01", freq="YS-JUL") >>> # July 8th 2020 and Jan 2nd 2022 >>> da = xr.DataArray([190, 2], dims=("time",), coords={"time": time}) >>> # Convert to days since Oct. 2nd, of the data's year. >>> doy_to_days_since(da, start="10-02").values array([-86, 92])
- xclim.core.calendar.ensure_cftime_array(time)[source]
Convert an input 1D array to a numpy array of cftime objects.
Python datetimes are converted to cftime.DatetimeGregorian (“standard” calendar).
- Parameters:
time (sequence) – A 1D array of datetime-like objects.
- Return type:
ndarray|Sequence[datetime]- Returns:
np.ndarray – An array of cftime.datetime objects.
- Raises:
ValueError – When unable to cast the input.:
- xclim.core.calendar.get_calendar(obj, dim='time')[source]
Return the calendar of an object.
- Parameters:
obj (Any) – An object defining some date. If obj is an array/dataset with a datetime coordinate, use dim to specify its name. Values must have either a datetime64 dtype or a cftime dtype. obj can also be a python datetime.datetime, a cftime object or a pandas Timestamp or an iterable of those, in which case the calendar is inferred from the first value.
dim (str) – Name of the coordinate to check (if obj is a DataArray or Dataset).
- Return type:
str- Returns:
str – The Climate and Forecasting (CF) calendar name. Will always return “standard” instead of “gregorian”, following CF-Conventions v1.9.
- Raises:
ValueError – If no calendar could be inferred.
- xclim.core.calendar.is_offset_divisor(divisor, offset)[source]
Check that divisor is a divisor of offset.
A frequency is a “divisor” of another if a whole number of periods of the former fit within a single period of the latter.
- Parameters:
divisor (str) – The divisor frequency.
offset (str) – The large frequency.
- Returns:
bool – Whether divisor is a divisor of offset.
Examples
>>> is_offset_divisor("QS-JAN", "YS") True >>> is_offset_divisor("QS-DEC", "YS-JUL") False >>> is_offset_divisor("D", "ME") True
- xclim.core.calendar.parse_offset(freq)[source]
Parse an offset string.
Parse a frequency offset and, if needed, convert to cftime-compatible components.
- Parameters:
freq (str) – Frequency offset.
- Return type:
tuple[int,str,bool,str|None]- Returns:
multiplier (int) – Multiplier of the base frequency. “[n]W” is always replaced with “[7n]D”, as xarray doesn’t support “W” for cftime indexes.
offset_base (str) – Base frequency.
is_start_anchored (bool) – Whether coordinates of this frequency should correspond to the beginning of the period (True) or its end (False). Can only be False when base is Y, Q or M; in other words, xclim assumes frequencies finer than monthly are all start-anchored.
anchor (str, optional) – Anchor date for bases Y or Q. As xarray doesn’t support “W”, neither does xclim (anchor information is lost when given).
- xclim.core.calendar.percentile_doy(arr, window=5, per=10.0, alpha=0.3333333333333333, beta=0.3333333333333333, copy=True)[source]
Percentile value for each day of the year.
Return the climatological percentile over a moving window around each day of the year. Different quantile estimators can be used by specifying alpha and beta according to specifications given by Hyndman and Fan [1996]. The default definition corresponds to method 8, which meets multiple desirable statistical properties for sample quantiles. Note that numpy.percentile corresponds to method 7, with alpha and beta set to 1.
- Parameters:
arr (xr.DataArray) – Input data, a daily frequency (or coarser) is required.
window (int) – Number of time-steps around each day of the year to include in the calculation.
per (float or sequence of float) – Percentile(s) between [0, 100].
alpha (float) – Plotting position parameter.
beta (float) – Plotting position parameter.
copy (bool) – If True (default) the input array will be deep-copied. It’s a necessary step to keep the data integrity, but it can be costly. If False, no copy is made of the input array. It will be mutated and rendered unusable, but performances may significantly improve. Put this flag to False only if you understand the consequences.
- Return type:
DataArray- Returns:
xr.DataArray – The percentiles indexed by the day of the year. For calendars with 366 days, percentiles of doys 1-365 are interpolated to the 1-366 range.
References
Hyndman and Fan [1996]
- xclim.core.calendar.resample_doy(doy, arr)[source]
Create a temporal DataArray where each day takes the value defined by the day-of-year.
- Parameters:
doy (xr.DataArray or xr.Dataset) – Array with dayofyear coordinate.
arr (xr.DataArray or xr.Dataset) – Array with time coordinate.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray or xr.Dataset – An array with the same dimensions as doy, except for dayofyear, which is replaced by the time dimension of arr. Values are filled according to the day of year value in doy.
- xclim.core.calendar.select_time(da, drop=False, season=None, month=None, doy_bounds=None, date_bounds=None, include_bounds=True, include_doy_bounds_nans=True, bounds_freq=None)[source]
Select entries according to a time period.
This conveniently improves xarray’s
xarray.DataArray.where()andxarray.DataArray.sel()with fancier ways of indexing over time elements. In addition to the data da and argument drop, only one of season, month, doy_bounds or date_bounds may be passed.- Parameters:
da (xr.DataArray or xr.Dataset) – Input data.
drop (bool) – Whether to drop elements outside the period of interest (True) or to simply mask them (False, default). This option is incompatible with passing date_bounds or array-like doy_bounds.
season (str or sequence of str, optional) – One or more of ‘DJF’, ‘MAM’, ‘JJA’ and ‘SON’.
month (int or sequence of int, optional) – Sequence of month numbers (January = 1 … December = 12).
doy_bounds (2-tuple of optional integers or DataArray, optional) – The bounds as (start, end) of the period of interest expressed in day-of-year, integers going from 1 (January 1st) to 365 or 366 (December 31st). If DataArrays are passed, they must have the same coordinates on the dimensions they share. They may have a time dimension, in which case the selection is done independently for each period defined by the coordinate, which means the time coordinate must have an inferable frequency (see
xr.infer_freq()) or the frequency must be passed explicitly with the bounds_freq argument. If None is passed as a bound, it is replaced by the start or end of the year (1 or 366) if the other bound is an integer, or by the start or end of the period defined by the inferred or passed frequency of DataArrays. Timesteps of the input not appearing in the time coordinate of the bounds are considered as “outside the bounds”.date_bounds (2-tuple of optional strings, optional) – The bounds as (start, end) of the period of interest expressed as dates in the month-day (%m-%d) format. If None is passed as a bounds, it is replaced by the start or end of the period defined by the bounds_freq argument, corresponding to 1st January or 31st December for default “YS” bounds frequency.
include_bounds (bool or 2-tuple of bool, optional) – Whether the bounds of doy_bounds or date_bounds should be inclusive or not. Either one value for both or a tuple. Default is True, meaning bounds are inclusive.
include_doy_bounds_nans (bool, optional) – Whether to include values associated with NaN in doy_bounds. If True (default), missing values (NaN) in the start and end bounds are replaced by the start and end of the period, respectively.
bounds_freq (str, optional) – Needed with array-like doy_bounds without a time dimension or date_bounds, and corresponding to the frequency used to determine the start and end of the period (default “YS”). If doy_bounds have a time dimension, the frequency is first tried to be inferred from the time coordinate of the bounds; if it cannot be inferred, the frequency must be passed explicitly.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray or xr.Dataset – Selected input values. If
drop=False, this has the same length asda(along dimension ‘time’), but with masked (NaN) values outside the period of interest.
Examples
Keep only the values of fall and spring.
>>> ds = xr.open_dataset("ERA5/daily_surface_cancities_1990-1993.nc") >>> ds.time.size 1461 >>> out = select_time(ds, drop=True, season=["MAM", "SON"]) >>> out.time.size 732
Or all values between two dates (included).
>>> out = select_time(ds, drop=True, date_bounds=("02-29", "03-02")) >>> out.time.values array(['1990-03-01T00:00:00.000000000', '1990-03-02T00:00:00.000000000', '1991-03-01T00:00:00.000000000', '1991-03-02T00:00:00.000000000', '1992-02-29T00:00:00.000000000', '1992-03-01T00:00:00.000000000', '1992-03-02T00:00:00.000000000', '1993-03-01T00:00:00.000000000', '1993-03-02T00:00:00.000000000'], dtype='datetime64[ns]')
- xclim.core.calendar.split_time_to_season_year(ds, freq)[source]
Split a resampled dataset into a yearly time and a season coordinate.
- Parameters:
ds (xr.Dataset or xr.DataArray) – The xarray object with a “time” coordinate. Only supports daily or coarser frequencies (excluding weekly). The time axis must be complete and regular (xr.infer_freq(ds.time) doesn’t fail).
freq (str) – Resampling frequency. Must be between “MS” and “YS” and divide a year evenly.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray or xr.Dataset – Input dataset with season coordinate and yearly time.
- xclim.core.calendar.stack_periods(da, window=30, stride=None, min_length=None, freq='YS', dim='period', start='1970-01-01', align_days=True, pad_value='<NA>')[source]
Construct a multi-period array.
Stack different equal-length periods of da into a new ‘period’ dimension.
This is similar to
da.rolling(time=window).construct(dim, stride=stride), but adapted for arguments in terms of a base temporal frequency that might be non-uniform (years, months, etc.). It is reversible for some cases (see stride). A rolling-construct method will be much more performant for uniform periods (days, weeks).- Parameters:
da (xr.Dataset or xr.DataArray) – An xarray object with a time dimension. Must have a uniform timestep length. Output might be strange if this does not use a uniform calendar (noleap, 360_day, all_leap).
window (int) – The length of the moving window as a multiple of
freq.stride (int, optional) – At which interval to take the windows, as a multiple of
freq. For the operation to be reversible withunstack_periods(), it must divide window into an odd number of parts. Default is window (no overlap between periods).min_length (int, optional) – Windows shorter than this are not included in the output. Given as a multiple of
freq. Default iswindow(every window must be complete). Similar to themin_periodsargument ofda.rolling. Iffreqis annual or quarterly andmin_length == ``window, the first period is considered complete if the first timestep is in the first month of the period.freq (str) – Units of
window,strideandmin_length, as a frequency string. Must be larger or equal to the data’s sampling frequency. Note that this function offers an easier interface for non-uniform period (like years or months) but is much slower than a rolling-construct method.dim (str) – The new dimension name.
start (str) – The start argument passed to
xarray.date_range()to generate the new placeholder time coordinate.align_days (bool) – When True (default), an error is raised if the output would have unaligned days across periods. If freq = ‘YS’, day-of-year alignment is checked and if freq is “MS” or “QS”, we check day-in-month. Only uniform-calendar will pass the test for freq=’YS’. For other frequencies, only the 360_day calendar will work. This check is ignored if the sampling rate of the data is coarser than “D”.
pad_value (Any) – When some periods are shorter than others, this value is used to pad them at the end. Passed directly as argument
fill_valuetoxarray.concat(), the default is the same as on that function.
- Return type:
TypeVar(DataType,DataArray,Dataset)- Returns:
xr.DataArray – A DataArray with a new period dimension and a time dimension with the length of the longest window. The new time coordinate has the same frequency as the input data but is generated using
xarray.date_range()with the given start value. That coordinate is the same for all periods, depending on the choice ofwindowandfreq, it might make sense. But for unequal periods or non-uniform calendars, it will certainly not. Ifstrideis a divisor ofwindow, the correct timeseries can be reconstructed withunstack_periods(). The coordinate of period is the first timestep of each window.
- xclim.core.calendar.time_bnds(time, freq=None)[source]
Find the time bounds for a datetime index by assuming an uniform sampling frequency.
As we are using datetime indices to stand in for period indices, assumptions regarding the period are made based on the given freq. This function does not implement finding bounds for an irregular time index.
- Parameters:
time (DataArray, Dataset, CFTimeIndex, DatetimeIndex, DataArrayResample or DatasetResample) – Object which contains a time index as a proxy representation for a period index.
freq (str, optional) – String specifying the frequency/offset such as ‘MS’, ‘2D’, or ‘3min’ If not given, it is inferred from the time index, which means that index must have at least three elements.
- Returns:
DataArray – The time bounds: start and end times of the periods inferred from the time index and a frequency. It has the original time index along it’s time coordinate and a new bnds coordinate. The dtype and calendar of the array are the same as the index. If a period follows another, its start is the same as the other’s end.
Notes
xclim assumes that indexes for greater-than-day frequencies are “floored” down to a daily resolution. For example, the coordinate “2000-01-31 00:00:00” with a “ME” frequency is assumed to mean a period going from “2000-01-01 00:00:00” to “2000-02-01 00:00:00”.
Similarly, it assumes that daily and finer frequencies yield indexes pointing to the period’s start. So “2000-01-31 00:00:00” with a “3h” frequency, means a period going from “2000-01-31 00:00:00” to “2000-01-31 03:00:00”.
See the relevant CF convention <https://cfconventions.org/Data/cf-conventions/cf-conventions-1.13/cf-conventions.html#bounds-one-d>.
- xclim.core.calendar.within_bnds_doy(arr, *, low, high)[source]
Return whether array values are within bounds for each day of the year.
- Parameters:
arr (xarray.DataArray) – Input array.
low (xarray.DataArray) – Low bound with dayofyear coordinate.
high (xarray.DataArray) – High bound with dayofyear coordinate.
- Return type:
DataArray- Returns:
xarray.DataArray – Boolean array of values within doy.
Formatting Utilities for Indicators¶
- class xclim.core.formatting.AttrFormatter(mapping, modifiers)[source]
Bases:
string.FormatterA formatter for frequently used attribute values.
- Parameters:
mapping (dict of str, sequence of str) – A mapping from values to their possible variations.
modifiers (sequence of str) – The list of modifiers. Must at least match the length of the longest value of mapping. Cannot include reserved modifier ‘r’.
Notes
See the doc of
format_field()for more details.- format(format_string, /, *args, **kwargs)[source]
Format a string.
- Parameters:
format_string (str) – The string to format.
*args (Any) – Arguments to format.
**kwargs (Any) – Keyword arguments to format.
- Return type:
str- Returns:
str – The formatted string.
- format_field(value, format_spec)[source]
Format a value given a formatting spec.
If format_spec is in this Formatter’s modifiers, the corresponding variation of value is given. If format_spec is ‘r’ (raw), the value is returned unmodified. If format_spec is not specified but value is in the mapping, the first variation is returned.
- Parameters:
value (Any) – The value to format.
format_spec (str) – The formatting spec.
- Return type:
str- Returns:
str – The formatted value.
Examples
Let’s say the string “The dog is {adj1}, the goose is {adj2}” is to be translated to French and that we know that possible values of adj are nice and evil. In French, the genre of the noun changes the adjective (cat = chat is masculine, and goose = oie is feminine) so we initialize the formatter as:
>>> fmt = AttrFormatter( ... { ... "nice": ["beau", "belle"], ... "evil": ["méchant", "méchante"], ... "smart": ["intelligent", "intelligente"], ... }, ... ["m", "f"], ... ) >>> fmt.format( ... "Le chien est {adj1:m}, l'oie est {adj2:f}, le gecko est {adj3:r}", ... adj1="nice", ... adj2="evil", ... adj3="smart", ... ) "Le chien est beau, l'oie est méchante, le gecko est smart"
The base values may be given using unix shell-like patterns:
>>> fmt = AttrFormatter( ... {"YS-*": ["annuel", "annuelle"], "MS": ["mensuel", "mensuelle"]}, ... ["m", "f"], ... ) >>> fmt.format( ... "La moyenne {freq:f} est faite sur un échantillon {src_timestep:m}", ... freq="YS-JUL", ... src_timestep="MS", ... ) 'La moyenne annuelle est faite sur un échantillon mensuel'
- xclim.core.formatting.capitalize_free_text(text, sep='. ')[source]
Ensure each sentence of the text begins with an uppercase letter.
- Parameters:
text (str) – A string.
sep (str) – The separator indicating the end and the beginning of sentences, in addition to the first letter of the text.
- Returns:
str – The capitalized text. In opposition to
str.capitalize(), case of letters not at the beginning of a sentence is preserved.
- xclim.core.formatting.gen_call_string(funcname, *args, **kwargs)[source]
Generate a signature string for use in the history attribute.
DataArrays and Dataset are replaced with their name, while Nones, floats, ints and strings are printed directly. All other objects have their type printed between < >.
Arguments given through positional arguments are printed positionnally and those given through keywords are printed prefixed by their name.
- Parameters:
funcname (str) – Name of the function.
*args (Any) – Arguments given to the function.
**kwargs (Any) – Keyword arguments given to the function.
- Return type:
str- Returns:
str – The formatted string.
Examples
>>> A = xr.DataArray([1], dims=("x",), name="A") >>> gen_call_string("func", A, b=2.0, c="3", d=[10] * 100) "func(A, b=2.0, c='3', d=<list>)"
- xclim.core.formatting.get_percentile_metadata(data, prefix)[source]
Get the metadata related to percentiles from the given DataArray as a dictionary.
- Parameters:
data (xr.DataArray) – Must be a percentile DataArray, this means the necessary metadata must be available in its attributes and coordinates.
prefix (str) – The prefix to be used in the metadata key. Usually this takes the form of “tasmin_per” or equivalent.
- Return type:
dict[str,str]- Returns:
dict – A mapping of the configuration used to compute these percentiles.
- xclim.core.formatting.merge_attributes(attribute, *inputs_list, new_line='\\n', missing_str=None, **inputs_kws)[source]
Merge attributes from several DataArrays or Datasets.
If more than one input is given, its name (if available) is prepended as: “<input name> : <input attribute>”.
- Parameters:
attribute (str) – The attribute to merge.
*inputs_list (xr.DataArray or xr.Dataset) – The datasets or variables that were used to produce the new object. Inputs given that way will be prefixed by their name attribute if available.
new_line (str) – The character to put between each instance of the attributes. Usually, in CF-conventions, the history attributes uses ‘\n’ while cell_methods uses ‘ ‘.
missing_str (str) – A string that is printed if an input doesn’t have the attribute. Defaults to None, in which case the input is simply skipped.
**inputs_kws (xr.DataArray or xr.Dataset) – Mapping from names to the datasets or variables that were used to produce the new object. Inputs given that way will be prefixes by the passed name.
- Return type:
str- Returns:
str – The new attribute made from the combination of the ones from all the inputs.
- xclim.core.formatting.prefix_attrs(source, keys, prefix)[source]
Rename some keys of a dictionary by adding a prefix.
- Parameters:
source (dict) – Source dictionary, for example data attributes.
keys (sequence) – Names of keys to prefix.
prefix (str) – Prefix to prepend to keys.
- Return type:
dict- Returns:
dict – Dictionary of attributes with some keys prefixed.
- xclim.core.formatting.unprefix_attrs(source, keys, prefix)[source]
Remove prefix from keys in a dictionary.
- Parameters:
source (dict) – Source dictionary, for example data attributes.
keys (sequence) – Names of original keys for which prefix should be removed.
prefix (str) – Prefix to remove from keys.
- Return type:
dict- Returns:
dict – Dictionary of attributes whose keys were prefixed, with prefix removed.
- xclim.core.formatting.update_history(hist_str, *inputs_list, new_name=None, **inputs_kws)[source]
Return a history string with the timestamped message and the combination of the history of all inputs.
The new history entry is formatted as “[<timestamp>] <new_name>: <hist_str> - xclim version: <xclim.__version__>.”
- Parameters:
hist_str (str) – The string describing what has been done on the data.
*inputs_list (xr.DataArray or xr.Dataset) – The datasets or variables that were used to produce the new object. Inputs given that way will be prefixed by their “name” attribute if available.
new_name (str, optional) – The name of the newly created variable or dataset to prefix hist_msg.
**inputs_kws (xr.DataArray or xr.Dataset) – Mapping from names to the datasets or variables that were used to produce the new object. Inputs given that way will be prefixes by the passed name.
- Return type:
str- Returns:
str – The combine history of all inputs starting with hist_str.
See also
merge_attributesMerge attributes from several DataArrays or Datasets.
- xclim.core.formatting.update_xclim_history(func)[source]
Decorator that auto-generates and fills the history attribute.
The history is generated from the signature of the function and added to the first output. Because of a limitation of the boltons wrapper, all arguments passed to the wrapped function will be printed as keyword arguments.
- Parameters:
func (Callable) – The function to decorate.
- Return type:
Callable- Returns:
Callable – The decorated function.
Options Submodule¶
Global or contextual options for xclim, similar to xarray.set_options.
- class xclim.core.options.set_options(**kwargs)[source]
Set options for xclim in a controlled context.
- Parameters:
metadata_locales (list[Any]) – List of IETF language tags or tuples of language tags and a translation dict, or tuples of language tags and a path to a json file defining translation of attributes. Default:
[].data_validation ({“log”, “raise”, “error”}) – Whether to “log”, “raise” an error or ‘warn’ the user on inputs that fail the data checks in
xclim.core.datachecks(). Default:"raise".cf_compliance ({“log”, “raise”, “error”}) – Whether to “log”, “raise” an error or “warn” the user on inputs that fail the CF compliance checks in
xclim.core.cfchecks(). Default:"warn".check_missing ({“any”, “wmo”, “pct”, “at_least_n”, “skip”}) – How to check for missing data and flag computed indicators. Available methods are “any”, “wmo”, “pct”, “at_least_n” and “skip”. Missing method can be registered through the xclim.core.options.register_missing_method decorator. Default:
"any"missing_options (dict) – Dictionary of options to pass to the missing method. Keys must the name of missing method and values must be mappings from option names to values.
run_length_ufunc (str) – Whether to use the 1D ufunc version of run length algorithms or the dask-ready broadcasting version. Default is
"auto", which means the latter is used for dask-backed and large arrays.as_dataset (bool) – If True, indicators output datasets. If False, they output DataArrays. The output dataset inherits attributes from the input dataset (if any) according to xarray’s
keep_attrsoption, which defaults to preserving attributes. Default :False.resample_map_blocks (bool) – If True, some indicators will wrap their resampling operations with xr.map_blocks, using
xclim.compute.helpers.resample_map(). This requires flox to be installed in order to ensure the chunking is appropriate.
Examples
You can use
set_optionseither as a context manager:>>> import xclim >>> ds = xr.open_dataset(path_to_tas_file).tas >>> with xclim.set_options(metadata_locales=["fr"]): ... out = xclim.atmos.tg_mean(ds)
Or to set global options:
import xclim xclim.set_options(missing_options={"pct": {"tolerance": 0.04}})
Miscellaneous Utilities¶
Helper functions for the computations, indicator construction and other things.
- class xclim.core.utils.CaseInsensitiveDict(data=None)[source]
Bases:
collections.abc.MutableMapping[str,Any]A basic dictionary but keys are strings and case-insensitive, stored all lowercase.
- get(key, default=None)[source]
- Return type:
Any
- setdefault(key, default=None)[source]
- Return type:
Any
- update(other, **kwargs)[source]
If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- items()[source]
- Return type:
Iterator[tuple[str,Any]]
- keys()[source]
- Return type:
Iterator[str]
- pop(key)[source]
If key is not found, d is returned if given, otherwise KeyError is raised.
- Return type:
Any
- popitem()[source]
as a 2-tuple; but raise KeyError if D is empty.
- Return type:
tuple[str,Any]
- copy()[source]
- Return type:
- xclim.core.utils.deprecated(from_version, suggested=None)[source]
Mark an index as deprecated and optionally suggest a replacement.
- Parameters:
from_version (str, optional) – The version of xclim from which the function is deprecated.
suggested (str, optional) – The name of the function to use instead.
- Return type:
Callable- Returns:
Callable – The decorated function.
- xclim.core.utils.load_module(path, name=None)[source]
Load a python module from a python file, optionally changing its name.
- Parameters:
path (os.PathLike) – The path to the python file.
name (str, optional) – The name to give to the module. If None, the module name will be the stem of the path.
- Return type:
ModuleType- Returns:
ModuleType – The loaded module.
Examples
Given a path to a module file (.py):
from pathlib import Path import os path = Path("path/to/example.py")
The two following imports are equivalent, the second uses this method.
os.chdir(path.parent) import example as mod1 os.chdir(previous_working_dir) mod2 = load_module(path) mod1 == mod2
- xclim.core.utils.ensure_chunk_size(da, **minchunks)[source]
Ensure that the input DataArray has chunks of at least the given size.
If only one chunk is too small, it is merged with an adjacent chunk. If many chunks are too small, they are grouped together by merging adjacent chunks.
- Parameters:
da (xr.DataArray) – The input DataArray, with or without the dask backend. Does nothing when passed a non-dask array.
**minchunks (dict[str, int]) – A kwarg mapping from dimension name to minimum chunk size. Pass -1 to force a single chunk along that dimension.
- Return type:
DataArray- Returns:
xr.DataArray – The input DataArray, possibly rechunked.
- xclim.core.utils.uses_dask(*das)[source]
Evaluate whether dask is installed and array is loaded as a dask array.
- Parameters:
*das (xr.DataArray or xr.Dataset) – DataArrays or Datasets to check.
- Return type:
bool- Returns:
bool – True if any of the passed objects is using dask.
- xclim.core.utils.lazy_indexing(da, index, dim=None)[source]
Get values of da at indices index in a NaN-aware and lazy manner.
- Parameters:
da (xr.DataArray) – Input array. If not 1D, dim must be given and must not appear in index.
index (xr.DataArray) – N-d integer indices, if DataArray is not 1D, all dimensions of index must be in DataArray.
dim (str, optional) – Dimension along which to index, unused if da is 1D, should not be present in index.
- Return type:
DataArray- Returns:
xr.DataArray – Values of da at indices index.
- xclim.core.utils.calc_perc(arr, percentiles=None, alpha=1.0, beta=1.0, copy=True)[source]
Compute percentiles using nan_calc_percentiles and move the percentiles’ axis to the end.
- Parameters:
arr (array_like) – The input array.
percentiles (sequence of float, optional) – The percentiles to compute. If None, only the median is computed.
alpha (float) – A constant used to correct the index computed.
beta (float) – A constant used to correct the index computed.
copy (bool) – If True, the input array is copied before computation. Default is True.
- Return type:
- Returns:
np.ndarray – The percentiles along the last axis.
- xclim.core.utils.nan_calc_percentiles(arr, percentiles=None, axis=-1, alpha=1.0, beta=1.0, copy=True)[source]
Convert the percentiles to quantiles and compute them using _nan_quantile.
- Parameters:
arr (array_like) – The input array.
percentiles (sequence of float, optional) – The percentiles to compute. If None, only the median is computed.
axis (int) – The axis along which to compute the percentiles.
alpha (float) – A constant used to correct the index computed.
beta (float) – A constant used to correct the index computed.
copy (bool) – If True, the input array is copied before computation. Default is True.
- Return type:
- Returns:
np.ndarray – The percentiles along the specified axis.
- xclim.core.utils.make_clix_meta_yaml(raw, adapted)[source]
Read in the clix-meta “index_definitions.yml” file and adapt it to a xclim virtual module yaml.
- Parameters:
raw (os.PathLike or StringIO or str) – The path to the clix-meta “index_definitions.yml” file or the string representation of the yaml.
adapted (os.PathLike) – The path where to write the adapted yaml.
- Return type:
None
- xclim.core.utils.split_auxiliary_coordinates(obj)[source]
Split auxiliary coords from the dataset.
An auxiliary coordinate is a coordinate variable that does not define a dimension and thus is not necessarily needed for dataset alignment. Any coordinate that has a name different from its dimension(s) is flagged as auxiliary. All scalar coordinates are flagged as auxiliary.
- Parameters:
obj (xr.DataArray or xr.Dataset) – An xarray object.
- Return type:
tuple[DataArray|Dataset,DataArray]- Returns:
clean_obj (xr.DataArray or xr.Dataset) – Same as obj but without any auxiliary coordinate.
aux_crd_ds (xr.Dataset) – The auxiliary coordinates as a dataset. Might be empty.
Notes
This is useful to circumvent xarray’s alignment checks that will sometimes look the auxiliary coordinate’s data, which can trigger unwanted dask computations.
The auxiliary coordinates can be merged back with the dataset with
xarray.Dataset.assign_coords()orxarray.DataArray.assign_coords().clean, aux = split_auxiliary_coordinates(ds) merged = clean.assign_coords(da.coords) merged.identical(ds) # -> True
- xclim.core.utils.get_temp_dimname(dims, new_dim)[source]
Get an new dimension name based on new_dim, that is not used in dims.
- Parameters:
dims (sequence of str) – The dimension names that already exist.
new_dim (str) – The new name we want.
- Return type:
str- Returns:
str – The new dimension name with as many underscores prepended as necessary to make it unique.
Modules for xclim Developers¶
Indicator Utilities¶
The Indicator class wraps computations with pre- and post-processing functionality. Prior to computations, the class runs data and metadata health checks. After computations, the class masks values that should be considered missing and adds metadata attributes to the output.
There are many ways to construct indicators. A good place to start is this notebook.
- class xclim.core.indicator.Parameter(kind, default, compute_name=<class 'xclim.core.indicator._empty'>, description='', units=<class 'xclim.core.indicator._empty'>, choices=<class 'xclim.core.indicator._empty'>, value=<class 'xclim.core.indicator._empty'>, annotation=<class 'xclim.core.indicator._empty'>)[source]
Object representing an indicator’s parameter.
For convenience, this class implements a special “contains”.
Examples
>>> p = Parameter(InputKind.NUMBER, default=2, description="A simple number") >>> p.units is Parameter._empty # has not been set True >>> "units" in p # Easier/retrocompatible way to test if units are set False >>> p.description 'A simple number'
- property injected: bool
Indicate whether values are injected.
- Returns:
bool – Whether values are injected.
- json()[source]
Return a json-serializable dictionary of the Parameter.
- Return type:
dict- Returns:
dict – Dictionary representation of the object, ready for serialization into json.
- update(other)[source]
Update a parameter’s values from a dict.
- Parameters:
other (dict) – A dictionary of parameters to update the current.
- Return type:
None
- class xclim.core.indicator.Output(var_name=None, dimensionality=None, units=None, units_metadata=None, **kwargs)[source]
Bases:
dictDictionary metadata for the output of an indicator.
- dimensionality: str | None
Dimensionality specification, similar but not necessarily compatible with pint.
- property meta: dict
A dictionary of the non-attribute metadata for this output.
- Returns:
dict – The non-attribute metadata of this Output.
- units: str | None
Units of the output.
- units_metadata: str | None
Additional CF metadata for the units.
- var_name: str | None
Output variable name.
- class xclim.core.indicator.Indicator(identifier, compute=None, title=None, abstract=None, realm=None, keywords=None, references=None, notes=None, input=None, parameters=None, attrs=None, context='none', src_freq=None, **attrs_kwargs)[source]
Climate indicator base class.
Climate indicator object that, when called, computes an indicator and assigns its output a number of CF-compliant attributes. These attributes can be templated, allowing metadata to reflect the value of call arguments.
Instantiating a new indicator returns an instance but also registers is in
xclim.core.indicator.registry.Attributes in Indicator.attrs will be formatted and added to the output variable(s). This attribute is a list of
Outputdict-like objects.A lot of the Indicator’s metadata is parsed from the underlying compute function’s docstring and signature. Input variables and parameters are listed in
xclim.core.indicator.Indicator.parameters, while parameters that will be injected in the compute function are inxclim.core.indicator.Indicator.injected_parameters.Compared to their base compute function, indicators add the possibility of using a dataset or a
xarray.DataTreeas input, with the added argument ds in the call signature. All arguments that were indicated by the compute function to be variables (DataArrays) through annotations will be promoted to also accept strings that correspond to variable names in the ds dataset (or on each DataTree nodes).- abstract: str
Description of the indicator.
- attrs: list[xclim.core.indicator.Output]
List of output metadata.
- cfcheck(**das)
Compare metadata attributes to CF-Convention standards.
Default cfchecks use the specifications in xclim.core.VARIABLES, assuming the indicator’s inputs are using the CMIP6/xclim variable names correctly. Variables absent from these default specs are silently ignored.
When subclassing this method, use functions decorated using xclim.core.options.cfcheck.
- Parameters:
**das (dict) – A dictionary of DataArrays to check.
- Return type:
None
- static compute(*args, **kwargs)
The index-like compute function.
- context: str = 'none'
Name of xclim.units.units context which will be enabled during computation.
- datacheck(**das)
Verify that input data is valid.
For example, checks could include: * assert no precipitation is negative * assert no temperature has the same value 5 days in a row
This base datacheck checks that the input data has a valid sampling frequency, as given in self.src_freq. If there are multiple inputs, it also checks if they all have the same frequency and the same anchor.
- Parameters:
**das (dict) – A dictionary of DataArrays to check.
- Raises:
if the frequency of any input can’t be inferred. - if inputs have different frequencies. - if inputs have a daily or hourly frequency, but they are not given at the same time of day.
- Return type:
None
- classmethod get_parent_ids()
Return the list of indicator identifiers this indicator was derived from.
- Returns:
list – All parent indicator classes of this indicator. Only classes defining an identifier are included.
- identifier: str = None
Unique ID identifying this indicator. Mostly for registry purposes.
- property injected_parameters: collections.abc.Mapping[str, Any]
Dictionary of all injected parameters (values).
- Returns:
dict – A dictionary of all injected parameters’ values.
- property is_generic: bool
If the indicator is “generic” returns True, meaning that it can accept variables with any units.
- Returns:
bool – True if the indicator is generic.
- json(args=None)
Return a serializable dictionary representation of the indicator.
- Parameters:
args (mapping, optional) – Arguments as passed to the call method of the indicator. If not given, the default arguments will be used when formatting the attributes.
- Return type:
dict- Returns:
dict – A dictionary representation of the indicator.
Notes
This is meant to be used by a third-party library wanting to wrap this indicator into another interface.
- keywords: tuple[str] = ()
Keywords describing the indicator and its domains of application. Child classes append to the list when inheriting.
- property n_outs: int
The number of outputs of this indicator.
- Returns:
int – The number of outputs.
- notes: str
Additional information about the indicator.
- property parameters: collections.abc.Mapping[str, xclim.core.indicator.Parameter]
Dictionary of controllable (non-injected) parameters.
Similar to
IndexWrapper._all_parameters, but doesn’t include injected parameters.- Returns:
dict – A dictionary of controllable parameters.
- realm: str = None
General domain of validity of the indicator. Should use the same vocabulary as CMIP.
- references: str
rst cite directives for literature about this indicator. Child classes append their references as a new line when inheriting.
- src_freq: str | list[str] | None = None
The expected frequency of the input data. Can be a list for multiple frequencies, or None if irrelevant.
- title: str
Short description of the indicator.
- translate(locale, fill_missing=True)
Return a dictionary of metadata and (unformatted) output attributes for the requested locale.
- Return type:
dict
- class xclim.core.indicator.ReducingIndicator(**kwargs)[source]
Indicator that performs a time-reducing computation.
- class xclim.core.indicator.IndexingIndicator(identifier, compute=None, title=None, abstract=None, realm=None, keywords=None, references=None, notes=None, input=None, parameters=None, attrs=None, context='none', src_freq=None, **attrs_kwargs)[source]
Indicator that also adds the “indexer” kwargs to subset the inputs before computation.
- class xclim.core.indicator.ResamplingIndicator(**kwargs)[source]
Indicator that performs a resampling computation.
Compared to the base Indicator, this adds the handling of missing data, and the check of allowed periods.
- allowed_periods: list[str] = None
A list of allowed periods, i.e. base parts of the freq parameter. For example, indicators meant to be computed annually only will have allowed_periods=[“Y”]. None means “any period” or that the indicator doesn’t take a freq argument.
- class xclim.core.indicator.ResamplingIndicatorWithIndexing(**kwargs)[source]
Resampling indicator that also adds “indexer” kwargs to subset the inputs before computation.
- class xclim.core.indicator.Hourly(**kwargs)[source]
Class for hourly inputs and resampling computes.
- src_freq: str | list[str] | None = 'h'
The expected frequency of the input data. Can be a list for multiple frequencies, or None if irrelevant.
- class xclim.core.indicator.Daily(**kwargs)[source]
Class for daily inputs and resampling computes.
- src_freq: str | list[str] | None = 'D'
The expected frequency of the input data. Can be a list for multiple frequencies, or None if irrelevant.
Bootstrapping Algorithms for Indicators Submodule¶
Module comprising the bootstrapping algorithm for indicators.
- xclim.core.bootstrapping.bootstrap_func(compute_index_func, **kwargs)[source]
Bootstrap the computation of percentile-based indicators.
Indicators measuring exceedance over percentile-based thresholds (such as tx90p) may contain artificial discontinuities at the beginning and end of the reference period used to calculate percentiles. The bootstrap procedure can reduce those discontinuities by iteratively computing the percentile estimate and the index on altered reference periods.
These altered reference periods are themselves built iteratively: When computing the index for year x, the bootstrapping creates as many altered reference periods as the number of years in the reference period. To build one altered reference period, the values of year x are replaced by the values of another year in the reference period, then the index is computed on this altered period. This is repeated for each year of the reference period, excluding year x. The final result of the index for year x is then the average of all the index results on altered years.
- Parameters:
compute_index_func (Callable) – Index function.
**kwargs (dict) – Arguments to func.
- Return type:
DataArray- Returns:
xr.DataArray – The result of func with bootstrapping.
Notes
This function is meant to be used by the percentile_bootstrap decorator. The parameters of the percentile calculation (percentile, window, reference_period) are stored in the attributes of the percentile DataArray. The bootstrap algorithm implemented here does the following:
For each temporal grouping in the calculation of the index If the group `g_t` is in the reference period For every other group `g_s` in the reference period Replace group `g_t` by `g_s` Compute percentile on resampled time series Compute index function using percentile Average output from index function over all resampled time series Else compute index function using original percentileReferences
Zhang, Hegerl, Zwiers, and Kenyon [2005]
- xclim.core.bootstrapping.build_bootstrap_year_da(da, groups, label, dim='time')[source]
Return an array where every other group replaces a group in the original along a new dimension.
- Parameters:
da (DataArray) – Original input array over the reference period.
groups (dict) – Output of grouping functions, such as DataArrayResample.groups.
label (Any) – Key identifying the group item to replace.
dim (str) – Dimension recognised as time. Default: time.
- Return type:
DataArray- Returns:
DataArray – Array where one group is replaced by values from every other group along the bootstrap dimension.
- xclim.core.bootstrapping.percentile_bootstrap(func)[source]
Decorator applying a bootstrap step to the calculation of exceedance over a percentile threshold.
This feature is experimental.
- Parameters:
func (Callable) – The function to decorate.
- Return type:
Callable- Returns:
Callable – The decorated function.
Notes
Bootstrapping avoids discontinuities in the exceedance between the reference period over which percentiles are computed, and “out of reference” periods. See bootstrap_func for details.
Declaration example:
@declare_units(tas="[temperature]", t90="[temperature]") @percentile_bootstrap def tg90p( tas: xarray.DataArray, t90: xarray.DataArray, freq: Freq = "YS", bootstrap: bool = False, ) -> xarray.DataArray: pass
Examples
>>> from xclim.core.calendar import percentile_doy >>> from xclim.compute import tg90p >>> tas = xr.open_dataset(path_to_tas_file).tas >>> # To start bootstrap reference period must not fully overlap the studied period. >>> tas_ref = tas.sel(time=slice("1990-01-01", "1992-12-31")) >>> t90 = percentile_doy(tas_ref, window=5, per=90) >>> tas_90th_percentile = tg90p(tas=tas, tas_per=t90.sel(percentiles=90), freq="YS", bootstrap=True)
Spatial Analogues Helpers¶
- xclim.analog.metric(func)[source]
Register a metric function in the metrics mapping and add some preparation/checking code.
- Parameters:
func (callable) – The metric function to be registered.
- Returns:
callable – The metric function with some overhead code.
Notes
All metric functions accept 2D inputs. This reshapes 1D inputs to (n, 1) and (m, 1). All metric functions are invalid when any non-finite values are present in the inputs.
Testing Module¶
Testing and Tutorial Utilities’ Module¶
- xclim.testing.utils.TESTDATA_BRANCH = 'v2025.4.29'
Sets the branch of the testing data repository to use when fetching datasets.
Notes
When running tests locally, this can be set for both pytest and tox by exporting the variable:
$ export XCLIM_TESTDATA_BRANCH="my_testing_branch"
or setting the variable at runtime:
$ env XCLIM_TESTDATA_BRANCH="my_testing_branch" pytest
- xclim.testing.utils.TESTDATA_CACHE_DIR = PosixPath('/home/docs/.cache/xclim-testdata')
Sets the directory to store the testing datasets.
If not set, the default location will be used (based on
platformdirs, seepooch.os_cache()).Notes
When running tests locally, this can be set for both pytest and tox by exporting the variable:
$ export XCLIM_TESTDATA_CACHE_DIR="/path/to/my/data"
or setting the variable at runtime:
$ env XCLIM_TESTDATA_CACHE_DIR="/path/to/my/data" pytest
- xclim.testing.utils.TESTDATA_REPO_URL = 'https://raw.githubusercontent.com/Ouranosinc/xclim-testdata/'
Sets the URL of the testing data repository to use when fetching datasets.
Notes
When running tests locally, this can be set for both pytest and tox by exporting the variable:
$ export XCLIM_TESTDATA_REPO_URL="https://github.com/my_username/xclim-testdata"
or setting the variable at runtime:
$ env XCLIM_TESTDATA_REPO_URL="https://github.com/my_username/xclim-testdata" pytest
- xclim.testing.utils.audit_url(url, context=None)[source]
Check if the URL is well-formed.
- Parameters:
url (str) – The URL to check.
context (str, optional) – Additional context to include in the error message. Default is None.
- Return type:
str- Returns:
str – The URL if it is well-formed.
- Raises:
URLError – If the URL is not well-formed.
- xclim.testing.utils.default_testdata_cache = PosixPath('/home/docs/.cache/xclim-testdata')
Default location for the testing data cache.
- xclim.testing.utils.default_testdata_repo_url = 'https://raw.githubusercontent.com/Ouranosinc/xclim-testdata/'
Default URL of the testing data repository to use when fetching datasets.
- xclim.testing.utils.default_testdata_version = 'v2025.4.29'
Default version of the testing data to use when fetching datasets.
- xclim.testing.utils.gather_testing_data(worker_cache_dir, worker_id, _cache_dir=PosixPath('/home/docs/.cache/xclim-testdata'))[source]
Gather testing data across workers.
- Parameters:
worker_cache_dir (str or Path) – The directory to store the testing data.
worker_id (str) – The worker ID.
_cache_dir (str or Path, optional) – The directory to store the testing data. Default is None.
- Raises:
ValueError – If the cache directory is not set.
FileNotFoundError – If the testing data is not found.
- Return type:
None
- xclim.testing.utils.list_input_variables(submodules=None, realms=None)[source]
List all possible variables names used in xclim’s indicators.
Made for development purposes. Parses all indicator parameters with the
xclim.core.utils.InputKind.VARIABLEor OPTIONAL_VARIABLE kinds.- Parameters:
submodules (str, optional) – Restrict the output to indicators of a list of submodules only. Default None, which parses all indicators.
realms (Sequence of str, optional) – Restrict the output to indicators of a list of realms only. Default None, which parses all indicators.
- Return type:
dict- Returns:
dict – A mapping from variable name to indicator class.
- xclim.testing.utils.nimbus(repo='https://raw.githubusercontent.com/Ouranosinc/xclim-testdata/', branch='v2025.4.29', cache_dir=PosixPath('/home/docs/.cache/xclim-testdata'), allow_updates=True)[source]
Pooch registry instance for xclim test data.
- Parameters:
repo (str) – URL of the repository to use when fetching testing datasets.
branch (str) – Branch of repository to use when fetching testing datasets.
cache_dir (str or Path, optional) – The path to the directory where the data files are stored.
allow_updates (bool) – If True, allow updates to the data files. Default is True.
- Returns:
pooch.Pooch – The Pooch instance for accessing the xclim testing data.
Notes
- There are three environment variables that can be used to control the behaviour of this registry:
XCLIM_TESTDATA_CACHE_DIR: If this environment variable is set, it will be used as the base directory to store the data files. The directory should be an absolute path (i.e., it should start with/). Otherwise, the default location will be used (based onplatformdirs, seepooch.os_cache()).XCLIM_TESTDATA_REPO_URL: If this environment variable is set, it will be used as the URL of the repository to use when fetching datasets. Otherwise, the default repository will be used.XCLIM_TESTDATA_BRANCH: If this environment variable is set, it will be used as the branch of the repository to use when fetching datasets. Otherwise, the default branch will be used.
Examples
Using the registry to download a file:
import xarray as xr from xclim.testing.helpers import nimbus example_file = nimbus().fetch("example.nc") data = xr.open_dataset(example_file)
- xclim.testing.utils.open_dataset(name, nimbus_kwargs=None, **xr_kwargs)[source]
Convenience function to open a dataset from the xclim testing data using the nimbus class.
This is a thin wrapper around the nimbus class to make it easier to open xclim testing datasets.
- Parameters:
name (str) – Name of the file containing the dataset.
nimbus_kwargs (dict) – Keyword arguments passed to the nimbus function.
**xr_kwargs (Any) – Keyword arguments passed to xarray.open_dataset.
- Return type:
Dataset- Returns:
xarray.Dataset – The dataset.
See also
xarray.open_datasetOpen and read a dataset from a file or file-like object.
nimbusPooch wrapper for accessing the xclim testing data.
- xclim.testing.utils.populate_testing_data(temp_folder=None, repo='https://raw.githubusercontent.com/Ouranosinc/xclim-testdata/', branch='v2025.4.29', local_cache=PosixPath('/home/docs/.cache/xclim-testdata'))[source]
Populate the local cache with the testing data.
- Parameters:
temp_folder (Path, optional) – Path to a temporary folder to use as the local cache. If not provided, the default location will be used.
repo (str, optional) – URL of the repository to use when fetching testing datasets.
branch (str, optional) – Branch of xclim-testdata to use when fetching testing datasets.
local_cache (Path or str, optional) – The path to the local cache. Defaults to the location set by the platformdirs library. The testing data will be downloaded to this local cache.
- Return type:
None
- xclim.testing.utils.publish_release_notes(style='md', file=None, changes=None)[source]
Format release notes in Markdown or ReStructuredText.
- Parameters:
style ({“rst”, “md”}) – Use ReStructuredText formatting or Markdown. Default: Markdown.
file ({os.PathLike, StringIO, TextIO}, optional) – If provided, prints to the given file-like object. Otherwise, returns a string.
changes (str or os.PathLike[str], optional) – If provided, manually points to the file where the changelog can be found. Assumes a relative path otherwise.
- Return type:
str|None- Returns:
str, optional – If file not provided, the formatted release notes.
Notes
This function is used solely for development and packaging purposes.
- xclim.testing.utils.run_doctests()[source]
Run the doctests for the module.
- xclim.testing.utils.show_versions(file=None, deps=None)[source]
Print the versions of xclim and its dependencies.
- Parameters:
file ({os.PathLike, StringIO, TextIO}, optional) – If provided, prints to the given file-like object. Otherwise, returns a string.
deps (list of str, optional) – A list of dependencies to gather and print version information from. Otherwise, prints xclim dependencies.
- Return type:
str|None- Returns:
str or None – If file not provided, the versions of xclim and its dependencies.
- xclim.testing.utils.testing_setup_warnings()[source]
Warn users about potential incompatibilities between xclim and xclim-testdata versions.
Module for loading testing data.
- xclim.testing.helpers.add_doctest_filepaths()[source]
Overload some libraries directly into the xdoctest namespace.
- Return type:
dict[str,Any]- Returns:
dict[str, Any] – A dictionary of xdoctest namespace objects.
- xclim.testing.helpers.add_ensemble_dataset_objects()[source]
Create a dictionary of xclim ensemble-related datasets to be patched into the xdoctest namespace.
- Return type:
dict[str,list[str]]- Returns:
dict[str, list[str]] – A dictionary of xclim ensemble-related datasets.
- xclim.testing.helpers.add_example_file_paths()[source]
Create a dictionary of doctest-relevant datasets to be patched into the xdoctest namespace.
- Return type:
dict[str,str|list[DataArray]]- Returns:
dict of str or dict of list of xr.DataArray – A dictionary of doctest-relevant datasets.
- xclim.testing.helpers.assert_lazy = <dask.callbacks.Callback object>
Context manager that raises an AssertionError if any dask computation is triggered.
- xclim.testing.helpers.generate_atmos(nimbus)[source]
Create the atmosds synthetic testing dataset.
- Parameters:
nimbus (pooch.Pooch) – The Pooch object to use for downloading the data.
- Return type:
dict[str,DataArray]- Returns:
dict[str, xr.DataArray] – A dictionary of xarray DataArrays.
- xclim.testing.helpers.test_timeseries(values, variable, start='2000-07-01', units=None, freq='D', as_dataset=False, cftime=None, calendar=None)[source]
Create a generic timeseries object based on pre-defined dictionaries of existing variables.
- Parameters:
values (np.ndarray) – The values of the DataArray.
variable (str) – The name of the DataArray.
start (str) – The start date of the time dimension. Default is “2000-07-01”.
units (str or None) – The units of the DataArray. Default is None.
freq (str) – The frequency of the time dimension. Default is daily/”D”.
as_dataset (bool) – Whether to return a Dataset or a DataArray. Default is False.
cftime (bool) – Whether to use cftime or not. Default is None, which uses cftime only for non-standard calendars.
calendar (str or None) – Whether to use a calendar. If a calendar is provided, cftime is used.
- Return type:
DataArray|Dataset- Returns:
xr.DataArray or xr.Dataset – A DataArray or Dataset with time, lon and lat dimensions.