Source code for mvtsa.representation.graphs

"""Network representations of time series.

* :func:`visibility_graph` -- natural visibility graph (Lacasa et al., 2008):
  samples are nodes, two samples are linked if the straight line between
  them passes above all intermediate samples;
* :func:`horizontal_visibility_graph` -- the horizontal variant (Luque et
  al., 2009), computed in linear time with a stack;
* :func:`six_sigma_visibility_graph` -- horizontal visibility graph whose
  nodes are labelled by the statistical process control zones of the
  control chart (C: within 1σ, B: 1--2σ, A: 2--3σ, and out of the control
  limits) following Ferenczi, Kummer and Abonyi (2026), so that SPC
  patterns (runs, trends, alternation, limit violations) become graph
  features (degree asymmetry, zone-to-zone edges, local clustering, hubs);
* :func:`ordinal_partition_network` -- transition network of ordinal
  patterns (Small, 2013; McCullough et al., 2015);
* :func:`recurrence_network` -- ε-recurrence network of the delay-embedded
  state space (Marwan et al., 2009);
* :func:`graph_features` -- summary features of these graphs.

All builders return :mod:`networkx` graphs with plain scalar attributes.
"""

from __future__ import annotations

import networkx as nx
import numpy as np

from .._base import as_series

__all__ = ["visibility_graph", "horizontal_visibility_graph", "spc_zones", "six_sigma_visibility_graph",
           "western_electric_rules", "ordinal_partition_network", "recurrence_network", "graph_features"]


def _uni(x):
    return as_series(x)[:, 0]


[docs] def visibility_graph(x) -> nx.Graph: """Natural visibility graph (divide and conquer, :math:`O(T\\log T)` on average).""" v = _uni(x) T = len(v) G = nx.Graph() G.add_nodes_from((i, {"value": float(v[i])}) for i in range(T)) def rec(lo, hi): if hi - lo < 1: return k = lo + int(np.argmax(v[lo:hi + 1])) for side in (range(k - 1, lo - 1, -1), range(k + 1, hi + 1)): max_slope = -np.inf for j in side: s = (v[j] - v[k]) / abs(j - k) if s > max_slope: G.add_edge(k, j) max_slope = s rec(lo, k - 1) rec(k + 1, hi) import sys lim = sys.getrecursionlimit() sys.setrecursionlimit(max(lim, 4 * T + 100)) try: rec(0, T - 1) finally: sys.setrecursionlimit(lim) return G
[docs] def horizontal_visibility_graph(x, directed: bool = False) -> nx.Graph: """Horizontal visibility graph: ``i < j`` are linked if every sample between them is lower than both. With ``directed`` the edges point forward in time (for in/out-degree asymmetry).""" v = _uni(x) G = nx.DiGraph() if directed else nx.Graph() G.add_nodes_from((i, {"value": float(v[i])}) for i in range(len(v))) stack: list[int] = [] for j in range(len(v)): while stack: i = stack[-1] G.add_edge(i, j) if v[i] < v[j]: stack.pop() else: break stack.append(j) return G
[docs] def spc_zones(x, center: float | None = None, sigma: float | None = None) -> np.ndarray: """Control-chart zone of every sample: ``"C"``, ``"B"``, ``"A"`` within 1, 2, 3 standard deviations, ``"OUT"`` beyond the 3σ control limits (center and σ default to the sample mean and standard deviation).""" v = _uni(x) c = float(v.mean()) if center is None else center s = float(v.std() or 1.0) if sigma is None else sigma z = np.abs(v - c) / s return np.where(z <= 1, "C", np.where(z <= 2, "B", np.where(z <= 3, "A", "OUT")))
[docs] def western_electric_rules(x, center: float | None = None, sigma: float | None = None) -> dict[str, np.ndarray]: """Boolean flags of the four Western Electric rules: beyond 3σ; 2 of 3 beyond 2σ on one side; 4 of 5 beyond 1σ on one side; 8 in a row on one side of the center.""" v = _uni(x) c = float(v.mean()) if center is None else center s = float(v.std() or 1.0) if sigma is None else sigma z = (v - c) / s T = len(v) r1 = np.abs(z) > 3 r2, r3, r4 = (np.zeros(T, bool) for _ in range(3)) for t in range(T): for sign in (1, -1): if t >= 2 and np.sum(sign * z[t - 2:t + 1] > 2) >= 2: r2[t] = True if t >= 4 and np.sum(sign * z[t - 4:t + 1] > 1) >= 4: r3[t] = True if t >= 7 and np.all(sign * z[t - 7:t + 1] > 0): r4[t] = True return {"rule1": r1, "rule2": r2, "rule3": r3, "rule4": r4}
[docs] def six_sigma_visibility_graph(x, center: float | None = None, sigma: float | None = None, directed: bool = True) -> nx.Graph: """SPC-zone labelled horizontal visibility graph. Node attributes: ``value``, ``zone`` (C/B/A/OUT), ``side`` (+1 above, -1 below the center), and the Western Electric rule flags; edge attribute ``zones`` (e.g. ``"C-A"``) for zone-transition statistics.""" v = _uni(x) G = horizontal_visibility_graph(v, directed=directed) zones = spc_zones(v, center, sigma) c = float(v.mean()) if center is None else center rules = western_electric_rules(v, center, sigma) for i in G.nodes: G.nodes[i]["zone"] = str(zones[i]) G.nodes[i]["side"] = int(np.sign(v[i] - c) or 1) for k, flag in rules.items(): G.nodes[i][k] = bool(flag[i]) for a, b in G.edges: G.edges[a, b]["zones"] = "-".join(sorted((str(zones[a]), str(zones[b])))) return G
[docs] def ordinal_partition_network(x, order: int = 3, delay: int = 1) -> nx.DiGraph: """Directed, weighted transition network of the ordinal patterns of length ``order`` (nodes are patterns, e.g. ``"012"``).""" v = _uni(x) n = len(v) - (order - 1) * delay emb = np.column_stack([v[i * delay:i * delay + n] for i in range(order)]) pats = ["".join(map(str, np.argsort(r))) for r in emb] G = nx.DiGraph() for p in pats: G.add_node(p, count=G.nodes[p]["count"] + 1 if p in G else 1) for a, b in zip(pats[:-1], pats[1:], strict=True): w = G.edges[a, b]["weight"] + 1 if G.has_edge(a, b) else 1 G.add_edge(a, b, weight=w) return G
[docs] def recurrence_network(X, epsilon: float | None = None, dim: int = 1, tau: int = 1) -> nx.Graph: """ε-recurrence network: nodes are (delay-embedded) states, linked if closer than ``epsilon`` (default: the 10 % quantile of the distances).""" from scipy.spatial.distance import pdist, squareform from ..preprocessing import delay_embedding A = as_series(X) S = delay_embedding(A[:, 0], dim, tau) if (dim > 1 and A.shape[1] == 1) else A D = squareform(pdist(S)) eps = float(np.quantile(D[np.triu_indices_from(D, 1)], 0.1)) if epsilon is None else epsilon G = nx.Graph() G.add_nodes_from(range(len(S))) ii, jj = np.nonzero(np.triu(D <= eps, 1)) G.add_edges_from(zip(ii.tolist(), jj.tolist(), strict=True)) return G
[docs] def graph_features(G) -> dict[str, float]: """Summary features: mean degree, degree entropy, clustering, assortativity, density; for directed graphs the mean in/out degree asymmetry; for zone-labelled graphs the fraction of edges per zone pair.""" U = G.to_undirected() if G.is_directed() else G deg = np.array([d for _, d in U.degree()], float) p = np.bincount(deg.astype(int)) / max(len(deg), 1) p = p[p > 0] out = { "mean_degree": float(deg.mean()) if len(deg) else 0.0, "degree_entropy": float(-(p * np.log(p)).sum()), "clustering": float(nx.average_clustering(U)) if len(U) else 0.0, "density": float(nx.density(U)), } try: out["assortativity"] = float(nx.degree_assortativity_coefficient(U)) except Exception: # noqa: BLE001 - undefined for regular graphs out["assortativity"] = 0.0 if G.is_directed(): ind = np.array([d for _, d in G.in_degree()], float) outd = np.array([d for _, d in G.out_degree()], float) out["degree_asymmetry"] = float(np.mean(outd - ind) / max(np.mean(outd + ind), 1e-12)) zones = nx.get_edge_attributes(G, "zones") if zones: vals, cnt = np.unique(list(zones.values()), return_counts=True) for v, c in zip(vals, cnt, strict=True): out[f"edges_{v}"] = float(c / len(zones)) return out