"""Figures of series, segmentations, states and change profiles."""
from __future__ import annotations
import numpy as np
from matplotlib import pyplot as plt
from .._base import Segmentation, as_series
from ._style import BRAND, GRAY, INK, ax_or_new, color, despine, standardized
__all__ = ["plot_series", "plot_segmentation", "plot_fuzzy_segmentation", "plot_states", "plot_profile",
"plot_run_length"]
[docs]
def plot_series(X, names=None, figsize=None, sharex=True, color_by_variable: bool = True):
"""Small multiples: one panel per variable. Returns the Figure."""
A = as_series(X)
n = A.shape[1]
nm = names or [f"x{j}" for j in range(n)]
fig, axes = plt.subplots(n, 1, figsize=figsize or (7.0, 1.1 * n + 0.6), sharex=sharex, squeeze=False)
for j, ax in enumerate(axes[:, 0]):
ax.plot(A[:, j], color=color(j) if color_by_variable else BRAND, lw=1)
ax.set_ylabel(nm[j], rotation=0, ha="right", va="center", fontsize=9)
despine(ax)
ax.tick_params(labelsize=8)
axes[-1, 0].set_xlabel("time")
fig.tight_layout(h_pad=0.3)
return fig
def _shade(ax, seg: Segmentation, alpha=0.12, states=True):
for i, (a, b) in enumerate(seg.segments):
k = seg.labels[i] if (states and seg.labels is not None) else i
ax.axvspan(a - 0.5, b - 0.5, color=color(k), alpha=alpha, lw=0)
[docs]
def plot_segmentation(X, segmentation: Segmentation, names=None, truth=None, fit: str | None = None, ax=None,
stacked: bool | None = None, standardize: bool = True, title: str | None = None):
"""Series with the segments shaded (state colours if the segmentation has
state labels), change points as vertical lines, optional true change
points (dashed, at the top) and segment fits (``"mean"`` or ``"linear"``).
Multivariate series are drawn standardized and vertically offset in one
panel (``stacked=False``) or as small multiples (``stacked=True``;
default for more than four variables). Returns the Axes (or Figure)."""
A = as_series(X)
Z = standardized(A) if standardize else A
n = A.shape[1]
nm = names or [f"x{j}" for j in range(n)]
stacked = n > 4 if stacked is None else stacked
if stacked and n > 1:
fig, axes = plt.subplots(n, 1, figsize=(7.0, 0.9 * n + 0.8), sharex=True, squeeze=False)
for j, a in enumerate(axes[:, 0]):
_shade(a, segmentation)
a.plot(Z[:, j], color=INK, lw=0.8)
for c in segmentation.change_points:
a.axvline(c - 0.5, color=BRAND, lw=1.1)
a.set_ylabel(nm[j], rotation=0, ha="right", va="center", fontsize=8)
despine(a)
a.tick_params(labelsize=7)
if truth is not None:
for c in np.ravel(getattr(truth, "change_points", truth)):
axes[0, 0].axvline(c - 0.5, color="#D55E00", lw=1.2, ls="--")
if title:
axes[0, 0].set_title(title, fontsize=10)
axes[-1, 0].set_xlabel("time")
fig.tight_layout(h_pad=0.2)
return fig
ax = ax_or_new(ax, (7.0, 1.0 + 0.8 * min(n, 4)))
_shade(ax, segmentation)
off = np.arange(n)[::-1] * (Z.max() - Z.min() + 0.5 if n > 1 else 0)
for j in range(n):
ax.plot(Z[:, j] + off[j], color=color(j) if n > 1 else INK, lw=0.9, label=nm[j])
if fit:
for a, b in segmentation.segments:
t = np.arange(a, b)
if fit == "linear" and b - a > 1:
p = np.polyfit(t, Z[a:b, j], 1)
ax.plot(t, np.polyval(p, t) + off[j], color=INK, lw=1.6, alpha=0.8)
else:
ax.plot([a, b - 1], [Z[a:b, j].mean() + off[j]] * 2, color=INK, lw=1.6, alpha=0.8)
for c in segmentation.change_points:
ax.axvline(c - 0.5, color=BRAND, lw=1.3)
if truth is not None:
ylim = ax.get_ylim()
for c in np.ravel(getattr(truth, "change_points", truth)):
ax.plot([c - 0.5] * 2, [ylim[1] - 0.08 * (ylim[1] - ylim[0]), ylim[1]], color="#D55E00", lw=2.5)
if n > 1:
ax.set_yticks(off)
ax.set_yticklabels(nm, fontsize=8)
ax.set_xlabel("time")
if title:
ax.set_title(title, fontsize=10)
despine(ax)
return ax
[docs]
def plot_fuzzy_segmentation(X, segmentation: Segmentation, names=None):
"""Two panels: the series with the crisp segments, and the fuzzy
memberships of the segments along time. Returns the Figure."""
if segmentation.memberships is None:
raise ValueError("the segmentation has no memberships")
U = segmentation.memberships
fig, (a1, a2) = plt.subplots(2, 1, figsize=(7.0, 4.2), sharex=True, gridspec_kw={"height_ratios": [2, 1]})
plot_segmentation(X, segmentation, names=names, ax=a1)
a1.set_xlabel("")
for i in range(U.shape[1]):
a2.fill_between(np.arange(len(U)), U[:, i], color=color(i), alpha=0.35, lw=0)
a2.plot(U[:, i], color=color(i), lw=1)
a2.set_ylim(0, 1.02)
a2.set_ylabel(r"$\beta_i(t)$")
a2.set_xlabel("time")
despine(a2)
fig.tight_layout()
return fig
[docs]
def plot_states(segmentation: Segmentation, ax=None, height: float = 1.0, names=None):
"""State timeline: one coloured bar per segment. Returns the Axes."""
ax = ax_or_new(ax, (7.0, 1.0))
lab = segmentation.labels if segmentation.labels is not None else np.arange(segmentation.n_segments)
for (a, b), k in zip(segmentation.segments, lab, strict=True):
ax.barh(0, b - a, left=a, height=height, color=color(k), edgecolor="white", lw=0.5)
ax.set_yticks([])
ax.set_xlim(0, segmentation.n_samples)
ax.set_xlabel("time")
handles = [plt.Rectangle((0, 0), 1, 1, color=color(k)) for k in np.unique(lab)]
ax.legend(handles, [names[k] if names else f"state {k}" for k in np.unique(lab)], ncol=min(6, len(handles)),
fontsize=7, frameon=False, loc="upper center", bbox_to_anchor=(0.5, 1.6))
despine(ax, keep=("bottom",))
return ax
[docs]
def plot_profile(profile, change_points=None, ax=None, label: str = "score", threshold: float | None = None,
invert: bool = False):
"""A change profile (ClaSP score, FLUSS arc curve, BOCPD change
probability, boundary agreement, similarity) with the detected change
points. Returns the Axes."""
ax = ax_or_new(ax, (7.0, 2.0))
p = np.asarray(profile, float)
ax.plot(p, color=BRAND, lw=1.1)
ax.fill_between(np.arange(len(p)), p, p.min() if not invert else p.max(), color=BRAND, alpha=0.12, lw=0)
if threshold is not None:
ax.axhline(threshold, color=GRAY, ls=":", lw=1)
for c in np.ravel(change_points) if change_points is not None else []:
ax.axvline(c, color="#D55E00", lw=1.2)
ax.set_ylabel(label)
ax.set_xlabel("time")
despine(ax)
return ax
[docs]
def plot_run_length(bocpd, ax=None, max_run: int | None = None):
"""Run-length posterior of :class:`~mvtsa.segmentation.BOCPD` (log scale)
with the MAP run length. Returns the Axes."""
ax = ax_or_new(ax, (7.0, 2.6))
P = bocpd.run_length_posterior_
R = P.shape[1] if max_run is None else max_run
im = ax.imshow(np.log10(P[:, :R].T + 1e-12), aspect="auto", origin="lower", cmap="Greys", vmin=-6, vmax=0)
ax.plot(bocpd.map_run_length_, color="#D55E00", lw=1)
ax.set_ylabel("run length")
ax.set_xlabel("time")
plt.colorbar(im, ax=ax, label=r"$\log_{10}P(r_t)$", pad=0.01)
return ax