-
Notifications
You must be signed in to change notification settings - Fork 92
/
muxLib_annotated.R
4585 lines (3965 loc) · 149 KB
/
muxLib_annotated.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
####################################################
# MuxNetLib: Library for Multilayer Network Analysis in muxViz
#
# Version: 3.0
# Last update: Jan 2021
# Authors: Manlio De Domenico
#
# History:
#
# Jan 2021: From R source file to an R package
# 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
###################################################################
## BASIC OPERATIONS
###################################################################
#' Build layers tensor
#'
#'
#' @param Layers scalar, number of layers, number of layers
#' @param OmegaParameter scalar, weight of links (future inter-layer links)
#' @param MultisliceType "ordered": chain, undirected; "categorical": all-to-all, undirected; "temporal": chain, directed
#' @return
#' Tensor matrix.
#' @export
BuildLayersTensor <-
function(Layers, OmegaParameter, MultisliceType) {
MultisliceType <- tolower(MultisliceType)
M <- Matrix::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 if (MultisliceType == "temporal") {
M <- (diagR(ones(1, Layers - 1), Layers, 1)) * OmegaParameter
}
} else {
M <- 0
cat("--> Algorithms for one layer will be used\n")
}
return(M)
}
#' Build supra-adjacency matrix from edge lists
#'
#'
#' @param mEdges data frame with extended edge list, i.e a data frame with
#' columns: \code{node.from, layer.from, node.to, layer.to weight}
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @param isDirected logical
#' @return
#' Supra-adjacency matrix, a square matrix of dimension \code{Nodes * Layers}.
#' @export
BuildSupraAdjacencyMatrixFromExtendedEdgelist <-
function(mEdges, Layers, Nodes, isDirected) {
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)
)
if (sum(abs(M - Matrix::t(M))) > 1e-12 && isDirected == FALSE) {
message(
"WARNING: The input data is directed but isDirected=FALSE, I am symmetrizing by average."
)
M <- (M + Matrix::t(M)) / 2
}
return(M)
}
#' Builds extended edgelist from supra-adjacency matrix
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @param isDirected logical
#' @return
#' Data frame with columns: \code{node.from, layer.from, node.to, layer.to weight}
#' @export
BuildExtendedEdgelistFromSupraAdjacencyMatrix <-
function(SupraAdjacencyMatrix,
Layers,
Nodes,
isDirected) {
if (sum(abs(SupraAdjacencyMatrix - Matrix::t(SupraAdjacencyMatrix))) > 1e-12 &&
isDirected == FALSE) {
message(
"WARNING: The input data is directed but isDirected=FALSE, I am symmetrizing by average."
)
SupraAdjacencyMatrix <-
(SupraAdjacencyMatrix + Matrix::t(SupraAdjacencyMatrix)) / 2
}
#Convert the supra-adjacency to a data.frame
dfM <- Matrix::summary(SupraAdjacencyMatrix)
#transform to layers and nodes
node.from <- (dfM$i - 1) %% Nodes + 1
node.to <- (dfM$j - 1) %% Nodes + 1
layer.from <- 1 + floor((dfM$i - 1) / Nodes)
layer.to <- 1 + floor((dfM$j - 1) / Nodes)
weight <- dfM$x
mEdges <- data.frame(
node.from = node.from,
layer.from = layer.from,
node.to = node.to,
layer.to = layer.to,
weight = weight
)
return(mEdges)
}
#' Build supra-adjacency matrix from edge-colored matrices
#'
#'
#' @param NodesTensor list of adjacency matrices, expected to be aligned (a node hassame index in any layer)
#' @param LayerTensor matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return a list of matrices. Let us call \code{AdjMatrix} the output of the function,
#' AdjMatrix (that here would play the role of NodesTensor) is vectorlist with
#' \code{Layers + 1} entries. Use \code{AdjMatrix[1:Layers]} to obtain the expected result.
#' @export
BuildSupraAdjacencyMatrixFromEdgeColoredMatrices <-
function(NodesTensor, LayerTensor, Layers, Nodes) {
Identity <- speye(Nodes)
M <- blkdiag(NodesTensor) + kron(LayerTensor, Identity)
return(M)
}
#' Return nodes tensor from supra-adjacency matrix
#'
#'
#' @param SupraAdjacencyMatrix sparse matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return
#' The diagonal blocks from a supra-adjacency matrix.
#' @export
SupraAdjacencyToNodesTensor <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
return(lapply(1:Layers, function(x)
SupraAdjacencyMatrix[(1 + (x - 1) * Nodes):(x * Nodes),
(1 + (x - 1) *
Nodes):(x * Nodes)]))
}
#' Return block tensor from supra-adjacency matrix
#'
#'
#' @param SupraAdjacencyMatrix sparse matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return
#' The blocks from input supra-adjacency matrix
#' @export
SupraAdjacencyToBlockTensor <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
#this is equivalent to Matlab's BlockTensor = {}
BlockTensor <- matrix(list(), Layers, Layers)
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)
}
#' Get aggregate matrix from nodes tensor
#'
#'
#' @param NodesTensor list of adjacency matrices, expected to be aligned (a node has same index in any layer)
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return Aggregate matrix
#' @export
GetAggregateMatrix <- function(NodesTensor, Layers, Nodes) {
Aggregate <- zeros(Nodes, Nodes)
for (i in 1:Layers) {
Aggregate <- Aggregate + NodesTensor[[i]]
}
return(Aggregate)
}
#' Get aggregate matrix from supra-adjacency matrix
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return Aggregate matrix
#' #' @export
GetAggregateMatrixFromSupraAdjacencyMatrix <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
NodesTensor <-
SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix, Layers, Nodes)
Aggregate <- GetAggregateMatrix(NodesTensor, Layers, Nodes)
return(Aggregate)
}
#' Get aggregate network from supra-adjacency matrix
#'
#'
#' @param SupraAdjacencyMatrix supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return Aggregate network
#' @export
GetAggregateNetworkFromSupraAdjacencyMatrix <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
Aggregate <-
GetAggregateMatrixFromSupraAdjacencyMatrix(SupraAdjacencyMatrix, Layers, Nodes)
if (sum(abs(Aggregate - Matrix::t(Aggregate))) == 0) {
return(igraph::as.undirected(igraph::graph.adjacency(Aggregate, weighted =
T)))
} else {
return(igraph::graph.adjacency(Aggregate, weighted = T))
}
}
#' Get aggregate Matrix from network List
#'
#'
#' @param g.list list of igraph objects
#' @return Aggregate matrix
#' @export
GetAggregateMatrixFromNetworkList <- function(g.list) {
W <- Matrix::sparseMatrix(
igraph::gorder(g.list[[1]]),
igraph::gorder(g.list[[1]])
)
for (g in g.list) {
if (!is.null(igraph::E(g)$weight)) {
W <- W + igraph::as_adjacency_matrix(g, attr = "weight")
} else {
W <- W + igraph::as_adjacency_matrix(g)
}
}
return(W)
}
#' Get aggregate Network from network List
#'
#'
#' @param g.list list of igraph objects
#' @return Aggregate network
#' @export
GetAggregateNetworkFromNetworkList <- function(g.list) {
W <- Matrix::sparseMatrix(
igraph::gorder(g.list[[1]]),
igraph::gorder(g.list[[1]])
)
for (g in g.list) {
if (!is.null(igraph::E(g)$weight)) {
W <- W + igraph::as_adjacency_matrix(g, attr = "weight")
} else {
W <- W + igraph::as_adjacency_matrix(g)
}
}
if (sum(W - Matrix::t(W)) == 0) {
return(igraph::as.undirected(igraph::graph.adjacency(W, weighted = T)))
} else {
return(igraph::graph.adjacency(W, weighted = T))
}
}
#' Get a sample of a Multiplex
#'
#'
#' @param Layers scalar, number of layers, number of layers
#' @param Nodes scalar, number of nodes
#' @param p scalar, parameter to build the sample
#' @return Adjacency Matrix of the Layer and nodes indicated
#' @export
GetSampleMultiplex <- function(Layers, Nodes, p) {
NodeTensor <- lapply(1:Layers, function(x) {
A <- rand(Nodes, Nodes)
A[Matrix::which(A < p)] <- 1
A[Matrix::which(row(A) == col(A))] <- 0
A[Matrix::which(A < 1)] <- 0
A[lower.tri(A)] <- 0
A <- A + Matrix::t(A)
return(A)
})
LayerTensor <- BuildLayersTensor(Layers, 1, "categorical")
M <-
BuildSupraAdjacencyMatrixFromEdgeColoredMatrices(NodeTensor, LayerTensor, Layers, Nodes)
diag(M) <- 0
return(Matrix::drop0(M))
}
#' 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...
#'
#'
#' @param Matrix matrix
#' @return Matrix of eigenvectors (Q),
#' Diagonal matrix of eigenvalues (L), and vector with ordered eigenvalues (E)
#' @export
SolveEigenvalueProblem <- function(Matrix) {
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 = Matrix::Diagonal(Re(tmp$values), n = length(tmp$values)),
Eigenvalues = cbind(sort(tmp$values))
))
}
#' Gets the largest Eigenvalue from a Matrix. A warning is raised if complex numbers emerge.
#'
#'
#' @param Matrix matrix
#' @return The eigenvector of largest eigenvalue, the largest eigenvalue
#' @export
GetLargestEigenv <- function(Matrix) {
#we must distinguish between symmetric and non-symmetric matrices to have correct results
# still to do for further improvements
# tmp <- RSpectra::eigs(Matrix, 1, which = "LM")
tmp <- eigen(Matrix, only.values = F)
lm <- which.max(Re(tmp$values[abs(Im(tmp$values)) < 1e-6]))
tmp$vectors <- tmp$vectors[, lm]
tmp$values <- tmp$values[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 risen
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[Matrix::which(tmp$vectors > -1e-12 & tmp$vectors < 1e-12)] <- 0
#now verify that all components are negative and change sign
if (all(tmp$vectors[Matrix::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
}
#' Binarize a matrix
#'
#' Get a binarized version (only 0s and 1s) of a Matrix, which is assumed to be
#' sparse. Matrix entries which are different from zero are set to one.
#'
#' @param A matrix
#' @return Matrix binarized
#' @export
binarizeMatrix <- function(A) {
#A is assumed to be sparse
A[Matrix::which(A != 0)] <- 1
return(A)
}
#binarizeMatrix <- function(A){
# return( Matrix::Matrix(as.numeric(A>0), dim(A)[1], dim(A)[2], sparse=T) )
#}
#' Return the ith canonical vector of a N-dimension basis
#'
#'
#' @param N sacalar, dimension of the basis
#' @param i sacalar, the ith vector
#' @return
#' Canonical vector
CanonicalVector <- function(N, i) {
vec <- zeros(1, N)
vec[i] <- 1
return(vec)
}
###################################################################
## REDUCIBILITY OF MULTILAYER NETWORKS
###################################################################
#Warning: this should be made compatible with code in SpectralEntropyLib and SpectralGeometryLib
#' Network combinatorial Laplacian
#'
#' Given an adjacency matrix \eqn{A}, the function builds the
#' combinatorial Laplacian \eqn{D - A} for a single-layer network.
#'
#' @param AdjacencyMatrix the adjacency matrix characterising the network
#' @return The network combinatorial Laplacian Matrix
#' @export
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))
}
#' Network normalized Laplacian
#'
#' Given an adjacency matrix \eqn{A}, the function builds the
#' random walk (RW) normalised Laplacian \eqn{I - D^{-1}A} for a single-layer
#' network.
#' The RW normalised Laplacian is defined only for graphs without isolated
#' nodes -- due to the inversion of the diagonal matrix of degrees
#' \eqn{D^{-1}}.
#' Despite this, a (classical) random walk is still defined also in presence
#' of isolates or nodes without out-going edges, simply setting the
#' transition probability from those nodes outwards to be zero.
#' Consequently we can extend the definition of the RW normalised Laplacian
#' setting \eqn{L_{ij} = 0} if \eqn{k_i = 0} for all \eqn{j}.
#' @param AdjacencyMatrix the adjacency matrix characterising the network
#' @return Normalized Laplacian Matrix
#' @export
GetNormalizedLaplacianMatrix <- function(AdjacencyMatrix) {
#Calculate the laplacian matrix from an adjacency matrix
N <- dim(AdjacencyMatrix)[1]
u <- ones(N, 1)
degs <- AdjacencyMatrix %*% u
#StrengthMatrix <- diagR(degs, N)
DisconnectedNodes <- sum(degs == 0)
if (DisconnectedNodes > 0) {
cat(paste0(
" #Trapping nodes (no outgoing-links): ",
DisconnectedNodes,
"\n"
))
}
# laplacian
# LaplacianMatrix <- GetLaplacianMatrix(AdjacencyMatrix)
# WARNING
# FOR NETWORKS WITH ISOLATED NODES, THE CALCULATION OF THE LAPLACIAN
# IS CORRECT ONLY IF THE LAPLACIAN IS COMBINATORIAL.
# FOR NORMALIZED LAPLACIAN, CARE MUST BE TAKEN (DIAGONAL ENTRIES SHOULD
# BE SET TO 0). RIGHT NOW THE DIAG ENTRY WOULD BE 1, THAT'S WHY THE CHECK
# CONSIDER DisconnectedNodes AGAINST THE SUM. BY SETTING DIAG ENTRIES
# TO 0, THAT CHECK CAN AVOID TO SUBTRACT DisconnectedNodes
# igraph with normalized=T gives the symmetric Laplacian, therefore this must be done
# internally and ad hoc here.
# THROWING A STOP
invD <- 1 / degs
invD[Matrix::which(is.infinite(invD))] <- 0
invD <- diagR(invD, N, 0)
LaplacianMatrix <- speye(N) - invD %*% AdjacencyMatrix
if (DisconnectedNodes > 0) {
cat(
" WARNING. Trying to use a Normalized Laplacian from a network with disconnected nodes. \n WARNING. Look inside the code for further details, but this could lead to wrong result. \n WARNING. Solution is implemented but check the results.\n"
)
diag(LaplacianMatrix)[Matrix::which(degs == 0)] <- 0
#w e have just corrected for disconnected nodes
DisconnectedNodes <- 0
}
#always check
if (sumR(sumR(LaplacianMatrix, 2), 1) - DisconnectedNodes > 1.e-8) {
stop(
"ERROR! The normalized Laplacian matrix has rows that don't sum to 0. Aborting process.\n"
)
}
return(Matrix::drop0(LaplacianMatrix))
}
# Warning: this should be made compatible with code in SpectralEntropyLib
# Functions below should allow to choose for the type of density matrix (BGS/DDB) and laplacian
#' Calculate the density matrix from an adjacency matrix
#'
#'
#' @param AdjacencyMatrix an adjacency matrix
#' @return Density matrix for the provided matrix
#' @references
#' S. L. Braunstein, S. Ghosh, S. Severini, Annals of Combinatorics 10, No 3, (2006)
#'
#' De Domenico, M., Set al. (2013). Mathematical formulation of
#' multilayer networks. Physical Review X, 3(4), 041022.
#' \href{https://doi.org/10.1103/PhysRevX.3.041022}{doi 10.1103/PhysRevX.3.041022}
#' @export
BuildDensityMatrixBGS <- function(AdjacencyMatrix) {
DensityMatrix <- GetLaplacianMatrix(AdjacencyMatrix)
#normalize to degree sum
return(DensityMatrix / (traceR(DensityMatrix)))
}
#' Calculate the eigenvalues of a density matrix
#'
#'
#' @param DensityMatrix an adjacency matrix
#' @return
#' The Eigenvalues for the provided Density matrix
#' @references
#' De Domenico, M., Set al. (2013). Mathematical formulation of
#' multilayer networks. Physical Review X, 3(4), 041022.
#' \href{https://doi.org/10.1103/PhysRevX.3.041022}{doi 10.1103/PhysRevX.3.041022}
#' @export
GetEigenvaluesOfDensityMatrix <- function(DensityMatrix) {
Eigenvalues <- cbind(eigen(DensityMatrix)$values)
#check that eigenvalues sum to 1
if (abs(sum(Eigenvalues) - 1) > 1e-8) {
stop("ERROR! Eigenvalues dont sum to 1! Aborting process.")
}
return(Eigenvalues)
}
#' Calculate the eigenvalues of a density matrix from an adjacency matrix
#'
#'
#' @param AdjacencyMatrix an adjacency matrix
#' @return
#' The Eigenvalues for the Density matrix of the provided adjacency matrix
#' @export
GetEigenvaluesOfDensityMatrixFromAdjacencyMatrix <-
function(AdjacencyMatrix) {
DensityMatrix <- BuildDensityMatrixBGS(AdjacencyMatrix)
return(GetEigenvaluesOfDensityMatrix(DensityMatrix))
}
#' Calculate the quantum Renyi entropy of a network
#'
#'
#' @param AdjacencyMatrix an adjacency matrix
#' @param Q scalar, computes for the relative entropy. Computing Von Neuman quantum entropy if Q=1 (default case), and Renyi quantum entropy otherwise
#' @return
#' Renyi Entropy matrix for the provided adjacency matrix
#' @references
#' De Domenico, M., Set al. (2013). Mathematical formulation of
#' multilayer networks. Physical Review X, 3(4), 041022.
#' \href{doi 10.1103/PhysRevX.3.041022}{https://doi.org/10.1103/PhysRevX.3.041022}
#'
#' De Domenico, M., et al. Structural reducibility of multilayer networks. Nat Commun 6, 6864 (2015).
#' \href{https://doi.org/10.1038/ncomms7864}{doi 10.1038/ncomms7864}
#' @export
GetRenyiEntropyFromAdjacencyMatrix <-
function(AdjacencyMatrix, Q = 1) {
Eigenvalues <-
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)
}
#' Calculate the Jensen-Shannon Divergence of two networks
#'
#'
#' @param AdjacencyMatrix1 an adjacency matrix
#' @param AdjacencyMatrix2 an adjacency matrix
#' @param VNEntropy1 the value of the Von Neumann entropy of the corresponding (1st) adjacency matrix
#' @param VNEntropy2 the value of the Von Neumann entropy of the corresponding (2nd) adjacency matrix
#' @return
#' The Jensen–Shannon distance between the two networks
#' @references
#' De Domenico, M., et al. Structural reducibility of multilayer networks. Nat Commun 6, 6864 (2015).
#' \href{https://doi.org/10.1038/ncomms7864}{doi 10.1038/ncomms7864}
#' @export
GetJensenShannonDivergence <-
function(AdjacencyMatrix1,
AdjacencyMatrix2,
VNEntropy1,
VNEntropy2) {
# %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 <- 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
###################################################################
#' Calculate the global number of triangles
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return
#' number of triangles
#' @references
#' De Domenico, M., Set al. (2013). Mathematical formulation of
#' multilayer networks. Physical Review X, 3(4), 041022.
#' \href{https://doi.org/10.1103/PhysRevX.3.041022}{doi 10.1103/PhysRevX.3.041022}
#' @export
GetGlobalNumberTriangles <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
if (sum(abs(SupraAdjacencyMatrix - Matrix::t(SupraAdjacencyMatrix))) != 0) {
num <-
traceR((SupraAdjacencyMatrix %*% SupraAdjacencyMatrix) %*% SupraAdjacencyMatrix)
} else {
#undirected edges requires to account for multiple ways to produce the same triangle
num <-
traceR((SupraAdjacencyMatrix %*% SupraAdjacencyMatrix) %*% SupraAdjacencyMatrix) /
6
}
return(num)
}
#' Calculate Global Clustering Coefficient
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return
#' Global clustering coefficient
#' @references
#' De Domenico, M., Set al. (2013). Mathematical formulation of
#' multilayer networks. Physical Review X, 3(4), 041022.
#' \href{https://doi.org/10.1103/PhysRevX.3.041022}{doi 10.1103/PhysRevX.3.041022}
#' @export
GetAverageGlobalClustering <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
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
#' Calculate Local Clustering Coefficient
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return
#' Local clustering coefficient
#' @references
#' De Domenico, M., Set al. (2013). Mathematical formulation of
#' multilayer networks. Physical Review X, 3(4), 041022.
#' \href{https://doi.org/10.1103/PhysRevX.3.041022}{doi 10.1103/PhysRevX.3.041022}
#' @export
GetLocalClustering <- function(SupraAdjacencyMatrix, Layers, Nodes) {
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
#' Gets the average global edge overlap on the multilayer
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @param fastBinary logical, optimization for undirected, unweighted, networks
#' @return
#' Average Global edge overlap
#' @references
#' De Domenico, M., et al. Structural reducibility of multilayer networks. Nat Commun 6, 6864 (2015).
#' \href{https://doi.org/10.1038/ncomms7864}{doi 10.1038/ncomms7864}
#' @export
GetAverageGlobalOverlapping <-
function(SupraAdjacencyMatrix,
Layers,
Nodes,
fastBinary = F) {
#fastBinary: optimization for undirected, unweighted, networks
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) {
if (fastBinary) {
O <- O * NodesTensor[[l]]
} else {
O <- pmin(O, NodesTensor[[l]])
}
NormTotal <- NormTotal + sum(sum(NodesTensor[[l]]))
}
}
if (fastBinary) {
O <- O > 0
}
AvGlobOverl <- Layers * sum(sum(O)) / NormTotal
if (sum(SupraAdjacencyMatrix - Matrix::t(SupraAdjacencyMatrix)) == 0) {
AvGlobOverl <- AvGlobOverl / 2
}
return(AvGlobOverl)
}
#Note: can be optimized
#' Calculates the average global node overlap Matrix
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return
#' Average Global Node Overlapping Matrix
#' @references
#' De Domenico, M., et al. Structural reducibility of multilayer networks. Nat Commun 6, 6864 (2015).
#' \href{https://doi.org/10.1038/ncomms7864}{doi 10.1038/ncomms7864}
#' @export
GetAverageGlobalNodeOverlappingMatrix <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
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 <- Matrix::which(sumR(NodesTensor[[l]], 2) != 0)
rows <- Matrix::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
#' Calculates the average global edge overlap Matrix
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @param fastBinary logical, optimization for undirected, unweighted, networks
#' @return
#' Average Global Edge Overlapping Matrix
#' @references
#' De Domenico, M., et al. Structural reducibility of multilayer networks. Nat Commun 6, 6864 (2015).
#' \href{https://doi.org/10.1038/ncomms7864}{doi 10.1038/ncomms7864}
#' @export
GetAverageGlobalOverlappingMatrix <-
function(SupraAdjacencyMatrix,
Layers,
Nodes,
fastBinary = F) {
#fastBinary: optimization for undirected, unweighted, networks
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) {
if (fastBinary) {
O <- NodesTensor[[l1]] * NodesTensor[[l2]]
O <- O > 0
} else {
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)
}
#' Returns pairwise similarity based on Frobenius norm
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @return
#' Pairwise similarity based on Frobenius norm
#' @export
GetSPSimilarityMatrix <-
function(SupraAdjacencyMatrix, Layers, Nodes) {
distanceList <- vector("list", Layers)
g.list <-
SupraAdjacencyToNetworkList(SupraAdjacencyMatrix, Layers, Nodes)
for (l in 1:Layers) {
distanceList[[l]] <- igraph::shortest.paths(g.list[[l]])
distanceList[[l]][is.infinite(distanceList[[l]])] <- 1e8
}
frobeniusNorm <-
Matrix::Matrix(0,
ncol = Layers,
nrow = Layers,
sparse = T)
for (l1 in 1:(Layers - 1)) {
for (l2 in (l1 + 1):Layers) {
frobeniusNorm[l1, l2] <-
sqrt(sum((distanceList[[l1]] - distanceList[[l2]]) ^ 2))
frobeniusNorm[l2, l1] <- frobeniusNorm[l1, l2]
}
}
frobeniusNorm <- 1 - frobeniusNorm / max(frobeniusNorm)
return(frobeniusNorm)
}
#' Return the multi-out-degree, not accounting for interlinks
#'
#'
#' @param SupraAdjacencyMatrix the supra-adjacency matrix
#' @param Layers scalar, number of layers
#' @param Nodes scalar, number of nodes
#' @param isDirected logical
#' @return
#' Vector of Multi-out-degree
#' @references