I am trying to generate a random network with preferential attachment. Here is the code:
library(purrr)
library(igraph)
get_random_integer = function(value) {
result = floor(runif(1, min=1, max=value))
return (result)
}
get_random_link = function(m, value) {
links = to_vector(m)
maxVal = length(links) + 1
result = floor(runif(1, min=1, max=maxVal))
return (links[result])
}
to_vector = function(listVar) {
return (unlist(listVar, use.names=FALSE))
}
set_initial_edges = function() {
loop = rep(1:4, each = 2)
vertices = c(loop[-1], loop[1])
return (vertices)
}
create_graph_data = function(start, end, gamma) {
l = list()
m = list(1,2,3,4)
for (i in seq(start,end)) {
p = rbernoulli(1, p = gamma)
if (p) {
x = get_random_integer(i)
} else {
x = get_random_link(m, i)
}
l = append(list(i,x), l)
m = append(list(x), m)
}
data = to_vector(l)
return (data)
}
generate_graph = function(end) {
gamma = 0.5 # the probability of choosing a link at random among all the pages
initial_vertices = 4 # the number of vertices of the initial graph
initial_edges = set_initial_edges() # the edges of the initial graph
start = initial_vertices + 1 # the starting value of the interval
increment = end - start + 1 # the number of vertices to add to the initial graph
data = create_graph_data(start, end, gamma) # creates an edge for each additional vertex
grph <- make_empty_graph() %>% # initialize an empty graph
add_vertices(initial_vertices) %>% # add the first 4 vertices
add_edges(initial_edges) %>% # add the first 4 edges
add_vertices(increment) %>% # add to the initial graph the remaining vertices
add_edges(data) # add to the initial graph the remaining edges
return (grph)
}
a = generate_graph(10000)
plot(a,edge.width=1,edge.arrow.size=0.1,vertex.size=1,vertex.label.cex=0.1)
I know this is not the most straightforward way, I should have probably used an adjacency matrix, but anyway…
every object is created as follows, see the second-to-last line of the code above:
a = generate_graph(10000)
where the parameter, 10000, is the number of nodes to be added to the graph.
I was able to do almost anything with such graphs, but I have encountered a problem: if I use igraph methods like transitivity or vertex_connectivity, the result is always zero, regardless of the dimension size of the graph.
Is this happening because of a property of the model I am building, or the way I am building the igraph objects is wrong?
Many thanks