1 def visibility_graph(series): 2 g = nx.Graph() 3 4 # convert list of magnitudes into list of tuples that hold the index 5 tseries = [] 6 n = 0 7 for magnitude in series: 8 tseries.append((n, magnitude)) 9 n += 1 10 11 '''add nodes''' 12 for i in range(len(tseries)): 13 (ta, ya) = tseries[i] 14 g.add_node(ta, mag=ya) 15 16 '''add edges''' 17 for a, b in combinations(tseries, 2): 18 (ta, ya) = a 19 (tb, yb) = b 20 connect = True 21 if tb - ta > 1: 22 (tc, yc) = max(tseries[ta + 1:tb]) #我的算法 23 print(tc,yc) 24 if (yc > yb + (ya - yb) * ((tb - tc) / (tb - ta))): 25 connect = False 26 27 # medium = tseries[ta+1 :tb] #别人的算法 28 # for tc, yc in medium: 29 # if yc > yb + (ya - yb) * ((tb - tc) / (tb - ta)): 30 # connect = False 31 32 if connect: 33 g.add_edge(ta, tb) 34 35 return g
在第22行中,由于tseires 变成了嵌入元组, 所以max(tseries[ta + 1:tb]) 会取下标最大的值, 而非最大的第二个元素.
[(0, 0.19024852355156963),
(1, 0.6660417262541884),
(2, 0.395523497583831),
(3, 0.19024852355156963)]