Rev. | ff3ceffdc2cf55b8672571921db0ba787eb074be |
---|---|
大小 | 2,836 字节 |
时间 | 2009-06-16 01:55:14 |
作者 | isella |
Log Message | I fixed a bug in the identification of the clusters (a 0/1 catch!). See comments in the code. |
rm(list=ls())
library(Matrix)
library(igraph)
library(Cairo)
set.seed(1234)
n<-300
p<-0.005
my_seq <- runif(n*n)
my_sel<-which(my_seq<p)
my_sel_out<-which(my_seq>p)
my_seq[my_sel] <- 1
my_seq[my_sel_out] <- 0
adj_mat <- forceSymmetric(Matrix(my_seq, n))
diag(adj_mat) <- 1
thres_giant = 1/(n-1)
print("The threshold for a giant component is, ")
print(thres_giant)
g <- graph.adjacency(adj_mat, "undirected")
g <- simplify(g)
l <- layout.fruchterman.reingold(g)
l <- layout.norm(l, -1,1, -1,1)
E(g)$color <- "grey"
E(g)$width <- 1
V(g)$label.color <- "blue"
V(g)$color <- "SkyBlue2"
pdf("random_graph.pdf")
plot(g, layout=layout.fruchterman.reingold,
vertex.label.dist=0.5,vertex.label=NA, vertex.size=5)
dev.off()
#get minimum spanning tree
d <- get.diameter(g)
E(g, path=d)$color <- "red"
E(g, path=d)$width <- 1
V(g)[ d ]$label.color <- "black"
V(g)[ d ]$color <- "red"
pdf("random_graph_diameter.pdf")
plot(g, layout=layout.fruchterman.reingold,
vertex.label.dist=0.5,vertex.label=NA, vertex.size=5)
title(main="Diameter of the random graph",
xlab="created by igraph 0.5")
axis(1, labels=FALSE, tick=TRUE)
axis(2, labels=FALSE, tick=TRUE)
dev.off()
############################################################################################
############################################################################################
############################################################################################
#Now identify the connected components
cluster_structure <- clusters(g)
print ("The overall number of clusters is, ")
print (cluster_structure$no)
print ("The membership of individual nodes is, ")
print (cluster_structure$membership)
#NB: the following line is plainly wrong! Due to a 0/1 catch, it cannot be used to detect the members of cluster labelled as zero.
#select_vertices <- V(g)[which(cluster_structure$membership==0)]
#the right way to go is the following
select_vertices <- V(g)[cluster_structure$membership==0]
#or one could use the line I commented below
#select_vertices <- V(g)[which(cluster_structure$membership==0)-1]
sub <- subgraph(g, select_vertices)
#test that all the nodes in this graph are connected
print ("The overall number of clusters in sub is, ")
print (clusters(sub)$no)
#now highlight the largest connected component
E(g)$color <- "grey"
E(g)$width <- 1
V(g)$label.color <- "blue"
V(g)$color <- "SkyBlue2"
V(g)[ select_vertices ]$label.color <- "black"
V(g)[ select_vertices ]$color <- "red"
pdf("clusters.pdf")
plot(g, layout=layout.fruchterman.reingold,
vertex.label.dist=0.5,vertex.label=NA, vertex.size=5)
title(main="Largest cluster in a random graph",
xlab="created by igraph 0.5")
axis(1, labels=FALSE, tick=TRUE)
axis(2, labels=FALSE, tick=TRUE)
dev.off()