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/core.py ADDED
@@ -0,0 +1,441 @@
1
+ """The :class:`VisibilityGraph` container shared by every builder of the package.
2
+
3
+ A visibility graph of a series :math:`(t_1,y_1),\\dots,(t_N,y_N)` has one node
4
+ per observation and an edge :math:`(i,j)`, :math:`i<j`, whenever the two
5
+ observations "see" each other under a visibility criterion. Every builder of
6
+ :mod:`visibgraph.construct` returns the graph in the same compact form: the series,
7
+ the time stamps, and an ``(E, 2)`` integer array of edges with :math:`i<j`,
8
+ sorted lexicographically. Everything else (degrees, spans, weights, adjacency
9
+ matrices, NetworkX graphs, tables) is derived from these arrays on demand.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterable, Sequence
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+ from scipy import sparse
19
+
20
+ __all__ = ["VisibilityGraph", "EDGE_WEIGHTS", "as_series"]
21
+
22
+ #: names of the edge weights that can be derived from the geometry of an edge
23
+ EDGE_WEIGHTS = (
24
+ "span",
25
+ "index_span",
26
+ "distance",
27
+ "slope",
28
+ "angle",
29
+ "abs_angle",
30
+ "view_angle",
31
+ "abs_diff",
32
+ )
33
+
34
+
35
+ def as_series(y, t=None) -> tuple[np.ndarray, np.ndarray, pd.Index | None]:
36
+ """Convert the input of a builder to float arrays ``(y, t)`` and an optional index.
37
+
38
+ ``y`` may be a list, a NumPy array or a :class:`pandas.Series`; the index of a
39
+ Series with a :class:`~pandas.DatetimeIndex` or numeric index becomes the time
40
+ axis when ``t`` is not given (datetimes are converted to seconds since the
41
+ first observation). Time stamps must be strictly increasing.
42
+ """
43
+ index = None
44
+ if isinstance(y, pd.Series):
45
+ index = y.index
46
+ if t is None:
47
+ if isinstance(index, pd.DatetimeIndex):
48
+ t = (index - index[0]).total_seconds().to_numpy(dtype=float)
49
+ elif pd.api.types.is_numeric_dtype(index) and not isinstance(index, pd.RangeIndex):
50
+ t = index.to_numpy(dtype=float)
51
+ y = y.to_numpy(dtype=float)
52
+ y = np.asarray(y, dtype=float).ravel()
53
+ if y.size and not np.all(np.isfinite(y)):
54
+ raise ValueError("the series contains NaN or infinite values; impute or drop them first")
55
+ if t is None:
56
+ t = np.arange(y.size, dtype=float)
57
+ else:
58
+ t = np.asarray(t, dtype=float).ravel()
59
+ if t.size != y.size:
60
+ raise ValueError(f"t has {t.size} elements, y has {y.size}")
61
+ if t.size > 1 and np.any(np.diff(t) <= 0):
62
+ raise ValueError("time stamps must be strictly increasing")
63
+ return y, t, index
64
+
65
+
66
+ def _sorted_edges(edges) -> np.ndarray:
67
+ e = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
68
+ if e.size == 0:
69
+ return np.empty((0, 2), dtype=np.int64)
70
+ if np.any(e[:, 0] >= e[:, 1]):
71
+ lo = np.minimum(e[:, 0], e[:, 1])
72
+ hi = np.maximum(e[:, 0], e[:, 1])
73
+ e = np.column_stack([lo, hi])
74
+ e = e[e[:, 0] < e[:, 1]]
75
+ e = np.unique(e, axis=0) # sorts lexicographically
76
+ return e
77
+
78
+
79
+ class VisibilityGraph:
80
+ """Visibility graph of a (univariate) series.
81
+
82
+ Parameters
83
+ ----------
84
+ y : array_like of shape (N,)
85
+ Values of the series.
86
+ edges : array_like of shape (E, 2)
87
+ Node pairs; stored with :math:`i<j`, unique and lexicographically sorted.
88
+ t : array_like of shape (N,), optional
89
+ Strictly increasing time stamps; ``0, 1, ..., N-1`` by default.
90
+ kind : str
91
+ Name of the visibility criterion (``"nvg"``, ``"hvg"``, ``"lphvg"``, ...).
92
+ directed : bool
93
+ If True the edges are read in the direction of time, :math:`i\\to j`,
94
+ and in- and out-degrees count links to the past and to the future.
95
+ labels : array_like of shape (N,), optional
96
+ Node labels (symbols), for instance SPC zone codes.
97
+ label_names : sequence of str, optional
98
+ Names of the integer labels.
99
+ params : dict, optional
100
+ Parameters of the builder (kept for reports and file export).
101
+ index : pandas.Index, optional
102
+ Index of the original :class:`pandas.Series`.
103
+
104
+ Attributes
105
+ ----------
106
+ y, t : ndarray
107
+ The series and its time stamps.
108
+ edges : ndarray of shape (E, 2)
109
+ The edges, :math:`i<j`.
110
+
111
+ Examples
112
+ --------
113
+ >>> import visibgraph as vg
114
+ >>> G = vg.hvg([3, 1, 2, 4])
115
+ >>> G.edges.tolist()
116
+ [[0, 1], [0, 2], [0, 3], [1, 2], [2, 3]]
117
+ >>> G.degree().tolist()
118
+ [3, 2, 3, 2]
119
+ """
120
+
121
+ def __init__(
122
+ self,
123
+ y,
124
+ edges,
125
+ t=None,
126
+ *,
127
+ kind: str = "custom",
128
+ directed: bool = False,
129
+ labels=None,
130
+ label_names: Sequence[str] | None = None,
131
+ params: dict | None = None,
132
+ index=None,
133
+ ):
134
+ self.y, self.t, idx = as_series(y, t)
135
+ self.index = index if index is not None else idx
136
+ self.edges = _sorted_edges(edges)
137
+ if self.edges.size and (self.edges.max() >= self.y.size or self.edges.min() < 0):
138
+ raise ValueError("edge index out of range")
139
+ self.kind = str(kind)
140
+ self.directed = bool(directed)
141
+ self.params = dict(params or {})
142
+ self.labels = None
143
+ self.label_names = None
144
+ if labels is not None:
145
+ self.set_labels(labels, label_names)
146
+
147
+ # ------------------------------------------------------------------ basics
148
+ @property
149
+ def n_nodes(self) -> int:
150
+ """Number of nodes :math:`N`."""
151
+ return int(self.y.size)
152
+
153
+ @property
154
+ def n_edges(self) -> int:
155
+ """Number of edges :math:`E`."""
156
+ return int(self.edges.shape[0])
157
+
158
+ def __len__(self) -> int:
159
+ return self.n_nodes
160
+
161
+ def __repr__(self) -> str:
162
+ d = "directed " if self.directed else ""
163
+ lab = ", labelled" if self.labels is not None else ""
164
+ return f"VisibilityGraph({d}{self.kind}, {self.n_nodes} nodes, {self.n_edges} edges{lab})"
165
+
166
+ def copy(self) -> VisibilityGraph:
167
+ """A deep copy."""
168
+ G = VisibilityGraph(
169
+ self.y.copy(), self.edges.copy(), self.t.copy(), kind=self.kind, directed=self.directed,
170
+ params=dict(self.params), index=self.index,
171
+ )
172
+ if self.labels is not None:
173
+ G.set_labels(self.labels.copy(), self.label_names)
174
+ return G
175
+
176
+ def set_labels(self, labels, label_names: Sequence[str] | None = None) -> VisibilityGraph:
177
+ """Attach node labels (in place) and return the graph.
178
+
179
+ Labels are stored as integer codes; non-integer labels (strings) are
180
+ encoded in order of first appearance and their names kept in
181
+ ``label_names``.
182
+ """
183
+ lab = np.asarray(labels)
184
+ if lab.shape[0] != self.n_nodes:
185
+ raise ValueError(f"{lab.shape[0]} labels for {self.n_nodes} nodes")
186
+ if lab.dtype.kind in "iub":
187
+ self.labels = lab.astype(np.int64)
188
+ self.label_names = list(label_names) if label_names is not None else None
189
+ else:
190
+ names = list(dict.fromkeys(lab.tolist())) if label_names is None else list(label_names)
191
+ code = {v: k for k, v in enumerate(names)}
192
+ self.labels = np.array([code[v] for v in lab.tolist()], dtype=np.int64)
193
+ self.label_names = [str(v) for v in names]
194
+ return self
195
+
196
+ def label_of(self, i: int) -> str | int | None:
197
+ """Label (name if available) of node ``i``."""
198
+ if self.labels is None:
199
+ return None
200
+ c = int(self.labels[i])
201
+ if self.label_names is not None and 0 <= c < len(self.label_names):
202
+ return self.label_names[c]
203
+ return c
204
+
205
+ # ----------------------------------------------------------------- degrees
206
+ def degree(self) -> np.ndarray:
207
+ """Degrees :math:`k_i` (number of visible neighbors)."""
208
+ if self.n_edges == 0:
209
+ return np.zeros(self.n_nodes, dtype=np.int64)
210
+ return np.bincount(self.edges.ravel(), minlength=self.n_nodes).astype(np.int64)
211
+
212
+ def in_degree(self) -> np.ndarray:
213
+ """Number of visible neighbors in the past, :math:`k^{\\leftarrow}_i=|\\{j<i:(j,i)\\in E\\}|`."""
214
+ return np.bincount(self.edges[:, 1], minlength=self.n_nodes).astype(np.int64)
215
+
216
+ def out_degree(self) -> np.ndarray:
217
+ """Number of visible neighbors in the future, :math:`k^{\\rightarrow}_i=|\\{j>i:(i,j)\\in E\\}|`."""
218
+ return np.bincount(self.edges[:, 0], minlength=self.n_nodes).astype(np.int64)
219
+
220
+ def strength(self, weight: str | np.ndarray = "span") -> np.ndarray:
221
+ """Weighted degree: the sum of the weights of the incident edges."""
222
+ w = self.weight(weight)
223
+ s = np.zeros(self.n_nodes)
224
+ np.add.at(s, self.edges[:, 0], w)
225
+ np.add.at(s, self.edges[:, 1], w)
226
+ return s
227
+
228
+ def neighbors(self, i: int) -> np.ndarray:
229
+ """Sorted indices of the nodes visible from node ``i``."""
230
+ e = self.edges
231
+ return np.sort(np.concatenate([e[e[:, 0] == i, 1], e[e[:, 1] == i, 0]]))
232
+
233
+ def has_edge(self, i: int, j: int) -> bool:
234
+ """True if nodes ``i`` and ``j`` see each other."""
235
+ i, j = (i, j) if i < j else (j, i)
236
+ lo = np.searchsorted(self.edges[:, 0], i, side="left")
237
+ hi = np.searchsorted(self.edges[:, 0], i, side="right")
238
+ return bool(np.any(self.edges[lo:hi, 1] == j))
239
+
240
+ # ------------------------------------------------------------ edge weights
241
+ def spans(self, unit: str = "time") -> np.ndarray:
242
+ """Temporal length of the edges, :math:`t_j-t_i` (``unit="time"``) or :math:`j-i` (``"index"``)."""
243
+ i, j = self.edges[:, 0], self.edges[:, 1]
244
+ if unit == "index":
245
+ return (j - i).astype(float)
246
+ return self.t[j] - self.t[i]
247
+
248
+ def weight(self, name: str | np.ndarray | None = "span") -> np.ndarray:
249
+ """Edge weights derived from the geometry of the edges.
250
+
251
+ ``name`` is one of :data:`EDGE_WEIGHTS`:
252
+
253
+ * ``"span"``: :math:`t_j-t_i`, the time over which the two observations
254
+ see each other (the edge weight of Ferenczi, Kummer and Abonyi, 2026);
255
+ * ``"index_span"``: :math:`j-i`;
256
+ * ``"distance"``: Euclidean length :math:`\\sqrt{(t_j-t_i)^2+(y_j-y_i)^2}`;
257
+ * ``"slope"``: :math:`(y_j-y_i)/(t_j-t_i)`;
258
+ * ``"angle"``: :math:`\\arctan` of the slope, in :math:`(-\\pi/2,\\pi/2)`;
259
+ * ``"abs_angle"``: its absolute value (weighted visibility graphs of EEG studies);
260
+ * ``"view_angle"``: :math:`\\pi/2+\\arctan` slope, the angle to the downward vertical
261
+ used by the parametric visibility graph;
262
+ * ``"abs_diff"``: :math:`|y_j-y_i|`.
263
+
264
+ An array of length :math:`E` is returned unchanged; ``None`` gives ones.
265
+ """
266
+ if name is None:
267
+ return np.ones(self.n_edges)
268
+ if not isinstance(name, str):
269
+ w = np.asarray(name, dtype=float)
270
+ if w.shape != (self.n_edges,):
271
+ raise ValueError("weight array must have one value per edge")
272
+ return w
273
+ i, j = self.edges[:, 0], self.edges[:, 1]
274
+ dt = self.t[j] - self.t[i]
275
+ dy = self.y[j] - self.y[i]
276
+ if name == "span":
277
+ return dt.copy()
278
+ if name == "index_span":
279
+ return (j - i).astype(float)
280
+ if name == "distance":
281
+ return np.hypot(dt, dy)
282
+ if name == "slope":
283
+ return dy / dt
284
+ if name == "angle":
285
+ return np.arctan(dy / dt)
286
+ if name == "abs_angle":
287
+ return np.abs(np.arctan(dy / dt))
288
+ if name == "view_angle":
289
+ return np.pi / 2 + np.arctan(dy / dt)
290
+ if name == "abs_diff":
291
+ return np.abs(dy)
292
+ if name in self.params.get("edge_attributes", {}):
293
+ return np.asarray(self.params["edge_attributes"][name], dtype=float)
294
+ raise ValueError(f"unknown edge weight {name!r}; choose from {EDGE_WEIGHTS}")
295
+
296
+ # ---------------------------------------------------------------- matrices
297
+ def adjacency(self, weight: str | np.ndarray | None = None, dense: bool = False, directed: bool | None = None):
298
+ """Adjacency matrix (SciPy CSR by default, NumPy array with ``dense=True``).
299
+
300
+ The matrix is symmetric unless the graph (or the ``directed`` argument)
301
+ is directed, in which case :math:`a_{ij}` is set for :math:`i<j` only.
302
+ """
303
+ directed = self.directed if directed is None else directed
304
+ w = self.weight(weight)
305
+ i, j = self.edges[:, 0], self.edges[:, 1]
306
+ n = self.n_nodes
307
+ if directed:
308
+ A = sparse.csr_matrix((w, (i, j)), shape=(n, n))
309
+ else:
310
+ A = sparse.csr_matrix((np.concatenate([w, w]), (np.concatenate([i, j]), np.concatenate([j, i]))), shape=(n, n))
311
+ return A.toarray() if dense else A
312
+
313
+ def laplacian(self, normalized: bool = False) -> np.ndarray:
314
+ """Graph Laplacian :math:`\\mathbf{L}=\\mathbf{D}-\\mathbf{A}` (dense)."""
315
+ A = self.adjacency(dense=True, directed=False)
316
+ d = A.sum(1)
317
+ if not normalized:
318
+ return np.diag(d) - A
319
+ with np.errstate(divide="ignore"):
320
+ s = np.where(d > 0, 1 / np.sqrt(d), 0)
321
+ return np.eye(self.n_nodes) - s[:, None] * A * s[None, :]
322
+
323
+ # ------------------------------------------------------------- operations
324
+ def window(self, start: int, stop: int) -> VisibilityGraph:
325
+ """Graph of the consecutive nodes ``start, ..., stop-1``, renumbered from 0.
326
+
327
+ Every visibility criterion of the package is *hereditary*: whether two
328
+ nodes see each other depends only on the observations between them.
329
+ The induced subgraph of a run of consecutive nodes is therefore exactly
330
+ the visibility graph of the corresponding piece of the series, and
331
+ sliding-window graphs can be cut out of one global graph.
332
+ """
333
+ start, stop = max(0, int(start)), min(self.n_nodes, int(stop))
334
+ e = self.edges
335
+ lo = np.searchsorted(e[:, 0], start, side="left")
336
+ hi = np.searchsorted(e[:, 0], stop, side="left")
337
+ sub = e[lo:hi]
338
+ sub = sub[sub[:, 1] < stop] - start
339
+ G = VisibilityGraph(
340
+ self.y[start:stop], sub, self.t[start:stop], kind=self.kind, directed=self.directed,
341
+ params={**self.params, "window": (start, stop)},
342
+ index=self.index[start:stop] if self.index is not None else None,
343
+ )
344
+ if self.labels is not None:
345
+ G.set_labels(self.labels[start:stop], self.label_names)
346
+ return G
347
+
348
+ def reverse(self) -> VisibilityGraph:
349
+ """Graph of the time-reversed series (the same edges, renumbered :math:`i\\mapsto N-1-i`)."""
350
+ n = self.n_nodes
351
+ e = (n - 1) - self.edges[:, ::-1]
352
+ t = self.t[-1] - self.t[::-1]
353
+ G = VisibilityGraph(self.y[::-1], e, t, kind=self.kind, directed=self.directed, params=dict(self.params))
354
+ if self.labels is not None:
355
+ G.set_labels(self.labels[::-1], self.label_names)
356
+ return G
357
+
358
+ def union(self, other: VisibilityGraph, kind: str | None = None) -> VisibilityGraph:
359
+ """Edges of either graph (the graphs must be built on the same series)."""
360
+ self._check_same(other)
361
+ return self._derive(np.vstack([self.edges, other.edges]), kind or f"{self.kind}|{other.kind}")
362
+
363
+ def intersection(self, other: VisibilityGraph, kind: str | None = None) -> VisibilityGraph:
364
+ """Edges common to both graphs."""
365
+ self._check_same(other)
366
+ a = {tuple(r) for r in self.edges.tolist()}
367
+ e = [r for r in other.edges.tolist() if tuple(r) in a]
368
+ return self._derive(e, kind or f"{self.kind}&{other.kind}")
369
+
370
+ def difference(self, other: VisibilityGraph, kind: str | None = None) -> VisibilityGraph:
371
+ """Edges of this graph that are not in ``other``."""
372
+ self._check_same(other)
373
+ b = {tuple(r) for r in other.edges.tolist()}
374
+ e = [r for r in self.edges.tolist() if tuple(r) not in b]
375
+ return self._derive(e, kind or f"{self.kind}-{other.kind}")
376
+
377
+ def filter_edges(self, mask, kind: str | None = None) -> VisibilityGraph:
378
+ """Keep the edges where the boolean ``mask`` is True."""
379
+ mask = np.asarray(mask, dtype=bool)
380
+ return self._derive(self.edges[mask], kind or self.kind)
381
+
382
+ def _check_same(self, other: VisibilityGraph) -> None:
383
+ if other.n_nodes != self.n_nodes:
384
+ raise ValueError("the graphs are built on series of different lengths")
385
+
386
+ def _derive(self, edges, kind: str) -> VisibilityGraph:
387
+ G = VisibilityGraph(self.y, edges, self.t, kind=kind, directed=self.directed, params=dict(self.params), index=self.index)
388
+ if self.labels is not None:
389
+ G.set_labels(self.labels, self.label_names)
390
+ return G
391
+
392
+ # ----------------------------------------------------------------- export
393
+ def to_networkx(self, weights: Iterable[str] = ("span",), node_attributes: bool = True):
394
+ """The graph as a :class:`networkx.Graph` (or ``DiGraph`` if directed).
395
+
396
+ Nodes are the integers ``0..N-1`` with attributes ``time``, ``value``,
397
+ ``degree`` and, if present, ``label``; edges carry the requested weights
398
+ (see :meth:`weight`). All attributes are plain Python scalars, so the
399
+ graph can be written to GraphML, GEXF or JSON without loss.
400
+ """
401
+ import networkx as nx
402
+
403
+ G = nx.DiGraph() if self.directed else nx.Graph()
404
+ G.graph.update({"kind": self.kind, **{k: v for k, v in self.params.items() if isinstance(v, (int, float, str, bool))}})
405
+ if node_attributes:
406
+ k = self.degree()
407
+ for i in range(self.n_nodes):
408
+ attrs = {"time": float(self.t[i]), "value": float(self.y[i]), "degree": int(k[i])}
409
+ if self.labels is not None:
410
+ attrs["label"] = str(self.label_of(i))
411
+ G.add_node(i, **attrs)
412
+ else:
413
+ G.add_nodes_from(range(self.n_nodes))
414
+ W = {w: self.weight(w) for w in (weights or ())}
415
+ for r, (i, j) in enumerate(self.edges.tolist()):
416
+ G.add_edge(i, j, **{w: float(v[r]) for w, v in W.items()})
417
+ return G
418
+
419
+ def edge_frame(self, weights: Iterable[str] = ("span", "slope")) -> pd.DataFrame:
420
+ """Edge table: ``source``, ``target`` and the requested weights."""
421
+ df = pd.DataFrame({"source": self.edges[:, 0], "target": self.edges[:, 1]})
422
+ for w in weights or ():
423
+ df[w] = self.weight(w)
424
+ return df
425
+
426
+ def node_frame(self) -> pd.DataFrame:
427
+ """Node table: time, value, degree, in- and out-degree and label."""
428
+ df = pd.DataFrame(
429
+ {
430
+ "time": self.t,
431
+ "value": self.y,
432
+ "degree": self.degree(),
433
+ "in_degree": self.in_degree(),
434
+ "out_degree": self.out_degree(),
435
+ }
436
+ )
437
+ if self.labels is not None:
438
+ df["label"] = [self.label_of(i) for i in range(self.n_nodes)]
439
+ if self.index is not None:
440
+ df.index = self.index
441
+ return df
@@ -0,0 +1,49 @@
1
+ """Data sets: synthetic generators, the six-sigma benchmark of the paper, and real series.
2
+
3
+ * generators with known structure — noise, AR(1), logistic and Hénon maps, the
4
+ Lorenz system, fractional Gaussian noise and Brownian motion, periodic
5
+ series, regime switching with known change points, control chart patterns;
6
+ * :func:`load_six_sigma_benchmark` — the benchmark of Ferenczi, Kummer and
7
+ Abonyi (2026), regenerated value for value;
8
+ * real series — the Nile flow (a classic change point), Canadian lynx
9
+ trappings and yearly sunspot numbers (cycles), and Tennessee Eastman process
10
+ data (multivariate industrial monitoring).
11
+ """
12
+
13
+ from ._bundled import TEP_FAULTS, load_lynx, load_nile, load_sunspots, load_tep
14
+ from .benchmark import SixSigmaBenchmark, inject_we_violation, load_six_sigma_benchmark
15
+ from .generators import (
16
+ ar1,
17
+ control_chart_patterns,
18
+ fbm,
19
+ fgn,
20
+ henon_map,
21
+ inject_shift,
22
+ logistic_map,
23
+ lorenz,
24
+ periodic,
25
+ regime_switching,
26
+ white_noise,
27
+ )
28
+
29
+ __all__ = [
30
+ "TEP_FAULTS",
31
+ "SixSigmaBenchmark",
32
+ "ar1",
33
+ "control_chart_patterns",
34
+ "fbm",
35
+ "fgn",
36
+ "henon_map",
37
+ "inject_shift",
38
+ "inject_we_violation",
39
+ "load_lynx",
40
+ "load_nile",
41
+ "load_six_sigma_benchmark",
42
+ "load_sunspots",
43
+ "load_tep",
44
+ "logistic_map",
45
+ "lorenz",
46
+ "periodic",
47
+ "regime_switching",
48
+ "white_noise",
49
+ ]
@@ -0,0 +1,78 @@
1
+ """Loaders of the real data sets shipped with the package (see ``data/README.md``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib import resources
6
+
7
+ import pandas as pd
8
+
9
+ __all__ = ["load_nile", "load_lynx", "load_sunspots", "load_tep", "TEP_FAULTS"]
10
+
11
+ #: Tennessee Eastman test sets shipped with the package and the faults they contain
12
+ TEP_FAULTS = {
13
+ 0: "normal operation",
14
+ 1: "A/C feed ratio, B composition constant (step)",
15
+ 4: "reactor cooling water inlet temperature (step)",
16
+ 5: "condenser cooling water inlet temperature (step)",
17
+ 6: "A feed loss (step)",
18
+ 11: "reactor cooling water inlet temperature (random variation)",
19
+ }
20
+
21
+
22
+ def _read(name: str, **kw) -> pd.DataFrame:
23
+ with resources.files(__package__).joinpath("data", name).open("rb") as fh:
24
+ return pd.read_csv(fh, compression="gzip" if name.endswith(".gz") else None, **kw)
25
+
26
+
27
+ def load_nile() -> pd.Series:
28
+ """Annual flow of the Nile at Aswan, 1871–1970 (10^8 m^3), with a change point near 1898.
29
+
30
+ Sources: Cobb (1978), Biometrika 65, 243–251; Durbin and Koopman (2001); R ``datasets``.
31
+ """
32
+ df = _read("nile.csv")
33
+ return pd.Series(df["flow"].to_numpy(dtype=float), index=pd.Index(df["year"], name="year"), name="Nile flow")
34
+
35
+
36
+ def load_lynx() -> pd.Series:
37
+ """Annual Canadian lynx trappings, 1821–1934 (Campbell and Walker, 1977; R ``datasets``)."""
38
+ df = _read("lynx.csv")
39
+ return pd.Series(df["trappings"].to_numpy(dtype=float), index=pd.Index(df["year"], name="year"), name="lynx trappings")
40
+
41
+
42
+ def load_sunspots() -> pd.Series:
43
+ """Yearly sunspot numbers, 1700–1988 (Tong, 1996; R ``datasets``)."""
44
+ df = _read("sunspots.csv")
45
+ return pd.Series(df["sunspots"].to_numpy(dtype=float), index=pd.Index(df["year"], name="year"), name="sunspots")
46
+
47
+
48
+ def load_tep(fault: int = 0, split: str = "test") -> pd.DataFrame:
49
+ """Tennessee Eastman process data (Downs and Vogel, 1993; Braatz data sets).
50
+
51
+ Parameters
52
+ ----------
53
+ fault : int
54
+ 0 (normal) or one of the faults in :data:`TEP_FAULTS`.
55
+ split : {"test", "train"}
56
+ ``"train"`` is available for normal operation only (500 samples); a test
57
+ set has 960 samples, the fault starting after sample 160.
58
+
59
+ Returns
60
+ -------
61
+ pandas.DataFrame
62
+ 52 columns ``XMEAS1``–``XMEAS41`` and ``XMV1``–``XMV11``; the attribute
63
+ ``df.attrs["fault_start"]`` gives the first faulty sample.
64
+ """
65
+ if split == "train":
66
+ if fault != 0:
67
+ raise ValueError("only the normal-operation training set is bundled")
68
+ df = _read("tep_d00.csv.gz")
69
+ df.attrs["fault_start"] = None
70
+ else:
71
+ if fault not in TEP_FAULTS:
72
+ raise ValueError(f"fault must be one of {sorted(TEP_FAULTS)}")
73
+ df = _read(f"tep_d{fault:02d}_te.csv.gz")
74
+ df.attrs["fault_start"] = None if fault == 0 else 160
75
+ df.index.name = "sample"
76
+ df.attrs["fault"] = fault
77
+ df.attrs["description"] = TEP_FAULTS[fault]
78
+ return df