-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultitool.py
More file actions
750 lines (504 loc) · 27.1 KB
/
Copy pathmultitool.py
File metadata and controls
750 lines (504 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 21 22:18:19 2022
@author: Patrick Gambill in collaboration with Dr. Daryl DeFord
"""
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from networkx.algorithms import community as com
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
from sklearn.cluster import AgglomerativeClustering
from sklearn.manifold import MDS
def readvillage(path):
''' Import the village data
Args:
path: A filepath to the data
Returns:
g: A NetworkX graph generated from the data'''
import math
import numpy as np
import networkx as nx
a = np.genfromtxt (path, delimiter=",") # The network data is imported as a vector. We need to reshape it into a matrix
a = np.reshape(a,[int(math.sqrt(len(a))),int(math.sqrt(len(a)))])
g = nx.from_numpy_matrix(a)
return g
def load(name):
'''This will load the data for an entire village as a multiplex network
Args:
name: A string containing the name of the village, ie "HH_1"
Returns:
M: The multitool.Multiplex object representing the village
'''
name = "Village/" + name
paths = [name + "_borrowmoney.csv", name + "_giveadvice.csv", name + "_helpdecision.csv", name + "_keroricecome.csv",
name + "_keroricego.csv", name + "_lendmoney.csv", name + "_medic.csv", name + "_nonrel.csv",
name + "_rel.csv", name + "_templecompany.csv", name + "_visitcome.csv", name + "_visitgo.csv"]
graphs = [readvillage(path) for path in paths]
M = Multiplex(graphs)
return M
def plot(G, title="", layout = nx.random_layout, node_color='black', edge_color='#dddddd', node_size=50, width=1):
''' Plot the nx graph
Args:
G: The graph to plot
title: Title the plot
layout: The type of layout. This will be a nx.layout function. Default is nx.random_layout
node_color: Node color for the plot. Default is black. This can also be a dictionary of numbers corresponding to distinct node colors
edge_color: Edge color for the plot. Default is light grey
node_size: Node size for plot. Default is 50
width: Edge width for plot. Default is 1
Returns:
None
'''
pos = layout(G)
plt.figure()
ax = plt.gca()
ax.set_title(title)
nx.draw(G,pos,node_size=node_size,node_color=node_color,edge_color=edge_color,width=width, cmap=plt.cm.tab20b)
class Multiplex:
'''This class represents multiplex networks.'''
def __init__(self, graphs):
'''
Args:
graphs: List of nx graph objects. Each graph in the list will be a layer in the multiplex network
Returns:
None
'''
nodes = graphs[0].nodes()
for graph in graphs:
if not graph.nodes() == nodes:
raise ValueError("The node sets of each layer needs to be the same in a multiplex network")
self.layers = graphs
self.nodes = graphs[0].nodes()
self.edges = [graph.edges() for graph in graphs]
for i in range(len(graphs)):
if not nx.is_connected(graphs[i]):
print("Warning: In layer " + str(i) + ", the graph is not connected.")
return
def flatten(self, weight_count = False):
'''Combine all layers into a single network
Args:
weight_count: This will make the flattened network weighted with the weight of an edge as the number
of times an arc appears over all layers
Returns:
G: The flattened network
The flattened network will create a network on the node set such that two nodes are adjacent in the flattened
network if they are adjacent on one layer of the multiplex network
'''
edges = []
for edgeset in self.edges:
for edge in edgeset:
edges.append(edge)
G = nx.Graph()
G.add_nodes_from(self.nodes)
G.add_edges_from(edges)
if weight_count:
#This will set the edge weight as the
counts = nx.adjacency_matrix(self.layers[0]).todense()
for i in range(1,len(self.layers)):
counts += nx.adjacency_matrix(self.layers[i]).todense()
for edge in G.edges:
G[edge[0]][edge[1]]['weight'] = counts[edge[0],[edge[1]]]
return G
def plots(self, layout = nx.random_layout, node_color='black', edge_color='#dddddd', node_size=50, width=1):
'''Plot all layers of the multiplex network
Args:
layout: The type of layout. This will be a nx.layout function. Default is nx.random_layout
node_color: Node color for the plot. Default is black. This can also be a dictionary of numbers corresponding to distinct node colors
edge_color: Edge color for the plot. Default is light grey
node_size: Node size for plot. Default is 50
width: Edge width for plot. Default is 1
Returns:
None
'''
for i in range(len(self.layers)):
plot(self.layers[i], "Layer " + str(i), layout = layout, node_size=node_size,node_color=node_color,edge_color=edge_color,width=width)
return
def plot(self, i, layout = nx.random_layout, node_color='black', edge_color='#dddddd', node_size=50, width=1):
'''Plot layer i of the multiplex network
Args:
i: The layer number.
layout: The type of layout. This will be a nx.layout function. Default is nx.random_layout
node_color: Node color for the plot. Default is black. This can also be a dictionary of numbers corresponding to distinct node colors
edge_color: Edge color for the plot. Default is light grey
node_size: Node size for plot. Default is 50
width: Edge width for plot. Default is 1
Returns:
None
'''
if not i in range(len(self.layers)):
raise ValueError("Index out of range.")
plot(self.layers[i], "Layer " + str(i), layout = layout, node_size=node_size,node_color=node_color,edge_color=edge_color,width=width)
return
def plot_flat(self, layout = nx.random_layout, node_color='black', edge_color='#dddddd', node_size=50, width=1):
'''Plot the flattened network
Args:
layout: The type of layout. This will be a nx.layout function. Default is nx.random_layout
node_color: Node color for the plot. Default is black. This can also be a dictionary of numbers corresponding to distinct node colors
edge_color: Edge color for the plot. Default is light grey
node_size: Node size for plot. Default is 50
width: Edge width for plot. Default is 1
Returns:
None
'''
G = self.flatten()
plot(G, '''Flattened Network''', layout = layout, node_size=node_size,node_color=node_color,edge_color=edge_color,width=width)
return
def spectral_embedding(self, i, k):
'''
Computes the first several diffusion eigenmodes of the network at layer i of the multiplex network.
Args:
i: The layer number.
k: The number of non- trivial eigenmodes.
Returns:
X: An n-by-k numpy array holding the eigenmodes.
Let G be the network on layer i.
Each column of X holds an eigenmode of G. Columns will be the eigenmodes associated
with increasing positive eigenvalues.
The entries in each column are ordered according to the natural ordering of the
nodes in the NetworkX data structure.
From More Clustering Assignment from KSU Math 726 Spring 2022, Taught by Albin and Poggi-Corradini.
'''
import networkx as nx
import scipy.sparse.linalg as sla
try:
G = self.layers[i]
except:
print(str(i) + " is not one of the layers in the multiplex network.")
L = nx.normalized_laplacian_matrix(G).astype(float)
#Get the k smallest eigenvalues and their eigenvectors
e,X = sla.eigsh(L,k+1,which='SM')
#Split the nodes based on the cluster
return X[:,1:]
def spectral_cluster(self, i, k, m = 2, random_state=None):
'''
Computes the spectral cluster of the given layer
Args:
i: The layer number.
k: The number of non-trivial eigenmodes.
m: The number of clusters. Default is 2
random_state: The seed used for kmeans. Default is None
Returns:
kmeans.labels_: A list with the cluster number of each node
Let G be the network on layer i.
Each column of X holds an eigenmode of G. Columns will be the eigenmodes associated
with increasing positive eigenvalues.
The entries in each column are ordered according to the natural ordering of the
nodes in the NetworkX data structure.
From More Clustering Assignment from KSU Math 726 Spring 2022, Taught by Albin and Poggi-Corradini.
'''
from sklearn.cluster import KMeans
#Get the spectral embedding
X = self.spectral_embedding(i, k)
kmeans = KMeans(n_clusters=m, random_state=random_state)
kmeans.fit(X)
return kmeans.labels_
def multi_cluster1(self, k, m=2, eps=False, min_samples = 2):
'''
This will attempt to cluster the nodes considering the contributions from each layer
of the multiplex network.
Args:
k: number of eigenvalues to compute when clustering by layer
m: number of clusters in a layer
eps: The maximum allowed distance between two samples in the same neighborhood. If False, this is calculated as number of layers / 5 + 1
min_samples: The number of samples in a neighborhood required for a core point
Returns:
db.labels_: A list with the cluster number of each node
'''
from sklearn.cluster import DBSCAN
#First let's compute a metric between nodes. The first attempt will build on Hamming distance
if not eps:
eps = len(self.layers)/5 + 1
n = len(self.nodes)
#We will start all pairs of distinct nodes with a distance of 1 apart.
X = np.ones((n,n))
for i in range(n):
X[i][i] = 0
#Now, for each layer, we will add 1 to the distance if the nodes are in a different cluster
numlayers = len(self.layers)
for i in range(numlayers):
clust = self.spectral_cluster(i, k, m)
for x in range(n):
for y in range(n):
if not clust[x] == clust[y]:
X[x][y] += 1
#Now that we have the Hamming distance built, let's use this to cluster the nodes
db = DBSCAN(eps, metric="precomputed", min_samples = min_samples)
db.fit(X)
return db.labels_
def multi_cluster2(self, eps=2, min_samples = 2):
'''
This will attempt to cluster the nodes considering the average distance between nodes between layers.
Args:
eps: The maximum allowed distance between two samples in the same neighborhood.
min_samples: The number of samples in a neighborhood required for a core point
Returns:
db.labels_: A list with the cluster number of each node
'''
from sklearn.cluster import DBSCAN
#First let's compute a metric between nodes. The first attempt will build on average path length between nodes
n = len(self.nodes)
#Initialize the distance matrix
X = np.zeros((n,n))
#Now, for each layer, we will add 1 to the distance if the nodes are in a different cluster
numlayers = len(self.layers)
for i in range(numlayers):
paths = dict(nx.shortest_path_length(self.layers[i]))
for x in range(n):
for y in range(n):
X[x][y] += paths[x][y]
X /= len(self.layers)
#Now that we have the Hamming distance built, let's use this to cluster the nodes
db = DBSCAN(eps, metric="precomputed")
db.fit(X)
return db.labels_
def multi_cluster3(self, k, m=2, eps=False, min_samples = 2, linkage='average'):
'''
This will attempt to cluster the nodes considering the contributions from each layer
of the multiplex network.
Args:
k: number of eigenvalues to compute when clustering by layer
m: number of clusters in a layer
eps: The maximum allowed distance between two samples in the same neighborhood. If False, this is calculated as number of layers / 5 + 1
min_samples: The number of samples in a neighborhood required for a core point
linkage: The linkage criterion used when merging clusters. These are listed in the sklearn.cluster.AgglomerativeClustering documentation
Returns:
ac.labels_: A list with the cluster number of each node
'''
from sklearn.cluster import AgglomerativeClustering
#First let's compute a metric between nodes. The first attempt will build on Hamming distance
if not eps:
eps = len(self.layers)/5 + 1
n = len(self.nodes)
#We will start all pairs of distinct nodes with a distance of 1 apart.
X = np.ones((n,n))
for i in range(n):
X[i][i] = 0
#Now, for each layer, we will add 1 to the distance if the nodes are in a different cluster
numlayers = len(self.layers)
for i in range(numlayers):
clust = self.spectral_cluster(i, k, m)
for x in range(n):
for y in range(n):
if not clust[x] == clust[y]:
X[x][y] += 1
#Now that we have the Hamming distance built, let's use this to cluster the nodes
ac = AgglomerativeClustering(eps, affinity="precomputed", linkage=linkage)
ac.fit(X)
return ac.labels_
def multi_cluster4(self, eps=2, min_samples = 2, linkage='average'):
'''
This will attempt to cluster the nodes considering the average distance between nodes between layers.
This method is broken
Args:
eps: The maximum allowed distance between two samples in the same neighborhood.
min_samples: The number of samples in a neighborhood required for a core point
linkage: The linkage criterion used when merging clusters. These are listed in the sklearn.cluster.AgglomerativeClustering documentation
Returns:
ac.labels_: A list with the cluster number of each node
'''
from sklearn.cluster import AgglomerativeClustering
#First let's compute a metric between nodes. The first attempt will build on average path length between nodes
n = len(self.nodes)
#Initialize the distance matrix
X = np.zeros((n,n))
#Now, for each layer, we will add 1 to the distance if the nodes are in a different cluster
numlayers = len(self.layers)
for i in range(numlayers):
paths = dict(nx.shortest_path_length(self.layers[i]))
for x in range(n):
for y in range(n):
X[x][y] += paths[x][y]
X /= len(self.layers)
#Now that we have the Hamming distance built, let's use this to cluster the nodes
ac = AgglomerativeClustering(eps, affinity="precomputed", linkage=linkage)
ac.fit(X)
return ac.labels_
def multi_cluster5(self, k, m=2, mds_dim = 2, kmeans_clusters=2):
'''Cluster the nodes by building a hamming distance based on the spectral cluster on each layer
Args:
k: The number of eigenvalues used to compute the clustering for the individual layers
m: The number of clusters in a layer
mds_dim: Number of dimensions to immerse the dissimilarities. Default is 2
kmeans_clusters: The number of clusters to form in the final result
Returns:
kmeans.labels_: A list with the cluster number of each node
'''
#First let's compute a metric between nodes. The first attempt will build on Hamming distance
n = len(self.nodes)
#We will start all pairs of distinct nodes with a distance of 1 apart.
X = np.ones((n,n))
for i in range(n):
X[i][i] = 0
#Now, for each layer, we will add 1 to the distance if the nodes are in a different cluster
numlayers = len(self.layers)
for i in range(numlayers):
clust = self.spectral_cluster(i, k, m)
for x in range(n):
for y in range(n):
if not clust[x] == clust[y]:
X[x][y] += 1
Xhat = MDS(n_components = mds_dim, dissimilarity = 'precomputed').fit_transform(X)
#Now that we have the Hamming distance built, let's use this to cluster the nodes
kmeans = KMeans(n_clusters= kmeans_clusters, random_state=0).fit(Xhat)
return kmeans.labels_
def multi_cluster6(self, mds_dim = 2, kmeans_clusters=2):
'''Cluster the nodes by building a hamming distance based on the average distance between nodes on each layer.
This method assumes the multiplex network is connceted on each layer
Args:
mds_dim: Number of dimensions to immerse the dissimilarities. Default is 2
kmeans_clusters: The number of clusters to form in the final result
Returns:
kmeans.labels_: A list with the cluster number of each node
'''
n = len(self.nodes)
#Initialize the distance matrix
X = np.zeros((n,n))
#Now, for each layer, we will add 1 to the distance if the nodes are in a different cluster
numlayers = len(self.layers)
for i in range(numlayers):
try:
paths = dict(nx.shortest_path_length(self.layers[i]))
for x in range(n):
for y in range(n):
X[x][y] += paths[x][y]
except:
print("This method will not work unless the netowrk is connected")
return
X /= len(self.layers)
Xhat = MDS(n_components = mds_dim, dissimilarity = 'precomputed').fit_transform(X)
#Now that we have the Hamming distance built, let's use this to cluster the nodes
kmeans = KMeans(n_clusters= kmeans_clusters, random_state=0).fit(Xhat)
return kmeans.labels_
def multi_cluster7(self, mds_dim = 2, kmeans_clusters=2, t1=False, t2=False):
'''Cluster the nodes by building a hamming distance based on the number of neighbors in a layer
and the number of paths of length 2 between layers
Args:
mds_dim: Number of dimensions to immerse the dissimilarities. Default is 2
kmeans_clusters: The number of clusters to form in the final result
t1: The weighting of the Type 1 connections. If left False (as default), this will be picked automatically
t2: The weighting of the Type 2 connections. If left False (as default), this will be picked automatically
Returns:
kmeans.labels_: A list with the cluster number of each node
'''
#First let's compute a metric between nodes. The first attempt will build on average path length between nodes
n = len(self.nodes)
numlayers = len(self.layers)
#Now, we will compute the similarities. First, we will count the number of connections of each type
#Type 1 connections, adjacent on the same layer
T1 = np.zeros((n,n))
for x in self.nodes:
for i in range(numlayers):
for y in self.layers[i].neighbors(x):
T1[x][y] += 1
#Type 2 connections, two nodes share a neighbor this neighbor could be on the same or a different layer
T2 = np.matmul(T1,T1)
for i in range(n):
T2[i][i] = 0
#Set t1, t2 if they are not already set. This will keep t2 from dominating
if (not t1) and (not t1==0):
t1 = 1/max(T1)
if (not t2) and (not t2==0):
t2 = 1/max(T2)
#Combine the two connection types with a weighted sum
T = t1*T1 + t2*T2
#Now, scale T so no entry can be >= 1.
T = T/(np.max(T)+1)
#Create the similarity matrix
#Initialize the similarity matrix
X = np.identity(n)
X += T
#Convert the similarity matrix into a distance matrix
X = 1-X
Xhat = MDS(n_components = mds_dim, dissimilarity = 'precomputed').fit_transform(X)
#Now that we have the Hamming distance built, let's use this to cluster the nodes
kmeans = KMeans(n_clusters= kmeans_clusters, random_state=0).fit(Xhat)
return kmeans.labels_
def getclust(M,kmeans_clusters = 3, mds_dim = 2,cl = 3, eigs = False, t1 = False, t2 = False, plots = False, layout = nx.circular_layout, node_color='black', edge_color='#dddddd', node_size=50, width=1):
'''This function will get the clusters for M using the multi_cluster5, multi_cluster6, multi_cluster7.
This function can also return plots if desired.
args:
Clustering inputs
M: A Multiplex network object
kmeans_clusters: The number of clusters to form in the final result
mds_dim: mds_dim: Number of dimensions to immerse the dissimilarities. Default is 2
cl: The number of clusters in a layer for multi_cluster5
eigs: The number of eigenvalues to use in multi_cluster5
t1: The weighting of the Type 1 connections for multi_cluster7. If left False (as default), this will be picked automatically
t2: The weighting of the Type 2 connections for multi_cluster7. If left False (as default), this will be picked automatically
Plot inputs
plots: If True, this function will plot the clusters. The default is False
layout: The type of layout. This will be a nx.layout function. Default is nx.random_layout
node_color: Node color for the plot. Default is black. This can also be a dictionary of numbers corresponding to distinct node colors
edge_color: Edge color for the plot. Default is light grey
node_size: Node size for plot. Default is 50
width: Edge width for plot. Default is 1
returns:
c1: The cluster from multi_cluster5
c2: The cluster from multi_cluster6
c3: The cluster from multi_cluster7
'''
if not eigs:
eigs = len(M.layers[0]) - 2
#Compute clusters
c1 = M.multi_cluster5(eigs, cl,mds_dim = mds_dim, kmeans_clusters = kmeans_clusters)
c2 = M.multi_cluster6(mds_dim = mds_dim, kmeans_clusters = kmeans_clusters)
c3 = M.multi_cluster7(mds_dim = mds_dim, kmeans_clusters = kmeans_clusters, t1=t1, t2=t2)
#Plot Results
if plots:
#Flattened networks
M.plot_flat(node_color = c1, layout = layout, edge_color = edge_color, node_size = node_size, width = width)
M.plot_flat(node_color = c2, layout = layout, edge_color = edge_color, node_size = node_size, width = width)
M.plot_flat(node_color = c3, layout = layout, edge_color = edge_color, node_size = node_size, width = width)
#C1 Layers
M.plots(node_color = c1, layout = layout, edge_color = edge_color, node_size = node_size, width = width)
#C2 Layers
M.plots(node_color = c2, layout = layout, edge_color = edge_color, node_size = node_size, width = width)
#C3 Layers
M.plots(node_color = c3, layout = layout, edge_color = edge_color, node_size = node_size, width = width)
return c1,c2,c3
def convert_cluster(cluster):
'''This is a helper function that will convert a cluster into a partition of nodes
args:
cluster: A list with the cluster number for each node
returns:
communities A partition of the nodes, with each list in the partition as a part
'''
nums = set(cluster)
communities = []
community = []
for clust in nums:
for i in range(len(cluster)):
if cluster[i] == clust:
community.append(i)
communities.append(community)
community = []
return communities
def layer_modularity(M, cluster):
'''This function will compute the modularity for each layer of M, using the cluster given.
args:
M: A multiplex network of the Multiplex type
cluster: A clustering of the nodes in the network, given as a list
returns:
mods: A list of modularities from the layers
'''
c = convert_cluster(cluster)
mods = []
for i in range(len(M.layers)):
mods.append(com.modularity(M.layers[i], c))
return mods
def flatten_modularity(M, cluster, weight_count = True):
'''This function will compute the modularity for the flattened M.
args:
M: A multiplex network of the Multiplex type
cluster: A clustering of the nodes in the network, given as a list
weight_count: This will find the modularity assuming that the weight of the flattened edge is
the count of an edge over all layers
returns:
mod: The modularity of the flattened network
'''
c = convert_cluster(cluster)
G = M.flatten(weight_count = weight_count)
mod = com.modularity(G, c, weight='weight')
return float(mod)