visibgraph 1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. visibgraph/__init__.py +136 -0
  2. visibgraph/accessor.py +64 -0
  3. visibgraph/construct/__init__.py +43 -0
  4. visibgraph/construct/horizontal.py +110 -0
  5. visibgraph/construct/multivariate.py +180 -0
  6. visibgraph/construct/natural.py +162 -0
  7. visibgraph/construct/penetrable.py +172 -0
  8. visibgraph/construct/spatial.py +145 -0
  9. visibgraph/construct/variants.py +152 -0
  10. visibgraph/construct/windows.py +128 -0
  11. visibgraph/core.py +441 -0
  12. visibgraph/datasets/__init__.py +49 -0
  13. visibgraph/datasets/_bundled.py +78 -0
  14. visibgraph/datasets/benchmark.py +229 -0
  15. visibgraph/datasets/data/README.md +35 -0
  16. visibgraph/datasets/data/lynx.csv +115 -0
  17. visibgraph/datasets/data/nile.csv +101 -0
  18. visibgraph/datasets/data/sunspots.csv +290 -0
  19. visibgraph/datasets/data/tep_d00.csv.gz +0 -0
  20. visibgraph/datasets/data/tep_d00_te.csv.gz +0 -0
  21. visibgraph/datasets/data/tep_d01_te.csv.gz +0 -0
  22. visibgraph/datasets/data/tep_d04_te.csv.gz +0 -0
  23. visibgraph/datasets/data/tep_d05_te.csv.gz +0 -0
  24. visibgraph/datasets/data/tep_d06_te.csv.gz +0 -0
  25. visibgraph/datasets/data/tep_d11_te.csv.gz +0 -0
  26. visibgraph/datasets/generators.py +216 -0
  27. visibgraph/interactive.py +84 -0
  28. visibgraph/io.py +153 -0
  29. visibgraph/labelled.py +263 -0
  30. visibgraph/measures.py +586 -0
  31. visibgraph/ml.py +179 -0
  32. visibgraph/networks.py +142 -0
  33. visibgraph/segment.py +642 -0
  34. visibgraph/spc.py +267 -0
  35. visibgraph/surrogates.py +147 -0
  36. visibgraph/symbolic.py +226 -0
  37. visibgraph/viz/__init__.py +62 -0
  38. visibgraph/viz/_style.py +92 -0
  39. visibgraph/viz/arcs.py +175 -0
  40. visibgraph/viz/distributions.py +202 -0
  41. visibgraph/viz/graphs.py +175 -0
  42. visibgraph/viz/multi.py +84 -0
  43. visibgraph/viz/series.py +223 -0
  44. visibgraph-1.0.dist-info/METADATA +181 -0
  45. visibgraph-1.0.dist-info/RECORD +47 -0
  46. visibgraph-1.0.dist-info/WHEEL +4 -0
  47. visibgraph-1.0.dist-info/licenses/LICENSE +21 -0
visibgraph/ml.py ADDED
@@ -0,0 +1,179 @@
1
+ """scikit-learn compatible transformers and baselines.
2
+
3
+ :class:`VisibilityFeatures` turns a set of series (rows of an array) into a
4
+ feature matrix of visibility-graph measures and label counts, so that graph
5
+ features can be used in any scikit-learn pipeline (scaling, selection,
6
+ classifiers, cross-validation). :class:`WERuleClassifier` is the deterministic
7
+ Western Electric rule engine wrapped as a classifier, the natural baseline for
8
+ the graph-based detection of rule violations.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable, Iterable
14
+
15
+ import numpy as np
16
+
17
+ from .construct.variants import visibility_graph
18
+ from .labelled import label_features
19
+ from .measures import EXTENDED_FEATURES, PAPER_FEATURES, graph_features, motif_names, motif_profile
20
+ from .spc import classify_we
21
+ from .symbolic import SPC_ZONES, Baseline, estimate_baseline, spc_zones
22
+
23
+ try: # scikit-learn is optional
24
+ from sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin
25
+ except ImportError: # pragma: no cover
26
+ BaseEstimator = object # type: ignore[assignment,misc]
27
+
28
+ class TransformerMixin: # type: ignore[no-redef]
29
+ def fit_transform(self, X, y=None):
30
+ return self.fit(X, y).transform(X)
31
+
32
+ class ClassifierMixin: # type: ignore[no-redef]
33
+ pass
34
+
35
+
36
+ __all__ = ["VisibilityFeatures", "WERuleClassifier", "rule_label"]
37
+
38
+
39
+ def rule_label(rule: int, direction: str) -> str:
40
+ """Class label of a WE rule violation: ``"0"`` for control, else e.g. ``"2up"``."""
41
+ return "0" if int(rule) == 0 else f"{int(rule)}{direction}"
42
+
43
+
44
+ class VisibilityFeatures(TransformerMixin, BaseEstimator):
45
+ """Visibility-graph features of a collection of series (scikit-learn transformer).
46
+
47
+ Parameters
48
+ ----------
49
+ kind : str
50
+ Visibility criterion.
51
+ features : "paper", "all" or iterable of str
52
+ Structural measures (see :func:`visibgraph.graph_features`).
53
+ labels : None, "spc" or callable
54
+ Append label counts: ``"spc"`` uses the eight SPC zones; a callable maps
55
+ a series (and a baseline) to integer labels.
56
+ baseline : "series", "mr", (mu, sigma) or None
57
+ Baseline of the SPC zones: estimated from each series (sample standard
58
+ deviation or moving range) or fixed.
59
+ label_features : sequence of str
60
+ With labels: which label-aware blocks to append, any of ``"counts"``
61
+ (class occupancies), ``"visibility"`` (edges between classes, the
62
+ zone-aggregated graph) and ``"transitions"`` (state transition counts);
63
+ see :func:`visibgraph.labelled.label_features`.
64
+ motifs : bool
65
+ Append the size-4 motif profile.
66
+ graph_kw : dict, optional
67
+ Extra arguments of the graph builder (``rho``, ``alpha``, ...).
68
+
69
+ Examples
70
+ --------
71
+ >>> import numpy as np
72
+ >>> from visibgraph.ml import VisibilityFeatures
73
+ >>> X = np.random.default_rng(0).normal(size=(5, 60))
74
+ >>> F = VisibilityFeatures(labels="spc").fit_transform(X)
75
+ >>> F.shape
76
+ (5, 16)
77
+ >>> VisibilityFeatures(features=None, labels="spc", label_features=("counts", "visibility")).fit_transform(X).shape
78
+ (5, 44)
79
+ """
80
+
81
+ def __init__(self, kind: str = "hvg", features: str | Iterable[str] = "paper", labels: str | Callable | None = None,
82
+ baseline="series", label_features: Iterable[str] = ("counts",), motifs: bool = False, graph_kw: dict | None = None):
83
+ self.kind = kind
84
+ self.features = features
85
+ self.labels = labels
86
+ self.baseline = baseline
87
+ self.label_features = label_features
88
+ self.motifs = motifs
89
+ self.graph_kw = graph_kw
90
+
91
+ def _feature_list(self) -> list[str]:
92
+ if self.features in (None, "none"):
93
+ return []
94
+ if self.features == "paper":
95
+ return list(PAPER_FEATURES)
96
+ if self.features == "all":
97
+ return list(PAPER_FEATURES) + list(EXTENDED_FEATURES)
98
+ return list(self.features)
99
+
100
+ def fit(self, X, y=None):
101
+ X = np.asarray(X, dtype=float)
102
+ self.n_features_in_ = X.shape[1]
103
+ names = self._feature_list()
104
+ self.n_labels_ = 0
105
+ if self.labels is not None:
106
+ self.n_labels_ = len(SPC_ZONES.names) if self.labels == "spc" else self._n_labels(X)
107
+ self.label_names_ = list(SPC_ZONES.names) if self.labels == "spc" else [str(c) for c in range(self.n_labels_)]
108
+ G0 = visibility_graph(X[0], kind=self.kind, **(self.graph_kw or {}))
109
+ names += list(label_features(G0, self._labels(X[0]), self.label_names_, include=tuple(self.label_features),
110
+ n_labels=self.n_labels_))
111
+ if self.motifs:
112
+ names += [f"motif_{m}" for m in motif_names(4)]
113
+ self.feature_names_out_ = np.array(names, dtype=object)
114
+ return self
115
+
116
+ def _n_labels(self, X) -> int:
117
+ return int(max(np.max(self._labels(row)) for row in X[: min(len(X), 50)]) + 1)
118
+
119
+ def _base(self, row) -> Baseline:
120
+ if self.baseline in (None, "series"):
121
+ return estimate_baseline(row)
122
+ if self.baseline == "mr":
123
+ return estimate_baseline(row, "mr")
124
+ mu, sigma = self.baseline
125
+ return Baseline(float(mu), float(sigma), "given")
126
+
127
+ def _labels(self, row):
128
+ if self.labels == "spc":
129
+ return spc_zones(row, self._base(row))
130
+ return np.asarray(self.labels(row), dtype=np.int64)
131
+
132
+ def transform(self, X) -> np.ndarray:
133
+ X = np.asarray(X, dtype=float)
134
+ feats = self._feature_list()
135
+ out = []
136
+ for row in X:
137
+ G = visibility_graph(row, kind=self.kind, **(self.graph_kw or {}))
138
+ f = graph_features(G, feats)
139
+ v = [f[k] for k in feats]
140
+ if self.labels is not None:
141
+ lf = label_features(G, self._labels(row), self.label_names_, include=tuple(self.label_features), n_labels=self.n_labels_)
142
+ v += list(lf.values())
143
+ if self.motifs:
144
+ v += motif_profile(G).tolist()
145
+ out.append(v)
146
+ return np.nan_to_num(np.asarray(out, dtype=float), nan=0.0)
147
+
148
+ def get_feature_names_out(self, input_features=None):
149
+ return self.feature_names_out_
150
+
151
+
152
+ class WERuleClassifier(ClassifierMixin, BaseEstimator):
153
+ """Western Electric rule engine as a scikit-learn classifier.
154
+
155
+ ``predict`` returns :func:`rule_label` of :func:`visibgraph.classify_we` for every
156
+ row, with the baseline estimated from the row (``baseline="series"``), by
157
+ the moving range (``"mr"``) or fixed ``(mu, sigma)``. ``fit`` only records
158
+ the classes.
159
+ """
160
+
161
+ def __init__(self, baseline="series"):
162
+ self.baseline = baseline
163
+
164
+ def fit(self, X, y=None):
165
+ self.classes_ = np.unique(y) if y is not None else np.array(["0"])
166
+ return self
167
+
168
+ def predict(self, X) -> np.ndarray:
169
+ X = np.asarray(X, dtype=float)
170
+ out = []
171
+ for row in X:
172
+ if self.baseline in (None, "series"):
173
+ b = estimate_baseline(row)
174
+ elif self.baseline == "mr":
175
+ b = estimate_baseline(row, "mr")
176
+ else:
177
+ b = Baseline(float(self.baseline[0]), float(self.baseline[1]), "given")
178
+ out.append(rule_label(*classify_we(row, b)))
179
+ return np.array(out, dtype=object)
visibgraph/networks.py ADDED
@@ -0,0 +1,142 @@
1
+ """Other routes from a series to a network, for comparison with visibility graphs.
2
+
3
+ Visibility graphs belong to a larger family of series-to-network mappings
4
+ (see Zou et al., 2019, for a review). Three widely used members are provided
5
+ so that their pictures and measures can be set side by side with those of
6
+ visibility graphs:
7
+
8
+ * :func:`ordinal_partition_network` — nodes are ordinal patterns, edges the
9
+ transitions between consecutive patterns (Small, 2013; McCullough et al., 2015);
10
+ * :func:`quantile_graph` — nodes are quantile bins of the values, edges the
11
+ transition probabilities between consecutive bins (Campanharo et al., 2011),
12
+ with the inverse map :func:`quantile_graph_walk` back to a series;
13
+ * :func:`recurrence_network` — nodes are time points of the delay embedding,
14
+ linked when their states are closer than :math:`\\varepsilon` (Marwan et al., 2009).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import numpy as np
20
+
21
+ from .symbolic import ordinal_patterns, quantile_labels
22
+
23
+ __all__ = ["ordinal_partition_network", "quantile_graph", "quantile_graph_walk", "recurrence_network", "delay_embedding"]
24
+
25
+
26
+ def delay_embedding(y, dim: int = 2, delay: int = 1) -> np.ndarray:
27
+ """Delay vectors :math:`(y_t,y_{t+\\tau},\\dots,y_{t+(m-1)\\tau})`, shape :math:`(N-(m-1)\\tau, m)`."""
28
+ y = np.asarray(y, dtype=float)
29
+ m = y.size - (dim - 1) * delay
30
+ if m <= 0:
31
+ raise ValueError("series too short for this embedding")
32
+ return np.column_stack([y[k * delay : k * delay + m] for k in range(dim)])
33
+
34
+
35
+ def ordinal_partition_network(y, order: int = 3, delay: int = 1, *, self_loops: bool = False):
36
+ """Ordinal partition (transition) network.
37
+
38
+ Returns a weighted :class:`networkx.DiGraph` whose nodes are the observed
39
+ ordinal patterns (attribute ``count``) and whose edge weights are the
40
+ numbers of transitions between consecutive patterns.
41
+
42
+ References
43
+ ----------
44
+ Small, M. (2013). Complex networks from time series: capturing dynamics. IEEE
45
+ International Symposium on Circuits and Systems, 2509–2512. McCullough, M., Small,
46
+ M., Stemler, T., Iu, H. H.-C. (2015). Time lagged ordinal partition networks for
47
+ capturing dynamics of continuous dynamical systems. Chaos 25, 053101.
48
+ """
49
+ import networkx as nx
50
+
51
+ codes = ordinal_patterns(y, order, delay)
52
+ G = nx.DiGraph(kind="ordinal_partition", order=order, delay=delay)
53
+ u, c = np.unique(codes, return_counts=True)
54
+ for a, k in zip(u.tolist(), c.tolist()):
55
+ G.add_node(int(a), count=int(k))
56
+ for a, b in zip(codes[:-1].tolist(), codes[1:].tolist()):
57
+ if a == b and not self_loops:
58
+ continue
59
+ w = G[a][b]["weight"] + 1 if G.has_edge(a, b) else 1
60
+ G.add_edge(a, b, weight=w)
61
+ return G
62
+
63
+
64
+ def quantile_graph(y, q: int = 10, *, lag: int = 1):
65
+ """Quantile graph: Markov transition network between the ``q`` quantile bins.
66
+
67
+ Returns
68
+ -------
69
+ networkx.DiGraph
70
+ Nodes ``0..q-1`` with ``low``/``high`` bin bounds; edges with ``count``
71
+ and ``weight`` (transition probability over ``lag`` steps).
72
+
73
+ References
74
+ ----------
75
+ Campanharo, A. S. L. O., Sirer, M. I., Malmgren, R. D., Ramos, F. M., Amaral, L. A. N.
76
+ (2011). Duality between time series and networks. PLoS ONE 6, e23378.
77
+ """
78
+ import networkx as nx
79
+
80
+ y = np.asarray(y, dtype=float)
81
+ lab = quantile_labels(y, q)
82
+ edges = np.quantile(y, np.linspace(0, 1, q + 1))
83
+ T = np.zeros((q, q))
84
+ np.add.at(T, (lab[:-lag], lab[lag:]), 1)
85
+ P = np.divide(T, T.sum(1, keepdims=True), out=np.zeros_like(T), where=T.sum(1, keepdims=True) > 0)
86
+ G = nx.DiGraph(kind="quantile_graph", q=q, lag=lag)
87
+ for a in range(q):
88
+ G.add_node(a, low=float(edges[a]), high=float(edges[a + 1]))
89
+ for a in range(q):
90
+ for b in range(q):
91
+ if T[a, b]:
92
+ G.add_edge(a, b, count=int(T[a, b]), weight=float(P[a, b]))
93
+ return G
94
+
95
+
96
+ def quantile_graph_walk(G, length: int, *, start: int | None = None, random_state=None) -> np.ndarray:
97
+ """Inverse map: a series generated by a random walk on a quantile graph.
98
+
99
+ Each step moves along an edge with its transition probability; the value
100
+ is drawn uniformly within the bin of the visited node.
101
+ """
102
+ rng = np.random.default_rng(random_state)
103
+ q = G.number_of_nodes()
104
+ P = np.zeros((q, q))
105
+ for a, b, d in G.edges(data=True):
106
+ P[a, b] = d["weight"]
107
+ node = int(rng.integers(q)) if start is None else int(start)
108
+ out = np.empty(length)
109
+ for k in range(length):
110
+ lo, hi = G.nodes[node]["low"], G.nodes[node]["high"]
111
+ out[k] = rng.uniform(lo, hi)
112
+ row = P[node]
113
+ node = int(rng.choice(q, p=row / row.sum())) if row.sum() > 0 else int(rng.integers(q))
114
+ return out
115
+
116
+
117
+ def recurrence_network(y, *, dim: int = 2, delay: int = 1, epsilon: float | None = None, recurrence_rate: float = 0.05):
118
+ """Epsilon-recurrence network of the delay-embedded series.
119
+
120
+ Nodes are the embedding vectors (time points); two are linked if their
121
+ Euclidean distance is below :math:`\\varepsilon`. Without ``epsilon`` the
122
+ threshold is set so that a fraction ``recurrence_rate`` of the pairs is
123
+ linked. :math:`O(N^2)` memory.
124
+
125
+ References
126
+ ----------
127
+ Marwan, N., Donges, J. F., Zou, Y., Donner, R. V., Kurths, J. (2009). Complex
128
+ network approach for recurrence analysis of time series. Phys. Lett. A 373,
129
+ 4246–4254.
130
+ """
131
+ import networkx as nx
132
+ from scipy.spatial.distance import pdist, squareform
133
+
134
+ X = delay_embedding(y, dim, delay)
135
+ d = pdist(X)
136
+ eps = float(np.quantile(d, recurrence_rate)) if epsilon is None else float(epsilon)
137
+ D = squareform(d)
138
+ A = (D <= eps) & ~np.eye(len(X), dtype=bool)
139
+ G = nx.from_numpy_array(A.astype(int))
140
+ nx.set_node_attributes(G, {k: float(X[k, 0]) for k in range(len(X))}, "value")
141
+ G.graph.update(kind="recurrence", dim=dim, delay=delay, epsilon=eps)
142
+ return G