xclim.core.indicator package¶
The Indicator object¶
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.
Submodules¶
xclim.core.indicator._indicator module¶
Indicator class definition.
- class xclim.core.indicator._indicator.CheckMissingIndicator(**kwargs)[source]
Bases:
xclim.core.indicator._indicator.IndicatorClass adding missing value checks to indicators.
This should not be used as-is, but subclassed by implementing the _get_missing_freq method. This method will be called in _postprocess using the compute parameters as only argument. It should return a freq string, the same as the output freq of the computed data. It can also be “None” to indicator the full time axis has been reduced, or “False” to skip the missing checks.
- _extra_doc()[source]
Method returning extra lines to the docstring, under the abstract.
Children classes can implemented this, appending to anything returned by super()._extra_doc().
- _gen_xclim_description(das, params, meta)[source]
Return a string for history. It will be prefixed by a timestamp and suffixed by xclim’s version.
- _get_missing_freq(params)[source]
Return the resampling frequency to be used in the missing values check.
- _postprocess(outs, das, params, meta)[source]
Masking of missing values.
- missing: str = 'from_context'
The name of the missing value method. See xclim.core.missing.MissingBase to create new custom methods. If None, this will be determined by the global configuration (see xclim.set_options).
- missing_options: dict = None
Arguments to pass to the missing function. If None, this will be determined by the global configuration.
- class xclim.core.indicator._indicator.Daily(**kwargs)[source]
Bases:
xclim.core.indicator._indicator.ResamplingIndicatorClass 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.
- class xclim.core.indicator._indicator.Hourly(**kwargs)[source]
Bases:
xclim.core.indicator._indicator.ResamplingIndicatorClass 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._indicator.IndexWrapper(compute)[source]
Bases:
objectTemplate object wrapping an index-like compute function by parsing its signature, docstring and declared units.
This class is not instantiable, but used as a base for
IndicatorBase, itself the base ofIndicator.- _all_parameters: collections.abc.Mapping[str, xclim.core.indicator._indicator.Parameter]
A dictionary mapping metadata about the input parameters to the indicator.
Keys are the arguments of the “compute” function. All parameters are listed, even those “injected”, absent from the indicator’s call signature. All are instances of
Parameter.
- _extra_doc()[source]
Method returning extra lines to the docstring, under the abstract.
Children classes can implemented this, appending to anything returned by super()._extra_doc().
- Return type:
list[str]
- _gen_docstring()[source]
Generate a docstring for this indicator.
- _gen_signature()[source]
Generate a signature for the indicator, skipping injected parameters.
The signature might be invalid if parameters are not properly ordered with [optional] variables first and kwargs last.
- abstract: str
Description of the indicator.
- static compute(*args, **kwargs)[source]
The index-like compute function.
- 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.
- property n_outs: int
The number of outputs of this indicator.
- Returns:
int – The number of outputs.
- notes: str
Additional information about the indicator.
- outputs: list[xclim.core.indicator._indicator.Output]
List of output metadata.
- property parameters: collections.abc.Mapping[str, xclim.core.indicator._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.
- references: str
rst cite directives for literature about this indicator. Child classes append their references as a new line when inheriting.
- title: str
Short description of the indicator.
- class xclim.core.indicator._indicator.IndexingIndicator(identifier=None, compute=None, title=None, abstract=None, realm=None, keywords=None, references=None, notes=None, input=None, parameters=None, outputs=None, context='none', src_freq=None, register=True, **outputs_kwargs)[source]
Bases:
xclim.core.indicator._indicator.IndicatorIndicator that also adds the “indexer” kwargs to subset the inputs before computation.
- classmethod _added_parameters()[source]
Create a list of tuples for arguments to add (name, Parameter).
- _preprocess_and_checks(das, params, meta)[source]
Perform parent’s checks and also check if freq is allowed.
- class xclim.core.indicator._indicator.Indicator(identifier=None, compute=None, title=None, abstract=None, realm=None, keywords=None, references=None, notes=None, input=None, parameters=None, outputs=None, context='none', src_freq=None, register=True, **outputs_kwargs)[source]
Bases:
xclim.core.indicator._indicator._RegistrerClimate 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.Metadata and attributes in Indicator.outputs will be formatted and added to the output variable(s). This attribute is a list of
Outputobjects. An history attribute is also created an added to the output, merging with a parent’s dataset history if possible. Finally axclim_descriptionattribute is added to each output variable, summarizing the xclim call done.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). Also, indicators return Datasets by default, while compute functions return one or multiple DataArrays.- classmethod copy(identifier=None, register=True, **kwargs)[source]
Create a new indicator by copying and modifying this indicator, similar to subclassing.
This accepts the same arguments as the indicator constructor, but parameters and attributes will default to this indicator’s data.
- Parameters:
identifier (str) – Unique ID for this indicator. Identifier are never inherited from their parent. This must be set if register is True.
register (bool) – Whether to register this new indicator in the
registry. Must be set to False is identifier is not given.**kwargs – All other arguments that
Indicator.__init__()accepts.
- Return type:
- Returns:
Indicator – A new indicator instance derived from this one.
See also
Indicator.__init__Indicator constructor.
- class xclim.core.indicator._indicator.IndicatorBase(**kwds)[source]
Bases:
xclim.core.indicator._indicator.IndexWrapperExtends IndexWrapper by allowing metadata overrides, adding non-parsable fields and orchestrating computation.
- classmethod _added_parameters()[source]
- classmethod _ensure_correct_outputs(outputs, identifier)[source]
Ensure all output attributes are correct.
- Parameters:
outputs (list of Output) – List of
Outputobjects.identifier (str, optional) – Identifier of the indicator.
- Returns:
list – Same as outputs, potentially modified.
- classmethod _ensure_correct_parameters(parameters)[source]
Ensure all input parameters are correct.
- Parameters:
parameters (dict of Parameters) – Dict of
xclim.core.indicator.Parameterobjects.- Returns:
dict – Same as input, potentially modified.
- _finalize(outs, das, params, meta)[source]
Finalize the computation.
Similar to _postprocess but done after and returns a single object, the return of the call.
- Parameters:
outs (list) – List of the output DataArrays.
das (dict) – Dictionary of variable (DataArray) inputs.
params (dict) – Dictionary of non-variable inputs.
meta (dict) – Dictionary of other metadata not passed to the compute function.
- Return type:
Any- Returns:
Any – The result from the computation of the indicator.
- _get_compute_args(das, params)[source]
Rename variables and parameters to match the compute function’s names and split VAR_KEYWORD arguments.
- Return type:
dict
- _parse_arguments(kwargs)[source]
Extract variable and optional variables from call arguments.
- _postprocess(outs, das, params, meta)[source]
Postprocessing of the outputs after calling the compute function.
- Parameters:
outs (list) – List of the output DataArrays.
das (dict) – Dictionary of variable (DataArray) inputs.
params (dict) – Dictionary of non-variable inputs.
meta (dict) – Dictionary of other metadata not passed to the compute function.
- Return type:
tuple[list[DataArray],dict]- Returns:
list – Same as outs.
dict – Same as meta, potentially modified.
- _preprocess_and_checks(das, params, meta)[source]
Preprocessing of the input parameters before calling the compute function.
- Parameters:
das (dict) – Dictionary of variable (DataArray) inputs.
params (dict) – Dictionary of non-variable inputs.
meta (dict) – Dictionary of other metadata not passed to the compute function.
- Return type:
tuple[dict,dict,dict]- Returns:
dict – Same as das, potentially modified.
dict – Same as params, potentially modified.
dict – Same as meta, potentially modified.
- classmethod _update_outputs(outputs, new_outputs)[source]
Merge parent output attributes with passed specifications.
- Parameters:
outputs (list of Output) – List of
Outputobjects.new_outputs (list of dict or list of Output or dict) – The output metadata passed to the indicator constructor.
- Returns:
list of Output – The merged list of Output objects, as long as the longest of outputs and new_outputs.
- classmethod _update_parameters(parameters, new_params, var_mapping)[source]
Merge parent input parameters with passed specifications, rename variables.
- Parameters:
parameters (dict of Parameters) – Dict of
Parameterobjects.new_params (dict) – Dict of parameters overrides passed to the indicator constructor (as parameters).
var_mapping (dict) – Mapping from variable name in the parent indicator or compute function to new name. The new name must be known by xclim, it must be in
xclim.core.VARIABLES.
- Returns:
dict – The merged dict of Parameter objects.
dict – For renamed variables, this maps the name in the compute function to the new units.
- context: str = 'none'
Name of xclim.units.units context which will be enabled during computation.
- classmethod get_parent_ids()[source]
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.
- keywords: tuple[str] = ()
Keywords describing the indicator and its domains of application. Child classes append to the list when inheriting.
- realm: str = None
General domain of validity of the indicator. Should use the same vocabulary as CMIP.
- class xclim.core.indicator._indicator.Output(var_name=None, dimensionality=None, units=None, units_metadata=None, attrs=None, **attrs_kwargs)[source]
Bases:
objectMetadata for the output of an indicator.
- _gen_doc(multiple_returns=True)[source]
Generate an item of a numpydoc style Returns section for this output.
- Parameters:
multiple_returns (bool) – If True and the var_name is defined, it is added at the beginning of the string. The numpydoc style forbids adding an output name if there’s only one output.
- Return type:
str- Returns:
str – A two lines string to be added in a Returns section of a numpydoc style docstring.
- attrs: dict
Output variable attributes.
- dimensionality: str | None
Dimensionality specification, similar but not necessarily compatible with pint.
- get(key, default=None)[source]
Convenience method to access any metadata element.
This method acts as if the
Outputobject was a single dictionary of all metadata elements and attributes.- Parameters:
key (str) – Name of the metadata element (or attribute) to return. If
keyis not one ofvar_name,dimensionality,unitsorunits_metadatait is searched inself.attrs.default (any) – If the key is not found, default value to return.
- Returns:
any – The corresponding value, or
defaultif the key isn’t found.
- 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.Parameter(kind, default, compute_name=<class 'xclim.core.indicator._indicator._empty'>, description='', units=<class 'xclim.core.indicator._indicator._empty'>, choices=<class 'xclim.core.indicator._indicator._empty'>, value=<class 'xclim.core.indicator._indicator._empty'>, annotation=<class 'xclim.core.indicator._indicator._empty'>)[source]
Bases:
objectObject 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'
- class _empty
Bases:
object
- _gen_doc(name=None)[source]
Generate an item of a numpydoc style Parameters section for this parameter.
- Parameters:
name (str, optional) – A new name for this parameter if it was overridden from the “compute_name”.
- Return type:
str- Returns:
str – A two lines string to be added in a Parameters section of a numpydoc style docstring.
- _gen_signature(name=None)[source]
Generate a
inspect.Parameterobject from this Parameter.- Return type:
Parameter
- annotation
alias of
xclim.core.indicator._indicator._empty
- choices
alias of
xclim.core.indicator._indicator._empty
- compute_name
alias of
xclim.core.indicator._indicator._empty
- default[source]
alias of
inspect._empty
- description: str = ''
- property injected: bool
Indicate whether values are injected.
- Returns:
bool – Whether values are injected.
- classmethod is_parameter_dict(other)[source]
Return whether other can update a parameter dictionary.
- Parameters:
other (dict) – A dictionary of parameters.
- Return type:
bool- Returns:
bool – Whether other can update a parameter dictionary.
- 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.
- units
alias of
xclim.core.indicator._indicator._empty
- 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
- value
alias of
xclim.core.indicator._indicator._empty
- class xclim.core.indicator._indicator.ReducingIndicator(**kwargs)[source]
Bases:
xclim.core.indicator._indicator.CheckMissingIndicatorIndicator that performs a time-reducing computation.
- _get_missing_freq(params)[source]
Return None, to indicate that the full time axis is to be reduced.
- class xclim.core.indicator._indicator.ResamplingIndicator(**kwargs)[source]
Bases:
xclim.core.indicator._indicator.CheckMissingIndicatorIndicator that performs a resampling computation.
Compared to the base Indicator, this adds the handling of missing data, and the check of allowed periods.
- classmethod _ensure_correct_parameters(parameters)[source]
Ensure all input parameters are correct.
- Parameters:
parameters (dict of Parameters) – Dict of
xclim.core.indicator.Parameterobjects.- Returns:
dict – Same as input, potentially modified.
- _extra_doc()[source]
Method returning extra lines to the docstring, under the abstract.
Children classes can implemented this, appending to anything returned by super()._extra_doc().
- _get_missing_freq(params)[source]
Return the resampling frequency to be used in the missing values check.
- _preprocess_and_checks(das, params, meta)[source]
Perform parent’s checks and also check if freq is allowed.
- 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._indicator.ResamplingIndicatorWithIndexing(**kwargs)[source]
Bases:
xclim.core.indicator._indicator.ResamplingIndicator,xclim.core.indicator._indicator.IndexingIndicatorResampling indicator that also adds “indexer” kwargs to subset the inputs before computation.
- class xclim.core.indicator._indicator.StandardizedIndexes(**kwargs)[source]
Bases:
xclim.core.indicator._indicator.ResamplingIndicatorResampling but flexible inputs indicators.
- context: str = 'hydro'
Name of xclim.units.units context which will be enabled during computation.
- src_freq: str | list[str] | None = ['D', 'MS']
The expected frequency of the input data. Can be a list for multiple frequencies, or None if irrelevant.