def ring(N, R): # Create glias ring g1 = nx.cycle_graph(N) for glia in range(0, N): for r in range(1, R + 1): k = glia + r if k > N - 1: k = k - N g1.add_edge(glia, k) k = glia - r if k < 0: k = k + N g1.add_edge(glia, k) # Create neurons ring g2 = nx.cycle_graph(N) # Create inter adjacency matrix adj_block = mx.lil_matrix(np.zeros((N * 2, N * 2))) adj_block[0:N, N:2 * N] = np.identity(N) adj_block += adj_block.T mg = mx.MultilayerGraph(list_of_layers=[g1, g2], inter_adjacency_matrix=adj_block) return mg
def build_mx_multigraph(func_mat, dwi_mat, name, namer_dir): """ It creates a symmetric (undirected) MultilayerGraph object from vertex-aligned structural and functional connectivity matrices. Parameters: ----------- func_mat : ndarray Functional adjacency matrix of size N x N. dwi_mat : ndarray Structural adjacency matrix of size N x N. name : str Intended name of the multiplex object. namer_dir : str Path to output directory. Returns: -------- mg_path : str A filepath to a gpickled MultilayerGraph object References ---------- .. [1] R. Amato, N. E Kouvaris, M. San Miguel and A. Diaz-Guilera, Opinion competition dynamics on multiplex networks, New J. Phys. DOI: https://doi.org/10.1088/1367-2630/aa936a .. [2] N. E. Kouvaris, S. Hata and A. Diaz-Guilera, Pattern formation in multiplex networks, Scientific Reports 5, 10840 (2015). http://www.nature.com/srep/2015/150604/srep10840/full/srep10840.html .. [3] A. Sole-Ribata, M. De Domenico, N. E. Kouvaris, A. Diaz-Guilera, S. Gomez and A. Arenas, Spectral properties of the Laplacian of a multiplex network, Phys. Rev. E 88, 032807 (2013). http://journals.aps.org/pre/abstract/10.1103/PhysRevE.88.032807 """ import networkx as nx import multinetx as mx import pickle5 as pickle mg = mx.MultilayerGraph() N = dwi_mat.shape[0] adj_block = mx.lil_matrix(np.zeros((N * 2, N * 2))) adj_block[0:N, N:2 * N] = np.identity(N) adj_block += adj_block.T G_dwi = nx.from_numpy_matrix(dwi_mat) G_func = nx.from_numpy_matrix(func_mat) mg.add_layer(G_dwi) mg.add_layer(G_func) mg.layers_interconnect(inter_adjacency_matrix=adj_block) mg.name = name # Save mG to pickle graph_dir = f"{namer_dir}/mplx_graphs" if not os.path.isdir(graph_dir): os.mkdir(graph_dir) mG_path = f"{graph_dir}/{name}.pkl" nx.write_gpickle(mg, mG_path, protocol=2) return mG_path
import numpy as np import matplotlib.pyplot as plt import multinetx as mx N = 10 g1 = mx.erdos_renyi_graph(N, 0.07, seed=218) g2 = mx.erdos_renyi_graph(N, 0.07, seed=211) adj_block = mx.lil_matrix(np.zeros((N * 2, N * 2))) adj_block[0:N, N:2 * N] = np.identity(N) # L_12 adj_block += adj_block.T mg = mx.MultilayerGraph(list_of_layers=[g1, g2], inter_adjacency_matrix=adj_block) mg.set_edges_weights(inter_layer_edges_weight=2) mg.set_intra_edges_weights(layer=0, weight=1) mg.set_intra_edges_weights(layer=1, weight=2) fig = plt.figure(figsize=(10, 10)) ax1 = fig.add_subplot(122) ax1.axis('off') ax1.set_title('regular interconnected network') pos = mx.get_position(mg, mx.fruchterman_reingold_layout(mg.get_layer(0)), layer_vertical_shift=1.4, layer_horizontal_shift=0.0, proj_angle=7)
if N > 4 and N % 2 == 0: g1.add_edge(0, 3) g2.add_edge(0, 3) g3.add_edge(0, 3) k = 4 j = N - 1 while True: g1.add_edge(k, j) g2.add_edge(k, j) g3.add_edge(k, j) k = k + 1 j = j - 1 if j - k < 2: break adj_block = mx.lil_matrix(np.zeros((N * 3, N * 3))) adj_block[0:N, N:2 * N] = np.identity(N) # L_12 adj_block[N:2 * N, 2 * N:3 * N] = np.identity(N) # L_23 adj_block += adj_block.T adj_block[adj_block > 1] = 1 mg = mx.MultilayerGraph(list_of_layers=[g1, g2, g3], inter_adjacency_matrix=adj_block) mg = setLayerAttributes(mg) AttributesmVelocity = nx.get_edge_attributes(mg, 'maxVelocity') AttributesCapacity = nx.get_edge_attributes(mg, 'capacity') AttributesDistance = nx.get_edge_attributes(mg, 'distance') AttributesTime = nx.get_edge_attributes(mg, 'time') AttributesEnergy = nx.get_edge_attributes(mg, 'energy')
def main(): data = collect_data('results/t6/') comm = collect_community('results/t6/') def find_best(data, method): key = max(data[method].iteritems(), key=operator.itemgetter(1))[0] y = data[method][key] return y, key, method print 'LART', data['lart']['9.0_1.0_1.0'] print 'PMM', data['pmm']['30.0_140.0'] print 'Glouvain', data['glouvain']['1.0_1.0'] gl = find_best(data, 'glouvain') ll = find_best(data, 'lart') pl = find_best(data, 'pmm') print 'LART', ll print 'PMM', pl print 'Glouvain', gl best = max([gl, ll, pl], key=operator.itemgetter(0)) best_comm = {} for b in comm[best[2]][best[1]].split('\n'): if b: a, l, c = b.split(',') best_comm['%s-%s' % (a, l)] = int(c) layers = {'RT': nx.Graph(), 'ff': nx.Graph(), 'Re': nx.Graph()} ids = {} counter = 0 groups = [] with open('data/t6/dk', 'r') as fd: for l in fd.readlines(): a1, a2, layer = l.replace('\n', '').split(",") if a1 not in ids: ids[a1] = counter counter = counter + 1 if a2 not in ids: ids[a2] = counter counter = counter + 1 groups.append(best_comm['%s-%s' % (a1, layer)]) groups.append(best_comm['%s-%s' % (a2, layer)]) for k, v in layers.iteritems(): v.add_node(ids[a1], label=best_comm['%s-%s' % (a1, layer)]) v.add_node(ids[a2], label=best_comm['%s-%s' % (a2, layer)]) layers[layer].add_edge(ids[a1], ids[a2]) truth = {} with open('data/t6/dk_truth', 'r') as fd: for l in fd.readlines(): actor, party = l.replace('\n', '').split(',') truth[actor] = party mapping = dict(zip(sorted(groups), count())) N, L = len(layers['ff'].nodes()), len(layers.keys()) adj_block = mx.lil_matrix(np.zeros((N * L, N * L))) for i in xrange(L): for j in xrange(L): if i < j: adj_block[N * i:N * (i + 1), N * j:(j + 1) * N] = np.identity(N) adj_block += adj_block.T mg = mx.MultilayerGraph(list_of_layers=[v for k, v in layers.items()]) #inter_adjacency_matrix = adj_block) mg.set_edges_weights(intra_layer_edges_weight=1) #inter_layer_edges_weight=2) fig = plt.figure(figsize=(16, 16)) plt.title('Twitter data of the Danish 2015 election') stats = collections.defaultdict(list) for k, v in best_comm.items(): stats[v].append(k) stats2 = collections.defaultdict(dict) for k, v in stats.items(): for e in v: actor, _ = e.split('-') if truth[actor] in stats2[k]: stats2[k][truth[actor]] += 1 else: stats2[k][truth[actor]] = 1 left = [ 'Dansk Folkeparti', 'Venstre', 'Liberal Alliance', 'Det Konservative Folkeparti', 'KristenDemokraterne', ] right = [ 'Socialistisk Folkeparti', 'Radikale Venstre', 'Socialdemokratiet', 'Alternativet', 'Enhedslisten' ] out = 'Udenfor partierne' for k, v in stats2.items(): total = 0 for k1, v1 in v.items(): total += v1 pscore = 0 for k1, v1 in v.items(): if k1 in left: pscore += (stats2[k][k1] * 1) if k1 in right: pscore -= (stats2[k][k1] * 1) stats2[k][k1] = round(float(v1) / float(total), 2) stats2[k]['nodes'] = filter( lambda x, i=mg, k=k: i.node[x]['label'] == k, mg.node) stats2[k]['pscore'] = pscore / float(total) stats2 = dict(stats2) if len(sys.argv) > 1 and sys.argv[1] == 'heat': cmap = plt.get_cmap('RdBu_r') colors = [stats2[mg.node[n]['label']]['pscore'] for n in mg.nodes()] pos = mx.get_position(mg, nx.spring_layout(layers[layers.keys()[2]], weight='pscore'), layer_vertical_shift=0.2, layer_horizontal_shift=0.0, proj_angle=47) for key, val in stats2.items(): set_trace() mx.draw_networkx_nodes(mg, pos=pos, node_size=100, with_labels=False, nodelist=val['nodes'], label=key, node_color=[colors[n] for n in val['']], cmap=cmap) else: val_map = { 0: 'k', 1: 'r', 2: 'g', 3: 'b', 4: 'c', 5: 'm', 6: 'y', 7: '0.75', 8: 'w', } colors = [val_map[mg.node[n]['label']] for n in mg.nodes()] pos = mx.get_position(mg, nx.spring_layout(layers[layers.keys()[2]]), layer_vertical_shift=0.2, layer_horizontal_shift=0.0, proj_angle=47) for k, v in stats2.items(): mx.draw_networkx_nodes(mg, pos=pos, node_size=100, with_labels=False, nodelist=v['nodes'], label=k, node_color=[colors[n] for n in v['nodes']], cmap=plt.get_cmap('Set2')) mx.draw_networkx_edges(mg, pos=pos, edge_color='b') fig.tight_layout() plt.legend(numpoints=1, loc=1) plt.xticks([]) plt.yticks([]) plt.show()
def multilayer(self, filename='multilayer_network'): import numpy as np import matplotlib.pyplot as plt import multinetx as mx import networkx as nx from mpl_toolkits.basemap import Basemap # %% Define the type of interconnection between the layers N = len(self.poi_nodes) + len(self.user_nodes) N1 = len(self.poi_nodes) adj_block = mx.lil_matrix(np.zeros((N, N))) for row in self.user_poi_s.iterrows(): user_ind = self.user_nodes[self.user_nodes['userId'] == row[1] ['userId']].index[0] pos_ind = self.poi_nodes[self.poi_nodes['venueId'] == row[1] ['venueId']].index[0] adj_block[pos_ind, user_ind] = row[1]['weight'] adj_block += adj_block.T # %% multilayer network poi_layer = nx.Graph(layer='POI') poi_layer.add_nodes_from(self.poi_nodes.index.values) poi_layer.add_weighted_edges_from(self.poi_edges) user_layer = nx.DiGraph(layer='User') user_layer.add_nodes_from(self.user_nodes.index.values) user_layer.add_weighted_edges_from(self.user_edges) mg = mx.MultilayerGraph(list_of_layers=[poi_layer, user_layer], inter_adjacency_matrix=adj_block) # venue position in decimal lat/lon lats_v = list(self.poi_nodes['latitude']) lons_v = list(self.poi_nodes['longitude']) min_lat = min(lats_v) max_lat = max(lats_v) min_lon = min(lons_v) max_lon = max(lons_v) # user position in decimal lat/lon lats_u = list(self.user_nodes['latitude']) lons_u = list(self.user_nodes['longitude']) min_lat = min(min_lat, min(lats_u)) max_lat = max(max_lat, max(lats_u)) min_lon = min(min_lon, min(lons_u)) max_lon = max(max_lon, max(lons_u)) m = Basemap(projection='merc', llcrnrlon=min_lon, llcrnrlat=min_lat, urcrnrlon=max_lon, urcrnrlat=max_lat, lat_ts=0, resolution='i', suppress_ticks=True) # convert lat and lon to map projection x, y = m(lons_v, lats_v) ppos = {} n = 0 for v in self.poi_nodes.index: ppos[v] = np.asarray([x[n], y[n]]) n += 1 # convert lat and lon to map projection x, y = m(lons_u, lats_u) n = 0 for v in self.user_nodes.index: ppos[v] = np.asarray([x[n], y[n]]) n += 1 target_userID = list(self.similar_users['userId1'])[0] node_of_target_user = self.user_nodes[self.user_nodes['userId'] == target_userID].index[0] for i in range(2): pos = mx.get_position(mg, ppos, layer_vertical_shift=1000.0, layer_horizontal_shift=400.0, proj_angle=0.2) fig, ax2 = plt.subplots(figsize=(10, 5)) # ax2.axis('off') ax2.set_title( 'Multilayer Network of User and PoI (Target User ID: {0})'. format(target_userID)) mg.set_edges_weights(inter_layer_edges_weight=3) mg.set_intra_edges_weights(layer=0, weight=5) # mg.set_intra_edges_weights(layer=1,weight=2) mx.draw_networkx( mg, pos=pos, ax=ax2, node_size=50, with_labels=False, node_color=[ 'y' if a < N1 else ('brown' if a == node_of_target_user else 'g') for a in mg.nodes() ], edge_color=[mg[a][b]['weight'] for a, b in mg.edges()], edge_cmap=plt.cm.Blues) # plt.show() plt.savefig('output/{0}.png'.format(filename), dpi=500, bbox_inches='tight')
## User layer # user_nodes = pd.Series(userIds_s, index=range(len(poi_nodes), len(poi_nodes) + len(userIds_s))) df = pd.read_csv('data/dataset_TSMC2014_NYC.csv') user_nodes = df[[w in userIds_s for w in df['userId']]].groupby('userId', as_index=False).mean()[['userId','latitude','longitude']] user_nodes = user_nodes.set_index(pd.Index(range(len(poi_nodes), len(poi_nodes) + len(user_nodes)))) user_edges = [] for row in users_s1.iterrows(): ind1 = user_nodes[user_nodes['userId'] == row[1]['userId1']].index[0] ind2 = user_nodes[user_nodes['userId'] == row[1]['userId2']].index[0] user_edges.append((ind1, ind2, row[1]['similarity'])) # %% Define the type of interconnection between the layers N = len(poi_nodes)+len(user_nodes) N1 = len(poi_nodes) adj_block = mx.lil_matrix(np.zeros((N,N))) user_poi_s = user_poi_s1.append(user_poi_s2) user_poi_s = user_poi_s.loc[~user_poi_s.index.duplicated(keep='last')] for row in user_poi_s.iterrows(): user_ind = user_nodes[user_nodes['userId'] == row[1]['userId']].index[0] pos_ind = poi_nodes[poi_nodes['venueId'] == row[1]['venueId']].index[0] adj_block[pos_ind, user_ind] = row[1]['weight'] adj_block += adj_block.T # %% multilayer network poi_layer = nx.Graph(layer='POI') poi_layer.add_nodes_from(poi_nodes.index.values)