Nothing
# Internal centrality functions
#
# These functions were originally written by Mahdi Jalili for the 'centiserve'
# package (version 1.0.0, GPL (>= 2), https://CRAN.R-project.org/package=centiserve).
# They are included in CINNA (GPL-3) so that CINNA no longer depends on
# 'centiserve'. The algorithms and results are unchanged; calls to deprecated
# or removed 'igraph' functions were replaced by their current equivalents.
# These functions are internal and are not exported.
#' @importFrom igraph all_shortest_paths as_adjacency_matrix as_edgelist cliques closeness components degree delete_edges delete_vertices diameter E ecount edge_attr ego igraph_opt induced_subgraph is_connected is_directed is_igraph is_named neighbors set_edge_attr transitivity V vcount vertex_attr_names which_loop which_multiple distances
#' @importFrom stats runif
#' @importFrom circlize circos.clear
NULL
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
.cs.checkPreconditions <- function(g, conditions = c()) {
if (!is_igraph(g)) {
stop("Not a graph object", call. = FALSE)
}
error <- character()
for (condition in conditions) {
switch(condition,
connected = {
if (!is_connected(g, mode = "weak"))
error <- append(error, "Graph is not connected.")
},
stronglyConnected = {
if (!is_connected(g, mode = "strong"))
error <- append(error, "Graph is not strongly connected.")
},
noMultiple = {
if (any(which_multiple(g)))
error <- append(error, "Graph have multiple edges.")
},
loopFree = {
if (any(which_loop(g)))
error <- append(error, "Graph is not loop free.")
},
undirected = {
if (is_directed(g))
error <- append(error, "Graph is not undirected.")
},
directed = {
if (!is_directed(g))
error <- append(error, "Graph is not directed.")
},
weighted = {
if (is.null(edge_attr(g, "weight")))
error <- append(error, "Graph is not weighted.")
},
{}
)
}
if (length(error) > 0) stop(paste(error, collapse = " "), call. = FALSE)
}
# Convert a vertex specification to numeric vertex ids
.cs.as.igraph.vs <- function(graph, v, na.ok = FALSE) {
if (is.character(v) && "name" %in% vertex_attr_names(graph)) {
v <- as.numeric(match(v, V(graph)$name))
if (!na.ok && any(is.na(v))) {
stop("Invalid vertex names")
}
v
} else {
if (is.logical(v)) {
res <- as.vector(V(graph))[v]
} else if (is.numeric(v) && any(v < 0)) {
res <- as.vector(V(graph))[v]
} else {
res <- as.numeric(v)
}
if (!na.ok && any(is.na(res))) {
stop("Invalid vertex name(s)")
}
res
}
}
# Add vertex names to a result vector if the graph is named
.cs.named <- function(graph, res, vids = NULL) {
if (igraph_opt("add.vertex.names") && is_named(graph)) {
if (is.null(vids)) names(res) <- V(graph)$name
else names(res) <- V(graph)$name[vids]
}
res
}
# Neighbours of a vertex (excluding the vertex itself), as integer ids
.cs.nei <- function(graph, v, order = 1, mode = "all") {
as.integer(ego(graph, order = order, nodes = v, mode = mode)[[1]])[-1]
}
# Set the "weight" edge attribute as centiserve did
.cs.set.weights <- function(graph, weights) {
if (!is.null(weights) && any(!is.na(weights))) {
graph <- set_edge_attr(graph, "weight", value = as.numeric(weights))
} else if (is.null(weights)) {
graph <- set_edge_attr(graph, "weight", value = 1)
}
graph
}
# ---------------------------------------------------------------------------
# Centrality measures
# ---------------------------------------------------------------------------
averagedis <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph, c("stronglyConnected", "loopFree"))
vids <- .cs.as.igraph.vs(graph, vids)
n <- vcount(graph) + 1
sp <- distances(graph, v = V(graph), mode = mode[1], weights = weights)
res <- as.double(rowSums(sp)[vids] / n)
.cs.named(graph, res, vids)
}
barycenter <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph, c("connected", "stronglyConnected"))
vids <- .cs.as.igraph.vs(graph, vids)
sp <- distances(graph, v = V(graph), mode = mode[1], weights = weights)
res <- vapply(vids, function(v) 1 / sum(sp[v, sp[v, ] != Inf]), numeric(1))
.cs.named(graph, res, vids)
}
bottleneck <- function(graph, vids = V(graph), mode = c("all", "out", "in")) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
res <- matrix(0, vcount(graph), 1)
for (v in seq_len(vcount(graph))) {
asp <- all_shortest_paths(graph, from = v, to = V(graph), mode = mode[1], weights = NA)
paths <- if (!is.null(asp$vpaths)) asp$vpaths else asp$res
s <- table(unlist(lapply(paths, as.integer)))
# indices refer to positions in the table, as in the original implementation
for (i in which(s > (length(s) / 4), arr.ind = TRUE)) {
if (i != v) res[i, 1] <- res[i, 1] + 1
}
}
res <- .cs.named(graph, res[, 1])
res[vids]
}
centroid <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph, c("stronglyConnected"))
vids <- .cs.as.igraph.vs(graph, vids)
numVertices <- vcount(graph)
sp <- distances(graph, v = V(graph), to = V(graph), mode = mode[1], weights = weights)
gammaValues <- matrix(0, numVertices, numVertices)
for (u in seq_len(numVertices)) {
for (v in seq_len(numVertices)) {
gammaValues[u, v] <- sum(sp[u, ] < sp[v, ])
}
}
fValues <- gammaValues - t(gammaValues)
# The original implementation compared against the last value of the loop
# variable 'u' (i.e. the last vertex); this is kept to preserve results.
u <- numVertices
res <- double()
for (w in vids) {
result <- 1.7 * (10^308)
for (i in seq_len(numVertices)) {
if (fValues[w, i] < result && u != i) {
result <- fValues[w, i]
}
}
res <- append(res, result)
}
.cs.named(graph, res, vids)
}
closeness.currentflow <- function(graph, vids = V(graph), weights = NULL) {
.cs.checkPreconditions(graph, c("undirected", "connected", "loopFree"))
vids <- .cs.as.igraph.vs(graph, vids)
graph <- .cs.set.weights(graph, weights)
numVertices <- vcount(graph)
resultVector <- double(numVertices)
kroneckerVector <- matrix(nrow = numVertices - 1, ncol = 1)
# L = D - A
L <- diag(degree(graph, mode = "all", loops = FALSE), nrow = numVertices, ncol = numVertices) -
as_adjacency_matrix(graph, attr = "weight", sparse = FALSE)
L <- L[-1, -1, drop = FALSE]
for (i in 1:(numVertices - 1)) {
kroneckerVector[, 1] <- 0
kroneckerVector[i, 1] <- 1
solveTemporaryVector <- solve(L, kroneckerVector)
resultVector[1] <- resultVector[1] + solveTemporaryVector[i, 1]
resultVector[i + 1] <- resultVector[i + 1] + solveTemporaryVector[i, 1]
for (j in 1:(numVertices - 1)) {
resultVector[i + 1] <- resultVector[i + 1] + (solveTemporaryVector[i, 1] - 2 * solveTemporaryVector[j, 1])
resultVector[j + 1] <- resultVector[j + 1] + solveTemporaryVector[i, 1]
}
}
resultVector <- (numVertices - 1) / resultVector
resultVector <- .cs.named(graph, resultVector)
resultVector[vids]
}
closeness.freeman <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL, normalized = FALSE) {
.cs.checkPreconditions(graph, c("connected", "stronglyConnected"))
vids <- .cs.as.igraph.vs(graph, vids)
closeness(graph, vids = vids, mode = mode[1], weights = weights, normalized = normalized)
}
closeness.latora <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL, normalized = FALSE) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
sp <- distances(graph, v = V(graph), mode = mode[1], weights = weights)
res <- vapply(vids, function(v) sum(1 / sp[v, sp[v, ] != 0]), numeric(1))
if (as.logical(normalized)) res <- res / (vcount(graph) * (vcount(graph) - 1))
.cs.named(graph, res, vids)
}
closeness.residual <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
sp <- distances(graph, v = V(graph), mode = mode[1], weights = weights)
res <- vapply(vids, function(v) sum(1 / (2^sp[v, ])), numeric(1))
.cs.named(graph, res, vids)
}
closeness.vitality <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph, c("connected", "stronglyConnected"))
vids <- .cs.as.igraph.vs(graph, vids)
graph <- .cs.set.weights(graph, weights)
totalWI <- .cs.wienerIndex(graph, mode[1])
res <- double()
for (v in vids) {
subgraph <- delete_vertices(graph, v)
if (!is_connected(subgraph, mode = "strong")) stop("Subgraph of graph is not strongly connected.", call. = FALSE)
res <- append(res, totalWI - .cs.wienerIndex(subgraph, mode[1]))
}
.cs.named(graph, res, vids)
}
# Wiener index of a graph (as computed in centiserve)
.cs.wienerIndex <- function(graph, mode) {
sum(1 / closeness(graph, vids = V(graph), mode = mode))
}
clusterrank <- function(graph, vids = V(graph), directed = TRUE, loops = TRUE) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
if (directed && is_directed(graph)) {
cc <- .cs.transitivity.directed(graph)
mode <- "out"
} else {
cc <- transitivity(graph, type = "local")
mode <- "all"
}
res <- double()
for (v in vids) {
if (is.nan(cc[v])) {
res <- append(res, NaN)
} else {
vNeighbors <- .cs.nei(graph, v, mode = mode)
cr <- 0
for (vv in vNeighbors) {
cr <- cr + degree(graph, v = vv, mode = mode, loops = as.logical(loops)) + 1
}
res <- append(res, cr * cc[v])
}
}
res <- unname(res)
.cs.named(graph, res, vids)
}
.cs.transitivity.directed <- function(graph) {
res <- double()
for (v in seq_len(vcount(graph))) {
nei <- .cs.nei(graph, v, mode = "out")
if (length(nei) < 2) {
res <- append(res, NaN)
} else {
g <- induced_subgraph(graph, nei)
res <- append(res, ecount(g) / (vcount(g) * (vcount(g) - 1)))
}
}
res
}
communibet <- function(graph, vids = V(graph), normalized = FALSE) {
if (!requireNamespace("expm", quietly = TRUE)) {
stop("The 'expm' package needed for this function to work. Please install it.", call. = FALSE)
}
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
n <- vcount(graph)
A <- as.matrix(as_adjacency_matrix(graph, names = FALSE, sparse = FALSE))
expA <- expm::expm(A)
res <- double()
for (v in vids) {
# remove row and col of node v
comrow <- A[v, ]
comcol <- A[, v]
A[v, ] <- 0
A[, v] <- 0
B <- (expA - expm::expm(A)) / expA
# sum with row/col of node v and diag set to zero
B[v, ] <- 0
B[, v] <- 0
B <- B - diag(diag(B))
res <- append(res, sum(B))
# put row and col back
A[v, ] <- comrow
A[, v] <- comcol
}
if (as.logical(normalized) && n > 2) {
res <- res * (1.0 / ((n - 1.0)^2 - (n - 1.0)))
}
.cs.named(graph, res, vids)
}
# Community centrality (Kalinka & Tomancak 2011) on link communities
# (Ahn, Bagrow & Lehmann 2010), reimplemented in R so that the archived
# 'linkcomm' package is not needed. Results match linkcomm 1.0-14.
communitycent <- function(graph, vids = V(graph), type = c("commweight", "commconn"), normalise = TRUE) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
if (missing(type)) {
type <- "commweight"
} else if (length(type) > 1 || !(as.character(type) %in% c("commweight", "commconn"))) {
stop("The type should be one of 'commweight' or 'commconn'.", call. = FALSE)
}
el <- as_edgelist(graph, names = FALSE)
lc <- .cs.linkCommunities(el, directed = is_directed(graph))
n <- vcount(graph)
clusters <- lc$clusters
K <- length(clusters)
# nodes belonging to each community, and communities of each node
commNodes <- lapply(clusters, function(ids) sort(unique(c(lc$edges[ids, ]))))
nodeComms <- vector("list", n)
for (k in seq_len(K)) for (v in commNodes[[k]]) nodeComms[[v]] <- c(nodeComms[[v]], k)
if (type == "commweight") {
res <- vapply(seq_len(n), function(v) {
cids <- nodeComms[[v]]
if (length(cids) == 0) return(0)
if (length(cids) == 1) return(1)
# pairwise community relatedness (Jaccard on node sets)
J <- matrix(NA_real_, length(cids), length(cids))
for (a in seq_along(cids)) for (b in seq_along(cids)) if (a != b) {
A <- commNodes[[cids[a]]]; B <- commNodes[[cids[b]]]
J[a, b] <- 1 - (1.0 - length(intersect(A, B)) / length(union(A, B)))
}
1 + sum(vapply(seq_along(cids), function(a) 1 - mean(J[a, -a]), numeric(1)))
}, numeric(1))
} else {
# community connectedness: inter-community / intra-community edge ratio
deg <- tabulate(c(lc$edges), nbins = n)
avdeg <- mean(deg[deg > 0])
cc <- vapply(seq_len(K), function(k) {
nodes <- commNodes[[k]]
intra <- length(clusters[[k]])
alledges <- which(lc$edges[, 1] %in% nodes | lc$edges[, 2] %in% nodes)
inter <- length(setdiff(alledges, clusters[[k]]))
if (inter == 0) inter <- 1e-5
if (normalise) {
intra <- intra / ((length(nodes) * (length(nodes) - 1)) / 2)
if (intra == 0) return(0)
inter <- inter / (length(nodes) * avdeg)
}
inter / intra
}, numeric(1))
res <- vapply(seq_len(n), function(v) {
s <- 0
for (k in nodeComms[[v]]) {
ee <- lc$edges[clusters[[k]], , drop = FALSE]
s <- s + sum(ee[, 1] == v | ee[, 2] == v) * cc[k]
}
s
}, numeric(1))
}
res <- .cs.named(graph, res)
res[vids]
}
# Link communities (Ahn, Bagrow & Lehmann 2010), following the algorithm of the
# 'linkcomm' package (Kalinka & Tomancak 2011): edge similarities, average-linkage
# hierarchical clustering of edges, and a cut at maximum partition density.
.cs.linkCommunities <- function(el, directed = FALSE, dirweight = 0.5, removetrivial = TRUE) {
# remove loops, duplicate and bi-directional edges (keeping the first occurrence)
el <- el[el[, 1] != el[, 2], , drop = FALSE]
key <- paste(pmin(el[, 1], el[, 2]), pmax(el[, 1], el[, 2]))
el <- el[!duplicated(key), , drop = FALSE]
m <- nrow(el)
if (m < 3) stop("no clusters were found in this network; maybe try a larger network", call. = FALSE)
if (m > 10000) stop("Community centrality is limited to networks with at most 10000 edges.", call. = FALSE)
nmax <- max(el)
# undirected neighbourhoods; out-neighbourhoods for directed weighting
nei <- split(c(el[, 2], el[, 1]), factor(c(el[, 1], el[, 2]), levels = seq_len(nmax)))
nei <- lapply(nei, function(x) sort(unique(as.integer(x))))
incl <- lapply(seq_len(nmax), function(v) sort(unique(c(nei[[v]], v))))
if (directed) {
outn <- split(el[, 2], factor(el[, 1], levels = seq_len(nmax)))
}
inc <- split(rep(seq_len(m), 2), factor(c(el[, 1], el[, 2]), levels = seq_len(nmax)))
D <- matrix(1, m, m)
for (v in seq_len(nmax)) {
es <- inc[[v]]
if (length(es) < 2) next
for (x in seq_len(length(es) - 1)) for (y in (x + 1):length(es)) {
i <- es[x]; j <- es[y]
a <- if (el[i, 1] == v) el[i, 2] else el[i, 1]
b <- if (el[j, 1] == v) el[j, 2] else el[j, 1]
nA <- incl[[a]]; nB <- incl[[b]]
common <- intersect(nA, nB)
if (!directed) {
d <- (length(nA) + length(nB) - 2 * length(common)) / (length(nA) + length(nB) - length(common))
} else {
w <- vapply(common, function(k) {
if ((k %in% outn[[a]]) == (k %in% outn[[b]])) 1 else dirweight
}, numeric(1))
dot <- sum(w * w)
absA <- dot + length(setdiff(nA, common))
absB <- dot + length(setdiff(nB, common))
d <- 1.0 - (dot / (absA + absB - dot))
}
D[i, j] <- d; D[j, i] <- d
}
}
hc <- stats::hclust(stats::as.dist(D), method = "average")
# cut the dendrogram at maximum partition density
ht <- round(hc$height, digits = 5)
hh <- unique(ht)
csum <- cumsum(vapply(hh, function(x) sum(ht == x), integer(1)))
members <- vector("list", m - 1)
current <- integer(0)
best <- 0; bestMembers <- NULL
p <- 1
for (i in seq_len(m - 1)) {
getm <- function(x) if (x < 0) -x else members[[x]]
members[[i]] <- sort(c(getm(hc$merge[i, 1]), getm(hc$merge[i, 2])))
current <- setdiff(c(current, i), hc$merge[i, hc$merge[i, ] > 0])
if (i == csum[p]) {
ldens <- 0
for (k in current) {
ne <- length(members[[k]])
nn <- length(unique(c(el[members[[k]], ])))
ldens <- ldens + (ne * (ne - nn + 1.0)) / ((nn - 2.0) * (nn - 1.0))
}
pd <- (2.0 / m) * ldens
if (pd > best) {
best <- pd
bestMembers <- members[current]
}
if (p < length(hh)) p <- p + 1
}
}
if (is.null(bestMembers)) stop("no clusters were found in this network; maybe try a larger network", call. = FALSE)
if (removetrivial) bestMembers <- bestMembers[lengths(bestMembers) > 2]
if (length(bestMembers) == 0) stop("no clusters were found in this network; maybe try a larger network", call. = FALSE)
list(edges = el, clusters = bestMembers)
}
crossclique <- function(graph, vids = V(graph)) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
# Note: directed graphs are treated as undirected; multiple edges and loops are ignored.
res <- as.vector(table(unlist(lapply(cliques(graph), as.integer))))
res <- .cs.named(graph, res)
res[vids]
}
decay <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL, decay = 0.5) {
.cs.checkPreconditions(graph, c("stronglyConnected"))
vids <- .cs.as.igraph.vs(graph, vids)
decay <- as.double(decay)
if (decay <= 0 || decay >= 1) stop("The decay parameter must be between 0 and 1", call. = FALSE)
sp <- distances(graph, mode = mode[1], weights = weights)
res <- unname(rowSums(decay^sp))
res <- .cs.named(graph, res)
res[vids]
}
diffusion.degree <- function(graph, vids = V(graph), mode = c("all", "out", "in"), loops = TRUE, lambda = 1) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
d <- unname(degree(graph, mode = mode[1], loops = as.logical(loops))) * as.numeric(lambda)
res <- vapply(vids, function(v) {
nb <- as.integer(ego(graph, order = 1, nodes = v, mode = mode[1])[[1]])
sum(d[nb])
}, numeric(1))
.cs.named(graph, res, vids)
}
dmnc <- function(graph, vids = V(graph), mode = c("all", "out", "in"), epsilon = 1.67) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
epsilon <- as.double(epsilon)
if (epsilon < 1 || epsilon > 2) stop("The epsilon parameter must be between 1 and 2", call. = FALSE)
res <- double()
for (v in vids) {
g <- induced_subgraph(graph, .cs.nei(graph, v, mode = mode[1]))
cl <- components(g, mode = "strong")
ec <- ifelse(length(cl$csize) == 0, 0,
ecount(induced_subgraph(graph, which(cl$membership %in% which(cl$csize == max(cl$csize))))))
if (ec == 0) {
res <- append(res, 0)
} else {
res <- append(res, ec / (max(cl$csize)^epsilon))
}
}
.cs.named(graph, res, vids)
}
entropy <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
graph <- .cs.set.weights(graph, weights)
res <- double()
for (v in vids) {
g <- delete_vertices(graph, v)
sp <- distances(g, v = V(g), mode = mode[1])
paths <- (length(sp[sp != Inf]) - vcount(g)) / 2
H <- 0.0
if (paths > 0) {
for (vv in seq_len(vcount(g))) {
Y <- (length(sp[vv, sp[vv, ] != Inf]) - 1) / paths
if (Y > 0) H <- H + (Y * log2(Y))
}
}
res <- append(res, -H)
}
.cs.named(graph, res, vids)
}
epc <- function(graph, vids = V(graph), threshold = 0.5) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
threshold <- as.double(threshold)
if (threshold < 0 || threshold > 1) stop("The threshold parameter must be between 0 and 1", call. = FALSE)
n <- vcount(graph)
epcT <- integer(n)
for (i in 1:1000) {
w <- runif(ecount(graph), 0, 1)
g <- delete_edges(graph, E(graph)[w < threshold])
membership <- components(g)$membership
epcT <- epcT + as.integer(table(membership)[as.character(membership)])
}
epcT <- epcT / n
epcT <- .cs.named(graph, epcT)
epcT[vids]
}
geokpath <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL, k = 3) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
k <- as.integer(k)
if (k <= 0) stop("The k parameter must be greater than 0.", call. = FALSE)
sp <- distances(graph, v = V(graph), mode = mode[1], weights = weights)
res <- vapply(vids, function(v) length(sp[v, sp[v, ] <= k]) - 1L, integer(1))
.cs.named(graph, res, vids)
}
# Original code from CentiLib
hubbell <- function(graph, vids = V(graph), weights = NULL, weightfactor = 0.5) {
.cs.checkPreconditions(graph, c("connected", "loopFree"))
vids <- .cs.as.igraph.vs(graph, vids)
graph <- .cs.set.weights(graph, weights)
vlen <- vcount(graph)
weightFactor <- as.double(weightfactor)
if (is.na(weightFactor) || weightFactor <= 0) {
stop("Hubbell index centrality is not solvable for this graph. Weight factor must be >0", call. = FALSE)
}
weightedAdjacencyMatrix <- as.matrix(as_adjacency_matrix(graph, names = FALSE, attr = "weight", sparse = FALSE)) * weightFactor
ev <- eigen(weightedAdjacencyMatrix)$values
if (length(ev[ev > 1.0]) > 0) {
stop("Hubbell index centrality is not solvable for this graph.", call. = FALSE)
}
# res = ((I-W)^-1)*vectorE
res <- solve(diag(x = 1, nrow = vlen) - weightedAdjacencyMatrix) %*% matrix(1, nrow = vlen, ncol = 1)
res <- .cs.named(graph, res[, 1])
res[vids]
}
katzcent <- function(graph, vids = V(graph), alpha = 0.1) {
.cs.checkPreconditions(graph, c("loopFree"))
vids <- .cs.as.igraph.vs(graph, vids)
alpha <- as.double(alpha)
if (alpha < 0.0 || alpha > 0.2) stop("Valid alpha is between 0.0-0.2", call. = FALSE)
adjacencyMatrix <- as.matrix(as_adjacency_matrix(graph, names = FALSE, sparse = FALSE))
aMnrow <- nrow(adjacencyMatrix)
maxEigenvalue <- (1 / eigen(adjacencyMatrix)$values[1])
if (alpha <= 0 || alpha >= maxEigenvalue) {
stop("Invalid alpha value.", call. = FALSE)
}
res <- solve(diag(x = 1, nrow = aMnrow) - (alpha * t(adjacencyMatrix))) %*% matrix(1, nrow = aMnrow, ncol = 1)
res <- .cs.named(graph, res[, 1])
res[vids]
}
laplacian <- function(graph, vids = V(graph), mode = c("all", "out", "in"), loops = TRUE) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
d <- unname(degree(graph, mode = mode[1], loops = as.logical(loops)))
res <- vapply(vids, function(aNode) {
nb <- .cs.nei(graph, aNode, mode = mode[1])
d[aNode]^2 + d[aNode] + 2 * sum(d[nb])
}, numeric(1))
.cs.named(graph, res, vids)
}
# Thanks to Alex Upton for the original implementation
leverage <- function(graph, vids = V(graph), mode = c("all", "out", "in"), loops = TRUE) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
k <- unname(degree(graph, mode = mode[1], loops = as.logical(loops)))
n <- vcount(graph)
res <- vapply(seq_len(n), function(v) {
nb <- as.integer(neighbors(graph, v, mode = mode[1]))
mean((k[v] - k[nb]) / (k[v] + k[nb]))
}, numeric(1))
res <- .cs.named(graph, res)
res[vids]
}
lincent <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
sp <- distances(graph, v = V(graph), mode = mode[1], weights = weights)
res <- vapply(vids, function(v) {
linrow <- sp[v, sp[v, ] != Inf]
((length(linrow) - 1)^2) / sum(linrow)
}, numeric(1))
res[res == Inf] <- 1
.cs.named(graph, res, vids)
}
lobby <- function(graph, vids = V(graph), mode = c("all", "out", "in"), loops = TRUE) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
d <- unname(degree(graph, mode = mode[1], loops = as.logical(loops)))
res <- vapply(vids, function(v) {
nb <- as.integer(ego(graph, order = 1, nodes = v, mode = mode[1])[[1]])
as.numeric(.cs.getHIndex(d[nb]))
}, numeric(1))
.cs.named(graph, res, vids)
}
.cs.getHIndex <- function(m) {
mlen <- length(m)
s <- numeric(mlen)
for (i in 1:mlen) {
imin <- min(mlen, m[i])
s[imin] <- s[imin] + 1
}
total <- 0
for (i in length(s):1) {
total <- total + s[i]
if (total >= i) return(i)
}
return(0)
}
markovcent <- function(graph, vids = V(graph)) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
edge.attr <- NULL
average.distances <- FALSE
cl <- components(graph)
clustN <- cl$no
clustMem <- cl$membership
vertN <- vcount(graph)
M <- matrix(rep(Inf, vertN^2), vertN, vertN)
adj <- as_adjacency_matrix(graph, attr = edge.attr, sparse = FALSE)
max.dist <- max(adj)
min.dist <- min(adj[adj > 0])
for (i in 1:clustN) {
locs <- which(clustMem == i)
M[locs, locs] <- suppressWarnings(.cs.markov.MFPTfct(delete_vertices(graph, (1:vertN)[-locs]),
edge.attr = edge.attr, max.dist = max.dist, min.dist = min.dist))
}
if (average.distances) {
lt <- lower.tri(M)
tmp <- apply(cbind(M[lt], t(M)[lt]), 1, mean)
M[lt] <- tmp
M <- t(M)
M[lt] <- tmp
}
diag(M) <- 0
M[M == Inf] <- 2 * max(M[M != Inf])
M <- 1 / apply(M, 2, mean)
M <- .cs.named(graph, M)
M[vids]
}
.cs.markov.MFPTfct <- function(g, edge.attr = NULL, max.dist = NULL, min.dist = NULL) {
adj <- as_adjacency_matrix(g, attr = edge.attr, sparse = FALSE)
if (is.null(max.dist)) max.dist <- max(adj)
if (is.null(min.dist)) min.dist <- min(adj[adj > 0])
adj[adj > 0] <- max.dist - adj[adj > 0] + min.dist
A <- adj / apply(adj, 1, sum)
if (all(is.nan(A))) A[1, 1] <- 1
I <- diag(vcount(g))
U <- matrix(1 / nrow(A), nrow(A), nrow(A))
pi <- U[1, ] %*% solve(I - A + U)
e <- rep(1, nrow(A))
Z <- solve(I - A - e %*% pi)
Zdg <- I * Z
E1 <- matrix(1, vcount(g), vcount(g))
(I - Z + E1 %*% Zdg) %*% (I * as.vector(1 / pi))
}
mnc <- function(graph, vids = V(graph), mode = c("all", "out", "in")) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
res <- vapply(vids, function(v) {
g <- induced_subgraph(graph, .cs.nei(graph, v, mode = mode[1]))
csize <- components(g, mode = "strong")$csize
if (length(csize) == 0) 0 else max(csize)
}, numeric(1))
.cs.named(graph, res, vids)
}
radiality <- function(graph, vids = V(graph), mode = c("all", "out", "in"), weights = NULL) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
numVertices <- vcount(graph)
diam <- diameter(graph)
sp <- distances(graph, mode = mode[1], weights = weights)
res <- vapply(vids, function(v) {
if (any(sp[v, ] == Inf)) Inf else sum(diam + 1.0 - sp[v, ]) / (numVertices - 1.0)
}, numeric(1))
.cs.named(graph, res, vids)
}
semilocal <- function(graph, vids = V(graph), mode = c("all", "out", "in")) {
.cs.checkPreconditions(graph)
vids <- .cs.as.igraph.vs(graph, vids)
n2 <- vapply(seq_len(vcount(graph)), function(u) length(.cs.nei(graph, u, order = 2, mode = mode[1])), numeric(1))
res <- vapply(vids, function(v) {
sl <- 0
for (vv in .cs.nei(graph, v, mode = mode[1])) {
sl <- sl + sum(n2[.cs.nei(graph, vv, mode = mode[1])])
}
sl
}, numeric(1))
.cs.named(graph, res, vids)
}
topocoefficient <- function(graph, vids = V(graph)) {
.cs.checkPreconditions(graph, c("undirected"))
vids <- .cs.as.igraph.vs(graph, vids)
tcs <- double()
for (aNode in vids) {
aNeighbors <- .cs.nei(graph, aNode)
comNeNodes <- vector()
tc <- 0
for (nb in aNeighbors) {
currentComNeNodes <- .cs.nei(graph, nb)
for (n in currentComNeNodes) {
if (n != aNode) {
tc <- tc + 1
if (!(n %in% comNeNodes)) {
comNeNodes <- append(comNeNodes, n)
if (n %in% aNeighbors) {
tc <- tc + 1
}
}
}
}
}
tcs <- c(tcs, tc / (length(comNeNodes) * length(aNeighbors)))
}
.cs.named(graph, tcs, vids)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.