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/segment.py ADDED
@@ -0,0 +1,642 @@
1
+ """Segmentation and change detection through visibility graphs.
2
+
3
+ Four complementary approaches are provided:
4
+
5
+ * **window features** (:func:`window_features`) — the sliding-window pipeline of
6
+ Ferenczi, Kummer and Abonyi (2026): one graph per window, structural
7
+ measures and label occupancies as a multivariate feature series, which any
8
+ change-point method can segment (:func:`pelt`, :func:`binary_segmentation`);
9
+ * **divergence profile** (:func:`divergence_profile`) — the Jensen–Shannon
10
+ divergence of the degree (or motif) distributions of the graphs just before
11
+ and just after every time point; peaks mark changes of the dynamics;
12
+ * **optimal contiguous modularity** (:func:`modularity_segmentation`) — an exact
13
+ dynamic program that cuts the series into the :math:`K` contiguous segments
14
+ that maximize the modularity of the visibility graph, for every :math:`K` at
15
+ once; unlike community detection followed by post-processing it yields
16
+ contiguous segments and a certificate of optimality;
17
+ * **multiscale view** (:func:`scalogram`) — a window statistic over all window
18
+ widths and positions, the *visibility scalogram*.
19
+
20
+ :func:`segmentation_scores` evaluates a segmentation against known change points.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from collections.abc import Callable, Iterable, Sequence
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ from .construct.variants import visibility_graph
31
+ from .construct.windows import sliding_windows
32
+ from .core import VisibilityGraph
33
+ from .measures import degree_distribution, distribution_divergence, exponential_fit, graph_features, irreversibility, motif_profile
34
+
35
+ __all__ = [
36
+ "window_features",
37
+ "divergence_profile",
38
+ "pelt",
39
+ "binary_segmentation",
40
+ "modularity_segmentation",
41
+ "ModularitySegmentation",
42
+ "community_segmentation",
43
+ "scalogram",
44
+ "segmentation_scores",
45
+ "boundaries_to_labels",
46
+ ]
47
+
48
+
49
+ # ------------------------------------------------------------ window features
50
+ def window_features(
51
+ y,
52
+ t=None,
53
+ *,
54
+ width: int,
55
+ step: int = 1,
56
+ kind: str = "hvg",
57
+ features: str | Iterable[str] = "paper",
58
+ labels=None,
59
+ n_labels: int | None = None,
60
+ label_names: Sequence[str] | None = None,
61
+ align: str = "end",
62
+ graph: VisibilityGraph | None = None,
63
+ **kw,
64
+ ) -> pd.DataFrame:
65
+ """Structural features and label occupancies of sliding-window visibility graphs.
66
+
67
+ Parameters
68
+ ----------
69
+ y, t : array_like
70
+ Series and time stamps.
71
+ width, step : int
72
+ Window length :math:`m` and shift.
73
+ kind : str
74
+ Visibility criterion (see :func:`visibgraph.visibility_graph`).
75
+ features : "paper", "all" or iterable of names
76
+ Passed to :func:`visibgraph.graph_features`.
77
+ labels : array_like of int, optional
78
+ Node labels (e.g. :func:`visibgraph.spc_zones`); their counts per window are
79
+ appended as columns ``count_<name>``.
80
+ align : {"end", "center", "start"}
81
+ Time point that represents a window. ``"end"`` uses only past
82
+ observations (causal monitoring).
83
+
84
+ Returns
85
+ -------
86
+ pandas.DataFrame
87
+ One row per window: ``start``, ``stop``, ``time`` and the features.
88
+
89
+ Notes
90
+ -----
91
+ The global graph is built once; the window graphs are its induced
92
+ subgraphs (exact for every hereditary criterion), so the construction costs
93
+ :math:`O(N)` for the HVG instead of :math:`O(Nm)`.
94
+ """
95
+ G = graph if graph is not None else visibility_graph(y, t, kind=kind, **kw)
96
+ lab = None
97
+ if labels is not None:
98
+ lab = np.asarray(labels, dtype=np.int64)
99
+ L = int(n_labels or max(lab.max() + 1, len(label_names) if label_names else 0))
100
+ names = list(label_names) if label_names else [str(c) for c in range(L)]
101
+ rows = []
102
+ for s, e in sliding_windows(G.n_nodes, width, step):
103
+ W = G.window(s, e)
104
+ r = {"start": s, "stop": e}
105
+ pos = {"end": e - 1, "center": (s + e - 1) // 2, "start": s}[align]
106
+ r["time"] = float(G.t[pos])
107
+ r.update(graph_features(W, features))
108
+ if lab is not None:
109
+ c = np.bincount(lab[s:e], minlength=L)
110
+ r.update({f"count_{names[q]}": int(c[q]) for q in range(L)})
111
+ rows.append(r)
112
+ return pd.DataFrame(rows)
113
+
114
+
115
+ # --------------------------------------------------------- divergence profile
116
+ def divergence_profile(
117
+ y,
118
+ t=None,
119
+ *,
120
+ width: int,
121
+ kind: str = "hvg",
122
+ representation: str = "degree",
123
+ statistic: str = "jsd",
124
+ graph: VisibilityGraph | None = None,
125
+ **kw,
126
+ ) -> pd.Series:
127
+ """Divergence of the visibility structure before and after every time point.
128
+
129
+ For every :math:`\\tau` the graphs of the windows :math:`[\\tau-m,\\tau)` and
130
+ :math:`[\\tau,\\tau+m)` are compared through their degree distributions
131
+ (``representation="degree"``) or size-4 motif profiles (``"motif"``) with
132
+ the Jensen–Shannon divergence. Under a stationary regime the two windows
133
+ are exchangeable and the divergence fluctuates around a small level that
134
+ shrinks with :math:`m`; a change of the dynamics — of the correlation
135
+ structure, not only of the level — produces a peak at the change point.
136
+ Because the HVG is invariant under monotone transformations, the HVG
137
+ profile is insensitive to pure changes of mean or scale and responds to
138
+ changes of the temporal organization; use ``kind="nvg"`` to see level
139
+ shifts as well.
140
+
141
+ Returns
142
+ -------
143
+ pandas.Series
144
+ Divergence indexed by the time of the split point :math:`\\tau`
145
+ (``m <= tau <= N-m``).
146
+ """
147
+ G = graph if graph is not None else visibility_graph(y, t, kind=kind, **kw)
148
+ n = G.n_nodes
149
+ vals, idx = [], []
150
+ for tau in range(width, n - width + 1):
151
+ A, B = G.window(tau - width, tau), G.window(tau, tau + width)
152
+ if representation == "degree":
153
+ kmax = int(max(A.degree().max(), B.degree().max()))
154
+ p, q = degree_distribution(A, kmax=kmax)[1], degree_distribution(B, kmax=kmax)[1]
155
+ elif representation == "motif":
156
+ p, q = motif_profile(A).to_numpy(), motif_profile(B).to_numpy()
157
+ else:
158
+ raise ValueError("representation must be 'degree' or 'motif'")
159
+ vals.append(distribution_divergence(p, q, statistic, base=2))
160
+ idx.append(G.t[tau])
161
+ return pd.Series(vals, index=pd.Index(idx, name="time"), name=f"{representation}-{statistic}")
162
+
163
+
164
+ # ----------------------------------------------------------- change points
165
+ def _cost_factory(X: np.ndarray):
166
+ X = np.asarray(X, dtype=float)
167
+ if X.ndim == 1:
168
+ X = X[:, None]
169
+ S1 = np.vstack([np.zeros(X.shape[1]), np.cumsum(X, 0)])
170
+ S2 = np.concatenate([[0.0], np.cumsum((X**2).sum(1))])
171
+
172
+ def cost(a: int, b: int) -> float:
173
+ """Sum of squared deviations from the segment mean of rows a..b-1."""
174
+ m = b - a
175
+ s = S1[b] - S1[a]
176
+ return float(S2[b] - S2[a] - (s @ s) / m)
177
+
178
+ return X, cost
179
+
180
+
181
+ def pelt(signal, penalty: float | None = None, *, min_size: int = 2, standardize: bool = True) -> list[int]:
182
+ """Optimal segmentation with a linear penalty by PELT (Killick et al., 2012).
183
+
184
+ Minimizes :math:`\\sum_{s}C(\\text{segment}_s)+\\beta K` with the squared-error
185
+ (piecewise constant mean) cost over all segmentations; the pruning keeps the
186
+ expected cost linear in the length.
187
+
188
+ Parameters
189
+ ----------
190
+ signal : array_like of shape (n,) or (n, d)
191
+ E.g. a table of :func:`window_features` (numeric columns).
192
+ penalty : float, optional
193
+ :math:`\\beta`; default :math:`2d\\ln n` (BIC-like), on standardized columns.
194
+ min_size : int
195
+ Minimal segment length.
196
+ standardize : bool
197
+ Scale every column to unit variance first.
198
+
199
+ Returns
200
+ -------
201
+ list of int
202
+ Change points (start indices of the segments after the first), increasing.
203
+
204
+ References
205
+ ----------
206
+ Killick, R., Fearnhead, P., Eckley, I. A. (2012). Optimal detection of changepoints
207
+ with a linear computational cost. J. Am. Stat. Assoc. 107, 1590–1598.
208
+ """
209
+ X = np.asarray(signal.select_dtypes("number") if isinstance(signal, pd.DataFrame) else signal, dtype=float)
210
+ if X.ndim == 1:
211
+ X = X[:, None]
212
+ if standardize:
213
+ sd = X.std(0)
214
+ X = (X - X.mean(0)) / np.where(sd > 0, sd, 1)
215
+ X = np.nan_to_num(X)
216
+ n, d = X.shape
217
+ beta = 2 * d * np.log(n) if penalty is None else float(penalty)
218
+ _, cost = _cost_factory(X)
219
+ F = np.full(n + 1, np.inf)
220
+ F[0] = -beta
221
+ last = np.zeros(n + 1, dtype=int)
222
+ cand = [0]
223
+ for b in range(min_size, n + 1):
224
+ vals = [F[a] + cost(a, b) + beta if b - a >= min_size else np.inf for a in cand]
225
+ k = int(np.argmin(vals))
226
+ F[b], last[b] = vals[k], cand[k]
227
+ cand = [a for a, v in zip(cand, vals) if v - beta <= F[b]]
228
+ if b - min_size + 1 >= 0:
229
+ cand.append(b - min_size + 1)
230
+ bps, b = [], n
231
+ while b > 0:
232
+ a = last[b]
233
+ if a > 0:
234
+ bps.append(int(a))
235
+ b = a
236
+ return sorted(bps)
237
+
238
+
239
+ def binary_segmentation(signal, n_bkps: int | None = None, penalty: float | None = None, *, min_size: int = 2,
240
+ standardize: bool = True) -> list[int]:
241
+ """Greedy binary segmentation with the squared-error cost.
242
+
243
+ Splits the segment whose best split reduces the cost most, until ``n_bkps``
244
+ change points are found or the reduction falls below ``penalty``.
245
+ """
246
+ X = np.asarray(signal.select_dtypes("number") if isinstance(signal, pd.DataFrame) else signal, dtype=float)
247
+ if X.ndim == 1:
248
+ X = X[:, None]
249
+ if standardize:
250
+ sd = X.std(0)
251
+ X = (X - X.mean(0)) / np.where(sd > 0, sd, 1)
252
+ X = np.nan_to_num(X)
253
+ n, d = X.shape
254
+ if n_bkps is None and penalty is None:
255
+ penalty = 2 * d * np.log(n)
256
+ _, cost = _cost_factory(X)
257
+ segs = [(0, n)]
258
+ bps: list[int] = []
259
+ while n_bkps is None or len(bps) < n_bkps:
260
+ best = None
261
+ for a, b in segs:
262
+ if b - a < 2 * min_size:
263
+ continue
264
+ c0 = cost(a, b)
265
+ for s in range(a + min_size, b - min_size + 1):
266
+ gain = c0 - cost(a, s) - cost(s, b)
267
+ if best is None or gain > best[0]:
268
+ best = (gain, a, s, b)
269
+ if best is None or (penalty is not None and best[0] < penalty):
270
+ break
271
+ _, a, s, b = best
272
+ segs.remove((a, b))
273
+ segs += [(a, s), (s, b)]
274
+ bps.append(s)
275
+ return sorted(bps)
276
+
277
+
278
+ # ------------------------------------------------ contiguous modularity (DP)
279
+ class ModularitySegmentation:
280
+ """Result of :func:`modularity_segmentation`.
281
+
282
+ Attributes
283
+ ----------
284
+ boundaries : list of int
285
+ Change points of the optimal segmentation (start indices of segments 2..K).
286
+ n_segments : int
287
+ Number of segments :math:`K^*` of the optimum.
288
+ modularity : float
289
+ Its modularity :math:`Q^*`.
290
+ profile : pandas.Series
291
+ :math:`Q^*_K` of the best segmentation with exactly :math:`K` segments.
292
+ segmentations : dict
293
+ :math:`K\\mapsto` change points of the best :math:`K`-segmentation.
294
+ """
295
+
296
+ def __init__(self, boundaries, n_segments, modularity, profile, segmentations, n):
297
+ self.boundaries = list(boundaries)
298
+ self.n_segments = int(n_segments)
299
+ self.modularity = float(modularity)
300
+ self.profile = profile
301
+ self.segmentations = segmentations
302
+ self.n = n
303
+
304
+ def __repr__(self) -> str:
305
+ return f"ModularitySegmentation(K={self.n_segments}, Q={self.modularity:.4f}, boundaries={self.boundaries})"
306
+
307
+ def labels(self) -> np.ndarray:
308
+ """Segment index of every node."""
309
+ return boundaries_to_labels(self.boundaries, self.n)
310
+
311
+
312
+ def _dp_table(G: VisibilityGraph, Kmax: int, min_size: int, resolution: float, weight, null: str):
313
+ n = G.n_nodes
314
+ w = G.weight(weight)
315
+ m = float(w.sum())
316
+ if m <= 0:
317
+ raise ValueError("the graph has no edges")
318
+ deg = np.zeros(n)
319
+ np.add.at(deg, G.edges[:, 0], w)
320
+ np.add.at(deg, G.edges[:, 1], w)
321
+ Dcum = np.concatenate([[0.0], np.cumsum(deg)])
322
+ dist = G.edges[:, 1] - G.edges[:, 0]
323
+ if null in ("span", "spatial"):
324
+ cnt = np.zeros(n)
325
+ np.add.at(cnt, dist, w)
326
+ if null == "span":
327
+ den = (n - np.arange(n)).astype(float)
328
+ else:
329
+ den = np.array([float(np.dot(deg[: n - d], deg[d:])) if d > 0 else 1.0 for d in range(n)])
330
+ f = np.divide(cnt, den, out=np.zeros(n), where=den > 0)
331
+ f[0] = 0.0
332
+ elif null != "configuration":
333
+ raise ValueError("null must be 'configuration', 'span' or 'spatial'")
334
+ order = np.argsort(G.edges[:, 1], kind="stable")
335
+ ej, ei, ew = G.edges[order, 1], G.edges[order, 0], w[order]
336
+ starts = np.searchsorted(ej, np.arange(n + 1))
337
+ F = np.full((Kmax + 1, n + 1), -np.inf)
338
+ arg = np.zeros((Kmax + 1, n + 1), dtype=np.int64)
339
+ F[0, 0] = 0.0
340
+ c = np.zeros(n) # c[i] = weight of edges (i, j), i < j < b
341
+ Eexp = np.zeros(n + 1) # expected internal weight of the segment a..b-1 (span/spatial nulls)
342
+ idx = np.arange(n + 1)
343
+ for b in range(1, n + 1):
344
+ j = b - 1
345
+ lo, hi = starts[j], starts[j + 1]
346
+ np.add.at(c, ei[lo:hi], ew[lo:hi])
347
+ suffix = np.concatenate([np.cumsum(c[:b][::-1])[::-1], [0.0]]) # L(a, b) for a = 0..b
348
+ if null == "configuration":
349
+ Dab = Dcum[b] - Dcum[: b + 1]
350
+ q = suffix / m - resolution * (Dab / (2 * m)) ** 2
351
+ else:
352
+ if j > 0:
353
+ g = f[j - idx[:j]] if null == "span" else deg[:j] * deg[j] * f[j - idx[:j]]
354
+ Eexp[: j + 1] += np.concatenate([np.cumsum(g[::-1])[::-1], [0.0]])
355
+ q = (suffix - resolution * Eexp[: b + 1]) / m
356
+ qv = np.where(idx[: b + 1] <= b - min_size, q, -np.inf)
357
+ for K in range(1, Kmax + 1):
358
+ cand = F[K - 1, : b + 1] + qv
359
+ k = int(np.argmax(cand))
360
+ F[K, b], arg[K, b] = cand[k], k
361
+ return F, arg
362
+
363
+
364
+ def _backtrack(arg, n: int, K: int) -> list[int]:
365
+ bps, b = [], n
366
+ for kk in range(K, 0, -1):
367
+ a = int(arg[kk, b])
368
+ if a > 0:
369
+ bps.append(a)
370
+ b = a
371
+ return sorted(bps)
372
+
373
+
374
+ def modularity_segmentation(
375
+ G: VisibilityGraph,
376
+ n_segments: int | str | None = "auto",
377
+ *,
378
+ max_segments: int = 12,
379
+ min_size: int = 2,
380
+ resolution: float = 1.0,
381
+ weight: str | None = None,
382
+ null: str = "span",
383
+ surrogate: str = "iaaft",
384
+ n_surrogates: int = 19,
385
+ quantile: float = 0.95,
386
+ random_state=0,
387
+ ) -> ModularitySegmentation:
388
+ """Exact contiguous segmentation of a visibility graph by modularity.
389
+
390
+ The modularity of a partition into node sets :math:`c` is additive,
391
+
392
+ .. math::
393
+
394
+ Q=\\frac1m\\sum_c\\Bigl[L_c-\\gamma\\,\\mathbb{E}[L_c]\\Bigr],
395
+
396
+ where :math:`L_c` is the number (weight) of edges inside :math:`c`,
397
+ :math:`\\mathbb{E}[L_c]` its expectation under a null model, :math:`m` the
398
+ number of edges and :math:`\\gamma` the resolution. Restricting the sets to
399
+ runs of consecutive nodes, the best :math:`K`-segmentation satisfies the
400
+ Bellman recursion
401
+
402
+ .. math::
403
+
404
+ F_K(b)=\\max_{a<b} F_{K-1}(a)+q(a,b),\\qquad F_0(0)=0,
405
+
406
+ with :math:`q(a,b)` the term of the segment :math:`a..b-1`. Internal and
407
+ expected edge counts of all segments ending at :math:`b` are updated
408
+ incrementally in :math:`O(N)`, so the whole table costs
409
+ :math:`O(K_{\\max}N^2)` time and :math:`O(K_{\\max}N)` memory, and returns the
410
+ certified optimum for every :math:`K\\le K_{\\max}`.
411
+
412
+ Null models (``null``):
413
+
414
+ * ``"configuration"`` — :math:`\\mathbb{E}[A_{ij}]=k_ik_j/2m`, the Newman–Girvan
415
+ modularity. Visibility edges are short, so this null rewards cutting any
416
+ series into many balanced pieces;
417
+ * ``"span"`` (default) — :math:`\\mathbb{E}[A_{ij}]=f(|i-j|)`, the empirical
418
+ probability that two observations at that distance see each other, a
419
+ spatial null model in the sense of Expert et al. (2011). It removes the
420
+ locality bias: a segment gains only if its observations see each other
421
+ more often than observations at the same distances elsewhere;
422
+ * ``"spatial"`` — :math:`\\mathbb{E}[A_{ij}]=k_ik_jf(|i-j|)`, the degree-corrected
423
+ (gravity) version of Expert et al. (2011).
424
+
425
+ Number of segments (``n_segments``): an integer fixes :math:`K`; ``None``
426
+ takes the :math:`K` of largest :math:`Q` (which tends to over-segment, since
427
+ the optimum adapts to noise); ``"auto"`` adds segments while the gain
428
+ :math:`Q^*_K-Q^*_{K-1}` exceeds the ``quantile`` of the gains obtained on
429
+ surrogate series (``"iaaft"``: stationary, same values and spectrum;
430
+ ``"shuffle"``: uncorrelated) — a surrogate-calibrated stopping rule.
431
+
432
+ Parameters
433
+ ----------
434
+ G : VisibilityGraph
435
+ n_segments : int, None or "auto"
436
+ max_segments : int
437
+ :math:`K_{\\max}`.
438
+ min_size : int
439
+ Minimal number of nodes per segment.
440
+ resolution : float
441
+ :math:`\\gamma`.
442
+ weight : str, optional
443
+ Edge weight (see :meth:`VisibilityGraph.weight`).
444
+
445
+ Returns
446
+ -------
447
+ ModularitySegmentation
448
+
449
+ References
450
+ ----------
451
+ Expert, P., Evans, T. S., Blondel, V. D., Lambiotte, R. (2011). Uncovering
452
+ space-independent communities in spatial networks. PNAS 108, 7663–7668.
453
+
454
+ Examples
455
+ --------
456
+ >>> import visibgraph as vg
457
+ >>> nile = vg.datasets.load_nile()
458
+ >>> res = vg.modularity_segmentation(vg.nvg(nile), n_segments=2, min_size=10)
459
+ >>> int(nile.index[res.boundaries[0]])
460
+ 1895
461
+ """
462
+ n = G.n_nodes
463
+ if isinstance(n_segments, (int, np.integer)):
464
+ Kmax = int(n_segments)
465
+ else:
466
+ Kmax = int(max_segments)
467
+ Kmax = max(1, min(Kmax, n // min_size))
468
+ F, arg = _dp_table(G, Kmax, min_size, resolution, weight, null)
469
+ profile = pd.Series({K: F[K, n] for K in range(1, Kmax + 1) if np.isfinite(F[K, n])}, name="modularity")
470
+ profile.index.name = "n_segments"
471
+ segs = {int(K): _backtrack(arg, n, int(K)) for K in profile.index}
472
+ if isinstance(n_segments, (int, np.integer)):
473
+ Kbest = int(n_segments)
474
+ elif n_segments is None:
475
+ Kbest = int(profile.idxmax())
476
+ elif n_segments == "auto":
477
+ from .construct.variants import visibility_graph as _vg
478
+ from .surrogates import surrogate as _sur
479
+
480
+ rng = np.random.default_rng(random_state)
481
+ kind = G.kind
482
+ kw = {k: v for k, v in G.params.items() if k in ("rho", "alpha", "max_span")}
483
+ gains = []
484
+ for _ in range(n_surrogates):
485
+ ys = _sur(G.y, surrogate, rng)
486
+ Fs, _ = _dp_table(_vg(ys, G.t, kind=kind, **kw), Kmax, min_size, resolution, weight, null)
487
+ gains.append(np.diff(Fs[1 : Kmax + 1, n]))
488
+ thr = np.quantile(np.asarray(gains), quantile, axis=0)
489
+ obs = np.diff(profile.reindex(range(1, Kmax + 1)).to_numpy())
490
+ Kbest = 1
491
+ for k in range(obs.size):
492
+ if np.isfinite(obs[k]) and obs[k] > thr[k]:
493
+ Kbest = k + 2
494
+ else:
495
+ break
496
+ else:
497
+ raise ValueError("n_segments must be an integer, None or 'auto'")
498
+ res = ModularitySegmentation(segs[Kbest], Kbest, profile[Kbest], profile, segs, n)
499
+ res.null = null
500
+ return res
501
+
502
+
503
+ def community_segmentation(G: VisibilityGraph, method: str = "louvain", *, random_state=0, resolution: float = 1.0) -> dict:
504
+ """Segmentation by community detection, the approach of earlier VG segmentation studies.
505
+
506
+ Communities are found without a contiguity constraint (Louvain or greedy
507
+ modularity); the boundaries are the time points where the community label
508
+ changes. The result reports the modularity and the fraction of nodes that
509
+ lie in a community run shorter than the community itself (non-contiguity).
510
+
511
+ Returns
512
+ -------
513
+ dict
514
+ ``boundaries``, ``labels``, ``modularity``, ``n_communities``, ``noncontiguous_fraction``.
515
+ """
516
+ import networkx as nx
517
+
518
+ H = G.to_networkx(weights=(), node_attributes=False)
519
+ if G.directed:
520
+ H = H.to_undirected()
521
+ if method == "louvain":
522
+ comm = nx.community.louvain_communities(H, seed=random_state, resolution=resolution)
523
+ else:
524
+ comm = nx.community.greedy_modularity_communities(H, resolution=resolution)
525
+ lab = np.empty(G.n_nodes, dtype=np.int64)
526
+ for c, nodes in enumerate(sorted(comm, key=min)):
527
+ lab[list(nodes)] = c
528
+ bps = (np.nonzero(np.diff(lab))[0] + 1).tolist()
529
+ runs = np.split(lab, bps) if bps else [lab]
530
+ largest_run = {}
531
+ for r in runs:
532
+ largest_run[int(r[0])] = max(largest_run.get(int(r[0]), 0), r.size)
533
+ noncontig = sum(r.size for r in runs if r.size < largest_run[int(r[0])]) / G.n_nodes
534
+ return {
535
+ "boundaries": bps,
536
+ "labels": lab,
537
+ "modularity": float(nx.community.modularity(H, comm, resolution=resolution)),
538
+ "n_communities": len(comm),
539
+ "noncontiguous_fraction": float(noncontig),
540
+ }
541
+
542
+
543
+ # ---------------------------------------------------------------- scalogram
544
+ _STATS: dict[str, Callable[[VisibilityGraph], float]] = {
545
+ "mean_degree": lambda W: float(W.degree().mean()),
546
+ "lambda": lambda W: exponential_fit(W)["lambda"],
547
+ "irreversibility": lambda W: irreversibility(W, statistic="jsd"),
548
+ "mean_span": lambda W: float(W.spans("index").mean()),
549
+ "max_degree": lambda W: float(W.degree().max()),
550
+ }
551
+
552
+
553
+ def scalogram(y, t=None, *, widths: Sequence[int] | None = None, kind: str = "hvg", statistic: str | Callable = "lambda",
554
+ step: int | None = None, reference: float | None = None, graph: VisibilityGraph | None = None, **kw) -> pd.DataFrame:
555
+ """Visibility scalogram: a window statistic over all widths and positions.
556
+
557
+ For every width :math:`m` in ``widths`` and every window centre the
558
+ statistic of the window graph is computed; the result is a table with one
559
+ row per width and one column per centre (NaN where the window does not
560
+ fit), the analogue of a wavelet scalogram for visibility structure. With
561
+ the HVG exponent :math:`\\lambda` (default) and ``reference=np.log(1.5)``, the
562
+ map shows where and on which scale the series departs from uncorrelated
563
+ behaviour (correlated: above, chaotic: below the reference).
564
+
565
+ Parameters
566
+ ----------
567
+ widths : sequence of int
568
+ Window widths; by default 12 geometrically spaced widths between 32 and N/4.
569
+ statistic : str or callable
570
+ ``"lambda"``, ``"mean_degree"``, ``"irreversibility"``, ``"mean_span"``,
571
+ ``"max_degree"`` or a function of a :class:`VisibilityGraph`.
572
+ step : int, optional
573
+ Shift between window centres (default: about N/200).
574
+ reference : float, optional
575
+ Subtracted from every value.
576
+ """
577
+ G = graph if graph is not None else visibility_graph(y, t, kind=kind, **kw)
578
+ n = G.n_nodes
579
+ if widths is None:
580
+ widths = np.unique(np.geomspace(32, max(33, n // 4), 12).astype(int))
581
+ step = step or max(1, n // 200)
582
+ f = _STATS[statistic] if isinstance(statistic, str) else statistic
583
+ centres = np.arange(0, n, step)
584
+ M = np.full((len(widths), centres.size), np.nan)
585
+ for r, wdt in enumerate(widths):
586
+ h = wdt // 2
587
+ for c, ctr in enumerate(centres):
588
+ s, e = ctr - h, ctr - h + wdt
589
+ if s < 0 or e > n:
590
+ continue
591
+ v = f(G.window(s, e))
592
+ M[r, c] = v if np.isfinite(v) else np.nan
593
+ if reference is not None:
594
+ M = M - reference
595
+ return pd.DataFrame(M, index=pd.Index(list(widths), name="width"), columns=pd.Index(G.t[centres], name="time"))
596
+
597
+
598
+ # --------------------------------------------------------------- evaluation
599
+ def boundaries_to_labels(boundaries: Sequence[int], n: int) -> np.ndarray:
600
+ """Segment index of each of ``n`` points for the given change points."""
601
+ lab = np.zeros(n, dtype=np.int64)
602
+ for b in sorted(boundaries):
603
+ lab[int(b) :] += 1
604
+ return lab
605
+
606
+
607
+ def segmentation_scores(true: Sequence[int], pred: Sequence[int], n: int, margin: int = 5) -> dict:
608
+ """Agreement of predicted and true change points.
609
+
610
+ Returns precision, recall and F1 with a tolerance of ``margin`` points
611
+ (each true change point matched at most once), the *covering* of the true
612
+ segmentation by the predicted one (van den Burg and Williams, 2020), the
613
+ adjusted Rand index of the segment labels and the Hausdorff distance of
614
+ the change-point sets.
615
+ """
616
+ from sklearn.metrics import adjusted_rand_score
617
+
618
+ true, pred = sorted(int(x) for x in true), sorted(int(x) for x in pred)
619
+ used = set()
620
+ tp = 0
621
+ for p in pred:
622
+ cands = [k for k, t_ in enumerate(true) if abs(t_ - p) <= margin and k not in used]
623
+ if cands:
624
+ used.add(min(cands, key=lambda k: abs(true[k] - p)))
625
+ tp += 1
626
+ prec = tp / len(pred) if pred else (1.0 if not true else 0.0)
627
+ rec = tp / len(true) if true else 1.0
628
+ f1 = 2 * prec * rec / (prec + rec) if prec + rec > 0 else 0.0
629
+ A = np.split(np.arange(n), true)
630
+ B = np.split(np.arange(n), pred)
631
+ cover = 0.0
632
+ for a in A:
633
+ sa = set(a.tolist())
634
+ best = max(len(sa & set(b.tolist())) / len(sa | set(b.tolist())) for b in B)
635
+ cover += len(a) * best
636
+ cover /= n
637
+ ari = adjusted_rand_score(boundaries_to_labels(true, n), boundaries_to_labels(pred, n))
638
+ if true and pred:
639
+ haus = max(max(min(abs(a - b) for b in pred) for a in true), max(min(abs(a - b) for a in true) for b in pred))
640
+ else:
641
+ haus = np.nan
642
+ return {"precision": prec, "recall": rec, "f1": f1, "covering": cover, "ari": float(ari), "hausdorff": float(haus)}