library(lpSolve)
##Defining vectors and matrices for graph
V <- 6
E <- choose(6,2) - floor(4*runif(1, 0,1))
print(paste("Number of nodes ", V, " Number of edges ",E, sep = ""))
## [1] "Number of nodes 6 Number of edges 14"
##Defining weight, cost, proportion vectors
W <- floor(runif(E, 1,5))
Q <- floor(runif(V, 1,5))
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 3 3 1 4 2 2"
print(paste(c("Population on routes is ",W), collapse = " "))
## [1] "Population on routes is 2 4 3 2 1 2 1 1 2 4 2 3 1 1"
print(paste(c("Cost of monitoring routes is ",Cw), collapse = " "))
## [1] "Cost of monitoring routes is 1 1 0 0 0 1 0 0 0 0 0 0 1 0"
print(paste(c("Cost of monitoring nodes is ",Cq), collapse = " "))
## [1] "Cost of monitoring nodes is 0 0 0 1 1 0"
##Generating Vector of proportions of trafficking
r <- runif(E, 0,0.5)
s <- runif(V, 0,0.6)
#Defining Objective function
W1 <- (1-r)
W2 <- r
S1 <- (1-s)
S2 <- s
tpr <- 0.38
tnr <- 0.36
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+E+V)
cofcon[1,] <- c(Cw, Cq)
cofcon[2,] <- c(W2*tpr,S2*tpr)
cofcon[3,] <- c(W1*tnr,S1*tnr)
for(i in seq(1, E+V, by=1)){
cofcon[3+i,i] <- 1
}
#Setting directionality of inequalities
f.dir <- c("<=", ">=","<=",rep("<=",E+V))
# Set right hand side coefficients
f.rhs <- c(20,1,10,W,Q)
# Final value (z)
z <- lp("min", cofobj, cofcon, f.dir, f.rhs, all.int = TRUE)
z$solution
## [1] 0 0 0 0 0 0 0 0 1 0 0 3 0 0 0 0 0 0 2 0
# Variables final values
idx <- which(z$solution>0)
eid <- which(idx<=E)
nid <- which(idx > E)
print(paste(c("No. of inspections ",z$solution[idx[eid]]," on edges ",idx[eid], collapse = " ")))
## [1] "No. of inspections " "1" "3"
## [4] " on edges " "9" "12"
## [7] " "
print(paste(c("No. of inspections ",z$solution[idx[nid]]," on nodes ",idx[nid], collapse = " ")))
## [1] "No. of inspections " "2" " on nodes "
## [4] "19" " "
#Objective function & Constraint values
z
## Success: the objective function is 3.786373
sum(z$solution*cofcon[1,])
## [1] 2
sum(z$solution*cofcon[2,])
## [1] 1.018917
sum(z$solution*cofcon[3,])
## [1] 1.19471