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/__init__.py ADDED
@@ -0,0 +1,136 @@
1
+ """visibgraph: visibility graphs of time series — construction, analysis, segmentation and visualization.
2
+
3
+ A visibility graph turns a series into a network: every observation is a node,
4
+ and two observations are linked if they "see" each other. visibgraph builds the
5
+ whole family of visibility graphs (natural, horizontal, directed, weighted,
6
+ limited penetrable, parametric, difference, dual-perspective, sliding-window,
7
+ online, multiplex and image visibility graphs), measures them (exact reference
8
+ distributions, exponents, irreversibility, motifs, global and node features,
9
+ surrogate tests), labels them with the zones of statistical process control
10
+ as proposed by Ferenczi, Kummer and Abonyi (2026), segments series through
11
+ them (including an exact contiguous-modularity dynamic program), and draws
12
+ them (sight lines, arc diagrams, visibility matrices, horizon and barrier
13
+ profiles, zone ladders, scalograms, dashboards). Graphs convert to NetworkX,
14
+ igraph, pandas and scikit-learn.
15
+ """
16
+
17
+ from . import accessor, construct, datasets, io, labelled, measures, ml, networks, segment, spc, surrogates, symbolic
18
+ from .construct import (
19
+ FieldVisibilityGraph,
20
+ MultiplexVisibilityGraph,
21
+ OnlineHVG,
22
+ bottom_visibility_graph,
23
+ difference_visibility_graph,
24
+ dual_perspective_visibility_graph,
25
+ horizontal_visibility_graph,
26
+ hvg,
27
+ image_visibility_graph,
28
+ limited_penetrable_hvg,
29
+ limited_penetrable_visibility_graph,
30
+ lphvg,
31
+ lpvg,
32
+ multiplex_visibility_graph,
33
+ natural_visibility_graph,
34
+ nvg,
35
+ parametric_visibility_graph,
36
+ pnvg,
37
+ sliding_windows,
38
+ visibility_graph,
39
+ window_graphs,
40
+ )
41
+ from .core import EDGE_WEIGHTS, VisibilityGraph
42
+ from .labelled import label_aggregated_graph, label_enrichment, label_visibility_matrix, state_transition_network
43
+ from .measures import (
44
+ cut_profile,
45
+ degree_distribution,
46
+ exponential_fit,
47
+ graph_features,
48
+ horizons,
49
+ hurst_exponent,
50
+ irreversibility,
51
+ motif_profile,
52
+ node_features,
53
+ power_law_fit,
54
+ )
55
+ from .segment import divergence_profile, modularity_segmentation, pelt, scalogram, segmentation_scores, window_features
56
+ from .spc import classify_we, nelson_rules, visibility_run_lengths, western_electric
57
+ from .surrogates import surrogate_test
58
+ from .symbolic import SPC_ZONES, Baseline, estimate_baseline, spc_zones
59
+
60
+ __version__ = "1.0"
61
+
62
+ __all__ = [
63
+ "EDGE_WEIGHTS",
64
+ "SPC_ZONES",
65
+ "Baseline",
66
+ "FieldVisibilityGraph",
67
+ "MultiplexVisibilityGraph",
68
+ "OnlineHVG",
69
+ "VisibilityGraph",
70
+ "__version__",
71
+ "accessor",
72
+ "bottom_visibility_graph",
73
+ "classify_we",
74
+ "construct",
75
+ "cut_profile",
76
+ "datasets",
77
+ "degree_distribution",
78
+ "difference_visibility_graph",
79
+ "divergence_profile",
80
+ "dual_perspective_visibility_graph",
81
+ "estimate_baseline",
82
+ "exponential_fit",
83
+ "graph_features",
84
+ "horizons",
85
+ "horizontal_visibility_graph",
86
+ "hurst_exponent",
87
+ "hvg",
88
+ "image_visibility_graph",
89
+ "io",
90
+ "irreversibility",
91
+ "label_aggregated_graph",
92
+ "label_enrichment",
93
+ "label_visibility_matrix",
94
+ "labelled",
95
+ "limited_penetrable_hvg",
96
+ "limited_penetrable_visibility_graph",
97
+ "lphvg",
98
+ "lpvg",
99
+ "measures",
100
+ "ml",
101
+ "modularity_segmentation",
102
+ "motif_profile",
103
+ "multiplex_visibility_graph",
104
+ "natural_visibility_graph",
105
+ "nelson_rules",
106
+ "networks",
107
+ "node_features",
108
+ "nvg",
109
+ "parametric_visibility_graph",
110
+ "pelt",
111
+ "pnvg",
112
+ "power_law_fit",
113
+ "scalogram",
114
+ "segment",
115
+ "segmentation_scores",
116
+ "sliding_windows",
117
+ "spc",
118
+ "spc_zones",
119
+ "state_transition_network",
120
+ "surrogate_test",
121
+ "surrogates",
122
+ "symbolic",
123
+ "visibility_graph",
124
+ "visibility_run_lengths",
125
+ "western_electric",
126
+ "window_features",
127
+ "window_graphs",
128
+ ]
129
+
130
+
131
+ def __getattr__(name): # lazy import of the plotting modules (matplotlib, plotly)
132
+ if name in ("viz", "interactive"):
133
+ import importlib
134
+
135
+ return importlib.import_module(f".{name}", __name__)
136
+ raise AttributeError(f"module 'visibgraph' has no attribute {name!r}")
visibgraph/accessor.py ADDED
@@ -0,0 +1,64 @@
1
+ """pandas accessor: ``series.vg`` builds and analyzes visibility graphs of a Series.
2
+
3
+ Importing :mod:`visibgraph` registers the accessor::
4
+
5
+ import pandas as pd, visibgraph
6
+ s = pd.Series(values, index=pd.date_range("2026-01-01", periods=500, freq="h"))
7
+ G = s.vg.hvg() # VisibilityGraph with datetime-based time stamps
8
+ s.vg.features(kind="nvg") # dict of graph features
9
+ s.vg.zones() # SPC zones as a categorical Series
10
+ s.vg.window_features(width=50) # DataFrame indexed like the Series
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import pandas as pd
16
+
17
+ __all__ = ["VisibilityAccessor"]
18
+
19
+
20
+ @pd.api.extensions.register_series_accessor("vg")
21
+ class VisibilityAccessor:
22
+ """Visibility graphs of a :class:`pandas.Series` (``series.vg``)."""
23
+
24
+ def __init__(self, series: pd.Series):
25
+ self._s = series
26
+
27
+ def graph(self, kind: str = "nvg", **kw):
28
+ """:func:`visibgraph.visibility_graph` of the Series (index used as time axis)."""
29
+ from .construct import visibility_graph
30
+
31
+ return visibility_graph(self._s, kind=kind, **kw)
32
+
33
+ def nvg(self, **kw):
34
+ """Natural visibility graph."""
35
+ return self.graph("nvg", **kw)
36
+
37
+ def hvg(self, **kw):
38
+ """Horizontal visibility graph."""
39
+ return self.graph("hvg", **kw)
40
+
41
+ def degree(self, kind: str = "nvg", **kw) -> pd.Series:
42
+ """Degrees as a Series with the original index."""
43
+ return pd.Series(self.graph(kind, **kw).degree(), index=self._s.index, name="degree")
44
+
45
+ def features(self, kind: str = "hvg", features="paper", **kw) -> dict:
46
+ """:func:`visibgraph.graph_features` of the whole Series."""
47
+ from .measures import graph_features
48
+
49
+ return graph_features(self.graph(kind, **kw), features)
50
+
51
+ def zones(self, baseline=None, **kw) -> pd.Series:
52
+ """SPC zones as a categorical Series."""
53
+ from .symbolic import SPC_ZONES, spc_zones
54
+
55
+ codes = spc_zones(self._s.to_numpy(dtype=float), baseline, **kw)
56
+ return pd.Series(pd.Categorical.from_codes(codes, categories=list(SPC_ZONES.names)), index=self._s.index, name="zone")
57
+
58
+ def window_features(self, width: int, step: int = 1, kind: str = "hvg", **kw) -> pd.DataFrame:
59
+ """:func:`visibgraph.window_features`, indexed by the index label of each window's last point."""
60
+ from .segment import window_features
61
+
62
+ df = window_features(self._s.to_numpy(dtype=float), width=width, step=step, kind=kind, **kw)
63
+ df.index = self._s.index[df["stop"].to_numpy() - 1]
64
+ return df
@@ -0,0 +1,43 @@
1
+ """Builders of visibility graphs and of related series-to-network mappings."""
2
+
3
+ from .horizontal import horizontal_visibility_graph, hvg, hvg_edges
4
+ from .multivariate import MultiplexVisibilityGraph, multiplex_visibility_graph
5
+ from .natural import natural_visibility_graph, nvg
6
+ from .penetrable import limited_penetrable_hvg, limited_penetrable_visibility_graph, lphvg, lpvg
7
+ from .spatial import FieldVisibilityGraph, image_visibility_graph
8
+ from .variants import (
9
+ KINDS,
10
+ bottom_visibility_graph,
11
+ difference_visibility_graph,
12
+ dual_perspective_visibility_graph,
13
+ parametric_visibility_graph,
14
+ pnvg,
15
+ visibility_graph,
16
+ )
17
+ from .windows import OnlineHVG, sliding_windows, window_graphs
18
+
19
+ __all__ = [
20
+ "KINDS",
21
+ "FieldVisibilityGraph",
22
+ "MultiplexVisibilityGraph",
23
+ "OnlineHVG",
24
+ "bottom_visibility_graph",
25
+ "difference_visibility_graph",
26
+ "dual_perspective_visibility_graph",
27
+ "horizontal_visibility_graph",
28
+ "hvg",
29
+ "hvg_edges",
30
+ "image_visibility_graph",
31
+ "limited_penetrable_hvg",
32
+ "limited_penetrable_visibility_graph",
33
+ "lphvg",
34
+ "lpvg",
35
+ "multiplex_visibility_graph",
36
+ "natural_visibility_graph",
37
+ "nvg",
38
+ "parametric_visibility_graph",
39
+ "pnvg",
40
+ "sliding_windows",
41
+ "visibility_graph",
42
+ "window_graphs",
43
+ ]
@@ -0,0 +1,110 @@
1
+ """Horizontal visibility graphs (Luque et al., 2009).
2
+
3
+ Two observations see each other horizontally if every observation between them
4
+ is strictly lower than both,
5
+
6
+ .. math::
7
+
8
+ y_k < \\min(y_i, y_j)\\qquad \\forall\\,k:\\ i<k<j.
9
+
10
+ The horizontal visibility graph (HVG) is a subgraph of the natural one, depends
11
+ only on the order relations of the data (it is invariant under every strictly
12
+ increasing transformation of the values and does not depend on the time
13
+ stamps), and can be built in :math:`O(N)` time with a stack: each new
14
+ observation is linked to the stacked observations it overtops, and to the first
15
+ one that is at least as high, which then blocks the view further back.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+
22
+ from ..core import VisibilityGraph, as_series
23
+
24
+ __all__ = ["horizontal_visibility_graph", "hvg", "hvg_edges"]
25
+
26
+
27
+ def hvg_edges(y: np.ndarray, max_span: int | None = None) -> np.ndarray:
28
+ """Edges of the HVG of ``y`` (``(E, 2)`` array, :math:`i<j`) by the stack algorithm.
29
+
30
+ The number of edges is at most :math:`2N-3`; with ``max_span`` only edges with
31
+ :math:`j-i\\le` ``max_span`` are kept.
32
+ """
33
+ y = np.asarray(y, dtype=float)
34
+ n = y.size
35
+ ei: list[int] = []
36
+ ej: list[int] = []
37
+ stack: list[int] = []
38
+ yl = y.tolist()
39
+ for j in range(n):
40
+ v = yl[j]
41
+ while stack and yl[stack[-1]] < v:
42
+ ei.append(stack.pop())
43
+ ej.append(j)
44
+ if stack:
45
+ ei.append(stack[-1])
46
+ ej.append(j)
47
+ if yl[stack[-1]] == v:
48
+ stack.pop()
49
+ stack.append(j)
50
+ e = np.column_stack([np.asarray(ei, dtype=np.int64), np.asarray(ej, dtype=np.int64)]) if ei else np.empty((0, 2), dtype=np.int64)
51
+ if max_span is not None:
52
+ e = e[(e[:, 1] - e[:, 0]) <= max_span]
53
+ return e
54
+
55
+
56
+ def horizontal_visibility_graph(
57
+ y,
58
+ t=None,
59
+ *,
60
+ max_span: float | None = None,
61
+ directed: bool = False,
62
+ labels=None,
63
+ label_names=None,
64
+ ) -> VisibilityGraph:
65
+ """Horizontal visibility graph (HVG) of a series.
66
+
67
+ Parameters
68
+ ----------
69
+ y : array_like or pandas.Series
70
+ The series.
71
+ t : array_like, optional
72
+ Time stamps; they do not change the edges of an HVG, but they are kept
73
+ for spans, plots and export.
74
+ max_span : float, optional
75
+ Keep only edges with :math:`t_j-t_i\\le` ``max_span``.
76
+ directed : bool
77
+ Return the directed HVG (DHVG): edges point forward in time; the in- and
78
+ out-degree distributions of the DHVG measure time irreversibility.
79
+ labels, label_names : optional
80
+ Node labels to attach, e.g. SPC zones (:func:`visibgraph.spc_zones`).
81
+
82
+ Notes
83
+ -----
84
+ Ties are resolved by the strict criterion: an intermediate observation equal
85
+ to the lower end point blocks the view. For a series of independent,
86
+ identically distributed continuous values the degree distribution is
87
+ :math:`P(k)=\\tfrac13(\\tfrac23)^{k-2}`, :math:`k\\ge2`, whatever the
88
+ distribution, and the mean degree tends to 4.
89
+
90
+ References
91
+ ----------
92
+ Luque, B., Lacasa, L., Ballesteros, F., Luque, J. (2009). Horizontal visibility
93
+ graphs: Exact results for random time series. Phys. Rev. E 80, 046103.
94
+
95
+ Examples
96
+ --------
97
+ >>> import visibgraph as vg
98
+ >>> vg.hvg([2, 1, 1, 3]).edges.tolist()
99
+ [[0, 1], [0, 3], [1, 2], [2, 3]]
100
+ """
101
+ ys, ts, index = as_series(y, t)
102
+ e = hvg_edges(ys)
103
+ params: dict = {}
104
+ if max_span is not None:
105
+ e = e[(ts[e[:, 1]] - ts[e[:, 0]]) <= max_span]
106
+ params["max_span"] = float(max_span)
107
+ return VisibilityGraph(ys, e, ts, kind="hvg", directed=directed, labels=labels, label_names=label_names, params=params, index=index)
108
+
109
+
110
+ hvg = horizontal_visibility_graph
@@ -0,0 +1,180 @@
1
+ """Multiplex visibility graphs of multivariate series (Lacasa, Nicosia and Latora, 2015).
2
+
3
+ An :math:`M`-variate series :math:`\\{y^{[\\alpha]}_t\\}` maps to an
4
+ :math:`M`-layer multiplex network on the same node set (the time points):
5
+ layer :math:`\\alpha` is the visibility graph of component :math:`\\alpha`.
6
+ Two scalar measures summarize the multiplex: the *average edge overlap*
7
+
8
+ .. math::
9
+
10
+ \\omega=\\frac{\\sum_{i<j}\\sum_\\alpha a^{[\\alpha]}_{ij}}{M\\sum_{i<j}\\bigl(1-\\prod_\\alpha(1-a^{[\\alpha]}_{ij})\\bigr)},
11
+
12
+ the expected fraction of layers that contain an edge present in at least one
13
+ layer, and the *interlayer mutual information* of the degree sequences of two
14
+ layers,
15
+
16
+ .. math::
17
+
18
+ I_{\\alpha\\beta}=\\sum_{k,k'}P(k^{[\\alpha]}=k,k^{[\\beta]}=k')\\log\\frac{P(k,k')}{P(k)P(k')},
19
+
20
+ whose average over the pairs of layers measures how strongly the components
21
+ co-structure.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from collections.abc import Sequence
27
+
28
+ import numpy as np
29
+ import pandas as pd
30
+
31
+ from ..core import VisibilityGraph
32
+ from .variants import visibility_graph
33
+
34
+ __all__ = ["MultiplexVisibilityGraph", "multiplex_visibility_graph"]
35
+
36
+
37
+ class MultiplexVisibilityGraph:
38
+ """Layers of visibility graphs on a common time axis.
39
+
40
+ Attributes
41
+ ----------
42
+ layers : list of VisibilityGraph
43
+ names : list of str
44
+ """
45
+
46
+ def __init__(self, layers: Sequence[VisibilityGraph], names: Sequence[str] | None = None):
47
+ if not layers:
48
+ raise ValueError("at least one layer is needed")
49
+ n = layers[0].n_nodes
50
+ if any(L.n_nodes != n for L in layers):
51
+ raise ValueError("all layers must have the same number of nodes")
52
+ self.layers = list(layers)
53
+ self.names = [str(s) for s in (names if names is not None else range(len(layers)))]
54
+
55
+ def __len__(self) -> int:
56
+ return len(self.layers)
57
+
58
+ def __repr__(self) -> str:
59
+ return f"MultiplexVisibilityGraph({len(self.layers)} layers, {self.n_nodes} nodes, kind={self.layers[0].kind})"
60
+
61
+ @property
62
+ def n_nodes(self) -> int:
63
+ return self.layers[0].n_nodes
64
+
65
+ def degrees(self) -> np.ndarray:
66
+ """Degree matrix of shape (M, N)."""
67
+ return np.vstack([L.degree() for L in self.layers])
68
+
69
+ def edge_overlap(self) -> float:
70
+ """Average edge overlap :math:`\\omega\\in[1/M,1]`."""
71
+ M = len(self.layers)
72
+ counts: dict[tuple[int, int], int] = {}
73
+ for L in self.layers:
74
+ for e in map(tuple, L.edges.tolist()):
75
+ counts[e] = counts.get(e, 0) + 1
76
+ if not counts:
77
+ return float("nan")
78
+ return float(sum(counts.values()) / (M * len(counts)))
79
+
80
+ def pairwise_overlap(self) -> pd.DataFrame:
81
+ """Jaccard overlap of the edge sets for every pair of layers."""
82
+ sets = [{tuple(r) for r in L.edges.tolist()} for L in self.layers]
83
+ M = len(sets)
84
+ J = np.ones((M, M))
85
+ for a in range(M):
86
+ for b in range(a + 1, M):
87
+ u = len(sets[a] | sets[b])
88
+ J[a, b] = J[b, a] = len(sets[a] & sets[b]) / u if u else np.nan
89
+ return pd.DataFrame(J, index=self.names, columns=self.names)
90
+
91
+ def interlayer_mutual_information(self, base: float = 2.0) -> pd.DataFrame:
92
+ """Matrix of interlayer mutual information of the degree sequences (bits by default)."""
93
+ K = self.degrees()
94
+ M = K.shape[0]
95
+ I = np.zeros((M, M))
96
+ for a in range(M):
97
+ for b in range(a, M):
98
+ I[a, b] = I[b, a] = _mutual_information(K[a], K[b], base)
99
+ return pd.DataFrame(I, index=self.names, columns=self.names)
100
+
101
+ def mean_mutual_information(self, base: float = 2.0) -> float:
102
+ """Average :math:`I_{\\alpha\\beta}` over the pairs of distinct layers."""
103
+ I = self.interlayer_mutual_information(base).to_numpy()
104
+ M = I.shape[0]
105
+ if M < 2:
106
+ return float("nan")
107
+ return float(I[np.triu_indices(M, 1)].mean())
108
+
109
+ def layer_graph(self, base: float = 2.0):
110
+ """Weighted NetworkX graph of the layers, edge weight = interlayer mutual information."""
111
+ import networkx as nx
112
+
113
+ I = self.interlayer_mutual_information(base)
114
+ G = nx.Graph()
115
+ for a in self.names:
116
+ G.add_node(a)
117
+ for x in range(len(self.names)):
118
+ for z in range(x + 1, len(self.names)):
119
+ G.add_edge(self.names[x], self.names[z], weight=float(I.iat[x, z]))
120
+ return G
121
+
122
+ def aggregate(self) -> VisibilityGraph:
123
+ """Graph of the edges present in at least one layer (on the first layer's series)."""
124
+ G = self.layers[0]
125
+ for L in self.layers[1:]:
126
+ G = G.union(L)
127
+ G.kind = f"aggregate-{self.layers[0].kind}"
128
+ return G
129
+
130
+ def window(self, start: int, stop: int) -> MultiplexVisibilityGraph:
131
+ """The multiplex of a window of consecutive time points."""
132
+ return MultiplexVisibilityGraph([L.window(start, stop) for L in self.layers], self.names)
133
+
134
+
135
+ def _mutual_information(a: np.ndarray, b: np.ndarray, base: float) -> float:
136
+ ua, ia = np.unique(a, return_inverse=True)
137
+ ub, ib = np.unique(b, return_inverse=True)
138
+ J = np.zeros((ua.size, ub.size))
139
+ np.add.at(J, (ia, ib), 1)
140
+ J /= J.sum()
141
+ pa, pb = J.sum(1, keepdims=True), J.sum(0, keepdims=True)
142
+ nz = J > 0
143
+ return float(np.sum(J[nz] * np.log(J[nz] / (pa @ pb)[nz])) / np.log(base))
144
+
145
+
146
+ def multiplex_visibility_graph(Y, t=None, *, kind: str = "hvg", names: Sequence[str] | None = None, **kw) -> MultiplexVisibilityGraph:
147
+ """Multiplex visibility graph of a multivariate series.
148
+
149
+ Parameters
150
+ ----------
151
+ Y : array_like of shape (N, M) or pandas.DataFrame
152
+ One column per component (variable).
153
+ kind : str
154
+ Visibility criterion of every layer (see :func:`visibility_graph`).
155
+ names : sequence of str, optional
156
+ Layer names; the DataFrame columns by default.
157
+
158
+ References
159
+ ----------
160
+ Lacasa, L., Nicosia, V., Latora, V. (2015). Network structure of multivariate time
161
+ series. Sci. Rep. 5, 15508.
162
+
163
+ Examples
164
+ --------
165
+ >>> import numpy as np, visibgraph as vg
166
+ >>> Y = np.random.default_rng(0).normal(size=(200, 3))
167
+ >>> M = vg.multiplex_visibility_graph(Y, kind="hvg")
168
+ >>> 1/3 <= M.edge_overlap() <= 1
169
+ True
170
+ """
171
+ if isinstance(Y, pd.DataFrame):
172
+ names = list(Y.columns) if names is None else names
173
+ if t is None and not isinstance(Y.index, pd.RangeIndex):
174
+ t = Y.index if pd.api.types.is_numeric_dtype(Y.index) else None
175
+ Y = Y.to_numpy(dtype=float)
176
+ Y = np.asarray(Y, dtype=float)
177
+ if Y.ndim == 1:
178
+ Y = Y[:, None]
179
+ layers = [visibility_graph(Y[:, a], t, kind=kind, **kw) for a in range(Y.shape[1])]
180
+ return MultiplexVisibilityGraph(layers, names)
@@ -0,0 +1,162 @@
1
+ """Natural visibility graphs (Lacasa et al., 2008).
2
+
3
+ Two observations :math:`(t_i,y_i)` and :math:`(t_j,y_j)`, :math:`i<j`, see each
4
+ other if every observation between them lies strictly below the straight line
5
+ joining them,
6
+
7
+ .. math::
8
+
9
+ y_k < y_i + (y_j-y_i)\\,\\frac{t_k-t_i}{t_j-t_i}\\qquad \\forall\\,k:\\ i<k<j.
10
+
11
+ Equivalently, seen from node :math:`i` the slope to :math:`j` exceeds the slope
12
+ to every intermediate node. Three algorithms are provided:
13
+
14
+ * ``"dc"`` — divide and conquer (Lan et al., 2015): the maximum of a segment
15
+ blocks every line across it, so the segment splits into two independent
16
+ halves after the visible neighbors of the maximum have been found;
17
+ :math:`O(N\\log N)` on average, :math:`O(N^2)` for monotone series;
18
+ * ``"scan"`` — for every node a vectorized running maximum of the slopes,
19
+ :math:`O(N^2)` but with NumPy speed, exact for any input;
20
+ * ``"naive"`` — the definition checked for every pair, :math:`O(N^3)`; for tests.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import numpy as np
26
+
27
+ from ..core import VisibilityGraph, as_series
28
+
29
+ __all__ = ["natural_visibility_graph", "nvg"]
30
+
31
+
32
+ def _visible_from(y0: float, t0: float, ys: np.ndarray, ts: np.ndarray) -> np.ndarray:
33
+ """Boolean mask: which of the points (ts, ys), ordered by distance from t0, see (t0, y0)."""
34
+ s = (ys - y0) / np.abs(ts - t0)
35
+ if s.size == 0:
36
+ return np.zeros(0, dtype=bool)
37
+ run = np.maximum.accumulate(s)
38
+ prev = np.empty_like(run)
39
+ prev[0] = -np.inf
40
+ prev[1:] = run[:-1]
41
+ return s > prev
42
+
43
+
44
+ def _nvg_scan(y: np.ndarray, t: np.ndarray, max_span: float | None) -> np.ndarray:
45
+ n = y.size
46
+ out = []
47
+ for i in range(n - 1):
48
+ stop = n if max_span is None else int(np.searchsorted(t, t[i] + max_span, side="right"))
49
+ if stop <= i + 1:
50
+ continue
51
+ vis = _visible_from(y[i], t[i], y[i + 1 : stop], t[i + 1 : stop])
52
+ j = np.nonzero(vis)[0] + i + 1
53
+ out.append(np.column_stack([np.full(j.size, i), j]))
54
+ return np.vstack(out) if out else np.empty((0, 2), dtype=np.int64)
55
+
56
+
57
+ def _nvg_dc(y: np.ndarray, t: np.ndarray) -> np.ndarray:
58
+ n = y.size
59
+ out = []
60
+ stack = [(0, n - 1)]
61
+ while stack:
62
+ lo, hi = stack.pop()
63
+ if hi <= lo:
64
+ continue
65
+ if hi == lo + 1:
66
+ out.append(np.array([[lo, hi]]))
67
+ continue
68
+ m = lo + int(np.argmax(y[lo : hi + 1]))
69
+ if m < hi:
70
+ vis = _visible_from(y[m], t[m], y[m + 1 : hi + 1], t[m + 1 : hi + 1])
71
+ j = np.nonzero(vis)[0] + m + 1
72
+ out.append(np.column_stack([np.full(j.size, m), j]))
73
+ stack.append((m + 1, hi))
74
+ if m > lo:
75
+ vis = _visible_from(y[m], t[m], y[lo:m][::-1], t[lo:m][::-1])
76
+ j = m - 1 - np.nonzero(vis)[0]
77
+ out.append(np.column_stack([j, np.full(j.size, m)]))
78
+ stack.append((lo, m - 1))
79
+ return np.vstack(out) if out else np.empty((0, 2), dtype=np.int64)
80
+
81
+
82
+ def _nvg_naive(y: np.ndarray, t: np.ndarray) -> np.ndarray:
83
+ n = y.size
84
+ out = []
85
+ for i in range(n - 1):
86
+ for j in range(i + 1, n):
87
+ k = np.arange(i + 1, j)
88
+ line = y[i] + (y[j] - y[i]) * (t[k] - t[i]) / (t[j] - t[i])
89
+ if np.all(y[k] < line):
90
+ out.append((i, j))
91
+ return np.array(out, dtype=np.int64).reshape(-1, 2)
92
+
93
+
94
+ def natural_visibility_graph(
95
+ y,
96
+ t=None,
97
+ *,
98
+ method: str = "auto",
99
+ max_span: float | None = None,
100
+ directed: bool = False,
101
+ labels=None,
102
+ label_names=None,
103
+ ) -> VisibilityGraph:
104
+ """Natural visibility graph (NVG) of a series.
105
+
106
+ Parameters
107
+ ----------
108
+ y : array_like or pandas.Series
109
+ The series :math:`y_1,\\dots,y_N`.
110
+ t : array_like, optional
111
+ Strictly increasing time stamps (irregular sampling is allowed); the
112
+ index positions by default, or the numeric/datetime index of a Series.
113
+ method : {"auto", "dc", "scan", "naive"}
114
+ Algorithm; ``"auto"`` uses divide and conquer.
115
+ max_span : float, optional
116
+ Keep only edges with :math:`t_j-t_i\\le` ``max_span`` (limited horizon).
117
+ The visibility criterion itself is unchanged.
118
+ directed : bool
119
+ Return the directed graph (edges point forward in time).
120
+ labels, label_names : optional
121
+ Node labels to attach (see :meth:`VisibilityGraph.set_labels`).
122
+
123
+ Returns
124
+ -------
125
+ VisibilityGraph
126
+
127
+ References
128
+ ----------
129
+ Lacasa, L., Luque, B., Ballesteros, F., Luque, J., Nuño, J. C. (2008).
130
+ From time series to complex networks: The visibility graph. PNAS 105, 4972–4975.
131
+ Lan, X., Mo, H., Chen, S., Liu, Q., Deng, Y. (2015). Fast transformation from
132
+ time series to visibility graphs. Chaos 25, 083105.
133
+
134
+ Examples
135
+ --------
136
+ >>> import visibgraph as vg
137
+ >>> G = vg.nvg([1, 3, 2, 4])
138
+ >>> G.edges.tolist()
139
+ [[0, 1], [1, 2], [1, 3], [2, 3]]
140
+ """
141
+ ys, ts, index = as_series(y, t)
142
+ if method == "auto":
143
+ method = "dc" if max_span is None else "scan"
144
+ if method == "dc":
145
+ e = _nvg_dc(ys, ts)
146
+ if max_span is not None:
147
+ e = e[(ts[e[:, 1]] - ts[e[:, 0]]) <= max_span]
148
+ elif method == "scan":
149
+ e = _nvg_scan(ys, ts, max_span)
150
+ elif method == "naive":
151
+ e = _nvg_naive(ys, ts)
152
+ if max_span is not None:
153
+ e = e[(ts[e[:, 1]] - ts[e[:, 0]]) <= max_span]
154
+ else:
155
+ raise ValueError(f"unknown method {method!r}")
156
+ params = {"method": method}
157
+ if max_span is not None:
158
+ params["max_span"] = float(max_span)
159
+ return VisibilityGraph(ys, e, ts, kind="nvg", directed=directed, labels=labels, label_names=label_names, params=params, index=index)
160
+
161
+
162
+ nvg = natural_visibility_graph