Skip to content

Temporal diagnostics

This page documents 5 public symbols. Each entry includes its purpose, import path, full API docstring, and the maintained example that exercises it.

Conceptual guide

TemporalGroups

Unique time values and row indices for a fitted spatiotemporal model.

Property Value
Type class
Import from pygwrx.diagnostics import TemporalGroups
Signature TemporalGroups(values: 'np.ndarray', indices: 'Tuple[np.ndarray, ...]') -> None
Maintained example examples/diagnostics/03_temporal_diagnostics.py

TemporalGroups dataclass

TemporalGroups(
    values: ndarray, indices: Tuple[ndarray, ...]
)

Unique time values and row indices for a fitted spatiotemporal model.

model_times

Return one time value per plotted row.

Property Value
Type function
Import from pygwrx.diagnostics import model_times
Signature model_times(model: 'Any') -> 'np.ndarray'
Maintained example examples/diagnostics/03_temporal_diagnostics.py

model_times

model_times(model: Any) -> np.ndarray

Return one time value per plotted row.

Source code in src/pygwrx/diagnostics/temporal.py
def model_times(model: Any) -> np.ndarray:
    """Return one time value per plotted row."""
    require_fitted(model)
    value = getattr(model, "times_train_", None)
    if value is not None:
        times = np.asarray(value).reshape(-1)
        if times.size != training_coords(model).shape[0]:
            raise ValueError(
                "times_train_ length does not match calibration coordinates."
            )
        return times
    # STWR estimates only the latest stage. Represent it by cumulative time.
    intervals = getattr(model, "time_intervals_", None)
    coords_stages = getattr(model, "coords_stages_", None)
    if intervals is not None and coords_stages:
        current = float(np.sum(np.asarray(intervals, dtype=float)))
        return np.full(len(coords_stages[-1]), current, dtype=float)
    raise ValueError(
        f"{model.__class__.__name__} does not expose row-aligned time values."
    )

parameter_trajectory

Aggregate a parameter surface over time or follow the nearest location.

Property Value
Type function
Import from pygwrx.diagnostics import parameter_trajectory
Signature parameter_trajectory(model: 'Any', feature: 'FeatureLike', *, location: 'Optional[Union[int, Sequence[float]]]' = None, reducer: 'str' = 'mean') -> 'pd.DataFrame'
Maintained example examples/diagnostics/03_temporal_diagnostics.py

parameter_trajectory

parameter_trajectory(
    model: Any,
    feature: FeatureLike,
    *,
    location: Optional[Union[int, Sequence[float]]] = None,
    reducer: str = "mean"
) -> pd.DataFrame

Aggregate a parameter surface over time or follow the nearest location.

Source code in src/pygwrx/diagnostics/temporal.py
def parameter_trajectory(
    model: Any,
    feature: FeatureLike,
    *,
    location: Optional[Union[int, Sequence[float]]] = None,
    reducer: str = "mean",
) -> pd.DataFrame:
    """Aggregate a parameter surface over time or follow the nearest location."""
    frame = temporal_parameter_frame(model, feature)
    if location is not None:
        if isinstance(location, (int, np.integer)) and not isinstance(
            location, (bool, np.bool_)
        ):
            reference = frame.loc[int(location), ["coord_0", "coord_1"]].to_numpy(float)
        else:
            reference = np.asarray(location, dtype=float).reshape(-1)
            if reference.size != 2:
                raise ValueError("location must be a row index or an (x, y) pair.")
        records: List[dict] = []
        for time, group in frame.groupby("time", sort=True):
            distances = np.sqrt(
                (group["coord_0"] - reference[0]) ** 2
                + (group["coord_1"] - reference[1]) ** 2
            )
            row = group.loc[distances.idxmin()]
            records.append(
                {
                    "time": time,
                    "coefficient": row["coefficient"],
                    "coord_0": row["coord_0"],
                    "coord_1": row["coord_1"],
                }
            )
        return pd.DataFrame(records)
    token = str(reducer).strip().lower()
    if token not in {"mean", "median", "min", "max"}:
        raise ValueError("reducer must be 'mean', 'median', 'min', or 'max'.")
    series = getattr(frame.groupby("time", sort=True)["coefficient"], token)()
    return series.rename("coefficient").reset_index()

temporal_groups

Group fitted rows by exact time value while preserving chronological order.

Property Value
Type function
Import from pygwrx.diagnostics import temporal_groups
Signature temporal_groups(model: 'Any') -> 'TemporalGroups'
Maintained example examples/diagnostics/03_temporal_diagnostics.py

temporal_groups

temporal_groups(model: Any) -> TemporalGroups

Group fitted rows by exact time value while preserving chronological order.

Source code in src/pygwrx/diagnostics/temporal.py
def temporal_groups(model: Any) -> TemporalGroups:
    """Group fitted rows by exact time value while preserving chronological order."""
    times = model_times(model)
    values = pd.unique(times)
    try:
        values = np.asarray(sorted(values))
    except TypeError:
        values = np.asarray(values)
    groups = tuple(np.flatnonzero(times == value) for value in values)
    return TemporalGroups(values=values, indices=groups)

temporal_parameter_frame

Return local parameters with coordinates and times in tidy form.

Property Value
Type function
Import from pygwrx.diagnostics import temporal_parameter_frame
Signature temporal_parameter_frame(model: 'Any', feature: 'FeatureLike') -> 'pd.DataFrame'
Maintained example examples/diagnostics/03_temporal_diagnostics.py

temporal_parameter_frame

temporal_parameter_frame(
    model: Any, feature: FeatureLike
) -> pd.DataFrame

Return local parameters with coordinates and times in tidy form.

Source code in src/pygwrx/diagnostics/temporal.py
def temporal_parameter_frame(model: Any, feature: FeatureLike) -> pd.DataFrame:
    """Return local parameters with coordinates and times in tidy form."""
    view = parameter_inference(model, feature)
    coords = training_coords(model)
    times = model_times(model)
    if view.values.size != coords.shape[0]:
        raise ValueError(
            "Parameter surface length does not match temporal coordinates."
        )
    return pd.DataFrame(
        {
            "coord_0": coords[:, 0],
            "coord_1": coords[:, 1],
            "time": times,
            "coefficient": view.values,
        }
    )

Runnable examples used on this page

examples/diagnostics/03_temporal_diagnostics.py
# SPDX-FileCopyrightText: 2026 Jinghao Hu
# SPDX-License-Identifier: MIT

"""Group time values and summarize temporal coefficient trajectories."""

# Allow this script to run directly from any working directory.
import sys
from pathlib import Path

_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_EXAMPLES_ROOT = _PROJECT_ROOT / "examples"
_SRC_ROOT = _PROJECT_ROOT / "src"
for _path in (_SRC_ROOT, _EXAMPLES_ROOT):
    if str(_path) not in sys.path:
        sys.path.insert(0, str(_path))

from _common import temporal_regression

from pygwrx import GTWR
from pygwrx.diagnostics import (
    TemporalGroups,
    model_times,
    parameter_trajectory,
    temporal_groups,
    temporal_parameter_frame,
)

X, y, coords, times = temporal_regression(n=48, p=2)
model = GTWR(bandwidth=24, adaptive=True, lambda_st=0.3).fit(X, y, coords, times)
groups = temporal_groups(model)
assert isinstance(groups, TemporalGroups)
print("times=", model_times(model)[:8])
print("group_values=", groups.values)
print(temporal_parameter_frame(model, "x1").head())
print(parameter_trajectory(model, "x1", reducer="mean"))
print(parameter_trajectory(model, "x1", location=3))