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.
- visibgraph/__init__.py +136 -0
- visibgraph/accessor.py +64 -0
- visibgraph/construct/__init__.py +43 -0
- visibgraph/construct/horizontal.py +110 -0
- visibgraph/construct/multivariate.py +180 -0
- visibgraph/construct/natural.py +162 -0
- visibgraph/construct/penetrable.py +172 -0
- visibgraph/construct/spatial.py +145 -0
- visibgraph/construct/variants.py +152 -0
- visibgraph/construct/windows.py +128 -0
- visibgraph/core.py +441 -0
- visibgraph/datasets/__init__.py +49 -0
- visibgraph/datasets/_bundled.py +78 -0
- visibgraph/datasets/benchmark.py +229 -0
- visibgraph/datasets/data/README.md +35 -0
- visibgraph/datasets/data/lynx.csv +115 -0
- visibgraph/datasets/data/nile.csv +101 -0
- visibgraph/datasets/data/sunspots.csv +290 -0
- visibgraph/datasets/data/tep_d00.csv.gz +0 -0
- visibgraph/datasets/data/tep_d00_te.csv.gz +0 -0
- visibgraph/datasets/data/tep_d01_te.csv.gz +0 -0
- visibgraph/datasets/data/tep_d04_te.csv.gz +0 -0
- visibgraph/datasets/data/tep_d05_te.csv.gz +0 -0
- visibgraph/datasets/data/tep_d06_te.csv.gz +0 -0
- visibgraph/datasets/data/tep_d11_te.csv.gz +0 -0
- visibgraph/datasets/generators.py +216 -0
- visibgraph/interactive.py +84 -0
- visibgraph/io.py +153 -0
- visibgraph/labelled.py +263 -0
- visibgraph/measures.py +586 -0
- visibgraph/ml.py +179 -0
- visibgraph/networks.py +142 -0
- visibgraph/segment.py +642 -0
- visibgraph/spc.py +267 -0
- visibgraph/surrogates.py +147 -0
- visibgraph/symbolic.py +226 -0
- visibgraph/viz/__init__.py +62 -0
- visibgraph/viz/_style.py +92 -0
- visibgraph/viz/arcs.py +175 -0
- visibgraph/viz/distributions.py +202 -0
- visibgraph/viz/graphs.py +175 -0
- visibgraph/viz/multi.py +84 -0
- visibgraph/viz/series.py +223 -0
- visibgraph-1.0.dist-info/METADATA +181 -0
- visibgraph-1.0.dist-info/RECORD +47 -0
- visibgraph-1.0.dist-info/WHEEL +4 -0
- visibgraph-1.0.dist-info/licenses/LICENSE +21 -0
visibgraph/measures.py
ADDED
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
"""Measures of visibility graphs and what they reveal about the series.
|
|
2
|
+
|
|
3
|
+
The functions fall into five groups:
|
|
4
|
+
|
|
5
|
+
* **degree statistics** — degree distributions, the exact distributions of
|
|
6
|
+
uncorrelated series, exponential and power-law fits, the Hurst exponent;
|
|
7
|
+
* **time irreversibility** — divergence of the in- and out-degree distributions
|
|
8
|
+
of the directed graph (Lacasa et al., 2012);
|
|
9
|
+
* **motifs** — sequential visibility-graph motifs (Iacovacci and Lacasa, 2016)
|
|
10
|
+
with their exact probabilities for uncorrelated series;
|
|
11
|
+
* **global and node features** — the network measures used by Ferenczi,
|
|
12
|
+
Kummer and Abonyi (2026) and an extended set, node tables, visibility
|
|
13
|
+
horizons and the cut (barrier) profile;
|
|
14
|
+
* **distances** — dissimilarities of series through their graphs.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from collections.abc import Iterable, Sequence
|
|
20
|
+
from itertools import permutations
|
|
21
|
+
from math import factorial
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import pandas as pd
|
|
25
|
+
|
|
26
|
+
from .construct.horizontal import hvg_edges
|
|
27
|
+
from .construct.natural import _nvg_dc
|
|
28
|
+
from .construct.variants import visibility_graph
|
|
29
|
+
from .core import VisibilityGraph
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"degree_distribution",
|
|
33
|
+
"hvg_iid_distribution",
|
|
34
|
+
"dhvg_iid_distribution",
|
|
35
|
+
"lphvg_iid_distribution",
|
|
36
|
+
"periodic_mean_degree",
|
|
37
|
+
"exponential_fit",
|
|
38
|
+
"power_law_fit",
|
|
39
|
+
"hurst_exponent",
|
|
40
|
+
"irreversibility",
|
|
41
|
+
"motif_profile",
|
|
42
|
+
"iid_motif_profile",
|
|
43
|
+
"motif_names",
|
|
44
|
+
"graph_features",
|
|
45
|
+
"PAPER_FEATURES",
|
|
46
|
+
"EXTENDED_FEATURES",
|
|
47
|
+
"node_features",
|
|
48
|
+
"horizons",
|
|
49
|
+
"cut_profile",
|
|
50
|
+
"degree_entropy",
|
|
51
|
+
"distribution_divergence",
|
|
52
|
+
"graph_distance",
|
|
53
|
+
"distance_matrix",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ---------------------------------------------------------------- degrees
|
|
58
|
+
def _degrees(G, which: str = "total") -> np.ndarray:
|
|
59
|
+
if isinstance(G, VisibilityGraph):
|
|
60
|
+
return {"total": G.degree, "in": G.in_degree, "out": G.out_degree}[which]()
|
|
61
|
+
return np.asarray(G, dtype=np.int64)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def degree_distribution(G: VisibilityGraph | np.ndarray, which: str = "total", kmax: int | None = None) -> tuple[np.ndarray, np.ndarray]:
|
|
65
|
+
"""Empirical degree distribution :math:`P(k)`.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
G : VisibilityGraph or array of degrees
|
|
70
|
+
which : {"total", "in", "out"}
|
|
71
|
+
Total degree, links to the past or links to the future.
|
|
72
|
+
kmax : int, optional
|
|
73
|
+
Largest degree reported (default: the maximum observed).
|
|
74
|
+
|
|
75
|
+
Returns
|
|
76
|
+
-------
|
|
77
|
+
k, p : ndarray
|
|
78
|
+
Degrees ``0..kmax`` and their relative frequencies.
|
|
79
|
+
"""
|
|
80
|
+
k = _degrees(G, which)
|
|
81
|
+
kmax = int(k.max()) if kmax is None else int(kmax)
|
|
82
|
+
c = np.bincount(np.minimum(k, kmax), minlength=kmax + 1).astype(float)
|
|
83
|
+
return np.arange(kmax + 1), c / max(c.sum(), 1)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def hvg_iid_distribution(k) -> np.ndarray:
|
|
87
|
+
"""Exact degree distribution of the HVG of an i.i.d. continuous series,
|
|
88
|
+
:math:`P(k)=\\frac13(\\frac23)^{k-2}` for :math:`k\\ge2` (Luque et al., 2009)."""
|
|
89
|
+
k = np.asarray(k, dtype=float)
|
|
90
|
+
return np.where(k >= 2, (1 / 3) * (2 / 3) ** (k - 2), 0.0)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def dhvg_iid_distribution(k) -> np.ndarray:
|
|
94
|
+
"""In- and out-degree distribution of the directed HVG of an i.i.d. series,
|
|
95
|
+
:math:`P(k)=2^{-k}` for :math:`k\\ge1` (Lacasa et al., 2012)."""
|
|
96
|
+
k = np.asarray(k, dtype=float)
|
|
97
|
+
return np.where(k >= 1, 0.5**k, 0.0)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def lphvg_iid_distribution(k, rho: int = 1) -> np.ndarray:
|
|
101
|
+
"""Degree distribution of the LPHVG of an i.i.d. series (Wang et al., 2018),
|
|
102
|
+
:math:`P(k)=\\frac{1}{2\\rho+3}\\bigl(\\frac{2\\rho+2}{2\\rho+3}\\bigr)^{k-2\\rho-2}`, :math:`k\\ge2\\rho+2`."""
|
|
103
|
+
k = np.asarray(k, dtype=float)
|
|
104
|
+
k0 = 2 * rho + 2
|
|
105
|
+
return np.where(k >= k0, (1 / (2 * rho + 3)) * ((2 * rho + 2) / (2 * rho + 3)) ** (k - k0), 0.0)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def periodic_mean_degree(period: int) -> float:
|
|
109
|
+
"""Mean degree of the HVG of an infinite periodic series of period :math:`T`
|
|
110
|
+
without repeated values in a period, :math:`\\bar k=4(1-\\frac{1}{2T})` (Núñez et al., 2012).
|
|
111
|
+
|
|
112
|
+
>>> periodic_mean_degree(1), periodic_mean_degree(2)
|
|
113
|
+
(2.0, 3.0)
|
|
114
|
+
"""
|
|
115
|
+
return 4.0 * (1.0 - 1.0 / (2.0 * period))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def exponential_fit(G: VisibilityGraph | np.ndarray, kmin: int | None = None, which: str = "total") -> dict:
|
|
119
|
+
"""Maximum-likelihood exponent :math:`\\lambda` of an exponential (geometric) degree tail.
|
|
120
|
+
|
|
121
|
+
For :math:`P(k)\\propto e^{-\\lambda k}`, :math:`k\\ge k_{\\min}`, the estimate is
|
|
122
|
+
:math:`\\hat\\lambda=\\ln\\bigl(1+1/(\\bar k-k_{\\min})\\bigr)`, where :math:`\\bar k` is the
|
|
123
|
+
mean of the degrees :math:`\\ge k_{\\min}`. For the HVG of an i.i.d. series
|
|
124
|
+
:math:`\\lambda=\\ln(3/2)\\approx0.405` for every :math:`k_{\\min}` (the geometric law is
|
|
125
|
+
memoryless); correlated stochastic series give larger and chaotic series
|
|
126
|
+
smaller tail exponents (Luque et al., 2009; Lacasa and Toral, 2010).
|
|
127
|
+
|
|
128
|
+
Parameters
|
|
129
|
+
----------
|
|
130
|
+
kmin : int, optional
|
|
131
|
+
Start of the tail; by default one above the median degree.
|
|
132
|
+
|
|
133
|
+
Notes
|
|
134
|
+
-----
|
|
135
|
+
The tail must exclude the smallest degrees: the mean degree of the HVG of
|
|
136
|
+
*any* aperiodic series tends to 4, so the fit from :math:`k_{\\min}=2` returns
|
|
137
|
+
:math:`\\ln(3/2)` whatever the dynamics.
|
|
138
|
+
|
|
139
|
+
Returns
|
|
140
|
+
-------
|
|
141
|
+
dict
|
|
142
|
+
``lambda``, ``kmin``, ``n_tail`` and the standard error ``se``.
|
|
143
|
+
"""
|
|
144
|
+
k = _degrees(G, which).astype(float)
|
|
145
|
+
if kmin is None:
|
|
146
|
+
kmin = int(np.ceil(np.median(k))) + 1 if k.size else 0
|
|
147
|
+
tail = k[k >= kmin]
|
|
148
|
+
if tail.size == 0:
|
|
149
|
+
return {"lambda": np.nan, "kmin": kmin, "n_tail": 0, "se": np.nan}
|
|
150
|
+
m = tail.mean() - kmin
|
|
151
|
+
if m <= 0:
|
|
152
|
+
return {"lambda": np.inf, "kmin": kmin, "n_tail": int(tail.size), "se": np.nan}
|
|
153
|
+
q = m / (m + 1.0) # geometric ratio
|
|
154
|
+
lam = -np.log(q)
|
|
155
|
+
se = (1 - q) / np.sqrt(q * tail.size) # delta method (independent degrees)
|
|
156
|
+
return {"lambda": float(lam), "kmin": int(kmin), "n_tail": int(tail.size), "se": float(se)}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def power_law_fit(G: VisibilityGraph | np.ndarray, kmin: int | None = None, which: str = "total") -> dict:
|
|
160
|
+
"""Exponent :math:`\\gamma` of a power-law degree tail :math:`P(k)\\propto k^{-\\gamma}`.
|
|
161
|
+
|
|
162
|
+
Uses the discrete maximum-likelihood approximation
|
|
163
|
+
:math:`\\hat\\gamma=1+n\\bigl[\\sum\\ln\\frac{k_i}{k_{\\min}-1/2}\\bigr]^{-1}`; without
|
|
164
|
+
``kmin`` the lower cut-off minimizing the Kolmogorov–Smirnov distance is
|
|
165
|
+
chosen (Clauset, Shalizi and Newman, 2009).
|
|
166
|
+
|
|
167
|
+
Returns
|
|
168
|
+
-------
|
|
169
|
+
dict
|
|
170
|
+
``gamma``, ``kmin``, ``n_tail``, ``ks`` (KS distance) and ``se``.
|
|
171
|
+
"""
|
|
172
|
+
k = _degrees(G, which).astype(float)
|
|
173
|
+
k = k[k > 0]
|
|
174
|
+
|
|
175
|
+
def fit(km):
|
|
176
|
+
t = k[k >= km]
|
|
177
|
+
g = 1.0 + t.size / np.sum(np.log(t / (km - 0.5)))
|
|
178
|
+
return g, t
|
|
179
|
+
|
|
180
|
+
if kmin is None:
|
|
181
|
+
best = None
|
|
182
|
+
for km in np.unique(k[k <= np.quantile(k, 0.9)]):
|
|
183
|
+
g, t = fit(km)
|
|
184
|
+
if t.size < max(50, 0.05 * k.size):
|
|
185
|
+
break
|
|
186
|
+
ks_vals = np.sort(t)
|
|
187
|
+
emp = np.arange(1, t.size + 1) / t.size
|
|
188
|
+
model = 1 - ((ks_vals + 0.5) / (km - 0.5)) ** (1 - g)
|
|
189
|
+
ks = float(np.max(np.abs(emp - model)))
|
|
190
|
+
if best is None or ks < best[2]:
|
|
191
|
+
best = (km, g, ks, t.size)
|
|
192
|
+
if best is None:
|
|
193
|
+
return {"gamma": np.nan, "kmin": None, "n_tail": 0, "ks": np.nan, "se": np.nan}
|
|
194
|
+
km, g, ks, n = best
|
|
195
|
+
else:
|
|
196
|
+
km = kmin
|
|
197
|
+
g, t = fit(km)
|
|
198
|
+
n, ks = t.size, np.nan
|
|
199
|
+
return {"gamma": float(g), "kmin": int(km), "n_tail": int(n), "ks": ks, "se": float((g - 1) / np.sqrt(n))}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def hurst_exponent(y, process: str = "fbm", kmin: int | None = 10) -> dict:
|
|
203
|
+
"""Hurst exponent from the power-law tail of the natural visibility graph.
|
|
204
|
+
|
|
205
|
+
Lacasa et al. (2009) found :math:`\\gamma=3-2H` for fractional Brownian motion
|
|
206
|
+
and :math:`\\gamma=5-2H` for fractional Gaussian noise; the estimate inverts
|
|
207
|
+
these relations with the tail above ``kmin`` (10 by default; ``None``
|
|
208
|
+
selects it by the Kolmogorov–Smirnov criterion). It is a rough estimator
|
|
209
|
+
(finite-size effects, cut-off choice, strongly anti-persistent series) and
|
|
210
|
+
is best used to compare series of equal length.
|
|
211
|
+
|
|
212
|
+
Returns
|
|
213
|
+
-------
|
|
214
|
+
dict
|
|
215
|
+
``H``, ``gamma`` and the fit details.
|
|
216
|
+
"""
|
|
217
|
+
G = visibility_graph(y, kind="nvg")
|
|
218
|
+
fit = power_law_fit(G, kmin)
|
|
219
|
+
g = fit["gamma"]
|
|
220
|
+
H = (3 - g) / 2 if process == "fbm" else (5 - g) / 2
|
|
221
|
+
return {"H": float(H), **fit}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ---------------------------------------------------------- irreversibility
|
|
225
|
+
def distribution_divergence(p: np.ndarray, q: np.ndarray, statistic: str = "kld", base: float = np.e) -> float:
|
|
226
|
+
"""Divergence of two discrete distributions on the same support.
|
|
227
|
+
|
|
228
|
+
``"kld"``: Kullback–Leibler divergence :math:`\\sum p\\log(p/q)` over the
|
|
229
|
+
states where both are positive; ``"jsd"``: Jensen–Shannon divergence, finite
|
|
230
|
+
and symmetric; ``"tv"``: total variation distance.
|
|
231
|
+
"""
|
|
232
|
+
n = max(len(p), len(q))
|
|
233
|
+
p = np.pad(np.asarray(p, float), (0, n - len(p)))
|
|
234
|
+
q = np.pad(np.asarray(q, float), (0, n - len(q)))
|
|
235
|
+
p, q = p / p.sum(), q / q.sum()
|
|
236
|
+
if statistic == "kld":
|
|
237
|
+
m = (p > 0) & (q > 0)
|
|
238
|
+
return float(np.sum(p[m] * np.log(p[m] / q[m])) / np.log(base))
|
|
239
|
+
if statistic == "jsd":
|
|
240
|
+
mix = (p + q) / 2
|
|
241
|
+
|
|
242
|
+
def kl(a, b):
|
|
243
|
+
m = a > 0
|
|
244
|
+
return np.sum(a[m] * np.log(a[m] / b[m]))
|
|
245
|
+
|
|
246
|
+
return float((kl(p, mix) + kl(q, mix)) / 2 / np.log(base))
|
|
247
|
+
if statistic == "tv":
|
|
248
|
+
return float(0.5 * np.abs(p - q).sum())
|
|
249
|
+
raise ValueError(f"unknown statistic {statistic!r}")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def irreversibility(G_or_y, kind: str = "hvg", statistic: str = "kld") -> float:
|
|
253
|
+
"""Time irreversibility from the directed visibility graph.
|
|
254
|
+
|
|
255
|
+
The divergence between the out-degree (future links) and in-degree (past
|
|
256
|
+
links) distributions vanishes for time-reversible processes and is positive
|
|
257
|
+
for irreversible ones such as dissipative chaotic maps (Lacasa et al., 2012).
|
|
258
|
+
|
|
259
|
+
Parameters
|
|
260
|
+
----------
|
|
261
|
+
G_or_y : VisibilityGraph or array_like
|
|
262
|
+
A graph, or a series from which a graph of ``kind`` is built.
|
|
263
|
+
statistic : {"kld", "jsd", "tv"}
|
|
264
|
+
``"kld"`` is :math:`D[P_{\\mathrm{out}}\\Vert P_{\\mathrm{in}}]` over the common support.
|
|
265
|
+
"""
|
|
266
|
+
G = G_or_y if isinstance(G_or_y, VisibilityGraph) else visibility_graph(G_or_y, kind=kind)
|
|
267
|
+
kmax = int(max(G.in_degree().max(), G.out_degree().max()))
|
|
268
|
+
_, pin = degree_distribution(G, "in", kmax)
|
|
269
|
+
_, pout = degree_distribution(G, "out", kmax)
|
|
270
|
+
return distribution_divergence(pout, pin, statistic)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# ------------------------------------------------------------------ motifs
|
|
274
|
+
def _pairs(size: int) -> list[tuple[int, int]]:
|
|
275
|
+
return [(a, b) for a in range(size) for b in range(a + 2, size)]
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def motif_names(size: int = 4) -> list[str]:
|
|
279
|
+
"""Names of the sequential motifs of ``size`` nodes: the extra (non-consecutive) edges present.
|
|
280
|
+
|
|
281
|
+
>>> motif_names(3)
|
|
282
|
+
['-', '02']
|
|
283
|
+
"""
|
|
284
|
+
pairs = _pairs(size)
|
|
285
|
+
out = []
|
|
286
|
+
for mask in range(1 << len(pairs)):
|
|
287
|
+
present = [f"{a}{b}" for q, (a, b) in enumerate(pairs) if mask >> q & 1]
|
|
288
|
+
out.append(",".join(present) if present else "-")
|
|
289
|
+
return out
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _motif_codes(edges: np.ndarray, n: int, size: int) -> np.ndarray:
|
|
293
|
+
keys = np.sort(edges[:, 0].astype(np.int64) * n + edges[:, 1])
|
|
294
|
+
s = np.arange(n - size + 1, dtype=np.int64)
|
|
295
|
+
code = np.zeros(s.size, dtype=np.int64)
|
|
296
|
+
for q, (a, b) in enumerate(_pairs(size)):
|
|
297
|
+
cand = (s + a) * n + (s + b)
|
|
298
|
+
pos = np.searchsorted(keys, cand)
|
|
299
|
+
pos = np.minimum(pos, keys.size - 1)
|
|
300
|
+
code |= ((keys[pos] == cand) if keys.size else np.zeros(s.size, bool)).astype(np.int64) << q
|
|
301
|
+
return code
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def motif_profile(G: VisibilityGraph, size: int = 4) -> pd.Series:
|
|
305
|
+
"""Sequential visibility-graph motif profile.
|
|
306
|
+
|
|
307
|
+
Every run of ``size`` consecutive nodes induces a subgraph that always
|
|
308
|
+
contains the path of consecutive nodes; the *motif* is the set of the other
|
|
309
|
+
edges present. The profile is the relative frequency of every motif along
|
|
310
|
+
the series (Iacovacci and Lacasa, 2016). Sizes 3–5 are practical.
|
|
311
|
+
|
|
312
|
+
Returns
|
|
313
|
+
-------
|
|
314
|
+
pandas.Series
|
|
315
|
+
Index: motif names (:func:`motif_names`), values: frequencies.
|
|
316
|
+
"""
|
|
317
|
+
codes = _motif_codes(G.edges, G.n_nodes, size)
|
|
318
|
+
m = len(_pairs(size))
|
|
319
|
+
c = np.bincount(codes, minlength=1 << m).astype(float)
|
|
320
|
+
return pd.Series(c / max(c.sum(), 1), index=motif_names(size), name=f"{G.kind} motifs")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def iid_motif_profile(kind: str = "hvg", size: int = 4, *, n_samples: int = 200_000, random_state=0) -> pd.Series:
|
|
324
|
+
"""Motif probabilities of an i.i.d. series.
|
|
325
|
+
|
|
326
|
+
For the HVG the probabilities depend only on the order of the values and
|
|
327
|
+
are computed exactly by enumerating the :math:`n!` orderings. The NVG is not
|
|
328
|
+
order-invariant; its profile is estimated by simulation of uniform noise.
|
|
329
|
+
"""
|
|
330
|
+
m = len(_pairs(size))
|
|
331
|
+
c = np.zeros(1 << m)
|
|
332
|
+
if kind == "hvg":
|
|
333
|
+
for perm in permutations(range(size)):
|
|
334
|
+
e = hvg_edges(np.asarray(perm, float))
|
|
335
|
+
c[_motif_codes(e, size, size)[0]] += 1
|
|
336
|
+
c /= factorial(size)
|
|
337
|
+
else:
|
|
338
|
+
rng = np.random.default_rng(random_state)
|
|
339
|
+
y = rng.random(n_samples)
|
|
340
|
+
e = _nvg_dc(y, np.arange(y.size, dtype=float))
|
|
341
|
+
codes = _motif_codes(e, y.size, size)
|
|
342
|
+
c = np.bincount(codes, minlength=1 << m) / codes.size
|
|
343
|
+
return pd.Series(c, index=motif_names(size), name=f"iid {kind} motifs")
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# ------------------------------------------------------------ node measures
|
|
347
|
+
def horizons(G: VisibilityGraph, unit: str = "index") -> tuple[np.ndarray, np.ndarray]:
|
|
348
|
+
"""Visibility horizons: distance to the farthest visible neighbor in the past and in the future.
|
|
349
|
+
|
|
350
|
+
Returns
|
|
351
|
+
-------
|
|
352
|
+
left, right : ndarray
|
|
353
|
+
:math:`h^{\\leftarrow}_i=i-\\min\\{j:(j,i)\\in E\\}` and :math:`h^{\\rightarrow}_i=\\max\\{j:(i,j)\\in E\\}-i`
|
|
354
|
+
(0 if there is none); in time units with ``unit="time"``.
|
|
355
|
+
"""
|
|
356
|
+
n = G.n_nodes
|
|
357
|
+
lo = np.arange(n)
|
|
358
|
+
hi = np.arange(n)
|
|
359
|
+
i, j = G.edges[:, 0], G.edges[:, 1]
|
|
360
|
+
np.minimum.at(lo, j, i)
|
|
361
|
+
np.maximum.at(hi, i, j)
|
|
362
|
+
if unit == "time":
|
|
363
|
+
return G.t - G.t[lo], G.t[hi] - G.t
|
|
364
|
+
return (np.arange(n) - lo).astype(float), (hi - np.arange(n)).astype(float)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def cut_profile(G: VisibilityGraph, normalized: bool = False) -> np.ndarray:
|
|
368
|
+
"""Number of lines of sight that cross each gap between consecutive observations.
|
|
369
|
+
|
|
370
|
+
Entry :math:`c_t`, :math:`t=0..N-2`, counts the edges :math:`(i,j)` with
|
|
371
|
+
:math:`i\\le t<j`. A dominant peak blocks the view across it, so the profile
|
|
372
|
+
dips at *visibility barriers*; in the bottom graph it dips at deep troughs.
|
|
373
|
+
With ``normalized=True`` the counts are divided by the number of node
|
|
374
|
+
pairs across the gap, :math:`(t+1)(N-t-1)`.
|
|
375
|
+
"""
|
|
376
|
+
n = G.n_nodes
|
|
377
|
+
d = np.zeros(n + 1)
|
|
378
|
+
np.add.at(d, G.edges[:, 0], 1)
|
|
379
|
+
np.add.at(d, G.edges[:, 1], -1)
|
|
380
|
+
c = np.cumsum(d)[: n - 1]
|
|
381
|
+
if normalized:
|
|
382
|
+
t = np.arange(n - 1)
|
|
383
|
+
c = c / ((t + 1) * (n - t - 1))
|
|
384
|
+
return c
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def degree_entropy(G: VisibilityGraph | np.ndarray, which: str = "total", base: float = 2.0) -> float:
|
|
388
|
+
"""Shannon entropy of the degree distribution (bits by default)."""
|
|
389
|
+
_, p = degree_distribution(G, which)
|
|
390
|
+
p = p[p > 0]
|
|
391
|
+
return float(-(p * np.log(p)).sum() / np.log(base))
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def node_features(G: VisibilityGraph, betweenness: bool = False) -> pd.DataFrame:
|
|
395
|
+
"""Node table: value, degree, in/out degree, clustering, horizons, mean span, label.
|
|
396
|
+
|
|
397
|
+
The table is a feature matrix for node-level learning (e.g. classifying
|
|
398
|
+
observations) and the data behind the node-colored views of :mod:`visibgraph.viz`.
|
|
399
|
+
"""
|
|
400
|
+
import networkx as nx
|
|
401
|
+
|
|
402
|
+
df = G.node_frame()
|
|
403
|
+
H = G.to_networkx(weights=(), node_attributes=False)
|
|
404
|
+
Hu = H.to_undirected() if G.directed else H
|
|
405
|
+
df["clustering"] = np.array([nx.clustering(Hu, v) for v in range(G.n_nodes)])
|
|
406
|
+
left, right = horizons(G)
|
|
407
|
+
df["horizon_past"], df["horizon_future"] = left, right
|
|
408
|
+
sp = G.spans("index")
|
|
409
|
+
tot = np.zeros(G.n_nodes)
|
|
410
|
+
np.add.at(tot, G.edges[:, 0], sp)
|
|
411
|
+
np.add.at(tot, G.edges[:, 1], sp)
|
|
412
|
+
k = G.degree()
|
|
413
|
+
df["mean_span"] = np.divide(tot, k, out=np.zeros_like(tot), where=k > 0)
|
|
414
|
+
if betweenness:
|
|
415
|
+
b = nx.betweenness_centrality(Hu)
|
|
416
|
+
df["betweenness"] = [b[v] for v in range(G.n_nodes)]
|
|
417
|
+
return df
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# --------------------------------------------------------- global features
|
|
421
|
+
#: the structural measures of Ferenczi, Kummer and Abonyi (2026)
|
|
422
|
+
PAPER_FEATURES = (
|
|
423
|
+
"density",
|
|
424
|
+
"average_degree",
|
|
425
|
+
"diameter",
|
|
426
|
+
"n_communities",
|
|
427
|
+
"modularity",
|
|
428
|
+
"average_clustering",
|
|
429
|
+
"transitivity",
|
|
430
|
+
"assortativity",
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
#: further measures computed with ``features="all"``
|
|
434
|
+
EXTENDED_FEATURES = (
|
|
435
|
+
"max_degree",
|
|
436
|
+
"degree_std",
|
|
437
|
+
"degree_entropy",
|
|
438
|
+
"lambda",
|
|
439
|
+
"mean_span",
|
|
440
|
+
"max_span",
|
|
441
|
+
"average_path_length",
|
|
442
|
+
"n_articulation_points",
|
|
443
|
+
"irreversibility",
|
|
444
|
+
"mean_horizon",
|
|
445
|
+
"algebraic_connectivity",
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def graph_features(G: VisibilityGraph, features: str | Iterable[str] = "paper", *, community: str = "greedy",
|
|
450
|
+
random_state=0, prefix: str = "") -> dict:
|
|
451
|
+
"""Global structural features of a visibility graph.
|
|
452
|
+
|
|
453
|
+
Parameters
|
|
454
|
+
----------
|
|
455
|
+
G : VisibilityGraph
|
|
456
|
+
features : "paper", "all" or iterable of names
|
|
457
|
+
``"paper"`` = :data:`PAPER_FEATURES`; ``"all"`` adds :data:`EXTENDED_FEATURES`.
|
|
458
|
+
community : {"greedy", "louvain"}
|
|
459
|
+
Modularity maximization for ``n_communities`` and ``modularity``:
|
|
460
|
+
greedy agglomeration (deterministic) or Louvain (seeded by ``random_state``).
|
|
461
|
+
prefix : str
|
|
462
|
+
Prefix of the keys (useful when several graphs are combined).
|
|
463
|
+
|
|
464
|
+
Returns
|
|
465
|
+
-------
|
|
466
|
+
dict
|
|
467
|
+
Feature name → value (NaN where undefined, e.g. assortativity of a
|
|
468
|
+
regular graph).
|
|
469
|
+
|
|
470
|
+
Examples
|
|
471
|
+
--------
|
|
472
|
+
>>> import visibgraph as vg
|
|
473
|
+
>>> f = vg.graph_features(vg.hvg([1, 3, 2, 5, 1, 4, 2, 3]))
|
|
474
|
+
>>> sorted(f)[:3], round(f["average_degree"], 3)
|
|
475
|
+
(['assortativity', 'average_clustering', 'average_degree'], 2.5)
|
|
476
|
+
"""
|
|
477
|
+
import warnings
|
|
478
|
+
|
|
479
|
+
import networkx as nx
|
|
480
|
+
|
|
481
|
+
if features == "paper":
|
|
482
|
+
names = list(PAPER_FEATURES)
|
|
483
|
+
elif features == "all":
|
|
484
|
+
names = list(PAPER_FEATURES) + list(EXTENDED_FEATURES)
|
|
485
|
+
else:
|
|
486
|
+
names = list(features)
|
|
487
|
+
H = G.to_networkx(weights=(), node_attributes=False)
|
|
488
|
+
if G.directed:
|
|
489
|
+
H = H.to_undirected()
|
|
490
|
+
n, m = G.n_nodes, G.n_edges
|
|
491
|
+
k = G.degree()
|
|
492
|
+
out: dict = {}
|
|
493
|
+
comm = None
|
|
494
|
+
for f in names:
|
|
495
|
+
v = np.nan
|
|
496
|
+
if f == "density":
|
|
497
|
+
v = 2 * m / (n * (n - 1)) if n > 1 else np.nan
|
|
498
|
+
elif f == "average_degree":
|
|
499
|
+
v = 2 * m / n if n else np.nan
|
|
500
|
+
elif f == "diameter":
|
|
501
|
+
v = nx.diameter(H) if n > 1 and nx.is_connected(H) else np.nan
|
|
502
|
+
elif f in ("n_communities", "modularity"):
|
|
503
|
+
if comm is None and m > 0:
|
|
504
|
+
if community == "louvain":
|
|
505
|
+
comm = nx.community.louvain_communities(H, seed=random_state)
|
|
506
|
+
else:
|
|
507
|
+
comm = nx.community.greedy_modularity_communities(H)
|
|
508
|
+
if comm is not None:
|
|
509
|
+
v = len(comm) if f == "n_communities" else nx.community.modularity(H, comm)
|
|
510
|
+
elif f == "average_clustering":
|
|
511
|
+
v = nx.average_clustering(H)
|
|
512
|
+
elif f == "transitivity":
|
|
513
|
+
v = nx.transitivity(H)
|
|
514
|
+
elif f == "assortativity":
|
|
515
|
+
with warnings.catch_warnings():
|
|
516
|
+
warnings.simplefilter("ignore")
|
|
517
|
+
v = nx.degree_assortativity_coefficient(H) if m > 1 else np.nan
|
|
518
|
+
elif f == "max_degree":
|
|
519
|
+
v = int(k.max())
|
|
520
|
+
elif f == "degree_std":
|
|
521
|
+
v = float(k.std())
|
|
522
|
+
elif f == "degree_entropy":
|
|
523
|
+
v = degree_entropy(k)
|
|
524
|
+
elif f == "lambda":
|
|
525
|
+
v = exponential_fit(k)["lambda"]
|
|
526
|
+
elif f == "mean_span":
|
|
527
|
+
v = float(G.spans("index").mean()) if m else np.nan
|
|
528
|
+
elif f == "max_span":
|
|
529
|
+
v = float(G.spans("index").max()) if m else np.nan
|
|
530
|
+
elif f == "average_path_length":
|
|
531
|
+
v = nx.average_shortest_path_length(H) if n > 1 and nx.is_connected(H) else np.nan
|
|
532
|
+
elif f == "n_articulation_points":
|
|
533
|
+
v = len(list(nx.articulation_points(H)))
|
|
534
|
+
elif f == "irreversibility":
|
|
535
|
+
v = irreversibility(G, statistic="jsd")
|
|
536
|
+
elif f == "mean_horizon":
|
|
537
|
+
a, b = horizons(G)
|
|
538
|
+
v = float((a + b).mean())
|
|
539
|
+
elif f == "algebraic_connectivity":
|
|
540
|
+
L = G.laplacian()
|
|
541
|
+
ev = np.linalg.eigvalsh(L)
|
|
542
|
+
v = float(ev[1]) if n > 1 else np.nan
|
|
543
|
+
else:
|
|
544
|
+
raise ValueError(f"unknown feature {f!r}")
|
|
545
|
+
out[prefix + f] = float(v) if v is not None else np.nan
|
|
546
|
+
return out
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
# ---------------------------------------------------------------- distances
|
|
550
|
+
def graph_distance(G1: VisibilityGraph, G2: VisibilityGraph, method: str = "degree") -> float:
|
|
551
|
+
"""Dissimilarity of two series through their visibility graphs.
|
|
552
|
+
|
|
553
|
+
``"degree"``: Jensen–Shannon divergence of the degree distributions;
|
|
554
|
+
``"motif"``: Jensen–Shannon divergence of the size-4 motif profiles;
|
|
555
|
+
``"degree+motif"``: their mean. The graphs may have different sizes.
|
|
556
|
+
"""
|
|
557
|
+
if method == "degree":
|
|
558
|
+
_, p = degree_distribution(G1)
|
|
559
|
+
_, q = degree_distribution(G2)
|
|
560
|
+
return distribution_divergence(p, q, "jsd", base=2)
|
|
561
|
+
if method == "motif":
|
|
562
|
+
return distribution_divergence(motif_profile(G1).to_numpy(), motif_profile(G2).to_numpy(), "jsd", base=2)
|
|
563
|
+
if method == "degree+motif":
|
|
564
|
+
return 0.5 * (graph_distance(G1, G2, "degree") + graph_distance(G1, G2, "motif"))
|
|
565
|
+
raise ValueError(f"unknown method {method!r}")
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def distance_matrix(series: Sequence, kind: str = "hvg", method: str = "degree", **kw) -> np.ndarray:
|
|
569
|
+
"""Pairwise :func:`graph_distance` of a collection of series (rows of an array or a list)."""
|
|
570
|
+
graphs = [s if isinstance(s, VisibilityGraph) else visibility_graph(s, kind=kind, **kw) for s in series]
|
|
571
|
+
n = len(graphs)
|
|
572
|
+
D = np.zeros((n, n))
|
|
573
|
+
if method in ("degree", "motif"):
|
|
574
|
+
if method == "degree":
|
|
575
|
+
kmax = max(int(g.degree().max()) for g in graphs)
|
|
576
|
+
P = np.vstack([degree_distribution(g, kmax=kmax)[1] for g in graphs])
|
|
577
|
+
else:
|
|
578
|
+
P = np.vstack([motif_profile(g).to_numpy() for g in graphs])
|
|
579
|
+
for a in range(n):
|
|
580
|
+
for b in range(a + 1, n):
|
|
581
|
+
D[a, b] = D[b, a] = distribution_divergence(P[a], P[b], "jsd", base=2)
|
|
582
|
+
return D
|
|
583
|
+
for a in range(n):
|
|
584
|
+
for b in range(a + 1, n):
|
|
585
|
+
D[a, b] = D[b, a] = graph_distance(graphs[a], graphs[b], method)
|
|
586
|
+
return D
|