Download this notebook from github.

Command Line Interface

xclim provides the xclim command line executable to perform basic indicator computation easily without having to start up a full Python environment. However, not all indicators listed in Climate Indicators are available through this tool.

Its use is simple; Type the following to see the usage message:

[2]:
!xclim --help
Usage: xclim [OPTIONS] INDICATOR1 [OPTIONS] ... [INDICATOR2 [OPTIONS] ... ]
             ...

  Command line tool to compute indicators on netCDF datasets. Indicators are
  referred to by their (case-insensitive) identifier, as in
  xclim.core.indicator.registry.

Options:
  -i, --input TEXT         Input files. Can be a netCDF path or a glob
                           pattern.
  -o, --output TEXT        Output filepath. A new file will be created
  -v, --verbose            Print details about context and progress.
  -V, --version            Prints xclim's version number and exits
  --dask-nthreads INTEGER  Start a dask.distributed Client with this many
                           threads and 1 worker. If not specified, the local
                           scheduler is used. If specified, '--dask-maxmem'
                           must also be given
  --dask-maxmem TEXT       Memory limit for the dask.distributed Client as a
                           human readable string (ex: 4GB). If specified, '--
                           dask-nthreads' must also be specified.
  --chunks TEXT            Chunks to use when opening the input dataset(s).
                           Given as <dim1>:num,<dim2:num>. Ex:
                           time:365,lat:168,lon:150.
  --engine TEXT            Engine to use when opening the input dataset(s). If
                           not specified, xarray decides.
  -h, --help               Show this message and exit.

Commands:
  list                   List indicators.
  info                   Give information about INDICATOR.
  dataflags              Run data flag checks for input variables.
  prefetch_testing_data  Prefetch xclim testing data for development purposes.
  release_notes          Print history for publishing purposes.
  show_version_info      Print versions of dependencies for debugging
                         purposes.

To list all available indicators, use the “indices” subcommand:

[3]:
!xclim indices
Error: Indicator 'indices' not found in xclim.

For more information about a specific indicator, you can either use the info sub-command or directly access the --help message of the indicator. The former gives more information about the metadata, while the latter only prints the usage. Note that the module name (atmos, convert, land or seaIce) is mandatory.

[4]:
!xclim info liquidprcptot
Indicator liquidprcptot:
    identifier : liquidprcptot
    title : Total accumulated liquid precipitation.
    abstract : Total accumulated liquid precipitation. Precipitation
  is considered liquid when the average daily temperature is above a given
  threshold.
    notes : Let :math:`PR_i` be the mean daily precipitation of day
  :math:`i`, then for a period :math:`j` starting at day :math:`a` and
  finishing on day :math:`b`:

  .. math::

     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.
    keywords : precipitation
    outputs (#1)
      long_name : Total accumulated precipitation when temperature is
  above 0 degC
      standard_name : lwe_thickness_of_liquid_precipitation_amount
      cell_methods : time: sum over days
      description : Annual total liquid precipitation, estimated as
  precipitation when temperature is above 0 degC.
      var_name : liquidprcptot
      dimensionality : [length]
      units : mm
      units_metadata : None

Options:
  --pr VAR_NAME   Mean daily precipitation flux.  [default: pr]
  --tas VAR_NAME  Mean, maximum or minimum daily temperature.  [default: tas]
  --thresh TEXT   Threshold of `tas` over which the precipication is assumed
                  to be liquid rain.   [default: 0 degC]
  --freq TEXT     Resampling frequency.   [default: YS]
  -h, --help      Show this message and exit.


In the usage message, VAR_NAME indicates that the passed argument must match a variable in the input dataset.

[5]:
import warnings

import numpy as np
import pandas as pd
import xarray as xr
from pandas.plotting import register_matplotlib_converters

register_matplotlib_converters()
warnings.filterwarnings("ignore", "implicitly registered datetime converter")
%matplotlib inline
xr.set_options(display_style="html")


time = pd.date_range("2000-01-01", periods=366)
tasmin = xr.DataArray(
    -5 * np.cos(2 * np.pi * time.dayofyear / 365) + 273.15,
    dims="time",
    coords={"time": time},
    attrs={"units": "K"},
)
tasmax = xr.DataArray(
    -5 * np.cos(2 * np.pi * time.dayofyear / 365) + 283.15,
    dims="time",
    coords={"time": time},
    attrs={"units": "K"},
)
pr = xr.DataArray(
    np.clip(10 * np.sin(18 * np.pi * time.dayofyear / 365), 0, None),
    dims="time",
    coords={"time": time},
    attrs={"units": "mm/d"},
)
ds = xr.Dataset({"tasmin": tasmin, "tasmax": tasmax, "pr": pr})

data_folder = notebook_folder / "data"
data_folder.mkdir(exist_ok=True)
ds.to_netcdf(data_folder / "example_data.nc")
/tmp/ipykernel_184468/961205126.py:16: Pandas4Warning: DatetimeIndex.dayofyear is deprecated and will be removed in a future version. Use DatetimeIndex.day_of_year instead.
  -5 * np.cos(2 * np.pi * time.dayofyear / 365) + 273.15,
/tmp/ipykernel_184468/961205126.py:22: Pandas4Warning: DatetimeIndex.dayofyear is deprecated and will be removed in a future version. Use DatetimeIndex.day_of_year instead.
  -5 * np.cos(2 * np.pi * time.dayofyear / 365) + 283.15,
/tmp/ipykernel_184468/961205126.py:28: Pandas4Warning: DatetimeIndex.dayofyear is deprecated and will be removed in a future version. Use DatetimeIndex.day_of_year instead.
  np.clip(10 * np.sin(18 * np.pi * time.dayofyear / 365), 0, None),

Computing indicators

Let’s say we have the following toy dataset:

[6]:
import xarray as xr

ds = xr.open_dataset(data_folder.joinpath("example_data.nc"))
display(ds)
<xarray.Dataset> Size: 12kB
Dimensions:  (time: 366)
Coordinates:
  * time     (time) datetime64[ns] 3kB 2000-01-01 2000-01-02 ... 2000-12-31
Data variables:
    tasmin   (time) float64 3kB ...
    tasmax   (time) float64 3kB ...
    pr       (time) float64 3kB ...
[7]:
import matplotlib.pyplot as plt

fig1, (ax_tas, ax_pr) = plt.subplots(1, 2, figsize=(10, 5))
ds.tasmin.plot(label="tasmin", ax=ax_tas)
ds.tasmax.plot(label="tasmax", ax=ax_tas)
ds.pr.plot(ax=ax_pr)
ax_tas.legend()
[7]:
<matplotlib.legend.Legend at 0x70fb95ca5790>
../_images/notebooks_cli_11_1.png

To compute an indicator, say the monthly solid precipitation accumulation, we simply call:

[8]:
!xclim -i data/example_data.nc -o data/out1.nc solidprcptot --pr pr --tas tasmin --freq MS
/home/docs/checkouts/readthedocs.org/user_builds/xclim/conda/stable/lib/python3.12/site-packages/xclim/core/cfchecks.py:80: UserWarning: Variable does not have a `standard_name` attribute.
  check_valid(vardata, "standard_name", data["standard_name"])
[########################################] | 100% Completed | 200.82 ms

In this example, we decided to use tasmin for the tas variable. We didn’t need to provide the --pr parameter, as our data has the same name.

Finally, more than one indicator can be computed and written to the output dataset by simply chaining the calls:

[9]:
!xclim -i data/example_data.nc -o data/out2.nc liquidprcptot --tas tasmin --freq MS tropical_nights --thresh "2 degC" --freq MS
/home/docs/checkouts/readthedocs.org/user_builds/xclim/conda/stable/lib/python3.12/site-packages/xclim/core/cfchecks.py:80: UserWarning: Variable does not have a `standard_name` attribute.
  check_valid(vardata, "standard_name", data["standard_name"])
/home/docs/checkouts/readthedocs.org/user_builds/xclim/conda/stable/lib/python3.12/site-packages/xclim/core/cfchecks.py:80: UserWarning: Variable does not have a `standard_name` attribute.
  check_valid(vardata, "standard_name", data["standard_name"])
[########################################] | 100% Completed | 200.96 ms

Let’s see the outputs:

[10]:
ds1 = xr.open_dataset(data_folder / "out1.nc")
ds2 = xr.open_dataset(data_folder / "out2.nc", decode_timedelta=False)

fig2, (ax_prcptot, ax_tropical_nights) = plt.subplots(1, 2, figsize=(10, 5))
ds1.solidprcptot.plot(ax=ax_prcptot, label=ds1.solidprcptot.long_name)
ds2.liquidprcptot.plot(ax=ax_prcptot, label=ds2.liquidprcptot.long_name)
ds2.tropical_nights.plot(ax=ax_tropical_nights, marker="o")
ax_prcptot.legend()
[10]:
<matplotlib.legend.Legend at 0x70fb95bdbb30>
../_images/notebooks_cli_17_1.png
[11]:
ds1.close()
[12]:
ds2.close()

Data Quality Checks

As of version 0.30.0, xclim now also provides a command-line utility for performing data quality control checks on existing NetCDF files.

These checks examine the values of data_variables for suspicious value patterns (e.g. values that repeat for many days) or erroneous values (e.g. humidity percentages outside 0-100, minimum temperatures exceeding maximum temperatures, etc.). The checks (called dataflags) are based on the ECAD ICCLIM quality control checks (https://www.ecad.eu/documents/atbd.pdf).

The full list of checks performed for each variable are listed in xclim/core/data/variables.yml.

[13]:
!xclim dataflags --help
Usage: xclim dataflags [OPTIONS] [VARIABLES]...

  Run quality control checks on input data variables and flag for quality
  control issues or suspicious values.

Options:
  -r, --raise-flags  Print an exception in the event that a variable is found
                     to have quality control issues.
  -a, --append       Return the netCDF dataset with the `ecad_qc_flag` array
                     appended as a data_var.
  -d, --dims TEXT    Dimensions upon which aggregation should be performed.
                     Default: "all". Ignored if no variable provided.
  -f, --freq TEXT    Resampling periods frequency used for aggregation.
                     Default: None. Ignored if no variable provided.
  -h, --help         Show this message and exit.

When running the dataflags CLI checks, you must either set an output file (-o filename.nc) or set the checks to raise if there are any failed checks (-r).

By default, when setting an output file, the returned file will only contain the flag value (True if no flags were raised, False otherwise). To append the flag to a copy of the dataset, we use the -a option.

The default behaviour is to raise a flag if any element of the array resolves to True (i.e. aggregated across all dimensions), but we can specify the level of aggregation by dimension with the -d or --dims option.

[14]:
# Create an output file with just the flag value and no aggregation (dims=None)

!xclim -i data/example_data.nc -o data/flag_output.nc dataflags -d none

# Need to wait until the file is written

!sleep 2s
[########################################] | 100% Completed | 102.09 ms

[15]:
import xarray as xr

ds1 = xr.open_dataset(data_folder / "flag_output.nc")
display(ds1.data_vars, ds1.ecad_qc_flag)
ds1.close()
Data variables:
    ecad_qc_flag  (time) bool 366B ...
<xarray.DataArray 'ecad_qc_flag' (time: 366)> Size: 366B
[366 values with dtype=bool]
Coordinates:
  * time     (time) datetime64[ns] 3kB 2000-01-01 2000-01-02 ... 2000-12-31
Attributes:
    comment:  Adheres to ECAD quality control checks.
    history:    - Performed the following checks:\n\n\n\n\n\n\n\n\n\n\n\n\n\n
[16]:
# Create an output file with values appended to the original dataset.

!xclim -i data/example_data.nc -o data/flag_output_appended.nc dataflags -a

# Need to wait until the file is written
!sleep 2s
[########################################] | 100% Completed | 101.91 ms

[17]:
import xarray as xr

ds2 = xr.open_dataset(data_folder / "flag_output_appended.nc")
display(ds2.data_vars, ds2.ecad_qc_flag)
ds2.close()
Data variables:
    tasmin        (time) float64 3kB ...
    tasmax        (time) float64 3kB ...
    pr            (time) float64 3kB ...
    ecad_qc_flag  bool 1B ...
<xarray.DataArray 'ecad_qc_flag' ()> Size: 1B
[1 values with dtype=bool]
Attributes:
    comment:  Adheres to ECAD quality control checks.
    history:    - Performed the following checks:\n\n\n\n\n\n\n\n\n\n\n\n\n\n
[18]:
# Raise an error if any quality control checks fail. Passing example:

!xclim -i data/example_data.nc dataflags -r
Dataset passes quality control checks!

[19]:
import xarray as xr

# Create some bad data with minimum temperatures exceeding max temperatures
bad_ds = xr.open_dataset(data_folder / "example_data.nc")

# Swap entire variable arrays
bad_ds["tasmin"].values, bad_ds["tasmax"].values = (
    bad_ds.tasmax.values,
    bad_ds.tasmin.values,
)
bad_ds.to_netcdf(data_folder / "suspicious_data.nc")
bad_ds.close()
[20]:
# Raise an error if any quality control checks fail. Failing example:

!xclim -i data/suspicious_data.nc dataflags -r
Data quality flags indicate suspicious values. Flags raised are:
  - Maximum temperature values found below minimum temperatures.
  - Maximum temperature values found below minimum temperatures.

These checks can also be set to examine a specific variable within a NetCDF file, with more descriptive information for each check performed.

[21]:
!xclim -i data/example_data.nc -o data/flag_output_pr.nc dataflags pr
[########################################] | 100% Completed | 2.69 s

[22]:
import xarray as xr

ds3 = xr.open_dataset(data_folder / "flag_output_pr.nc")
display(ds3.data_vars)
for dv in ds3.data_vars:
    display(ds3[dv])
Data variables:
    negative_accumulation_values               bool 1B ...
    very_large_precipitation_events            bool 1B ...
    values_eq_5_repeating_for_5_or_more_days   bool 1B ...
    values_eq_1_repeating_for_10_or_more_days  bool 1B ...
<xarray.DataArray 'negative_accumulation_values' ()> Size: 1B
[1 values with dtype=bool]
Attributes:
    description:  Negative values found for pr.
    units:
    history:      [2026-11-04 22:04:46] pr: negative_accumulation_values(da=<...
<xarray.DataArray 'very_large_precipitation_events' ()> Size: 1B
[1 values with dtype=bool]
Attributes:
    description:  Precipitation events in excess of 300 mm d-1 for pr.
    units:        1
    history:      [2026-11-04 22:04:46] pr: very_large_precipitation_events(d...
<xarray.DataArray 'values_eq_5_repeating_for_5_or_more_days' ()> Size: 1B
[1 values with dtype=bool]
Attributes:
    description:  Repetitive values at 5.0 for at least 5 days found for pr.
    units:
    history:      [2026-11-04 22:04:46] pr: values_op_thresh_repeating_for_n_...
<xarray.DataArray 'values_eq_1_repeating_for_10_or_more_days' ()> Size: 1B
[1 values with dtype=bool]
Attributes:
    description:  Repetitive values at 1.0 for at least 10 days found for pr.
    units:
    history:      [2026-11-04 22:04:46] pr: values_op_thresh_repeating_for_n_...