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/io.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Import and export: NetworkX, igraph, ts2vg, pandas tables and graph files.
|
|
2
|
+
|
|
3
|
+
Every :class:`~visibgraph.VisibilityGraph` converts to a NetworkX graph whose node and
|
|
4
|
+
edge attributes are plain scalars, so it can be written to GraphML (yEd,
|
|
5
|
+
Cytoscape), GEXF (Gephi), GML, Pajek or node-link JSON without loss; the
|
|
6
|
+
reverse conversions rebuild a :class:`~visibgraph.VisibilityGraph` from these files,
|
|
7
|
+
from igraph graphs and from the graphs of the ``ts2vg`` package.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import pathlib
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
from .core import VisibilityGraph
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"to_networkx",
|
|
22
|
+
"from_networkx",
|
|
23
|
+
"to_igraph",
|
|
24
|
+
"from_igraph",
|
|
25
|
+
"from_ts2vg",
|
|
26
|
+
"to_frames",
|
|
27
|
+
"write_graph",
|
|
28
|
+
"read_graph",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def to_networkx(G: VisibilityGraph, weights=("span",)):
|
|
33
|
+
"""NetworkX graph of a visibility graph (see :meth:`VisibilityGraph.to_networkx`)."""
|
|
34
|
+
return G.to_networkx(weights=weights)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def from_networkx(H, value: str = "value", time: str = "time", label: str = "label", kind: str | None = None) -> VisibilityGraph:
|
|
38
|
+
"""Rebuild a :class:`VisibilityGraph` from a NetworkX graph written by :func:`to_networkx`.
|
|
39
|
+
|
|
40
|
+
Nodes must be the integers ``0..N-1`` (or strings of them, as after GraphML
|
|
41
|
+
round trips) with ``value`` and ``time`` attributes.
|
|
42
|
+
"""
|
|
43
|
+
nodes = sorted(H.nodes, key=lambda v: int(v))
|
|
44
|
+
pos = {v: k for k, v in enumerate(nodes)}
|
|
45
|
+
y = np.array([float(H.nodes[v][value]) for v in nodes])
|
|
46
|
+
t = np.array([float(H.nodes[v].get(time, k)) for k, v in enumerate(nodes)])
|
|
47
|
+
e = np.array([(pos[a], pos[b]) for a, b in H.edges()], dtype=np.int64).reshape(-1, 2)
|
|
48
|
+
G = VisibilityGraph(y, e, t, kind=kind or H.graph.get("kind", "custom"), directed=H.is_directed())
|
|
49
|
+
if all(label in H.nodes[v] for v in nodes):
|
|
50
|
+
G.set_labels([H.nodes[v][label] for v in nodes])
|
|
51
|
+
return G
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def to_igraph(G: VisibilityGraph, weights=("span",)):
|
|
55
|
+
"""igraph ``Graph`` with vertex attributes ``time``, ``value`` (and ``label``) and edge weights."""
|
|
56
|
+
import igraph as ig
|
|
57
|
+
|
|
58
|
+
g = ig.Graph(n=G.n_nodes, edges=G.edges.tolist(), directed=G.directed)
|
|
59
|
+
g.vs["time"] = G.t.tolist()
|
|
60
|
+
g.vs["value"] = G.y.tolist()
|
|
61
|
+
if G.labels is not None:
|
|
62
|
+
g.vs["label"] = [str(G.label_of(i)) for i in range(G.n_nodes)]
|
|
63
|
+
for w in weights or ():
|
|
64
|
+
g.es[w] = G.weight(w).tolist()
|
|
65
|
+
g["kind"] = G.kind
|
|
66
|
+
return g
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def from_igraph(g, kind: str | None = None) -> VisibilityGraph:
|
|
70
|
+
"""Rebuild a :class:`VisibilityGraph` from an igraph graph made by :func:`to_igraph`."""
|
|
71
|
+
y = np.asarray(g.vs["value"], dtype=float)
|
|
72
|
+
t = np.asarray(g.vs["time"], dtype=float) if "time" in g.vs.attributes() else None
|
|
73
|
+
G = VisibilityGraph(y, np.asarray(g.get_edgelist(), dtype=np.int64).reshape(-1, 2), t,
|
|
74
|
+
kind=kind or (g["kind"] if "kind" in g.attributes() else "custom"), directed=g.is_directed())
|
|
75
|
+
if "label" in g.vs.attributes():
|
|
76
|
+
G.set_labels(g.vs["label"])
|
|
77
|
+
return G
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def from_ts2vg(g, y=None, t=None, kind: str | None = None) -> VisibilityGraph:
|
|
81
|
+
"""Convert a graph built with the ``ts2vg`` package (``NaturalVG``, ``HorizontalVG``).
|
|
82
|
+
|
|
83
|
+
``ts2vg`` stores the series in ``g.ts`` and the time stamps in ``g.xs``;
|
|
84
|
+
they are used unless ``y``/``t`` are given.
|
|
85
|
+
"""
|
|
86
|
+
ys = np.asarray(g.ts if y is None else y, dtype=float)
|
|
87
|
+
ts_ = t if t is not None else getattr(g, "xs", None)
|
|
88
|
+
e = np.asarray(list(g.edges), dtype=np.int64)[:, :2]
|
|
89
|
+
if kind is None:
|
|
90
|
+
kind = "hvg" if "Horizontal" in type(g).__name__ else "nvg"
|
|
91
|
+
return VisibilityGraph(ys, e, ts_, kind=kind)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def to_frames(G: VisibilityGraph, weights=("span", "slope")) -> tuple[pd.DataFrame, pd.DataFrame]:
|
|
95
|
+
"""Node and edge tables (see :meth:`VisibilityGraph.node_frame`, :meth:`VisibilityGraph.edge_frame`)."""
|
|
96
|
+
return G.node_frame(), G.edge_frame(weights)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def write_graph(G: VisibilityGraph, path: str | pathlib.Path, weights=("span", "slope"), fmt: str | None = None) -> pathlib.Path:
|
|
100
|
+
"""Write a graph; the format follows the extension (or ``fmt``).
|
|
101
|
+
|
|
102
|
+
``.graphml``, ``.gexf``, ``.gml``, ``.net`` (Pajek), ``.json`` (node-link,
|
|
103
|
+
with the series), ``.csv`` (edge list; the node table goes to
|
|
104
|
+
``<name>_nodes.csv``).
|
|
105
|
+
"""
|
|
106
|
+
import networkx as nx
|
|
107
|
+
|
|
108
|
+
path = pathlib.Path(path)
|
|
109
|
+
fmt = (fmt or path.suffix.lstrip(".")).lower()
|
|
110
|
+
H = G.to_networkx(weights=weights)
|
|
111
|
+
if fmt == "graphml":
|
|
112
|
+
nx.write_graphml(H, path)
|
|
113
|
+
elif fmt == "gexf":
|
|
114
|
+
nx.write_gexf(H, path)
|
|
115
|
+
elif fmt == "gml":
|
|
116
|
+
nx.write_gml(H, path)
|
|
117
|
+
elif fmt in ("net", "pajek"):
|
|
118
|
+
nx.write_pajek(H, path)
|
|
119
|
+
elif fmt == "json":
|
|
120
|
+
data = nx.node_link_data(H, edges="edges")
|
|
121
|
+
path.write_text(json.dumps(data))
|
|
122
|
+
elif fmt == "csv":
|
|
123
|
+
G.edge_frame(weights).to_csv(path, index=False)
|
|
124
|
+
G.node_frame().to_csv(path.with_name(path.stem + "_nodes.csv"), index=True)
|
|
125
|
+
else:
|
|
126
|
+
raise ValueError(f"unknown format {fmt!r}")
|
|
127
|
+
return path
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def read_graph(path: str | pathlib.Path, fmt: str | None = None) -> VisibilityGraph:
|
|
131
|
+
"""Read a graph written by :func:`write_graph`."""
|
|
132
|
+
import networkx as nx
|
|
133
|
+
|
|
134
|
+
path = pathlib.Path(path)
|
|
135
|
+
fmt = (fmt or path.suffix.lstrip(".")).lower()
|
|
136
|
+
if fmt == "graphml":
|
|
137
|
+
H = nx.read_graphml(path)
|
|
138
|
+
elif fmt == "gexf":
|
|
139
|
+
H = nx.read_gexf(path)
|
|
140
|
+
elif fmt == "gml":
|
|
141
|
+
H = nx.read_gml(path)
|
|
142
|
+
elif fmt == "json":
|
|
143
|
+
H = nx.node_link_graph(json.loads(path.read_text()), edges="edges")
|
|
144
|
+
elif fmt == "csv":
|
|
145
|
+
e = pd.read_csv(path)
|
|
146
|
+
nodes = pd.read_csv(path.with_name(path.stem + "_nodes.csv"), index_col=0)
|
|
147
|
+
G = VisibilityGraph(nodes["value"].to_numpy(), e[["source", "target"]].to_numpy(), nodes["time"].to_numpy())
|
|
148
|
+
if "label" in nodes:
|
|
149
|
+
G.set_labels(nodes["label"].astype(str).to_numpy())
|
|
150
|
+
return G
|
|
151
|
+
else:
|
|
152
|
+
raise ValueError(f"unknown format {fmt!r}")
|
|
153
|
+
return from_networkx(H)
|
visibgraph/labelled.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Analysis of labelled visibility graphs.
|
|
2
|
+
|
|
3
|
+
Once every node carries a symbol (an SPC zone, a quantile bin, an ordinal
|
|
4
|
+
pattern), the graph can be summarized on the level of the alphabet:
|
|
5
|
+
|
|
6
|
+
* :func:`state_transition_network` — the symbols as nodes and the transitions
|
|
7
|
+
between consecutive observations as edges (the *state transition network* of
|
|
8
|
+
Ferenczi, Kummer and Abonyi, 2026), weighted by frequency, probability or
|
|
9
|
+
zone distance;
|
|
10
|
+
* :func:`label_aggregated_graph` — the visibility edges aggregated over the
|
|
11
|
+
label pairs (the *zone-aggregated HVG* of the paper): counts, mean and range
|
|
12
|
+
of the spans, and self-visibility of a zone;
|
|
13
|
+
* :func:`label_visibility_matrix` and :func:`label_enrichment` — the same
|
|
14
|
+
counts as matrices, compared with their exact expectation under random
|
|
15
|
+
relabelling. The enrichment separates what the graph adds from what the label
|
|
16
|
+
frequencies alone imply, and is one answer to the circularity of labels and
|
|
17
|
+
graph being functions of the same values.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from collections.abc import Sequence
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pandas as pd
|
|
26
|
+
|
|
27
|
+
from .core import VisibilityGraph
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"label_features",
|
|
31
|
+
"state_transition_network",
|
|
32
|
+
"transition_matrix",
|
|
33
|
+
"label_aggregated_graph",
|
|
34
|
+
"label_visibility_matrix",
|
|
35
|
+
"label_enrichment",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _labels_of(G: VisibilityGraph, labels, names):
|
|
40
|
+
if labels is None:
|
|
41
|
+
if G.labels is None:
|
|
42
|
+
raise ValueError("the graph has no labels; pass labels= or build it with labels")
|
|
43
|
+
labels, names = G.labels, (names or G.label_names)
|
|
44
|
+
labels = np.asarray(labels, dtype=np.int64)
|
|
45
|
+
L = int(max(labels.max() + 1, len(names) if names else 0))
|
|
46
|
+
names = list(names) if names else [str(c) for c in range(L)]
|
|
47
|
+
return labels, names, L
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def transition_matrix(labels, n_states: int | None = None, normalize: bool = False) -> np.ndarray:
|
|
51
|
+
"""Counts (or row-normalized probabilities) of transitions between consecutive labels."""
|
|
52
|
+
lab = np.asarray(labels, dtype=np.int64)
|
|
53
|
+
L = int(n_states if n_states is not None else lab.max() + 1)
|
|
54
|
+
T = np.zeros((L, L))
|
|
55
|
+
np.add.at(T, (lab[:-1], lab[1:]), 1)
|
|
56
|
+
if normalize:
|
|
57
|
+
r = T.sum(1, keepdims=True)
|
|
58
|
+
T = np.divide(T, r, out=np.zeros_like(T), where=r > 0)
|
|
59
|
+
return T
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def state_transition_network(labels, names: Sequence[str] | None = None, *, weighting: str = "frequency",
|
|
63
|
+
keep_self_loops: bool = True):
|
|
64
|
+
"""State transition network of a label sequence.
|
|
65
|
+
|
|
66
|
+
Parameters
|
|
67
|
+
----------
|
|
68
|
+
labels : array_like of int
|
|
69
|
+
Label codes of consecutive observations (e.g. :func:`spc_zones`).
|
|
70
|
+
names : sequence of str, optional
|
|
71
|
+
Names of the codes (all codes become nodes, also unobserved ones).
|
|
72
|
+
weighting : {"frequency", "probability", "distance"}
|
|
73
|
+
``"frequency"``: the number of transitions (self-loops measure the
|
|
74
|
+
persistence of a state); ``"probability"``: row-normalized frequency,
|
|
75
|
+
the transition probability of a first-order Markov chain; ``"distance"``:
|
|
76
|
+
the frequency multiplied by the zone distance :math:`|a-b|`, so that
|
|
77
|
+
large jumps between zones dominate (self-loops get zero weight).
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
networkx.DiGraph
|
|
82
|
+
Nodes carry ``code``, ``name`` and ``occupancy`` (number of
|
|
83
|
+
observations), edges ``count``, ``probability``, ``distance`` and ``weight``.
|
|
84
|
+
|
|
85
|
+
Examples
|
|
86
|
+
--------
|
|
87
|
+
>>> G = state_transition_network([3, 4, 4, 5, 4, 3], names=["LCL","A-","B-","C-","C+","B+","A+","UCL"])
|
|
88
|
+
>>> G["C+"]["C+"]["count"], round(G["C+"]["B+"]["probability"], 3)
|
|
89
|
+
(1, 0.333)
|
|
90
|
+
"""
|
|
91
|
+
import networkx as nx
|
|
92
|
+
|
|
93
|
+
lab = np.asarray(labels, dtype=np.int64)
|
|
94
|
+
L = int(max(lab.max() + 1, len(names) if names is not None else 0))
|
|
95
|
+
names = [str(s) for s in names] if names is not None else [str(c) for c in range(L)]
|
|
96
|
+
T = transition_matrix(lab, L)
|
|
97
|
+
P = transition_matrix(lab, L, normalize=True)
|
|
98
|
+
occ = np.bincount(lab, minlength=L)
|
|
99
|
+
G = nx.DiGraph(kind="state_transition", weighting=weighting)
|
|
100
|
+
for c in range(L):
|
|
101
|
+
G.add_node(names[c], code=c, name=names[c], occupancy=int(occ[c]))
|
|
102
|
+
for a in range(L):
|
|
103
|
+
for b in range(L):
|
|
104
|
+
if T[a, b] == 0 or (a == b and not keep_self_loops):
|
|
105
|
+
continue
|
|
106
|
+
dist = abs(a - b)
|
|
107
|
+
w = {"frequency": T[a, b], "probability": P[a, b], "distance": T[a, b] * dist}[weighting]
|
|
108
|
+
G.add_edge(names[a], names[b], count=int(T[a, b]), probability=float(P[a, b]), distance=int(dist), weight=float(w))
|
|
109
|
+
return G
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def label_visibility_matrix(G: VisibilityGraph, labels=None, names: Sequence[str] | None = None, *,
|
|
113
|
+
statistic: str = "count", unit: str = "index") -> pd.DataFrame:
|
|
114
|
+
"""Matrix of visibility statistics between label classes.
|
|
115
|
+
|
|
116
|
+
Entry :math:`(a,b)` aggregates the edges :math:`(i,j)` with
|
|
117
|
+
:math:`\\{\\ell_i,\\ell_j\\}=\\{a,b\\}` (the matrix is symmetric; the diagonal
|
|
118
|
+
holds the self-visibility of a class).
|
|
119
|
+
|
|
120
|
+
Parameters
|
|
121
|
+
----------
|
|
122
|
+
statistic : {"count", "mean_span", "median_span", "min_span", "max_span", "density"}
|
|
123
|
+
``"density"`` divides the counts by the number of node pairs of the two
|
|
124
|
+
classes.
|
|
125
|
+
unit : {"index", "time"}
|
|
126
|
+
Unit of the spans.
|
|
127
|
+
"""
|
|
128
|
+
lab, names, L = _labels_of(G, labels, names)
|
|
129
|
+
i, j = G.edges[:, 0], G.edges[:, 1]
|
|
130
|
+
a, b = np.minimum(lab[i], lab[j]), np.maximum(lab[i], lab[j])
|
|
131
|
+
sp = G.spans(unit)
|
|
132
|
+
M = np.full((L, L), np.nan)
|
|
133
|
+
if statistic in ("count", "density"):
|
|
134
|
+
M = np.zeros((L, L))
|
|
135
|
+
np.add.at(M, (a, b), 1)
|
|
136
|
+
M = M + np.triu(M, 1).T
|
|
137
|
+
if statistic == "density":
|
|
138
|
+
n = np.bincount(lab, minlength=L).astype(float)
|
|
139
|
+
pairs = np.outer(n, n)
|
|
140
|
+
np.fill_diagonal(pairs, n * (n - 1) / 2)
|
|
141
|
+
M = np.divide(M, pairs, out=np.full_like(M, np.nan), where=pairs > 0)
|
|
142
|
+
else:
|
|
143
|
+
f = {"mean_span": np.mean, "median_span": np.median, "min_span": np.min, "max_span": np.max}[statistic]
|
|
144
|
+
for x in range(L):
|
|
145
|
+
for z in range(x, L):
|
|
146
|
+
s = sp[(a == x) & (b == z)]
|
|
147
|
+
if s.size:
|
|
148
|
+
M[x, z] = M[z, x] = f(s)
|
|
149
|
+
return pd.DataFrame(M, index=names, columns=names)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def label_aggregated_graph(G: VisibilityGraph, labels=None, names: Sequence[str] | None = None, *, unit: str = "index",
|
|
153
|
+
include_empty: bool = False):
|
|
154
|
+
"""Aggregate the visibility edges over label classes (zone-aggregated graph).
|
|
155
|
+
|
|
156
|
+
Returns
|
|
157
|
+
-------
|
|
158
|
+
networkx.Graph
|
|
159
|
+
One node per label class with ``occupancy``; one edge per pair of
|
|
160
|
+
classes that see each other, with ``count``, ``mean_span``,
|
|
161
|
+
``min_span``, ``max_span`` and ``weight`` (= count). Self-loops record the
|
|
162
|
+
self-visibility of a class, e.g. two A\\ :sup:`+` points that see each
|
|
163
|
+
other over two steps — the signature of the WE rule 2 in the paper.
|
|
164
|
+
"""
|
|
165
|
+
import networkx as nx
|
|
166
|
+
|
|
167
|
+
lab, names, L = _labels_of(G, labels, names)
|
|
168
|
+
C = label_visibility_matrix(G, lab, names, statistic="count").to_numpy()
|
|
169
|
+
S = {s: label_visibility_matrix(G, lab, names, statistic=s, unit=unit).to_numpy() for s in ("mean_span", "min_span", "max_span")}
|
|
170
|
+
occ = np.bincount(lab, minlength=L)
|
|
171
|
+
H = nx.Graph(kind=f"label-aggregated-{G.kind}")
|
|
172
|
+
for c in range(L):
|
|
173
|
+
if occ[c] or include_empty:
|
|
174
|
+
H.add_node(names[c], code=c, occupancy=int(occ[c]))
|
|
175
|
+
for x in range(L):
|
|
176
|
+
for z in range(x, L):
|
|
177
|
+
if C[x, z] > 0:
|
|
178
|
+
H.add_edge(names[x], names[z], count=int(C[x, z]), weight=float(C[x, z]),
|
|
179
|
+
**{s: float(S[s][x, z]) for s in S})
|
|
180
|
+
return H
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def label_enrichment(G: VisibilityGraph, labels=None, names: Sequence[str] | None = None, *, n_permutations: int = 0,
|
|
184
|
+
random_state=None) -> pd.DataFrame:
|
|
185
|
+
"""Over- and under-representation of visibility between label classes.
|
|
186
|
+
|
|
187
|
+
The expected number of edges between classes :math:`a\\ne b` under a random
|
|
188
|
+
relabelling of the nodes (labels permuted, graph fixed) is
|
|
189
|
+
:math:`E\\,2n_an_b/(N(N-1))`, and :math:`E\\,n_a(n_a-1)/(N(N-1))` within a
|
|
190
|
+
class, where :math:`E` is the number of edges and :math:`n_a` the class
|
|
191
|
+
sizes. The function returns the observed counts, these exact expectations,
|
|
192
|
+
their :math:`\\log_2` ratio and, with ``n_permutations > 0``, permutation
|
|
193
|
+
:math:`z`-scores.
|
|
194
|
+
|
|
195
|
+
Returns
|
|
196
|
+
-------
|
|
197
|
+
pandas.DataFrame
|
|
198
|
+
One row per unordered pair of classes with columns ``a``, ``b``,
|
|
199
|
+
``observed``, ``expected``, ``log2_ratio`` and (optionally) ``z``.
|
|
200
|
+
"""
|
|
201
|
+
lab, names, L = _labels_of(G, labels, names)
|
|
202
|
+
N, E = lab.size, G.n_edges
|
|
203
|
+
n = np.bincount(lab, minlength=L).astype(float)
|
|
204
|
+
obs = label_visibility_matrix(G, lab, names, statistic="count").to_numpy()
|
|
205
|
+
exp = E * 2 * np.outer(n, n) / (N * (N - 1))
|
|
206
|
+
np.fill_diagonal(exp, E * n * (n - 1) / (N * (N - 1)))
|
|
207
|
+
rows = []
|
|
208
|
+
perm_vals = None
|
|
209
|
+
if n_permutations:
|
|
210
|
+
rng = np.random.default_rng(random_state)
|
|
211
|
+
i, j = G.edges[:, 0], G.edges[:, 1]
|
|
212
|
+
perm_vals = np.zeros((n_permutations, L, L))
|
|
213
|
+
for p in range(n_permutations):
|
|
214
|
+
pl = rng.permutation(lab)
|
|
215
|
+
a, b = np.minimum(pl[i], pl[j]), np.maximum(pl[i], pl[j])
|
|
216
|
+
M = np.zeros((L, L))
|
|
217
|
+
np.add.at(M, (a, b), 1)
|
|
218
|
+
perm_vals[p] = M + np.triu(M, 1).T
|
|
219
|
+
for x in range(L):
|
|
220
|
+
for z in range(x, L):
|
|
221
|
+
if n[x] == 0 or n[z] == 0:
|
|
222
|
+
continue
|
|
223
|
+
r = {"a": names[x], "b": names[z], "observed": int(obs[x, z]), "expected": float(exp[x, z])}
|
|
224
|
+
r["log2_ratio"] = float(np.log2((obs[x, z] + 0.5) / (exp[x, z] + 0.5)))
|
|
225
|
+
if perm_vals is not None:
|
|
226
|
+
sd = perm_vals[:, x, z].std(ddof=1)
|
|
227
|
+
r["z"] = float((obs[x, z] - perm_vals[:, x, z].mean()) / sd) if sd > 0 else float("nan")
|
|
228
|
+
rows.append(r)
|
|
229
|
+
return pd.DataFrame(rows)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def label_features(G: VisibilityGraph, labels=None, names: Sequence[str] | None = None, *,
|
|
233
|
+
include: Sequence[str] = ("counts", "visibility", "transitions"), n_labels: int | None = None) -> dict:
|
|
234
|
+
"""Label-aware features of a labelled visibility graph.
|
|
235
|
+
|
|
236
|
+
* ``"counts"`` — occupancy of every class (``count_<a>``);
|
|
237
|
+
* ``"visibility"`` — number of visibility edges between every unordered pair
|
|
238
|
+
of classes, the entries of the zone-aggregated graph (``vis_<a>_<b>``);
|
|
239
|
+
* ``"transitions"`` — number of transitions between consecutive
|
|
240
|
+
observations for every ordered pair (``trans_<a>_<b>``), the state
|
|
241
|
+
transition network.
|
|
242
|
+
|
|
243
|
+
Every class of the alphabet gets its columns, also when it does not occur,
|
|
244
|
+
so that the features of different series line up.
|
|
245
|
+
"""
|
|
246
|
+
lab, names, L = _labels_of(G, labels, names)
|
|
247
|
+
if n_labels is not None and n_labels > L:
|
|
248
|
+
names = list(names) + [str(c) for c in range(L, n_labels)]
|
|
249
|
+
L = n_labels
|
|
250
|
+
out: dict = {}
|
|
251
|
+
if "counts" in include:
|
|
252
|
+
c = np.bincount(lab, minlength=L)
|
|
253
|
+
out.update({f"count_{names[a]}": int(c[a]) for a in range(L)})
|
|
254
|
+
if "visibility" in include:
|
|
255
|
+
i, j = G.edges[:, 0], G.edges[:, 1]
|
|
256
|
+
a, b = np.minimum(lab[i], lab[j]), np.maximum(lab[i], lab[j])
|
|
257
|
+
M = np.zeros((L, L), dtype=np.int64)
|
|
258
|
+
np.add.at(M, (a, b), 1)
|
|
259
|
+
out.update({f"vis_{names[x]}_{names[z]}": int(M[x, z]) for x in range(L) for z in range(x, L)})
|
|
260
|
+
if "transitions" in include:
|
|
261
|
+
T = transition_matrix(lab, L)
|
|
262
|
+
out.update({f"trans_{names[x]}_{names[z]}": int(T[x, z]) for x in range(L) for z in range(L)})
|
|
263
|
+
return out
|