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
@@ -0,0 +1,172 @@
1
+ """Limited penetrable visibility graphs (LPVG, LPHVG).
2
+
3
+ The limited penetrable variants tolerate up to :math:`\\rho` blocking
4
+ observations between two nodes (the *penetrable distance*). With
5
+ :math:`\\rho=0` they reduce to the natural and horizontal visibility graphs.
6
+ The tolerance makes the graphs robust to isolated noise spikes and links
7
+ observations over longer horizons. For a series of independent, identically
8
+ distributed continuous values the LPHVG has the exponential degree distribution
9
+
10
+ .. math::
11
+
12
+ P(k)=\\frac{1}{2\\rho+3}\\Bigl(\\frac{2\\rho+2}{2\\rho+3}\\Bigr)^{k-2\\rho-2},\\qquad k\\ge 2\\rho+2,
13
+
14
+ with mean degree :math:`4(\\rho+1)` (Wang et al., 2018).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import bisect
20
+ import heapq
21
+
22
+ import numpy as np
23
+
24
+ from ..core import VisibilityGraph, as_series
25
+
26
+ __all__ = ["limited_penetrable_visibility_graph", "lpvg", "limited_penetrable_hvg", "lphvg"]
27
+
28
+
29
+ def _lphvg_edges(y: np.ndarray, rho: int, max_span: int | None) -> np.ndarray:
30
+ n = y.size
31
+ ei: list[np.ndarray] = []
32
+ ej: list[np.ndarray] = []
33
+ for i in range(n - 1):
34
+ hi = n if max_span is None else min(n, i + max_span + 1)
35
+ seg = y[i + 1 : hi]
36
+ if seg.size == 0:
37
+ continue
38
+ ge = np.nonzero(seg >= y[i])[0]
39
+ # beyond the (rho+1)-th observation at least as high as y_i nothing is visible
40
+ stop = seg.size if ge.size <= rho else int(ge[rho]) + 1
41
+ seg = seg[:stop]
42
+ w = seg.size
43
+ if w <= 600:
44
+ # blockers of (i, i+1+q): earlier entries of seg >= min(y_i, seg[q])
45
+ thr = np.minimum(y[i], seg)
46
+ M = (seg[None, :] >= thr[:, None]) & np.tri(w, w, -1, dtype=bool)
47
+ blockers = M.sum(1)
48
+ q = np.nonzero(blockers <= rho)[0]
49
+ else:
50
+ q_list = []
51
+ srt: list[float] = []
52
+ for qq in range(w):
53
+ v = seg[qq]
54
+ m = min(y[i], v)
55
+ nb = len(srt) - bisect.bisect_left(srt, m)
56
+ if nb <= rho:
57
+ q_list.append(qq)
58
+ bisect.insort(srt, v)
59
+ q = np.asarray(q_list, dtype=np.int64)
60
+ ei.append(np.full(q.size, i, dtype=np.int64))
61
+ ej.append(q + i + 1)
62
+ if not ei:
63
+ return np.empty((0, 2), dtype=np.int64)
64
+ return np.column_stack([np.concatenate(ei), np.concatenate(ej)])
65
+
66
+
67
+ def _lpvg_edges(y: np.ndarray, t: np.ndarray, rho: int, max_span: float | None) -> np.ndarray:
68
+ n = y.size
69
+ ei: list[int] = []
70
+ ej: list[int] = []
71
+ for i in range(n - 1):
72
+ stop = n if max_span is None else int(np.searchsorted(t, t[i] + max_span, side="right"))
73
+ s = ((y[i + 1 : stop] - y[i]) / (t[i + 1 : stop] - t[i])).tolist()
74
+ top: list[float] = [] # min-heap of the rho+1 largest slopes seen so far
75
+ for q, sq in enumerate(s):
76
+ # blockers are the earlier slopes >= sq; there are at most rho of them
77
+ # iff fewer than rho+1 slopes were seen or the smallest of the rho+1
78
+ # largest ones is below sq
79
+ if len(top) <= rho or sq > top[0]:
80
+ ei.append(i)
81
+ ej.append(i + 1 + q)
82
+ if len(top) <= rho:
83
+ heapq.heappush(top, sq)
84
+ elif sq > top[0]:
85
+ heapq.heapreplace(top, sq)
86
+ if not ei:
87
+ return np.empty((0, 2), dtype=np.int64)
88
+ return np.column_stack([np.asarray(ei, dtype=np.int64), np.asarray(ej, dtype=np.int64)])
89
+
90
+
91
+ def limited_penetrable_hvg(
92
+ y, t=None, *, rho: int = 1, max_span: int | None = None, directed: bool = False, labels=None, label_names=None
93
+ ) -> VisibilityGraph:
94
+ """Limited penetrable horizontal visibility graph (LPHVG).
95
+
96
+ Nodes :math:`i<j` are linked if at most :math:`\\rho` intermediate
97
+ observations satisfy :math:`y_k\\ge\\min(y_i,y_j)`.
98
+
99
+ Parameters
100
+ ----------
101
+ y, t : array_like
102
+ Series and optional time stamps.
103
+ rho : int
104
+ Penetrable distance :math:`\\rho\\ge0`; ``rho=0`` gives the HVG.
105
+ max_span : int, optional
106
+ Maximum index distance :math:`j-i` of an edge (speeds up long series).
107
+ directed, labels, label_names : optional
108
+ As for :func:`horizontal_visibility_graph`.
109
+
110
+ References
111
+ ----------
112
+ Zhou, T.-T., Jin, N.-D., Gao, Z.-K., Luo, Y.-B. (2012). Limited penetrable
113
+ visibility graph for establishing complex network from time series. Acta
114
+ Physica Sinica 61, 030506. Wang, M. et al. (2018). Exact results of the limited
115
+ penetrable horizontal visibility graph associated to random time series and its
116
+ application. Sci. Rep. 8, 5130.
117
+
118
+ Examples
119
+ --------
120
+ >>> import visibgraph as vg
121
+ >>> vg.lphvg([3, 1, 2, 0, 4], rho=1).n_edges > vg.hvg([3, 1, 2, 0, 4]).n_edges
122
+ True
123
+ """
124
+ if rho < 0:
125
+ raise ValueError("rho must be non-negative")
126
+ ys, ts, index = as_series(y, t)
127
+ e = _lphvg_edges(ys, int(rho), max_span)
128
+ return VisibilityGraph(
129
+ ys, e, ts, kind="lphvg", directed=directed, labels=labels, label_names=label_names,
130
+ params={"rho": int(rho), **({"max_span": max_span} if max_span else {})}, index=index,
131
+ )
132
+
133
+
134
+ def limited_penetrable_visibility_graph(
135
+ y, t=None, *, rho: int = 1, max_span: float | None = None, directed: bool = False, labels=None, label_names=None
136
+ ) -> VisibilityGraph:
137
+ """Limited penetrable (natural) visibility graph (LPVG).
138
+
139
+ Nodes :math:`i<j` are linked if at most :math:`\\rho` intermediate
140
+ observations lie on or above the line joining them. Seen from node
141
+ :math:`i` this means that fewer than :math:`\\rho+1` intermediate slopes are
142
+ at least as large as the slope to :math:`j`; the algorithm keeps the
143
+ :math:`\\rho+1` largest slopes in a heap, :math:`O(N^2\\log\\rho)`.
144
+
145
+ Parameters
146
+ ----------
147
+ y, t : array_like
148
+ Series and optional time stamps.
149
+ rho : int
150
+ Penetrable distance; ``rho=0`` gives the natural visibility graph.
151
+ max_span : float, optional
152
+ Maximum time distance of an edge.
153
+
154
+ References
155
+ ----------
156
+ Zhou, T.-T., Jin, N.-D., Gao, Z.-K., Luo, Y.-B. (2012). Acta Physica Sinica 61, 030506.
157
+ Gao, Z.-K., Cai, Q., Yang, Y.-X., Dang, W.-D., Zhang, S.-S. (2016). Multiscale limited
158
+ penetrable horizontal visibility graph for analyzing nonlinear time series.
159
+ Sci. Rep. 6, 35622.
160
+ """
161
+ if rho < 0:
162
+ raise ValueError("rho must be non-negative")
163
+ ys, ts, index = as_series(y, t)
164
+ e = _lpvg_edges(ys, ts, int(rho), max_span)
165
+ return VisibilityGraph(
166
+ ys, e, ts, kind="lpvg", directed=directed, labels=labels, label_names=label_names,
167
+ params={"rho": int(rho), **({"max_span": max_span} if max_span else {})}, index=index,
168
+ )
169
+
170
+
171
+ lphvg = limited_penetrable_hvg
172
+ lpvg = limited_penetrable_visibility_graph
@@ -0,0 +1,145 @@
1
+ """Visibility graphs of scalar fields and images (Lacasa and Iacovacci, 2017).
2
+
3
+ A two-dimensional field :math:`z_{ab}` (an image, a height map, a spatial
4
+ snapshot) maps to a graph on its pixels: two pixels on the same row, column or
5
+ (optionally) diagonal are linked if they see each other along that line under
6
+ the natural or horizontal visibility criterion. With ``directions=4`` the lines
7
+ are the rows and columns (:math:`\\mathrm{IVG}_4`), with ``directions=8`` the two
8
+ diagonals are added (:math:`\\mathrm{IVG}_8`). Each line is an ordinary series,
9
+ so for an uncorrelated random field every line contributes a mean degree close
10
+ to 4 in the horizontal version: about 8 for :math:`\\mathrm{IHVG}_4` and 16 for
11
+ :math:`\\mathrm{IHVG}_8` away from the borders.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import numpy as np
17
+
18
+ from .horizontal import hvg_edges
19
+ from .natural import _nvg_dc
20
+
21
+ __all__ = ["FieldVisibilityGraph", "image_visibility_graph"]
22
+
23
+
24
+ class FieldVisibilityGraph:
25
+ """Visibility graph of a 2-D field; nodes are pixels in row-major order.
26
+
27
+ Attributes
28
+ ----------
29
+ field : ndarray of shape (R, C)
30
+ edges : ndarray of shape (E, 2)
31
+ Pairs of flat pixel indices :math:`i<j`.
32
+ direction : ndarray of shape (E,)
33
+ 0 = row, 1 = column, 2 = main diagonal, 3 = anti-diagonal.
34
+ """
35
+
36
+ def __init__(self, field: np.ndarray, edges: np.ndarray, direction: np.ndarray, kind: str, directions: int):
37
+ self.field = field
38
+ self.edges = edges
39
+ self.direction = direction
40
+ self.kind = kind
41
+ self.directions = directions
42
+
43
+ def __repr__(self) -> str:
44
+ r, c = self.field.shape
45
+ return f"FieldVisibilityGraph({self.kind}, {r}x{c} pixels, {self.edges.shape[0]} edges, {self.directions} directions)"
46
+
47
+ @property
48
+ def shape(self) -> tuple[int, int]:
49
+ return self.field.shape
50
+
51
+ @property
52
+ def n_nodes(self) -> int:
53
+ return int(self.field.size)
54
+
55
+ @property
56
+ def n_edges(self) -> int:
57
+ return int(self.edges.shape[0])
58
+
59
+ def degree(self) -> np.ndarray:
60
+ """Degrees of the pixels (flat)."""
61
+ return np.bincount(self.edges.ravel(), minlength=self.n_nodes)
62
+
63
+ def degree_image(self) -> np.ndarray:
64
+ """Degrees arranged as the field, shape (R, C) — the *degree image*."""
65
+ return self.degree().reshape(self.field.shape)
66
+
67
+ def to_networkx(self):
68
+ """NetworkX graph with pixel coordinates ``row``, ``col`` and ``value``."""
69
+ import networkx as nx
70
+
71
+ G = nx.Graph(kind=self.kind, directions=self.directions)
72
+ R, C = self.field.shape
73
+ for p in range(self.n_nodes):
74
+ G.add_node(p, row=p // C, col=p % C, value=float(self.field.flat[p]))
75
+ for (i, j), d in zip(self.edges.tolist(), self.direction.tolist()):
76
+ G.add_edge(i, j, direction=int(d))
77
+ return G
78
+
79
+
80
+ def _line_edges(vals: np.ndarray, kind: str) -> np.ndarray:
81
+ if vals.size < 2:
82
+ return np.empty((0, 2), dtype=np.int64)
83
+ if kind == "hvg":
84
+ return hvg_edges(vals)
85
+ return _nvg_dc(vals, np.arange(vals.size, dtype=float))
86
+
87
+
88
+ def image_visibility_graph(Z, *, kind: str = "hvg", directions: int = 4) -> FieldVisibilityGraph:
89
+ """Visibility graph of a two-dimensional field or gray-scale image.
90
+
91
+ Parameters
92
+ ----------
93
+ Z : array_like of shape (R, C)
94
+ The field.
95
+ kind : {"hvg", "nvg"}
96
+ Horizontal or natural visibility along each line.
97
+ directions : {4, 8}
98
+ Rows and columns, or rows, columns and both diagonals.
99
+
100
+ References
101
+ ----------
102
+ Lacasa, L., Iacovacci, J. (2017). Visibility graphs of random scalar fields and
103
+ spatial data. Phys. Rev. E 96, 012318. Iacovacci, J., Lacasa, L. (2020). Visibility
104
+ graphs for image processing. IEEE Trans. Pattern Anal. Mach. Intell. 42, 974–987.
105
+
106
+ Examples
107
+ --------
108
+ >>> import numpy as np, visibgraph as vg
109
+ >>> F = vg.image_visibility_graph(np.random.default_rng(1).random((60, 60)))
110
+ >>> 7.0 < float(F.degree_image()[10:-10, 10:-10].mean()) < 8.5
111
+ True
112
+ """
113
+ if directions not in (4, 8):
114
+ raise ValueError("directions must be 4 or 8")
115
+ if kind not in ("hvg", "nvg"):
116
+ raise ValueError("kind must be 'hvg' or 'nvg'")
117
+ Z = np.asarray(Z, dtype=float)
118
+ if Z.ndim != 2:
119
+ raise ValueError("Z must be two-dimensional")
120
+ R, C = Z.shape
121
+ idx = np.arange(R * C).reshape(R, C)
122
+ blocks, dirs = [], []
123
+
124
+ def add(line_idx: np.ndarray, d: int):
125
+ e = _line_edges(Z.flat[line_idx], kind)
126
+ if e.size:
127
+ blocks.append(np.column_stack([line_idx[e[:, 0]], line_idx[e[:, 1]]]))
128
+ dirs.append(np.full(e.shape[0], d))
129
+
130
+ for r in range(R):
131
+ add(idx[r], 0)
132
+ for c in range(C):
133
+ add(idx[:, c], 1)
134
+ if directions == 8:
135
+ for off in range(-(R - 1), C):
136
+ add(np.diagonal(idx, offset=off), 2)
137
+ add(np.diagonal(idx[:, ::-1], offset=off), 3)
138
+ if blocks:
139
+ E = np.vstack(blocks)
140
+ D = np.concatenate(dirs)
141
+ lo, hi = np.minimum(E[:, 0], E[:, 1]), np.maximum(E[:, 0], E[:, 1])
142
+ E = np.column_stack([lo, hi])
143
+ else:
144
+ E, D = np.empty((0, 2), dtype=np.int64), np.empty(0, dtype=np.int64)
145
+ return FieldVisibilityGraph(Z, E, D, kind=f"i{kind}", directions=directions)
@@ -0,0 +1,152 @@
1
+ """Derived members of the visibility graph family.
2
+
3
+ * :func:`parametric_visibility_graph` — the natural visibility graph restricted
4
+ to edges whose *view angle* is below a threshold (Bezsudnov and Snarskii, 2014);
5
+ * :func:`difference_visibility_graph` — natural minus horizontal visibility
6
+ edges (Zhu, Li and Wen, 2014): the links that need a sloping line of sight;
7
+ * :func:`bottom_visibility_graph` — visibility from below (the graph of
8
+ :math:`-y`), which sees the troughs instead of the peaks;
9
+ * :func:`dual_perspective_visibility_graph` — the union of the top and bottom
10
+ graphs (Zheng et al., 2021), sensitive to peaks and pits at the same time.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import numpy as np
16
+
17
+ from ..core import VisibilityGraph, as_series
18
+ from .horizontal import horizontal_visibility_graph
19
+ from .natural import natural_visibility_graph
20
+ from .penetrable import limited_penetrable_hvg, limited_penetrable_visibility_graph
21
+
22
+ __all__ = [
23
+ "parametric_visibility_graph",
24
+ "pnvg",
25
+ "difference_visibility_graph",
26
+ "bottom_visibility_graph",
27
+ "dual_perspective_visibility_graph",
28
+ "visibility_graph",
29
+ "KINDS",
30
+ ]
31
+
32
+
33
+ def parametric_visibility_graph(y, t=None, *, alpha: float = np.pi / 2, directed: bool = True, **kw) -> VisibilityGraph:
34
+ """Parametric natural visibility graph PNVG(:math:`\\alpha`).
35
+
36
+ The natural visibility edges are oriented in the direction of time and
37
+ kept if their view angle, the angle between the edge and the downward
38
+ vertical, :math:`\\theta_{ij}=\\pi/2+\\arctan\\frac{y_j-y_i}{t_j-t_i}`, is
39
+ smaller than :math:`\\alpha`. ``alpha=pi`` recovers the NVG, ``alpha=pi/2``
40
+ keeps the descending lines of sight only. Unlike the NVG, the PNVG need not
41
+ be connected; the number of its components as a function of :math:`\\alpha`
42
+ characterizes the series.
43
+
44
+ References
45
+ ----------
46
+ Bezsudnov, I. V., Snarskii, A. A. (2014). From the time series to the complex
47
+ networks: The parametric natural visibility graph. Physica A 414, 53–60.
48
+ """
49
+ G = natural_visibility_graph(y, t, directed=directed, **kw)
50
+ theta = G.weight("view_angle")
51
+ H = G.filter_edges(theta < alpha, kind="pnvg")
52
+ H.params["alpha"] = float(alpha)
53
+ return H
54
+
55
+
56
+ pnvg = parametric_visibility_graph
57
+
58
+
59
+ def difference_visibility_graph(y, t=None, **kw) -> VisibilityGraph:
60
+ """Difference visibility graph: edges of the NVG that are not in the HVG.
61
+
62
+ Because the HVG is a subgraph of the NVG, the difference keeps exactly the
63
+ lines of sight that are not horizontal-feasible; its degree sequence was
64
+ proposed as a noise-robust feature of EEG epochs.
65
+
66
+ References
67
+ ----------
68
+ Zhu, G., Li, Y., Wen, P. (2014). Analysis and classification of sleep stages based
69
+ on difference visibility graphs from a single-channel EEG signal. IEEE J. Biomed.
70
+ Health Inform. 18, 1813–1821.
71
+ """
72
+ G = natural_visibility_graph(y, t, **kw)
73
+ H = horizontal_visibility_graph(y, t)
74
+ return G.difference(H, kind="dvg")
75
+
76
+
77
+ def bottom_visibility_graph(y, t=None, *, kind: str = "nvg", **kw) -> VisibilityGraph:
78
+ """Visibility graph seen from below: the graph of :math:`-y` drawn on :math:`y`.
79
+
80
+ Peaks dominate the ordinary (top) visibility graph, troughs dominate the
81
+ bottom one; comparing the two quantifies peak–pit asymmetry.
82
+ """
83
+ ys, ts, index = as_series(y, t)
84
+ G = visibility_graph(-ys, ts, kind=kind, **kw)
85
+ B = VisibilityGraph(ys, G.edges, ts, kind=f"bottom-{kind}", directed=G.directed, params=G.params, index=index)
86
+ if G.labels is not None:
87
+ B.set_labels(G.labels, G.label_names)
88
+ return B
89
+
90
+
91
+ def dual_perspective_visibility_graph(y, t=None, *, kind: str = "nvg", **kw) -> VisibilityGraph:
92
+ """Union of the top and bottom visibility graphs.
93
+
94
+ The edge attribute ``perspective`` (in ``G.params["edge_attributes"]``)
95
+ is 1 for top-only, -1 for bottom-only and 0 for edges seen from both sides
96
+ (only adjacent observations can be seen from both sides).
97
+
98
+ References
99
+ ----------
100
+ Zheng, M., Domanskyi, S., Piermarocchi, C., Mias, G. I. (2021). Visibility graph
101
+ based temporal community detection with applications in biological time series.
102
+ Sci. Rep. 11, 5623.
103
+ """
104
+ top = visibility_graph(y, t, kind=kind, **kw)
105
+ bot = bottom_visibility_graph(y, t, kind=kind, **kw)
106
+ U = top.union(bot, kind=f"dual-{kind}")
107
+ tset = {tuple(r) for r in top.edges.tolist()}
108
+ bset = {tuple(r) for r in bot.edges.tolist()}
109
+ persp = np.array([(1 if tuple(r) in tset else 0) - (1 if tuple(r) in bset else 0) for r in U.edges.tolist()], dtype=float)
110
+ U.params["edge_attributes"] = {"perspective": persp}
111
+ return U
112
+
113
+
114
+ #: builders accepted by :func:`visibility_graph`
115
+ KINDS = {
116
+ "nvg": natural_visibility_graph,
117
+ "hvg": horizontal_visibility_graph,
118
+ "lpvg": limited_penetrable_visibility_graph,
119
+ "lphvg": limited_penetrable_hvg,
120
+ "pnvg": parametric_visibility_graph,
121
+ "dvg": difference_visibility_graph,
122
+ }
123
+
124
+
125
+ def visibility_graph(y, t=None, *, kind: str = "nvg", **kw) -> VisibilityGraph:
126
+ """Build a visibility graph of any kind by name.
127
+
128
+ Parameters
129
+ ----------
130
+ y, t : array_like
131
+ Series and optional time stamps.
132
+ kind : str
133
+ ``"nvg"``, ``"hvg"``, ``"lpvg"``, ``"lphvg"``, ``"pnvg"``, ``"dvg"``,
134
+ ``"bottom-nvg"``, ``"bottom-hvg"``, ``"dual-nvg"`` or ``"dual-hvg"``.
135
+ **kw
136
+ Passed to the builder (``rho``, ``alpha``, ``max_span``, ``directed``,
137
+ ``labels``, ...).
138
+
139
+ Examples
140
+ --------
141
+ >>> import visibgraph as vg
142
+ >>> vg.visibility_graph([1, 3, 2, 4], kind="hvg")
143
+ VisibilityGraph(hvg, 4 nodes, 4 edges)
144
+ """
145
+ k = kind.lower()
146
+ if k.startswith("bottom-"):
147
+ return bottom_visibility_graph(y, t, kind=k[7:], **kw)
148
+ if k.startswith("dual-"):
149
+ return dual_perspective_visibility_graph(y, t, kind=k[5:], **kw)
150
+ if k not in KINDS:
151
+ raise ValueError(f"unknown kind {kind!r}; choose from {sorted(KINDS)} or bottom-/dual- variants")
152
+ return KINDS[k](y, t, **kw)
@@ -0,0 +1,128 @@
1
+ """Sliding-window and streaming construction.
2
+
3
+ Because every visibility criterion is *hereditary* (the visibility of two nodes
4
+ depends only on the observations between them), the graph of a window of
5
+ consecutive observations is the induced subgraph of the global graph. A long
6
+ series therefore needs one global construction; the window graphs are cut out
7
+ of it (:func:`window_graphs`). :class:`OnlineHVG` updates a horizontal
8
+ visibility graph observation by observation in amortized constant time, which
9
+ suits monitoring applications.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterator
15
+
16
+ import numpy as np
17
+
18
+ from ..core import VisibilityGraph, as_series
19
+ from .variants import visibility_graph
20
+
21
+ __all__ = ["sliding_windows", "window_graphs", "OnlineHVG"]
22
+
23
+
24
+ def sliding_windows(n: int, width: int, step: int = 1, *, drop_last: bool = True) -> list[tuple[int, int]]:
25
+ """Start and stop indices of windows of ``width`` observations, moved by ``step``.
26
+
27
+ >>> sliding_windows(10, 4, 3)
28
+ [(0, 4), (3, 7), (6, 10)]
29
+ """
30
+ if width < 2:
31
+ raise ValueError("width must be at least 2")
32
+ out = [(s, s + width) for s in range(0, n - width + 1, step)]
33
+ if not drop_last and out and out[-1][1] < n:
34
+ out.append((n - width, n))
35
+ return out
36
+
37
+
38
+ def window_graphs(
39
+ y, t=None, *, width: int, step: int = 1, kind: str = "hvg", labels=None, label_names=None, graph: VisibilityGraph | None = None, **kw
40
+ ) -> Iterator[tuple[int, int, VisibilityGraph]]:
41
+ """Yield ``(start, stop, G_window)`` for sliding windows of the series.
42
+
43
+ The global graph is built once (or passed as ``graph``) and every window
44
+ graph is its induced subgraph, which is exact for all hereditary kinds.
45
+ """
46
+ G = graph if graph is not None else visibility_graph(y, t, kind=kind, labels=labels, label_names=label_names, **kw)
47
+ for s, e in sliding_windows(G.n_nodes, width, step):
48
+ yield s, e, G.window(s, e)
49
+
50
+
51
+ class OnlineHVG:
52
+ """Horizontal visibility graph grown one observation at a time.
53
+
54
+ The stack of the :math:`O(N)` construction is kept between updates: a new
55
+ observation pops the lower observations it can see and links to the first
56
+ one at least as high. Each update returns the new edges; the amortized cost
57
+ per observation is constant.
58
+
59
+ Parameters
60
+ ----------
61
+ max_history : int, optional
62
+ Forget edges older than this many observations (bounded memory); the
63
+ stack itself is always exact.
64
+
65
+ Examples
66
+ --------
67
+ >>> from visibgraph.construct import OnlineHVG
68
+ >>> h = OnlineHVG()
69
+ >>> for v in [3, 1, 2, 4]:
70
+ ... _ = h.append(v)
71
+ >>> h.graph().edges.tolist()
72
+ [[0, 1], [0, 2], [0, 3], [1, 2], [2, 3]]
73
+ """
74
+
75
+ def __init__(self, max_history: int | None = None):
76
+ self.max_history = max_history
77
+ self._y: list[float] = []
78
+ self._t: list[float] = []
79
+ self._stack: list[int] = []
80
+ self._edges: list[tuple[int, int]] = []
81
+ self._deg: list[int] = []
82
+
83
+ def __len__(self) -> int:
84
+ return len(self._y)
85
+
86
+ def append(self, value: float, time: float | None = None) -> list[tuple[int, int]]:
87
+ """Add an observation; return the edges ``(i, j)`` it creates (``j`` is the new node)."""
88
+ j = len(self._y)
89
+ v = float(value)
90
+ if not np.isfinite(v):
91
+ raise ValueError("observations must be finite")
92
+ self._y.append(v)
93
+ self._t.append(float(j if time is None else time))
94
+ self._deg.append(0)
95
+ new = []
96
+ st = self._stack
97
+ while st and self._y[st[-1]] < v:
98
+ new.append((st.pop(), j))
99
+ if st:
100
+ new.append((st[-1], j))
101
+ if self._y[st[-1]] == v:
102
+ st.pop()
103
+ st.append(j)
104
+ for i, _ in new:
105
+ self._deg[i] += 1
106
+ self._deg[j] = len(new)
107
+ self._edges.extend(new)
108
+ if self.max_history is not None:
109
+ cut = j - self.max_history
110
+ if self._edges and self._edges[0][0] < cut:
111
+ self._edges = [e for e in self._edges if e[0] >= cut]
112
+ return new
113
+
114
+ def extend(self, values) -> list[tuple[int, int]]:
115
+ """Append several observations; return all new edges."""
116
+ out = []
117
+ for v in values:
118
+ out.extend(self.append(v))
119
+ return out
120
+
121
+ def degree(self) -> np.ndarray:
122
+ """Current degrees of all nodes."""
123
+ return np.asarray(self._deg, dtype=np.int64)
124
+
125
+ def graph(self) -> VisibilityGraph:
126
+ """The current graph as a :class:`VisibilityGraph`."""
127
+ y, t, _ = as_series(self._y, self._t)
128
+ return VisibilityGraph(y, self._edges, t, kind="hvg", params={"online": True})