Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/generators/time_series.py: 36%
14 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
1"""
2Time Series Graphs
3"""
4import itertools
6import networkx as nx
8__all__ = ["visibility_graph"]
11@nx._dispatch(graphs=None)
12def visibility_graph(series):
13 """
14 Return a Visibility Graph of an input Time Series.
16 A visibility graph converts a time series into a graph. The constructed graph
17 uses integer nodes to indicate which event in the series the node represents.
18 Edges are formed as follows: consider a bar plot of the series and view that
19 as a side view of a landscape with a node at the top of each bar. An edge
20 means that the nodes can be connected by a straight "line-of-sight" without
21 being obscured by any bars between the nodes.
23 The resulting graph inherits several properties of the series in its structure.
24 Thereby, periodic series convert into regular graphs, random series convert
25 into random graphs, and fractal series convert into scale-free networks [1]_.
27 Parameters
28 ----------
29 series : Sequence[Number]
30 A Time Series sequence (iterable and sliceable) of numeric values
31 representing times.
33 Returns
34 -------
35 NetworkX Graph
36 The Visibility Graph of the input series
38 Examples
39 --------
40 >>> series_list = [range(10), [2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1, 3]]
41 >>> for s in series_list:
42 ... g = nx.visibility_graph(s)
43 ... print(g)
44 Graph with 10 nodes and 9 edges
45 Graph with 12 nodes and 18 edges
47 References
48 ----------
49 .. [1] Lacasa, Lucas, Bartolo Luque, Fernando Ballesteros, Jordi Luque, and Juan Carlos Nuno.
50 "From time series to complex networks: The visibility graph." Proceedings of the
51 National Academy of Sciences 105, no. 13 (2008): 4972-4975.
52 https://www.pnas.org/doi/10.1073/pnas.0709247105
53 """
55 # Sequential values are always connected
56 G = nx.path_graph(len(series))
57 nx.set_node_attributes(G, dict(enumerate(series)), "value")
59 # Check all combinations of nodes n series
60 for (n1, t1), (n2, t2) in itertools.combinations(enumerate(series), 2):
61 # check if any value between obstructs line of sight
62 slope = (t2 - t1) / (n2 - n1)
63 offset = t2 - slope * n2
65 obstructed = any(
66 t >= slope * n + offset
67 for n, t in enumerate(series[n1 + 1 : n2], start=n1 + 1)
68 )
70 if not obstructed:
71 G.add_edge(n1, n2)
73 return G