-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmuxLib DF.R
1285 lines (1000 loc) · 46.3 KB
/
muxLib DF.R
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library(Matrix)
library(RSpectra)
library(igraph)
####################################################
# MuxNetLib: Library for Multilayer Network Analysis in muxViz
#
# Version: 0.1
# Last update: Dec 2017
# Authors: Manlio De Domenico
#
# History:
#
# Mar 2017: From Matlab to R!
# May 2014: First release, including part of muxNet
####################################################
#Good refs, to check in general:
#https://cran.r-project.org/doc/contrib/Hiebeler-matlabR.pdf
#http://mathesaurus.sourceforge.net/octave-r.html
#https://cran.r-project.org/web/packages/Matrix/Matrix.pdf
###################################################################
## MATLAB-like function
###################################################################
inv <- function(A){
return( solve(A) )
}
kron <- function(A, B){
#return the kronecker product between two matrices
return( Matrix::kronecker(A, B) )
}
speye <- function(n){
#return the identity matrix in sparse format
return( Matrix::Diagonal(n,1) )
}
zeros <- function(n,m){
#return a matrix full of zeros
#return( Matrix::Matrix(Matrix::kronecker( cbind(rep(0,n)), rbind(rep(1,m)), sparse=T), sparse=T) )
return(Matrix::Matrix(0, n, m, sparse=T))
}
ones <- function(n,m){
#return a matrix full of ones
#return( Matrix::Matrix(Matrix::kronecker( cbind(rep(1,n)), rbind(rep(1,m)) )) )
return(Matrix::Matrix(1, n, m, sparse=T))
}
spcan <- function(n, i, j){
#return a canonical matrix
A <- zeros(n,n)
A[i,j] <- 1
return(A)
}
rand <- function(n,m){
#return a matrix full of random numbers (uniformly distributed in [0,1])
return( Matrix::Matrix( runif(n*m), n, m, sparse=T ) )
}
blkdiag <- function(...){
#return a list of matrices in block diagonal form
return( Matrix::bdiag(...) )
}
reshapeR <- function(A, n, m){
#cannot call this function just "reshape", because it's an R builtin command
#return a matrix reshaped according to dimension n and m
dim(A) <- c(n,m)
return( A )
}
diagR <- function(x, n, offset=0){
#cannot call this function just "diag", because it's an R builtin command
#return a matrix with elements on a diagonal specified by offset (0=main diagonal)
M <- zeros(n,n)
M[which(row(M)+offset == col(M))] <- x
return(M)
}
traceR <- function(A){
#return the trace of a matrix
return(sum(diag(A)))
}
modR <- function(x,y){
#return the reminder between x and y
return( unlist(lapply(x, function(z) z %% y)) )
}
sumR <- function(A, n){
#return the sum across rows (n=1) or columns (n=2) of a matrix
if(n==1){
return( rbind(colSums(A)) )
}else if(n==2){
return( cbind(rowSums(A)) )
}else{
stop("ERROR! Not a valid dimension.")
}
}
###################################################################
## BASIC OPERATIONS
###################################################################
BuildLayersTensor <- function(Layers, OmegaParameter, MultisliceType){
#Layers: scalar, number of layers
#OmegaParameter: scalar, weight of links (future inter-layer links)
#MultisliceType: "ordered" or "categorical"
M <- Matrix(0, Layers, Layers, sparse=T)
if(Layers>1){
if(MultisliceType=="ordered"){
M <- (diagR(ones(1,Layers-1),Layers,1) + diagR(ones(1,Layers-1),Layers,-1) )*OmegaParameter
}else if(MultisliceType=="categorical"){
M <- (ones(Layers,Layers) - speye(Layers))*OmegaParameter
}
}else{
M <- 0
cat("--> Algorithms for one layer will be used\n")
}
return( M )
}
BuildSupraAdjacencyMatrixFromExtendedEdgelist <- function(mEdges, Layers, Nodes, isDirected){
#mEdges: data frame with extended edge list
#Layers and Nodes are scalars
if( max(max(mEdges[,2]), max(mEdges[,4]))!=Layers ){
stop("Error: expected number of layers does not match the data. Aborting process.")
}
edges <- data.frame(from=mEdges[,1] + Nodes*(mEdges[,2]-1),
to=mEdges[,3] + Nodes*(mEdges[,4]-1),
weight=mEdges[,5]
)
M <- Matrix::sparseMatrix(i=edges$from, j=edges$to, x = edges$weight, dims=c(Nodes*Layers,Nodes*Layers))
return( M )
}
BuildSupraAdjacencyMatrixFromEdgeColoredMatrices <- function(NodesTensor, LayerTensor, Layers, Nodes){
#NodesTensor: list of adjacency matrices, expected to be aligned (a node has same index in any layer)
#LayerTensor: matrix
#Layers and Nodes are scalars
# Remind that AdjMatrix (that here would play the role of NodesTensor) is vector list with Layers+1 entries.
#Use AdjMatrix[1:LAYERS] to obtain the expected result
Identity <- speye(Nodes)
M <- blkdiag(NodesTensor) + kron(LayerTensor, Identity)
return( M )
}
SupraAdjacencyToNodesTensor <- function(SupraAdjacencyMatrix, Layers, Nodes){
#SupraAdjacencyMatrix: sparse matrix
#Layers and Nodes are scalars
# return the diagonal blocks from a supradajcency matrix
return( lapply(1:Layers, function(x) SupraAdjacencyMatrix[(1+ (x-1)*Nodes):(x*Nodes),
(1+ (x-1)*Nodes):(x*Nodes)])
)
}
SupraAdjacencyToBlockTensor <- function(SupraAdjacencyMatrix, Layers, Nodes){
#SupraAdjacencyMatrix: sparse matrix
#Layers and Nodes are scalars
# return the the blocks from a supradajcency matrix
#this is equivalent to Matlab's BlockTensor = {}
BlockTensor <- matrix(list(), Layers, Layers)
# for(i in 1:Layers){
# for(j in 1:Layers){
# BlockTensor[[i,j]] <- SupraAdjacencyMatrix[(1+ (i-1)*Nodes):(i*Nodes),
# (1+ (j-1)*Nodes):(j*Nodes)]
# }
# }
#this should be faster :-D
lapply(1:Layers, function(i){
lapply(1:Layers, function(j){
BlockTensor[[i,j]] <<- SupraAdjacencyMatrix[(1+ (i-1)*Nodes):(i*Nodes),
(1+ (j-1)*Nodes):(j*Nodes)]
})
})
return( BlockTensor )
}
GetAggregateMatrix <- function(NodesTensor, Layers, Nodes){
#NodesTensor: list of adjacency matrices, expected to be aligned (a node has same index in any layer)
#LayerTensor: matrix
#Layers and Nodes are scalars
Aggregate <- zeros(Nodes,Nodes)
for(i in 1:Layers){
Aggregate <- Aggregate + NodesTensor[[i]]
}
return(Aggregate)
}
GetAggregateMatrixFromNetworkList <- function(g.list){
#g.list is a list of igraph objects
W <- sparseMatrix( length(V(g.list[[1]])), length(V(g.list[[1]])))
for(g in g.list){
W <- W + igraph::get.adjacency(g)
}
return( W )
}
GetAggregateNetworkFromNetworkList <- function(g.list){
#g.list is a list of igraph objects
W <- sparseMatrix( length(V(g.list[[1]])), length(V(g.list[[1]])))
for(g in g.list){
W <- W + igraph::get.adjacency(g)
}
return( igraph::graph.adjacency(W, weighted=T) )
}
GetSampleMultiplex <- function(Layers, Nodes, p){
NodeTensor <- lapply(1:Layers, function(x){
A <- rand(Nodes,Nodes)
A[which(A < p)] <- 1
A[which(row(A)==col(A))] <- 0
A[which(A < 1)] <- 0
A[lower.tri(A)] <- 0
A <- A + t(A)
return(A)
})
LayerTensor <- BuildLayersTensor(Layers, 1, "categorical")
M <- BuildSupraAdjacencyMatrixFromEdgeColoredMatrices(NodeTensor, LayerTensor, Layers, Nodes)
diag(M) <- 0
return(Matrix::drop0(M))
}
SolveEigenvalueProblem <- function(Matrix){
#return the matrix of eigenvectors (Q) and the diagonal matrix of eigenvalues (L)
#as well as a vector with ordered eigenvalues (E)
#Note that it is assumed that we work with real values (up to now, no applications
#required to use complex numbers)
#A warning is raised if complex numbers emerge...
tmp <- eigen(Matrix)
if(is.complex(tmp$vectors)){
cat(" Warning! Complex eigenvectors. Using the real part.\n")
}
if(is.complex(tmp$values)){
cat(" Warning! Complex eigenvalues. Using the real part.\n")
}
return( list( QMatrix=Re(tmp$vectors),
LMatrix=Diagonal(Re(tmp$values), n=length(tmp$values)),
Eigenvalues=cbind(sort(tmp$values))
) )
}
GetLargestEigenv <- function(Matrix){
#we must distinguish between symmetric and nonsymmetric matrices to have correct results
#still to do for further improvements
tmp <- RSpectra::eigs(Matrix, 1, which="LM")
#The result of some computation might return complex numbers with 0 imaginary part
#If this is the case, we fix it, otherwise a warning is rised
if( all(Im(tmp$vectors)==0) ){
tmp$vectors <- Re(tmp$vectors)
}else{
cat("Warning! Complex numbers in the leading eigenvector.\n")
}
if( all(Im(tmp$values)==0) ){
tmp$values <- Re(tmp$values)
}else{
cat("Warning! Complex numbers in the leading eigenvalue.\n")
}
#check if the eigenvector has all negative components.. in that case we change the sign
#first, set to zero everything that is so small that can create problems even if it compatible with zero
tmp$vectors[which(tmp$vectors>-1e-12 & tmp$vectors<1e-12)] <- 0
#now verify that all components are negative and change sign
if( all( tmp$vectors[which(tmp$vectors!=0)] < 0 ) ){
tmp$vectors <- -tmp$vectors
}
return( list(QMatrix=tmp$vectors, LMatrix=tmp$values) )
##remind to return a column vector result.. check always that returned result is compatible with original octave result
}
#GetLargestEigenv <- function(Matrix){
# #we must distinguish between symmetric and nonsymmetric matrices to have correct results
# tmp <- eigen(Matrix)
# QMatrix <- tmp$vectors
# LMatrix <- tmp$values
#
# k <- which.max(abs(LMatrix))
# LMatrix <- LMatrix[k]
# QMatrix <- cbind(QMatrix[,k]) #return column vector
#
# #The result of some computation might return complex numbers with 0 imaginary part
# #If this is the case, we fix it, otherwise a warning is rised
# if( all(Im(QMatrix)==0) ){
# QMatrix <- Re(QMatrix)
# }else{
# cat("Warning! Complex numbers in the leading eigenvector.\n")
# }
#
# if( all(Im(LMatrix)==0) ){
# LMatrix <- Re(LMatrix)
# }else{
# cat("Warning! Complex numbers in the leading eigenvalue.\n")
# }
#
# #check if the eigenvector has all negative components.. in that case we change the sign
# #first, set to zero everything that is so small that can create problems even if it compatible with zero
# QMatrix[which(QMatrix>-1e-12 & QMatrix<1e-12)] <- 0
# #now verify that all components are negative and change sign
# if( all( QMatrix[QMatrix!=0] < 0 ) ){
# QMatrix <- -QMatrix
# }
#
#
# return( list(QMatrix=QMatrix, LMatrix=LMatrix) )
#
# ##remind to return a column vector result.. check always that returned result is compatible with original octave result
#}
binarizeMatrix <- function(A){
#A is assumed to be sparse
A[which(A != 0)] <- 1
return( A )
}
#binarizeMatrix <- function(A){
# return( Matrix::Matrix(as.numeric(A>0), dim(A)[1], dim(A)[2], sparse=T) )
#}
CanonicalVector <- function(N, i){
vec <- zeros(1,N)
vec[i] <- 1
return(vec)
}
###################################################################
## REDUCIBILITY OF MULTILAYER NETWORKS
###################################################################
GetLaplacianMatrix <- function(AdjacencyMatrix){
#Calculate the laplacian matrix from an adjacency matrix
N <- dim(AdjacencyMatrix)[1]
u <- ones(N,1)
#laplacian
LaplacianMatrix <- diagR(AdjacencyMatrix %*% u, N, 0) - AdjacencyMatrix
#always check
if(sum(LaplacianMatrix %*% u) > 1.e-8){
stop("ERROR! The Laplacian matrix has rows that don't sum to 0. Aborting process.\n")
}
return(Matrix::drop0(LaplacianMatrix))
}
BuildDensityMatrixBGS <- function(AdjacencyMatrix){
#Calculate the density matrix from an adjacency matrix
# References:
# S. L. Braunstein, S. Ghosh, S. Severini, Annals of Combinatorics 10, No 3, (2006)
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
DensityMatrix <- GetLaplacianMatrix(AdjacencyMatrix)
#normalize to degree sum
return( DensityMatrix/(traceR(DensityMatrix)) )
}
GetEigenvaluesOfDensityMatrix <- function(DensityMatrix){
#Calculate the eigenvalues of a density matrix
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
Eigenvalues <- cbind(eigen(DensityMatrix)$values)
#check that eigenvalues sum to 1
if(abs(Re(sum(Eigenvalues)-1))>1e-8){
stop("ERROR! Eigenvalues dont sum to 1! Aborting process.")
}
return(Eigenvalues)
}
GetEigenvaluesOfDensityMatrixFromAdjacencyMatrix <- function(AdjacencyMatrix){
DensityMatrix <- BuildDensityMatrixBGS(AdjacencyMatrix)
return(GetEigenvaluesOfDensityMatrix(DensityMatrix))
}
GetRenyiEntropyFromAdjacencyMatrix <- function(AdjacencyMatrix, Q=1){
#Calculate the quantum Renyi entropy of a network
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
Eigenvalues <- Re(GetEigenvaluesOfDensityMatrixFromAdjacencyMatrix(AdjacencyMatrix))
if (Q==1.){
#Von Neuman quantum entropy
RenyiEntropy <- -sum(Eigenvalues[Eigenvalues>0]*log(Eigenvalues[Eigenvalues>0]))
}else{
#Renyi quantum entropy
RenyiEntropy <- (1 - sum(Eigenvalues[Eigenvalues>0]^Q))/(Q-1)
}
return(RenyiEntropy)
}
GetJensenShannonDivergence <- function(AdjacencyMatrix1,AdjacencyMatrix2,VNEntropy1,VNEntropy2){
#Calculate the Jensen-Shannon Divergence of two networks
# References:
# M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
# %M = 0.5 * (RHO + SIGMA)
# %JSD: 0.5 * DKL( RHO || M ) + 0.5 * DKL( SIGMA || M )
# %DKL( A || B ) = tr[ A log A - A log B ] = -entropy(A) - tr[ A log B ]
# %
# %JSD: 0.5 * ( -entropy(RHO) - entropy(SIGMA) - tr[ RHO log M ] - tr[ SIGMA log M ] )
# % -0.5 * [ entropy(RHO) + entropy(SIGMA) ] - tr[ M log M ] )
# % -0.5 * [ entropy(RHO) + entropy(SIGMA) ] + entropy(M)
DensityMatrix1 <- BuildDensityMatrixBGS(AdjacencyMatrix1)
DensityMatrix2 <- BuildDensityMatrixBGS(AdjacencyMatrix2)
DensityMatrixM <- (DensityMatrix1 +DensityMatrix2)/2.
EigenvaluesM <- Re(eigen(DensityMatrixM)$values)
CrossEntropyM = -sum(EigenvaluesM[EigenvaluesM>0]*log(EigenvaluesM[EigenvaluesM>0]))
JSD <- CrossEntropyM - 0.5*(VNEntropy1 + VNEntropy2)
return(JSD)
}
###################################################################
## TOPOLOGICAL DESCRIPTORS OF MULTILAYER NETWORKS
###################################################################
GetGlobalNumberTriangles <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
num <- traceR( (SupraAdjacencyMatrix %*% SupraAdjacencyMatrix) %*% SupraAdjacencyMatrix )
return(num)
}
GetAverageGlobalClustering <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
FMatrix <- ones(Nodes*Layers, Nodes*Layers) - speye(Nodes*Layers)
num <- traceR( (SupraAdjacencyMatrix %*% SupraAdjacencyMatrix) %*% SupraAdjacencyMatrix )
den <- traceR( (SupraAdjacencyMatrix %*% FMatrix) %*% SupraAdjacencyMatrix )
return(num/(max(SupraAdjacencyMatrix)*den))
}
#Note: can be optimized
GetLocalClustering <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
FMatrix <- ones(Nodes*Layers, Nodes*Layers) - speye(Nodes*Layers)
M3 <- (SupraAdjacencyMatrix %*% SupraAdjacencyMatrix) %*% SupraAdjacencyMatrix
F3 <- (SupraAdjacencyMatrix %*% FMatrix) %*% SupraAdjacencyMatrix
blocks.num <- SupraAdjacencyToBlockTensor(M3, Layers, Nodes)
blocks.den <- SupraAdjacencyToBlockTensor(F3, Layers, Nodes)
B.num <- zeros(Nodes,Nodes)
B.den <- zeros(Nodes,Nodes)
for(i in 1:Layers){
for(j in 1:Layers){
B.num <- B.num + blocks.num[[i,j]]
B.den <- B.den + blocks.den[[i,j]]
}
}
clus <- cbind(diag(B.num)/diag(B.den))
if(any(clus>1 | clus <0)){
stop("GetLocalClustering:ERROR! Impossible clustering coefficients. Aborting process.")
}
return( clus )
}
#Note: can be optimized
GetAverageGlobalOverlapping <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
if(Layers==1){
stop("GetAverageGlobalOverlapping:ERROR! At least two layers required. Aborting process.")
}
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix, Layers, Nodes)
O <- pmin(NodesTensor[[1]],NodesTensor[[2]])
NormTotal <- sum(sum(NodesTensor[[1]]))
if(Layers > 2){
#assuming that LayerTensor is an undirected clique
for(l in 2:Layers){
O <- pmin(O,NodesTensor[[l]])
NormTotal <- NormTotal + sum(sum(NodesTensor[[l]]))
}
}
AvGlobOverl <- Layers*sum(sum(O))/NormTotal
if(sum(SupraAdjacencyMatrix-t(SupraAdjacencyMatrix))==0){
AvGlobOverl <- AvGlobOverl/2
}
return(AvGlobOverl)
}
#Note: can be optimized
GetAverageGlobalNodeOverlappingMatrix <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
if(Layers==1){
stop("GetAverageGlobalNodeOverlappingMatrix:ERROR! At least two layers required. Aborting process.\n")
}
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
existingNodes <- vector("list", Layers)
for(l in 1:Layers){
#find cols and rows where sum > zero to identify connected nodes
cols <- which(sumR(NodesTensor[[l]],2)!=0)
rows <- which(sumR(NodesTensor[[l]],1)!=0)
#merge the two (this approach is necessary to deal also with directed networks)
existingNodes[[l]] <- union(cols, rows)
}
AvGlobOverlMatrix <- Matrix::Matrix(0, Layers, Layers, sparse=T)
diag(AvGlobOverlMatrix) <- 1
for(l1 in 1:(Layers-1)){
for(l2 in (l1+1):Layers){
AvGlobOverlMatrix[l1,l2] <- length(intersect( existingNodes[[l1]], existingNodes[[l2]] ))/Nodes;
AvGlobOverlMatrix[l2,l1] <- AvGlobOverlMatrix[l1,l2]
}
}
return(AvGlobOverlMatrix)
}
#Note: can be optimized
GetAverageGlobalOverlappingMatrix <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
if(Layers==1){
stop("GetAverageGlobalOverlappingMatrix:ERROR! At least two layers required. Aborting process.\n")
}
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
AvGlobOverlMatrix <- Matrix::Matrix(0, Layers, Layers, sparse=T)
diag(AvGlobOverlMatrix) <- 1
for(l1 in 1:(Layers-1)){
Norm1 <- sum(sum(NodesTensor[[l1]]))
for(l2 in (l1+1):Layers){
O <- pmin(NodesTensor[[l1]], NodesTensor[[l2]])
AvGlobOverlMatrix[l1,l2] <- 2*sum(sum(O))/(Norm1 + sum(sum(NodesTensor[[l2]])))
AvGlobOverlMatrix[l2,l1] <- AvGlobOverlMatrix[l1,l2]
}
}
return(AvGlobOverlMatrix)
}
GetMultiOutDegree <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# Return the multi-out-degree, not accounting for interlinks
NodesTensor <- SupraAdjacencyToNodesTensor(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes)
AggrMatrix <- GetAggregateMatrix(NodesTensor, Layers, Nodes)
MultiOutDegreeVector <- sumR(AggrMatrix, 2)
return(MultiOutDegreeVector)
}
GetMultiInDegree <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# Return the multi-out-degree, not accounting for interlinks
NodesTensor <- SupraAdjacencyToNodesTensor(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes)
AggrMatrix <- GetAggregateMatrix(NodesTensor, Layers, Nodes)
MultiInDegreeVector <- sumR(AggrMatrix, 1)
#return in column format
return(t(MultiInDegreeVector))
}
GetMultiDegree <- function(SupraAdjacencyMatrix, Layers, Nodes, isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInDegreeVector <- GetMultiInDegree(SupraAdjacencyMatrix, Layers, Nodes, isDirected)
MultiOutDegreeVector <- GetMultiOutDegree(SupraAdjacencyMatrix, Layers, Nodes, isDirected)
if(!isDirected){
MultiDegreeVector <- (MultiInDegreeVector + MultiOutDegreeVector)/2
}else{
MultiDegreeVector <- MultiInDegreeVector + MultiOutDegreeVector
}
return(MultiDegreeVector)
}
#Note: can be optimized
GetInterAssortativityTensor <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected,Type){
if(Layers==1){
stop("GetInterAssortativityTensor: ERROR! At least two layers required. Aborting process.\n")
}
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
InterPearson <- speye(Layers)
InterSpearman <- speye(Layers)
if (Type=="IO" || Type=="OI"){
InDegree <- vector("list", Layers)
OutDegree <- vector("list", Layers)
for(l in 1:Layers){
InDegree[[l]] <- GetMultiInDegree(NodesTensor[[l]],1,Nodes,isDirected)
OutDegree[[l]] <- GetMultiOutDegree(NodesTensor[[l]],1,Nodes,isDirected)
}
for(l1 in 1:Layers){
for(l2 in 1:Layers){
InterPearson[l1,l2] <- cor(x=InDegree[[l1]],OutDegree[[l2]], method="pearson")
InterSpearman[l1,l2] <- cor(x=InDegree[[l1]],OutDegree[[l2]], method="spearman")
}
}
if (Type=="OI"){
InterPearson <- t(InterPearson)
InterSpearman <- t(InterSpearman)
}
}else{
Degree <- vector("list", Layers)
if (Type=="OO"){
for(l in 1:Layers){
Degree[[l]] <- GetMultiOutDegree(NodesTensor[[l]],1,Nodes,isDirected)
}
}
if (Type=="II"){
for(l in 1:Layers){
Degree[[l]] <- GetMultiInDegree(NodesTensor[[l]],1,Nodes,isDirected)
}
}
if (Type=="TT"){
for(l in 1:Layers){
Degree[[l]] <- GetMultiDegree(NodesTensor[[l]],1,Nodes,isDirected)
}
}
for(l1 in 1:(Layers-1)){
for(l2 in (l1+1):Layers){
InterPearson[l1,l2] <- cor(x=Degree[[l1]], y=Degree[[l2]], method="pearson")
InterSpearman[l1,l2] <- cor(x=Degree[[l1]], y=Degree[[l2]], method="spearman")
InterPearson[l2,l1] <- InterPearson[l1,l2]
InterSpearman[l2,l1] <- InterSpearman[l1,l2]
}
}
}
return( list(InterPearson=InterPearson, InterSpearman=InterSpearman) )
}
GetMultiOutDegreeSum <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
#this degree include multiple times the interlinks
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraDegree <- sumR(binarizeMatrix(SupraAdjacencyMatrix),2)
MultiOutDegreeVector <- sumR(reshapeR(SupraDegree,Nodes,Layers),2)
return(MultiOutDegreeVector)
}
GetMultiInDegreeSum <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
#this degree include multiple times the interlinks
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraDegree <- t(sumR(binarizeMatrix(SupraAdjacencyMatrix),1))
MultiInDegreeVector <- sumR(reshapeR(SupraDegree,Nodes,Layers),2)
return(MultiInDegreeVector)
}
GetMultiDegreeSum <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInDegreeVector <- GetMultiInDegreeSum(SupraAdjacencyMatrix,Layers,Nodes,isDirected)
MultiOutDegreeVector <- GetMultiOutDegreeSum(SupraAdjacencyMatrix,Layers,Nodes,isDirected)
if(!isDirected){
MultiDegreeVector <- (MultiInDegreeVector + MultiOutDegreeVector)/2
}else{
MultiDegreeVector <- MultiInDegreeVector + MultiOutDegreeVector
}
return(MultiDegreeVector)
}
GetMultiOutStrength <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# Return the multi-out-Strength, not accounting for interlinks
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
AggrMatrix <- GetAggregateMatrix(NodesTensor, Layers, Nodes)
MultiOutStrengthVector <- sumR(AggrMatrix, 2)
return(MultiOutStrengthVector)
}
GetMultiInStrength <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# Return the multi-out-Strength, not accounting for interlinks
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
AggrMatrix <- GetAggregateMatrix(NodesTensor, Layers, Nodes)
MultiInStrengthVector <- sumR(AggrMatrix, 1)
#return in column format
return(t(MultiInStrengthVector))
}
GetMultiStrength <- function(SupraAdjacencyMatrix, Layers, Nodes, isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInStrengthVector <- GetMultiInStrength(SupraAdjacencyMatrix, Layers, Nodes, isDirected)
MultiOutStrengthVector <- GetMultiOutStrength(SupraAdjacencyMatrix, Layers, Nodes, isDirected)
if(!isDirected){
MultiStrengthVector <- (MultiInStrengthVector + MultiOutStrengthVector)/2
}else{
MultiStrengthVector <- MultiInStrengthVector + MultiOutStrengthVector
}
return(MultiStrengthVector)
}
GetMultiOutStrengthSum <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
#this Strength include multiple times the interlinks
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraStrength <- sumR(SupraAdjacencyMatrix,2)
MultiOutStrengthVector <- sumR(reshapeR(SupraStrength,Nodes,Layers),2)
return(MultiOutStrengthVector)
}
GetMultiInStrengthSum <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
#this Strength include multiple times the interlinks
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraStrength <- t(sumR(SupraAdjacencyMatrix,1))
MultiInStrengthVector <- sumR(reshapeR(SupraStrength,Nodes,Layers),2)
return(MultiInStrengthVector)
}
GetMultiStrengthSum <- function(SupraAdjacencyMatrix,Layers,Nodes,isDirected){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInStrengthVector <- GetMultiInStrengthSum(SupraAdjacencyMatrix,Layers,Nodes,isDirected)
MultiOutStrengthVector <- GetMultiOutStrengthSum(SupraAdjacencyMatrix,Layers,Nodes,isDirected)
if(!isDirected){
MultiStrengthVector <- (MultiInStrengthVector + MultiOutStrengthVector)/2
}else{
MultiStrengthVector <- MultiInStrengthVector + MultiOutStrengthVector
}
return(MultiStrengthVector)
}
GetMultiKatzCentrality <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
# we pass the transpose of the transition matrix to get the left eigenvectors
tmp <- GetLargestEigenv(t(SupraAdjacencyMatrix))
LeadingEigenvalue <- tmp$LMatrix
#Katz kernel tensor
deltaTensor <- kron(speye(Nodes), speye(Layers))
#this ensures convergence of the Katz kernel tensor
a <- 0.99999/abs(LeadingEigenvalue)
KatzKernelTensor <- inv(deltaTensor - a*SupraAdjacencyMatrix)
KatzCentralitySupraVector <- KatzKernelTensor %*% ones(Nodes*Layers,1)
CentralityVector <- sumR(reshapeR(KatzCentralitySupraVector,Nodes,Layers),2)
CentralityVector <- CentralityVector/max(CentralityVector)
return(CentralityVector)
}
GetMultiEigenvectorCentrality <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
#we pass the transpose of the transition matrix to get the left eigenvectors
tmp <- GetLargestEigenv(t(SupraAdjacencyMatrix))
LeadingEigenvector <- tmp$QMatrix
CentralityVector <- sumR(reshapeR(LeadingEigenvector,Nodes,Layers),2)
CentralityVector <- CentralityVector/max(CentralityVector)
return(CentralityVector)
}
#An edit I'm making, to stop all max eigenvector centralities being 1
GetMultiEigenvectorCentrality2 <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
#we pass the transpose of the transition matrix to get the left eigenvectors
tmp <- GetLargestEigenv(t(SupraAdjacencyMatrix))
LeadingEigenvector <- tmp$QMatrix
CentralityVector <- sumR(reshapeR(LeadingEigenvector,Nodes,Layers),2)
#CentralityVector <- CentralityVector/max(CentralityVector)
return(CentralityVector)
}
GetMultiHubCentrality <- function(SupraAdjacencyMatrix,Layers,Nodes){
#see review http://arxiv.org/pdf/0805.3322v2.pdf
#References:
# M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
#build the A A'
SupraMatrix <- SupraAdjacencyMatrix %*% t(SupraAdjacencyMatrix)
#we pass the matrix to get the right eigenvectors
#to deal with the possible degeneracy of the leading eigenvalue, we add an eps to the matrix
#this ensures that we can apply the Perron-Frobenius theorem to say that there is a unique
#leading eigenvector. Here we add eps, a very very small number (<1e-8, generally)
tmp <- GetLargestEigenv(SupraMatrix + 1e-16)
LeadingEigenvector <- tmp$QMatrix
CentralityVector <- sumR(reshapeR(LeadingEigenvector,Nodes,Layers),2)
CentralityVector <- CentralityVector/max(CentralityVector)
return(CentralityVector)
}
GetMultiAuthCentrality <- function(SupraAdjacencyMatrix,Layers,Nodes){
#see review http://arxiv.org/pdf/0805.3322v2.pdf
# References:
# M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
#build the A' A
SupraMatrix <- t(SupraAdjacencyMatrix) %*% SupraAdjacencyMatrix
#we pass the matrix to get the right eigenvectors
#to deal with the possible degeneracy of the leading eigenvalue, we add an eps to the matrix
#this ensures that we can apply the Perron-Frobenius theorem to say that there is a unique
#leading eigenvector. Here we add eps, a very very small number (<1e-8, generally)
tmp <- GetLargestEigenv(SupraMatrix + 1e-16)
LeadingEigenvector <- tmp$QMatrix
CentralityVector <- sumR(reshapeR(LeadingEigenvector,Nodes,Layers),2)
CentralityVector <- CentralityVector/max(CentralityVector)
return(CentralityVector)
}
GetMultiKCoreCentrality <- function(SupraAdjacencyMatrix,Layers,Nodes){
#calculate centrality in each layer separately and then get the max per node
kcore.table <- matrix(0, nrow=Nodes, ncol=Layers)
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
for(l in 1:Layers){
g.tmp <- graph.adjacency(NodesTensor[[l]], weighted=T)
kcore.table[,l] <- graph.coreness(g.tmp, mode="all")
}
CentralityVector <- apply(kcore.table, 1, max)
return(CentralityVector)
}
GetMultiplexityCentrality <- function(SupraAdjacencyMatrix,Layers,Nodes){
NodesTensor <- SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
existingNodes <- vector("list", Layers)
nodeMultiplexity <- rep(0, Nodes)
for(l in 1:Layers){
#find cols and rows where sum > zero to identify connected nodes
cols <- which(sumR(NodesTensor[[l]],2)!=0)
rows <- which(sumR(NodesTensor[[l]],1)!=0)
#merge the two (this approach is necessary to deal also with directed networks)
existingNodes[[l]] <- union(cols, rows)
nodeMultiplexity[ existingNodes[[l]] ] <- nodeMultiplexity[ existingNodes[[l]] ] + 1
}
CentralityVector <- cbind(c(nodeMultiplexity))/Layers
return(CentralityVector)
}
###################################################################
## RANDOM WALKS IN MULTILAYER NETWORKS
###################################################################
BuildSupraTransitionMatrixFromSupraAdjacencyMatrix <- function(SupraAdjacencyMatrix,Layers,Nodes){
# References:
# M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
# M. De Domenico, A. Sole-Ribalta, S. Gomez, A. Arenas, PNAS 11, 8351 (2014)
Order <- Layers*Nodes
#SupraUnitVector = ones(Order,1);
SupraStrengthMatrix <- sumR(SupraAdjacencyMatrix,2)
DisconnectedNodes <- length(SupraStrengthMatrix[SupraStrengthMatrix==0])
if(DisconnectedNodes>0){
cat(paste0(" #Trapping nodes (no outgoing-links): ", DisconnectedNodes, "\n"))
}
SupraStrengthMatrix[ SupraStrengthMatrix>0 ] <- 1./SupraStrengthMatrix[SupraStrengthMatrix>0]
SupraStrengthMatrix <- diagR(SupraStrengthMatrix, Nodes*Layers, 0)
SupraTransitionMatrix <- SupraStrengthMatrix %*% SupraAdjacencyMatrix
alpha <- 0.85
if(DisconnectedNodes>0){