I will then learn to convert my time series data into a network map using visibility_graph. But when I typed in my data, I didn't get a very obvious network, and most of them just presented a ring. https://github.com/rgarcia-herrera/visibility_graph
Below is my data example
[ 8.34 3.24 9.82 2.09 6.43 2.88 6.51 6.47 12.41 6.52 5.65 6.13
5.28 6.87 13.22 7.05 13.65 5.7 16.88 3.43 15.81 4.87 9.74 4.43
18.77 8.24 16.2 10.58 18.31 10.4 12.33 8.21 22.74 5.67 19.18 8.55
16.9 10.22 21.68 8.61 17.81 11.4 27.51 11.19 25.78 8.31 29.87 6.35
24.14 10.36 20.13 12.01 25.47 6.66 14.09 10.72 23.52 7.11 24.88 9.75
22.6 7.24]
Below is the code I tried (I tried smoothing)
from visibility_graph import visibility_graph
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import scipy as sp
import scipy.ndimage
for user, group in data.groupby('cons_no'):
for i in range(12): # every month
u = pd.DataFrame(group)
u.sort_index(inplace=True) # Time sorting
values = []
for row in u.itertuples():
if row.Index.year == 2017 and row.Index.month == i + 1:
values.append((round(row.pap_r1, 1), round(row.pap_r2, 1)))
temp = []
for v in values:
temp.append(v[0])
temp.append(v[1])
temp = np.array(temp)
# Min = np.min(temp)
# Max = np.max(temp)
# temp = [max_min(x, Max, Min) for x in temp]
temp = sp.ndimage.gaussian_filter(temp, sigma=1, mode='constant')
print(temp)
temp = [round(x, 1) for x in temp]
temp = np.log10(temp)
values = temp
# print(values)
G = visibility_graph(values)
plt.subplot(121)
nx.draw_networkx(G, with_labels=False, node_size=50)
plt.title(str(user))
plt.savefig('./user_' + str(user) + '_com.png')
print('./user_' + str(user) + '_com.png')
# plt.show()
I hope someone can help me understand how to properly modify my data so that visibility_graph appears on the network.
Answer my own question. I think there is a bug in this package. So I modified the source code to make it work properly.
from itertools import combinations
import networkx as nx
def visibility_graph(series):
g = nx.Graph()
# convert list of magnitudes into list of tuples that hold the index
tseries = []
n = 0
for magnitude in series:
tseries.append( (n, magnitude ) )
n += 1
# contiguous time points always have visibility
for n in range(0,len(tseries)-1):
(ta, ya) = tseries[n]
(tb, yb) = tseries[n+1]
g.add_node(ta, mag=ya)
g.add_node(tb, mag=yb)
g.add_edge(ta, tb)
for a,b in combinations(tseries, 2):
# two points, maybe connect
(ta, ya) = a
(tb, yb) = b
connect = True
# let's see all other points in the series
for tc, yc in tseries:
# other points, not a or b
if tc != ta and tc != tb and ta < tc < tb: # The condition here is the key.
# does c obstruct?
if yc > yb + (ya - yb) * ( (tb - tc) / (tb - ta) ):
connect = False
if connect:
g.add_edge(ta, tb)
return g