"""Figures of representations: PLA, SAX, qualitative episodes, recurrence
plots and (SPC-zone labelled) visibility graphs."""
from __future__ import annotations
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
from .._base import as_series
from ._style import BRAND, BRAND_SEQ, EPISODE_COLORS, GRAY, INK, ax_or_new, despine
__all__ = ["plot_pla", "plot_sax", "plot_episodes", "plot_recurrence", "plot_visibility_graph"]
[docs]
def plot_pla(x, pla, ax=None, channel: int = 0):
"""Series and its piecewise linear approximation; each segment is
annotated with its slope angle. Returns the Axes."""
ax = ax_or_new(ax)
v = as_series(x)[:, channel]
R = pla.reconstruct()[:, channel]
ax.plot(v, color=GRAY, lw=0.9)
for k, (a, b) in enumerate(pla.segmentation.segments):
ax.plot(range(a, b), R[a:b], color=BRAND, lw=2)
ax.annotate(f"{np.degrees(pla.angles[k, channel]):.0f}°", ((a + b) / 2, R[a:b].mean()), fontsize=6,
color=INK, ha="center", va="bottom")
ax.set_xlabel("time")
despine(ax)
return ax
[docs]
def plot_sax(x, n_segments: int = 8, alphabet_size: int = 4, ax=None):
"""z-normalized series, its PAA and the SAX symbols with the Gaussian
breakpoints. Returns the Axes."""
from ..representation.symbolic import SAX
ax = ax_or_new(ax)
v = as_series(x)[:, 0]
z = (v - v.mean()) / (v.std() or 1.0)
s = SAX(n_segments, alphabet_size)
idx = np.array_split(np.arange(len(z)), n_segments)
sym = s.transform(z)
ax.plot(z, color=GRAY, lw=0.9)
for b in s.breakpoints_:
ax.axhline(b, color=GRAY, ls=":", lw=0.8)
for k, ii in enumerate(idx):
m = z[ii].mean()
ax.plot([ii[0], ii[-1]], [m, m], color=BRAND, lw=2.2)
ax.text((ii[0] + ii[-1]) / 2, m + 0.15, sym[k], color="#D55E00", fontsize=11, ha="center", fontweight="bold")
ax.set_xlabel("time")
despine(ax)
return ax
[docs]
def plot_episodes(x, episodes, ax=None, smooth: float | None = None, show_triangles: bool = True):
"""Series with its qualitative episodes: coloured bands labelled by the
primitive codes and, above them, the triangular glyphs of the
representation of Cheung and Stephanopoulos (1990). Returns the Axes."""
from scipy import ndimage
ax = ax_or_new(ax, (7.0, 3.0))
v = as_series(x)[:, 0]
s = ndimage.gaussian_filter1d(v, smooth, mode="nearest") if smooth else v
lo, hi = s.min(), s.max()
pad = 0.18 * (hi - lo or 1)
for e in episodes:
c = EPISODE_COLORS[e.primitive]
ax.axvspan(e.start - 0.5, e.stop - 0.5, color=c, alpha=0.13, lw=0)
ax.text((e.start + e.stop) / 2, hi + 0.55 * pad, e.primitive, ha="center", va="center", fontsize=8,
color=c, fontweight="bold")
if show_triangles and e.stop - e.start > 2:
a, b = e.start, e.stop - 1
ya, yb = s[a], s[b]
# triangle formed by the tangents at the two ends (qualitative shape)
da, db = np.gradient(s)[a], np.gradient(s)[b]
if abs(da - db) > 1e-12:
tm = np.clip((yb - ya + da * a - db * b) / (da - db), a, b)
ym = ya + da * (tm - a)
ax.add_patch(Polygon([[a, ya], [tm, ym], [b, yb]], closed=True, fill=False, ec=c, lw=0.8, alpha=0.8))
ax.plot(v, color=GRAY, lw=0.8)
if smooth:
ax.plot(s, color=INK, lw=1.2)
ax.set_ylim(lo - pad, hi + pad)
ax.set_xlabel("time")
despine(ax)
return ax
[docs]
def plot_recurrence(R, ax=None, title: str | None = None):
"""Recurrence plot (thresholded or distance matrix). Returns the Axes."""
ax = ax_or_new(ax, (4.0, 4.0))
R = np.asarray(R)
binary = set(np.unique(R)) <= {0, 1}
ax.imshow(R, origin="lower", cmap="Greys" if binary else BRAND_SEQ, interpolation="nearest")
ax.set_xlabel("time")
ax.set_ylabel("time")
if title:
ax.set_title(title, fontsize=9)
return ax
_ZONE_COLORS = {"C": "#009E73", "B": "#E69F00", "A": "#D55E00", "OUT": "#000000"}
[docs]
def plot_visibility_graph(x, G, ax=None, max_arcs: int = 2000):
"""Series as bars with its visibility arcs drawn above; if the graph is
zone labelled (:func:`~mvtsa.representation.six_sigma_visibility_graph`)
nodes are coloured by their SPC zone and the control-chart zones are
shaded. Returns the Axes."""
ax = ax_or_new(ax, (7.0, 3.0))
v = as_series(x)[:, 0]
zones = {i: G.nodes[i].get("zone") for i in G.nodes}
labelled = any(z is not None for z in zones.values())
if labelled:
mu, sd = v.mean(), v.std() or 1.0
for k, c in ((1, "#E8F5EF"), (2, "#FCF1DC"), (3, "#F9E1D3")):
ax.axhspan(mu + (k - 1) * sd, mu + k * sd, color=c, lw=0, zorder=0)
ax.axhspan(mu - k * sd, mu - (k - 1) * sd, color=c, lw=0, zorder=0)
cols = [_ZONE_COLORS.get(zones[i], BRAND) if labelled else BRAND for i in range(len(v))]
ax.vlines(np.arange(len(v)), v.min() - 0.1 * np.ptp(v), v, color=cols, lw=1.0)
ax.scatter(np.arange(len(v)), v, s=6, color=cols, zorder=3)
edges = list(G.edges())[:max_arcs]
for a, b in edges:
if abs(a - b) == 1:
continue
t = np.linspace(0, np.pi, 20)
xs = (a + b) / 2 + (b - a) / 2 * np.cos(t)
ys = max(v[a], v[b]) + 0.15 * abs(b - a) / len(v) * np.ptp(v) * np.sin(t)
ax.plot(xs, ys, color=GRAY, lw=0.4, alpha=0.6)
ax.set_xlabel("time")
despine(ax)
if labelled:
handles = [plt.Line2D([], [], marker="o", ls="", color=c, label=f"zone {z}") for z, c in _ZONE_COLORS.items()]
ax.legend(handles=handles, frameon=False, fontsize=7, ncol=4, loc="upper center", bbox_to_anchor=(0.5, 1.15))
return ax