Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewiring weighted graph produces NAs

Tags:

graph

r

igraph

A previous answer to another question provided some code to rewire a weighted graph as:

g <- graph.ring(10)
E(g)$weight <- seq_len(ecount(g))
E(g)$weight
# [1]  1  2  3  4  5  6  7  8  9 10
is.weighted(g)
# [1] TRUE
g2 <- rewire(g,niter=3)
plot(g2)
is.weighted(g2)
# [1] TRUE

Playing with this code however shows that NAs are introduced in to the edge weights vector:

set.seed(1) 
g <- graph.ring(10) 
E(g)$weight <- seq_len(ecount(g)) 
E(g)$weight 
# [1] 1 2 3 4 5 6 7 8 9 10 
is.weighted(g) 
# [1] TRUE 
g2 <- rewire(g,niter=3) 
E(g2)$weight 
# [1] 1 2 4 5 6 7 9 NA NA NA 
is.weighted(g2) 
# [1] TRUE

Following from this I have two related questions:

1) Is the easiest way to fix the NA problem to just reallocate edges manually as in:

g2 <- rewire(g,niter=3) 
E(g2)$weight <- sample( seq_len(ecount(g)) )

or is there a better way in which we can correct this in igraph or at least explain what is going on in igraph for this to happen?

2) Is there a rewiring system that also randomises the the weights so that that the network retains its total strength but both the binary edges are rewired and the individual edge weights across edges change swell?

e.g. not just

id  id w
A - B  6
C - D  1
E - F  1

to

id  id w
A - C  6
D - E  1
B - F  1

but also does:
id  id w
A - B  6
C - D  1
E - F  1

to

id  id w
A - C  4
D - E  3
B - F  1
like image 837
user1320502 Avatar asked Aug 11 '16 12:08

user1320502


Video Answer


1 Answers

1) Reallocating the edges manually is pretty simple. But another simple way is to label the edges and then permute the labels, e.g.:

V(g)$name <- letters[1: ecount(g)]
E(g)
# + 10/10 edges (vertex names):
#  [1] a--b b--c c--d d--e e--f f--g g--h h--i i--j a--j
E(g)$weight
# [1]  1  2  3  4  5  6  7  8  9 10

V(g)$name <- sample(letters[1: ecount(g)])
E(g)
# + 10/10 edges (vertex names):
#  [1] g--h h--c c--d d--e e--j j--a a--b b--f f--i g--i
E(g)$weight
# [1]  1  2  3  4  5  6  7  8  9 10

# visualize:
plot(g, edge.width = E(g)$weight)

Reason for the NAs you saw: for any edge that survives the rewiring, igraph can retain its edge weight. But for new edges it has no weight to assign to it so assigns NA. On the other hand, by just relabeling the vertices as above the original weights are maintained while the edges are shuffled (as you can see by plotting), so no NAs.

2) I don't know of such a rewiring, but you can reassign edge weights that you draw from an integer partition on the total weight, e.g.:

w <- sum(E(g)$weight)
s <- sample(w, size = ecount(g) - 1)
E(g)$weight <- c(sort(s), w) - c(0, sort(s))
sum(E(g)$weight) == w
# [1] TRUE
plot(g, edge.width = E(g)$weight)

or you can do that using the partitions package mentioned here

like image 72
jac Avatar answered Oct 09 '22 11:10

jac