set.seed(756745)
N.patches <- 8
### Patch configurations
patch.network2 <- matrix(
  c(0,1,0,1,
    1,0,0,0,
    0,0,0,1,
    1,0,1,0),
  nrow=N.patches/2,ncol=N.patches/2)

patch.network <- matrix(0,nrow=N.patches,ncol=N.patches)
patch.network[1:4,1:4] <- patch.network2
patch.network[5:8,5:8] <- patch.network2
patch.network[2,8] <- 1
patch.network[8,2] <- 1


## FUNCTION
run_sim <- function (N= 20, N.patches,move.prob,reps=100) {
  inds <- data.frame(ID=1:N, 
                     Start.patch=sample(1:N.patches,
                                        N,
                                        replace=T))
  inds$Current.patch <- inds$Start.patch
  
  network <- matrix(0,N,N)
  diag(network) <- NA
  
  for (z in 1:reps) {
    # first select current.patch
    probs <- move.prob[inds$Current.patch,]
    inds$Current.patch <- apply(probs,
                                1,
                                function(x) { 
                                  sample(1:N.patches,
                                         1,
                                         prob=x) 
                                } 
    )
    
    # second update network
    network <- network + outer(inds$Current.patch,
                               inds$Current.patch,
                               "==")
  }
  network <- network/reps
  return(list(network=network,inds=inds))
}

### Environment
prob.stay <- 0.99

# SELECT YOUR PATCH HERE
move.prob <- sweep(patch.network,1,(1-prob.stay)/rowSums(patch.network),"*")
diag(move.prob) <- prob.stay
move.prob[!is.finite(move.prob)] <- 0

### Individuals
reps <- 100
N <- 40
out <- run_sim(N,N.patches,move.prob,reps)
network <- out$network
inds <- out$inds

### Now run 100 sims to get ranges
sims <- 100
den <- rep(NA, sims)
wei <- rep(NA, sims)
ass <- rep(NA, sims)
mod <- rep(NA, sims)

for (z in 1:sims) {
  out <- run_sim(N,N.patches,move.prob,reps)
  net.tmp <- out$network
  inds.tmp <- out$inds
  g <- graph_from_adjacency_matrix(net.tmp, 
                                   weighted=T,
                                   mode="undirected",
                                   diag=FALSE)
  den[z] <- graph.density(g)
  wei[z] <- mean(E(g)$weight)
  mod[z] <- modularity(cluster_edge_betweenness(g))
  diag(net.tmp) <- 0
  ass[z] <- assortment.discrete(net.tmp,inds.tmp$Start.patch)$r
}

## Plot FROM HERE ##############################################################
par(mar=c(2.75,2.75,0,0))
layout(matrix(c(1,2,2,2,
                3,2,2,2,
                3,2,2,2), nrow = 3, ncol = 4, byrow = TRUE))

# plot habitat patches
nodes <- data.frame(id=1:N.patches,
                    x=c(1,1.3,1.3,1,1.6,1.9,1.9,1.6),
                    y=c(1.3,1.3,1,1,1.9,1.9,1.6,1.6))
plot(nodes$x, nodes$y, xlim=c(0.9,2.1), ylim=c(0.9,2.1),axes=F, pch=15, cex=4,xlab="",ylab="")
node.pairs <- expand.grid(nodes$id,nodes$id)
node.pairs <- node.pairs[which(node.pairs$Var1 < node.pairs$Var2),]
node.pairs$weight <- move.prob[cbind(node.pairs$Var1,node.pairs$Var2)]
node.pairs <- node.pairs[which(node.pairs$weight > 0),]
segments(x0=nodes$x[node.pairs$Var1],
         y0=nodes$y[node.pairs$Var1],
         x1=nodes$x[node.pairs$Var2],
         y1=nodes$y[node.pairs$Var2],
         lwd=900*node.pairs$weight)

# plot social network
library(igraph)
g <- graph_from_adjacency_matrix(network, 
                                 weighted=T,
                                 mode="undirected",
                                 diag=FALSE)
E(g)$width <- E(g)$weight*9

plot(cluster_edge_betweenness(g), g,vertex.size=8,vertex.label=NA,asp =3/3)
text(x=1.1,y=1.0,labels = "(e)",cex = 4)



# plot means and cis
mean.den <- mean(den)
qs.den <- quantile(den,c(0.025,0.975))

mean.wei <- mean(wei)
qs.wei <- quantile(wei,c(0.025,0.975))

mean.ass <- mean(ass)
qs.ass <- quantile(ass,c(0.025,0.975))

mean.mod <- mean(mod)
qs.mod <- quantile(mod,c(0.025,0.975))

plot(c(1,2,3,4),
     c(mean.den,mean.wei,mean.ass,mean.mod),
     ylim=c(0,1),
     axes=FALSE,
     xlim=c(0.5,4.5),pch=20,cex=4,xlab="",ylab="",
     col=c("red","green","blue","black"))
arrows(1,qs.den[1],1,qs.den[2],code=3,len=0.05,angle=90,col = "red")
arrows(2,qs.wei[1],2,qs.wei[2],code=3,len=0.05,angle=90,col = "green")
arrows(3,qs.ass[1],3,qs.ass[2],code=3,len=0.05,angle=90,col = "blue")
arrows(4,qs.mod[1],4,qs.mod[2],code=3,len=0.05,angle=90,col = "black")
box()
axis(2,at=c(0,.5,1),cex.axis=2.3)
axis(1,at=c(1,2,3,4),labels=c("D","W","A","M"),cex.axis=2, padj=0.25)


