visibility_graph   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 44
dl 0
loc 67
rs 10
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A obstruction_predicate() 0 8 1
A sliding_window_visibility_graph() 0 6 2
A visibility_graph() 0 19 4
1
import itertools
2
from collections.abc import Iterable
3
4
import more_itertools
5
import networkx as nx
6
from matplotlib import pyplot
7
8
9
def sliding_window_visibility_graph(series: Iterable[float], window_size: int | None = None):
10
    if window_size:
11
        yield from itertools.chain(
12
            visibility_graph(subseries) for subseries in more_itertools.sliding_window(series, window_size))
13
    else:
14
        yield visibility_graph(series)
15
16
17
def obstruction_predicate(n1, t1, n2, t2):
18
    slope = (t2 - t1) / (n2 - n1)
19
    constant = t2 - slope * n2
20
21
    def is_obstruction(n, t):
22
        return t >= constant + slope * n
23
24
    return is_obstruction
25
26
27
def visibility_graph(series: Iterable[float]):
28
    graph = nx.Graph()
29
    # Check all combinations of nodes n series
30
31
    for s1, s2 in itertools.combinations(enumerate(series), 2):
32
        n1, t1 = s1
33
        n2, t2 = s2
34
35
        if n2 == n1 + 1:
36
            graph.add_node(n1, value=t1)
37
            graph.add_node(n2, value=t2)
38
            graph.add_edge(n1, n2)
39
        else:
40
            is_obstruction = obstruction_predicate(n1, t1, n2, t2)
41
            obstructed = any(is_obstruction(n, t) for n, t in enumerate(series) if n1 < n < n2)
42
            if not obstructed:
43
                graph.add_edge(n1, n2)
44
45
    return graph
46
47
48
if __name__ == '__main__':
49
    series_list = [
50
        # range(10),
51
        # [2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1, 3, 4],
52
        [-(x ** 3) for x in range(-10, 11)],
53
        # [2, 1, 3, 4, 2, 1, 4, 3, 1, 1, 3, 4, 2, 4, 1, 3],
54
        # random.sample(range(1000), 500)
55
    ]
56
57
    for s in series_list:
58
        g = visibility_graph(s)
59
        print(g)
60
61
        pos = [[x, 0] for x in range(len(s))]
62
        labels = nx.get_node_attributes(g, 'value')
63
        nx.draw_networkx_nodes(g, pos)
64
        nx.draw_networkx_labels(g, pos, labels=labels)
65
        nx.draw_networkx_edges(g, pos, arrows=True, connectionstyle='arc3,rad=-1.57079632679')
66
        pyplot.show()
67