Skip to content

Regime diagnostics

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

Conceptual guide

boundary_frame

Return unique regime-boundary edges and their endpoints.

Property Value
Type function
Import from pygwrx.diagnostics import boundary_frame
Signature boundary_frame(model: 'Any') -> 'pd.DataFrame'
Maintained example examples/diagnostics/05_regime_diagnostics.py

boundary_frame

boundary_frame(model: Any) -> pd.DataFrame

Return unique regime-boundary edges and their endpoints.

Source code in src/pygwrx/diagnostics/regimes.py
def boundary_frame(model: Any) -> pd.DataFrame:
    """Return unique regime-boundary edges and their endpoints."""
    require_fitted(model)
    coords = training_coords(model)
    boundaries = getattr(model, "regime_boundaries_", None)
    if boundaries is None:
        raise ValueError(
            f"{model.__class__.__name__} does not expose regime_boundaries_."
        )
    records = []
    for left, right in boundaries:
        i, j = int(left), int(right)
        records.append(
            {
                "left": i,
                "right": j,
                "x0": coords[i, 0],
                "y0": coords[i, 1],
                "x1": coords[j, 0],
                "y1": coords[j, 1],
            }
        )
    return pd.DataFrame(records)

regime_frame

Return coordinates, regime labels, residuals, and connectivity metadata.

Property Value
Type function
Import from pygwrx.diagnostics import regime_frame
Signature regime_frame(model: 'Any') -> 'pd.DataFrame'
Maintained example examples/diagnostics/05_regime_diagnostics.py

regime_frame

regime_frame(model: Any) -> pd.DataFrame

Return coordinates, regime labels, residuals, and connectivity metadata.

Source code in src/pygwrx/diagnostics/regimes.py
def regime_frame(model: Any) -> pd.DataFrame:
    """Return coordinates, regime labels, residuals, and connectivity metadata."""
    require_fitted(model)
    regimes = getattr(model, "regimes_", None)
    if regimes is None:
        raise ValueError(f"{model.__class__.__name__} does not expose regimes_.")
    labels = np.asarray(regimes, dtype=int).reshape(-1)
    coords = training_coords(model)
    if labels.size != coords.shape[0]:
        raise ValueError("regimes_ length does not match coordinates.")
    frame = pd.DataFrame(
        {"coord_0": coords[:, 0], "coord_1": coords[:, 1], "regime": labels}
    )
    residuals = getattr(model, "residuals_", None)
    if residuals is not None:
        frame["residual"] = np.asarray(residuals, dtype=float).reshape(-1)
    return frame

regime_summary

Summarize regime sizes, residual error, and component counts.

Property Value
Type function
Import from pygwrx.diagnostics import regime_summary
Signature regime_summary(model: 'Any') -> 'pd.DataFrame'
Maintained example examples/diagnostics/05_regime_diagnostics.py

regime_summary

regime_summary(model: Any) -> pd.DataFrame

Summarize regime sizes, residual error, and component counts.

Source code in src/pygwrx/diagnostics/regimes.py
def regime_summary(model: Any) -> pd.DataFrame:
    """Summarize regime sizes, residual error, and component counts."""
    frame = regime_frame(model)
    grouped = frame.groupby("regime", sort=True)
    summary = grouped.size().rename("n_samples").to_frame()
    if "residual" in frame:
        summary["rmse"] = grouped["residual"].apply(
            lambda values: float(np.sqrt(np.mean(np.asarray(values, dtype=float) ** 2)))
        )
        summary["mae"] = grouped["residual"].apply(
            lambda values: float(np.mean(np.abs(np.asarray(values, dtype=float))))
        )
    counts = getattr(model, "regime_component_counts_", None)
    if counts is not None:
        array = np.asarray(counts, dtype=int).reshape(-1)
        if array.size == summary.shape[0]:
            summary["connected_components"] = array
    return summary

Runnable examples used on this page

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

"""Export observation, regime, and boundary summaries for GR-GWR."""

# 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 regime_regression

from pygwrx import GRGWR
from pygwrx.diagnostics import boundary_frame, regime_frame, regime_summary

X, y, coords, _ = regime_regression(n=54)
model = GRGWR(n_regimes=2, bandwidth=18, max_iter=2, random_state=0).fit(X, y, coords)
print(regime_frame(model).head())
print(regime_summary(model))
print(boundary_frame(model).head())