"""Input normalization and time-index helpers for labeled time series.
The package is dims/coords-first: models, forecasts, and metrics all speak
named dimensions. Users may still pass pandas or numpy objects at the API
boundary; this module converts them once, attaching real time coordinates
(a ``DatetimeIndex``, periods, or a fallback integer range). Series inputs
become ``xarray.DataArray`` objects with a leading ``"time"`` dim; the
time-index helpers return ``pandas.Index`` objects.
"""
from numbers import Integral
from typing import Literal
import numpy as np
import xarray as xr
from pymc_forecast.exceptions import AlignmentError
__all__ = [
"CHAIN_DIM",
"DRAW_DIM",
"FUTURE_DIM",
"SAMPLE_DIMS",
"TIME_DIM",
"as_dataarray",
"as_time_index",
"concat_covariates",
"concat_time_index",
"extend_time_index",
"null_covariates",
"validate_alignment",
]
CHAIN_DIM = "chain"
"""First posterior-sample dim on every prediction output."""
DRAW_DIM = "draw"
"""Second posterior-sample dim on every prediction output."""
SAMPLE_DIMS = (CHAIN_DIM, DRAW_DIM)
"""The ordered sample dims guaranteed to lead every prediction output."""
TIME_DIM = "time"
"""Dim name of the observed (in-sample) time dimension."""
FUTURE_DIM = "time_future"
"""Dim name of the forecast-horizon time dimension."""
def _drop_axis_name(index):
"""Return ``index`` with a scalar axis name cleared.
xarray treats ``Index.name`` as the coordinate dimension. A named pandas
axis would then either fail validation (``set_index("date")``) or, on a
square frame, bind the other axis's labels. MultiIndex level names are
not a single ``.name``, and ``MultiIndex.rename(None)`` raises, so those
indexes are returned unchanged. An unnamed index is returned as-is so
timezone and frequency objects are not copied away.
"""
import pandas as pd
if isinstance(index, pd.MultiIndex) or index.name is None:
return index
renamed = index.copy()
renamed.name = None
return renamed
_DEFAULT_SECOND_DIM: dict[str, str] = {"data": "series", "covariates": "covariate"}
_RESERVED_DIM_NAMES = frozenset({TIME_DIM, FUTURE_DIM, *_DEFAULT_SECOND_DIM.values()})
def _safe_series_name(name):
"""Return a pandas Series name, or ``None`` if it collides with a dim name.
A DataArray named like one of its coordinates cannot be turned into a
Dataset (``to_dataset`` raises), so a Series called ``"time"`` would fail
later, far from where it was built.
"""
if isinstance(name, str) and name in _RESERVED_DIM_NAMES:
return None
return name
Role = Literal["data", "covariates"]
[docs]
def as_dataarray(obj, *, role: Role = "data") -> xr.DataArray:
"""Normalize ``obj`` to a ``DataArray`` with ``"time"`` as the leading dim.
Accepted inputs:
- ``xarray.DataArray`` with a ``"time"`` dim (transposed time-first);
- ``pandas.Series`` (index becomes the time coord; a scalar index name is
ignored, and so is a Series name equal to a dim name such as
``"time"``) or ``pandas.DataFrame`` (index → time coord, columns →
``"series"``/``"covariate"`` coord; scalar axis names are ignored);
- 1-d/2-d array-likes converted with ``np.asarray`` (integer-range time
coord is attached).
Parameters
----------
obj : xarray.DataArray, pandas.Series, pandas.DataFrame or array_like
The object to normalize.
role : {"data", "covariates"}, default "data"
Sets the default name of the second dim for 2-d pandas/array inputs
(``"series"`` / ``"covariate"``) and is used in error messages.
Returns
-------
xarray.DataArray
``obj`` with ``"time"`` as the leading dim. Inputs without a time
coord get an integer range ``0..n-1``; a pandas ``DatetimeIndex``
keeps its frequency.
Raises
------
pymc_forecast.exceptions.AlignmentError
If a DataArray has no ``"time"`` dim, or an array-like input is not
1-d or 2-d.
KeyError
If ``role`` is not ``"data"`` or ``"covariates"``.
"""
second = _DEFAULT_SECOND_DIM[role]
if isinstance(obj, xr.DataArray):
if TIME_DIM not in obj.dims:
msg = f"DataArray {role} must have a '{TIME_DIM}' dim, got dims {obj.dims}"
raise AlignmentError(msg)
da = obj.transpose(TIME_DIM, ...)
else:
# Lazy import: pandas is an optional path but a hard dependency of both
# pymc and xarray in practice, so this never fails in a working env.
import pandas as pd
if isinstance(obj, pd.Series):
da = xr.DataArray(
obj.to_numpy(),
dims=(TIME_DIM,),
coords={TIME_DIM: _drop_axis_name(obj.index)},
name=_safe_series_name(obj.name),
)
elif isinstance(obj, pd.DataFrame):
da = xr.DataArray(
obj.to_numpy(),
dims=(TIME_DIM, second),
coords={
TIME_DIM: _drop_axis_name(obj.index),
second: _drop_axis_name(obj.columns),
},
)
else:
arr = np.asarray(obj)
if arr.ndim == 1:
da = xr.DataArray(arr, dims=(TIME_DIM,))
elif arr.ndim == 2:
da = xr.DataArray(arr, dims=(TIME_DIM, second))
else:
msg = (
f"bare numpy {role} must be 1-d or 2-d (got ndim={arr.ndim}); "
"pass an xarray.DataArray with named dims for higher-dimensional data"
)
raise AlignmentError(msg)
if isinstance(obj, pd.Series | pd.DataFrame) and isinstance(obj.index, pd.DatetimeIndex):
# Older xarray converts pandas' microsecond datetimes to ns and
# drops freq in the process. Restore the known frequency on the
# converted index, without forcing a datetime unit on newer xarray.
time_index = da.get_index(TIME_DIM)
if obj.index.freq is not None and time_index.freq is None:
da = da.assign_coords({TIME_DIM: pd.DatetimeIndex(time_index, freq=obj.index.freq)})
if TIME_DIM not in da.coords:
da = da.assign_coords({TIME_DIM: np.arange(da.sizes[TIME_DIM])})
return da
[docs]
def as_time_index(index):
"""Return a pandas Index without dropping a timezone.
``np.asarray`` and ``DataArray.values`` turn a timezone-aware
``DatetimeIndex`` into naive UTC and shift the clock (``22:00`` in
``America/Los_Angeles`` becomes ``06:00`` the next day). This helper
reads the ``"time"`` index of a ``DataArray`` or ``Dataset`` with
``get_index`` and returns a ``pandas.Index`` unchanged. A bare array is
wrapped with ``pd.Index`` only when it is not already an index — never via
``np.asarray`` on a timezone-aware index.
Parameters
----------
index : pandas.Index, xarray.DataArray, xarray.Dataset or array_like
A time index, or an xarray object with a ``"time"`` dimension.
Returns
-------
pandas.Index
The time index, timezone included when the input had one.
Raises
------
pymc_forecast.exceptions.AlignmentError
If ``index`` is a ``DataArray`` or ``Dataset`` with no ``"time"``
index.
"""
import pandas as pd
if isinstance(index, xr.DataArray | xr.Dataset):
try:
return index.get_index(TIME_DIM)
except KeyError as err:
msg = f"as_time_index requires a '{TIME_DIM}' index; got dims {tuple(index.dims)}"
raise AlignmentError(msg) from err
if isinstance(index, pd.Index):
return index
return pd.Index(index)
_NOT_DATETIME = object()
def _tzinfo_of(value):
"""Timezone of a datetime-like value, or a sentinel when it is not one."""
import datetime as dt
if isinstance(value, np.datetime64):
return None
if isinstance(value, dt.datetime):
return value.tzinfo
return _NOT_DATETIME
def _is_naive_datetime(index) -> bool:
"""True for a timezone-naive datetime index, not an integer or period index."""
if getattr(index, "tz", None) is not None:
return False
if getattr(getattr(index, "dtype", None), "kind", None) == "M":
return True
if getattr(getattr(index, "dtype", None), "kind", None) != "O":
return False
import pandas as pd
saw = False
for value in index:
if value is None or value is pd.NaT:
continue
tzinfo = _tzinfo_of(value)
if tzinfo is _NOT_DATETIME or tzinfo is not None:
return False
saw = True
return saw
def _single_zone(index):
"""Timezone of ``index``, or ``None`` when it has none.
An object index of timestamps may carry more than one zone, or mix a
naive timestamp with an aware one. That is not a time index this package
can extend or stamp. Integer and period indexes have no zone.
"""
tz = getattr(index, "tz", None)
if tz is not None:
return tz
dtype = getattr(index, "dtype", None)
if dtype is None or dtype.kind != "O":
return None
import pandas as pd
msg = "time index mixes timezones; pass one zone"
aware = []
saw_naive = False
for value in index:
if value is None or value is pd.NaT:
continue
tzinfo = _tzinfo_of(value)
if tzinfo is _NOT_DATETIME:
continue
if tzinfo is None:
saw_naive = True
else:
aware.append(value)
if not aware:
return None
if saw_naive:
raise AlignmentError(msg)
# Let pandas decide whether the values share one zone: tzinfo objects of
# one zone can compare unequal (``ZoneInfo("UTC")`` vs ``datetime.UTC``,
# pytz's per-offset EST/EDT instances), and pandas rejects real mixes.
try:
return pd.DatetimeIndex(aware).tz
except (TypeError, ValueError) as err:
raise AlignmentError(msg) from err
def _common_zone(reference, other):
"""Express ``other`` in ``reference``'s timezone when both are aware.
Two aware indexes are compared as instants: ``other`` is converted to the
reference zone, so the same zone from different tz libraries (``pytz``,
``zoneinfo``, ``dateutil``, ``datetime.timezone.utc``) and a different zone
holding the same instants both line up. Zone objects are never compared
with ``==``, since aliases of one zone compare unequal. A naive index next
to an aware one is returned unchanged; comparing them fails later with the
usual not-comparable error.
Raises
------
pymc_forecast.exceptions.AlignmentError
If either index mixes timezones.
"""
import pandas as pd
ref_tz = _single_zone(reference)
other_tz = _single_zone(other)
if ref_tz is None or other_tz is None:
return reference, other
reference = pd.DatetimeIndex(reference)
other = pd.DatetimeIndex(other).tz_convert(reference.tz)
return reference, other
_DATETIME_UNITS = ("s", "ms", "us", "ns")
def _same_time_labels(left, right) -> bool:
"""Whether two time indexes hold the same labels.
Aware indexes are compared as instants (see :func:`_common_zone`), and
datetimes are compared independent of their stored resolution: pandas 2
``Index.equals`` is ``False`` for the same days at ``datetime64[s]`` and
``datetime64[ns]``. A naive index is never equal to an aware one.
Raises
------
pymc_forecast.exceptions.AlignmentError
If either index mixes timezones.
"""
import pandas as pd
if (_single_zone(left) is None) != (_single_zone(right) is None):
return False
left, right = _common_zone(left, right)
if (
isinstance(left, pd.DatetimeIndex)
and isinstance(right, pd.DatetimeIndex)
and left.unit != right.unit
):
unit = max(left.unit, right.unit, key=_DATETIME_UNITS.index)
left, right = left.as_unit(unit), right.as_unit(unit)
return left.equals(right)
[docs]
def null_covariates(index) -> xr.DataArray:
"""Zero-width covariates carrying only the time coord.
Covariates are the horizon carrier of the whole API (their time coord spans
train + forecast). Models without real covariates use this helper:
``null_covariates(full_time_index)``.
Parameters
----------
index : array_like
Time coordinate values spanning the full horizon (observed + future),
e.g. a ``pandas.DatetimeIndex`` or an integer range.
Returns
-------
xarray.DataArray
Zeros of shape ``(len(index), 0)`` with dims ``("time", "covariate")``
and only a ``"time"`` coord.
"""
index = as_time_index(index)
return xr.DataArray(
np.zeros((len(index), 0)),
dims=(TIME_DIM, _DEFAULT_SECOND_DIM["covariates"]),
coords={TIME_DIM: index},
)
[docs]
def extend_time_index(index, horizon: int):
"""Extend a time index by ``horizon`` steps, inferring the spacing.
Used to build the forecast horizon for covariate-free models: a
``DatetimeIndex`` is extended at its stored or inferred frequency, a
``PeriodIndex`` at its stored frequency, and a numeric index by its
constant step (step 1 for fewer than 2 values).
Parameters
----------
index : array_like
Training time coordinate values (anything ``pandas.Index`` accepts):
datetime, period, or numeric.
horizon : int
Number of steps to append (non-negative; ``bool`` is rejected).
Returns
-------
pandas.Index
The full ``observed + horizon`` index. With ``horizon=0`` the index is
returned unchanged, without further checks.
Raises
------
pymc_forecast.exceptions.AlignmentError
If ``horizon`` is not a non-negative integer, the index is empty or not
strictly increasing, a datetime frequency cannot be inferred (no stored
frequency and fewer than 3 values or an irregular index), the index is
not numeric, datetime or period, or the numeric spacing is not
constant.
"""
import pandas as pd
if isinstance(horizon, bool) or not isinstance(horizon, Integral) or horizon < 0:
msg = f"horizon must be a non-negative integer, got {horizon}"
raise AlignmentError(msg)
idx = as_time_index(index)
if horizon == 0:
return idx
if len(idx) == 0 or not (idx.is_monotonic_increasing and idx.is_unique):
msg = "training time index must be non-empty and strictly increasing"
raise AlignmentError(msg)
if isinstance(idx, pd.PeriodIndex):
return idx.append(pd.period_range(idx[-1] + 1, periods=horizon, freq=idx.freq))
if isinstance(idx, pd.DatetimeIndex):
freq = idx.freq or (pd.infer_freq(idx) if len(idx) >= 3 else None)
if freq is None:
msg = (
"cannot infer a frequency from the datetime index to build the "
"forecast horizon; pass future_index= or explicit covariates instead of horizon="
)
raise AlignmentError(msg)
future = pd.date_range(idx[-1], periods=horizon + 1, freq=freq)[1:]
return idx.append(future)
values = np.asarray(idx)
if not np.issubdtype(values.dtype, np.number):
msg = "horizon= requires a numeric, datetime, or period time index; pass future_index="
raise AlignmentError(msg)
if len(values) < 2:
step = 1
else:
steps = np.diff(values)
if not np.allclose(steps, steps[0]):
msg = (
"numeric time index is not evenly spaced; cannot extend by "
"horizon=, pass explicit covariates instead"
)
raise AlignmentError(msg)
step = steps[0]
future = values[-1] + step * np.arange(1, horizon + 1)
return pd.Index(np.concatenate([values, future]))
[docs]
def concat_time_index(index, future_index):
"""Concatenate a training time index with a predict-time future index.
The future index supplies the forecast horizon at predict time (its length
need not be known when the model is fit). Its values must be strictly
increasing and lie strictly after the last training value; gaps are
allowed — forecast steps are labeled with the supplied coordinates.
Parameters
----------
index : array_like
Time coordinate values of the training window (may be empty).
future_index : array_like
Time coordinate values of the forecast horizon.
Returns
-------
pandas.Index
The full ``observed + future`` index.
Raises
------
pymc_forecast.exceptions.AlignmentError
If the future index is empty, not strictly increasing, does not sort
after the training index, mixes timezones, or cannot be compared to it.
Notes
-----
Two timezone-aware indexes are compared as instants, and the future index
is relabeled in the training index's zone. A future index built on
another zone's calendar can therefore fall off the training grid: UTC
midnights appended to ``America/New_York`` daily data become
``19:00-05:00`` the previous evening. To keep the grid, localize the
future index in the training zone.
"""
idx = as_time_index(index)
fut = as_time_index(future_index)
if len(fut) == 0:
msg = "future time index is empty; supply at least one forecast step"
raise AlignmentError(msg)
idx, fut = _common_zone(idx, fut)
if not (fut.is_monotonic_increasing and fut.is_unique):
msg = "future time index must be strictly increasing"
raise AlignmentError(msg)
try:
starts_after = len(idx) == 0 or fut[0] > idx[-1]
except TypeError as err:
msg = (
"future time index is not comparable to the training time index "
f"({fut.dtype} vs {idx.dtype})"
)
raise AlignmentError(msg) from err
if not starts_after:
msg = (
"future time index must lie strictly after the training window: "
f"got first future value {fut[0]!r} <= last training value {idx[-1]!r}"
)
raise AlignmentError(msg)
return idx.append(fut)
[docs]
def concat_covariates(covariates, future_covariates) -> xr.DataArray:
"""Append future covariate rows to training covariates along ``"time"``.
``future_covariates`` covers only the forecast horizon (both inputs are
normalized via :func:`as_dataarray` first); its time index must lie
strictly after the training window and its non-time structure — dims in
the same order, and covariate names in order — must match the training
covariates, since models consume covariate columns positionally. Every
mismatch is rejected explicitly, so xarray never silently aligns,
reorders, or fills feature columns.
Parameters
----------
covariates : xarray.DataArray, pandas.Series, pandas.DataFrame or array_like
Training covariates, normalized with ``role="covariates"``.
future_covariates : xarray.DataArray, pandas.Series, pandas.DataFrame or array_like
Covariates for the forecast horizon only, normalized the same way. A
bare array gets the time coord ``0..h-1``, so pass labeled input
whose time coords follow the training window.
Returns
-------
xarray.DataArray
The full-horizon covariates, concatenated along ``"time"``.
Raises
------
pymc_forecast.exceptions.AlignmentError
If an input cannot be normalized, the future time index does not
extend the training window, or the dims (including their order),
sizes, or coordinates of the non-time dims differ. A naive index
beside an aware one is not comparable. An aware future index in
another zone is not an error: it is stamped in the training zone
before concatenation, same as :func:`concat_time_index`.
"""
covariates = as_dataarray(covariates, role="covariates")
fut = as_dataarray(future_covariates, role="covariates")
_validate_covariate_structure(covariates, fut)
full = concat_time_index(as_time_index(covariates), as_time_index(fut))
# Stamp both pieces with the validated index, so a future block in another
# zone (or the same zone from another tz library) lands on the training clock.
t_obs = covariates.sizes[TIME_DIM]
covariates = covariates.assign_coords({TIME_DIM: full[:t_obs]})
fut = fut.assign_coords({TIME_DIM: full[t_obs:]})
return xr.concat([covariates, fut], dim=TIME_DIM, join="exact")
def _validate_covariate_structure(covariates: xr.DataArray, fut: xr.DataArray) -> None:
"""Require identical non-time structure for every predict-time input path."""
if covariates.dims != fut.dims:
msg = (
"prediction covariates must have the same dims as the training "
f"covariates: got {fut.dims}, expected {covariates.dims}"
)
raise AlignmentError(msg)
_validate_shared_coords(covariates, fut, context="prediction covariates")
def _validate_shared_coords(left: xr.DataArray, right: xr.DataArray, *, context: str) -> None:
"""Reject positional ambiguity on shared non-time dimensions."""
for dim in left.dims:
if dim == TIME_DIM or dim not in right.dims:
continue
if left.sizes[dim] != right.sizes[dim]:
msg = (
f"{context} size mismatch along '{dim}': "
f"got {right.sizes[dim]}, expected {left.sizes[dim]}"
)
raise AlignmentError(msg)
if (dim in left.coords) != (dim in right.coords):
msg = f"{context} must carry matching '{dim}' coordinates; one side is unlabeled"
raise AlignmentError(msg)
if dim in left.coords and not left.get_index(dim).equals(right.get_index(dim)):
msg = (
f"{context} '{dim}' coords must match (same names, same order): "
f"got {right[dim].values!r}, expected {left[dim].values!r}"
)
raise AlignmentError(msg)
[docs]
def validate_alignment(data: xr.DataArray, covariates: xr.DataArray) -> None:
"""Require the covariate time coord to extend the data time coord.
``covariates`` must be at least as long as ``data`` along ``"time"``, and
the first ``len(data.time)`` coordinate values must match exactly — the
surplus is the forecast horizon and must be strictly increasing after
training. Shared non-time dimensions must have identical sizes and
coordinates, so panel covariates cannot silently change series order.
Parameters
----------
data : xarray.DataArray
Normalized data with a ``"time"`` dim.
covariates : xarray.DataArray
Normalized covariates with a ``"time"`` dim.
Raises
------
pymc_forecast.exceptions.AlignmentError
If ``covariates`` is shorter than ``data`` along ``"time"``, the leading
covariate time coords differ from the data time coords, one datetime
index is timezone-aware and the other is timezone-naive, a shared
non-time dim differs in size or coordinates (or is labeled on one side
only), or the surplus time coords are not strictly increasing after
training.
"""
t_obs = data.sizes[TIME_DIM]
if covariates.sizes[TIME_DIM] < t_obs:
msg = (
f"covariates must extend data along '{TIME_DIM}': got "
f"{covariates.sizes[TIME_DIM]} covariate steps < {t_obs} data steps"
)
raise AlignmentError(msg)
data_time = as_time_index(data)
cov_time = as_time_index(covariates)
data_tz = _single_zone(data_time)
cov_tz = _single_zone(cov_time)
if (data_tz is None) != (cov_tz is None) and (
_is_naive_datetime(data_time) or _is_naive_datetime(cov_time)
):
msg = (
f"data '{TIME_DIM}' is timezone-{'aware' if data_tz else 'naive'} but "
f"covariates '{TIME_DIM}' is timezone-{'aware' if cov_tz else 'naive'}; "
"localize both to one zone"
)
raise AlignmentError(msg)
data_time, cov_time = _common_zone(data_time, cov_time)
if not _same_time_labels(data_time, cov_time[:t_obs]):
msg = (
f"the first {t_obs} covariate '{TIME_DIM}' coords must equal the data "
f"'{TIME_DIM}' coords; the arrays are misaligned"
)
raise AlignmentError(msg)
_validate_shared_coords(data, covariates, context="data and covariates")
if covariates.sizes[TIME_DIM] > t_obs:
concat_time_index(data_time, cov_time[t_obs:])