library(lpSolve)
##Defining vectors and matrices for graph
V <- 10
E <- choose(10,2) - floor(4*runif(1, 0,1))
print(paste("Number of nodes ", V, " Number of edges ",E, sep = ""))
## [1] "Number of nodes 10 Number of edges 45"
##Defining weight, cost, proportion vectors
W <- floor(runif(E, 0,4))
Q <- floor(runif(V, 0,4))
Cw <- floor(runif(E, 0,2))
Cq <- floor(runif(V, 0,2))
print(paste(c("Population on nodes is ",Q), collapse = " "))
## [1] "Population on nodes is 0 0 0 0 1 1 2 3 3 3"
print(paste(c("Population on routes is ",W), collapse = " "))
## [1] "Population on routes is 1 3 1 1 3 2 0 1 3 3 1 2 2 1 2 0 3 2 1 1 0 1 1 1 3 1 1 3 1 2 1 3 2 1 3 1 0 0 3 3 2 3 0 3 0"
print(paste(c("Cost of monitoring routes is ",Cw), collapse = " "))
## [1] "Cost of monitoring routes is 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 0 1 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 1 0"
print(paste(c("Cost of monitoring nodes is ",Cq), collapse = " "))
## [1] "Cost of monitoring nodes is 1 0 1 1 1 1 0 1 1 1"
##Generating Vector of proportions of trafficking
r <- runif(E, 0,0.5)
s <- runif(V, 0,0.6)
#Defining Objective function
W1 <- W*(1-r)
W2 <- W*r
S1 <- Q*(1-s)
S2 <- Q*s
tpr <- 0.38
tnr <- 0.46
cow <- W1*(1-tnr)+W2*(1-tpr)
coq <- S1*(1-tnr)+S2*(1-tpr)
#Coefficients of Objective function
cofobj <- c(cow,coq)
cofcon <- matrix(data = 0, ncol = E+V, nrow = 3)
cofcon[1,] <- c(Cw, Cq)
cofcon[2,] <- c(W2*tpr,S2*tpr)
cofcon[3,] <- c(W1*tnr,S1*tnr)
#Setting directionality of inequalities
f.dir <- c("<=", ">=","<=")
# Set right hand side coefficients
f.rhs <- c(7,1,10)
# Final value (z)
z <- lp("min", cofobj, cofcon, f.dir, f.rhs, all.bin = TRUE)
# Variables final values
idx <- which(z$solution>0)
print(paste(c("Edges to allocate resources ",idx[which(idx<=E)]),collapse = " "))
## [1] "Edges to allocate resources 8 11 23"
print(paste(c("Nodes to allocate resources ",idx[which(idx>E)]-E), collapse = " "))
## [1] "Nodes to allocate resources 10"
#Objective function & Constraint values
z
## Success: the objective function is 3.451736
sum(z$solution*cofcon[1,])
## [1] 2
sum(z$solution*cofcon[2,])
## [1] 1.005744
sum(z$solution*cofcon[3,])
## [1] 1.54252