2017-02-28 958 views
0

我正在尋找一種有效的方法來查找大圖中所有節點的精確度的鄰域。即使它存儲圖形爲稀疏矩陣,igraph::ego炸燬:R中圖節點的二階鄰居

require(Matrix) 
require(igraph) 
require(ggplot2) 

N <- 10^(1:5) 
runtimes <- function(N) { 
    g <- erdos.renyi.game(N, 1/N) 
    system.time(ego(g, 2, mindist = 2))[3] 
} 
runtime <- sapply(N, runtimes) 
qplot(log10(N), runtime, geom = "line") 

enter image description here

有沒有更有效的方法?

回答

0

直接使用鄰接矩陣提供了重大改進。

# sparse adjacency-matrix calculation of indirect neighbors ------------------- 

diff_sparse_mat <- function(A, B) { 
    # Difference between sparse matrices. 
    # Input: sparse matrices A and B 
    # Output: C = (A & !B), using element-wise diffing, treating B as logical 
    stopifnot(identical(dim(A), dim(B))) 
    A <- as(A, "generalMatrix") 
    AT <- as.data.table(summary(as(A, "TsparseMatrix"))) 
    setkeyv(AT, c("i", "j")) 
    B <- drop0(B) 
    B <- as(B, "generalMatrix") 
    BT <- as.data.table(summary(as(B, "TsparseMatrix"))) 
    setkeyv(BT, c("i", "j")) 
    C <- AT[!BT] 
    if (length(C) == 2) { 
    return(sparseMatrix(i = C$i, j = C$j, dims = dim(A))) 
    } else { 
    return(sparseMatrix(i = C$i, j = C$j, x = C$x, dims = dim(A))) 
    } 
} 

distance2_peers <- function(adj_mat) { 
    # Returns a matrix of indirect neighbors, excluding the diagonal 
    # Input: adjacency matrix A (assumed symmetric) 
    # Output: (A %*% A & !A) with zero diagonal 
    indirect <- forceSymmetric(adj_mat %*% adj_mat) 
    indirect <- diff_sparse_mat(indirect, adj_mat) # excl. direct neighbors 
    indirect <- diff_sparse_mat(indirect, Diagonal(n = dim(indirect)[1])) # excl. diag. 
    return(indirect) 
}  

爲鄂爾多斯仁義例如,在半分鐘現在的10^7網絡,而不是10^5可以分析:

N <- 10^(1:7) 
runtimes <- function(N) { 
    g <- erdos.renyi.game(N, 1/N, directed = FALSE) 
    system.time(distance2_peers(as_adjacency_matrix(g)))[3] 
} 
runtime <- sapply(N, runtimes) 
qplot(log10(N), runtime, geom = "line") 

the new runtimes

所得矩陣containst在(i,j)從i到j的長度爲2的路徑的數量(不包括包含我自己的路徑)。