Limited optimizations in R are worse than manual
I am doing limited optimizations in R. Code works and there are no errors. But the optimized solution is worse than what I see manually! Optimization completes without errors and 0 exit code. However, my solution has a lower cost. Even when the manual solution is submitted as the original solution, the program starts up and does not complain that the first solution is not feasible (which happens in another case) and still falls back to the more costly optimal solution.
Can you help what's going on? Below code runs and can be directly tested in R.
num.prod <- 4
cd.penalty <- 0.001
in.data <- data.frame(V1=c(70.22, 249.92, 241.55, 70.75), V2=c(185.04, 287.43, 240.07, 277.88))
# initial solution
temp <- max(in.data$V1, in.data$V2)
init.flow <- rep(round(temp,-floor(log10(temp))), (num.prod+1)^2)
# cost matrix
cost.mat <- matrix(0, nrow=num.prod+1, ncol=num.prod+1)
for (i in (num.prod/2+1):num.prod) {
cost.mat[i, 1:num.prod/2] <- cd.penalty
cost.mat[i, setdiff((num.prod/2+1):num.prod, i)] <- cd.penalty
cost.mat[i, num.prod+1] <- cd.penalty
}
# constraint matrix
n <- num.prod + 1
cons.mat <- matrix(0, nrow=2*n+n*n, ncol=n*n)
for (i in 1:n) { # outflow
cons.mat[i, ((i-1)*n+1):(i*n)] <- 1
}
for (i in 1:n) { # inflow
cons.mat[i+n, seq(i, n*n, n)] <- 1
}
for (i in 1:(n*n)) { # var level
cons.mat[i+2*n, i] <- 1
}
# constraints constants
balance <- c(c(round(in.data$V1,2), 0), c(round(in.data$V2,2), 0), rep(0, (num.prod+1)^2))
# objective function
flow.cost <- function(flow) {
flow1 <- matrix(flow, nrow=num.prod+1, byrow=T)
cost <- sum(flow1 * cost.mat) + sum(flow1 > 0.01)
return(cost)
}
# optimized solution
result12 <- constrOptim(theta=init.flow, f=flow.cost, ui=cons.mat, ci=balance,
method="Nelder-Mead", outer.iterations=500, control=list(maxit=1000))
matrix(result12$par, nrow=num.prod+1, byrow=T) # optimize solution
result12$value # 17
# manual solution
mysol <- matrix(c(70.22291, rep(0,5), 249.92384, rep(0,5), 240.0733, 0, 1.47988, rep(0,3), 70.75244, 0, 114.81899, 37.50806, 0, 207.13116, 0), nrow=num.prod+1, byrow=T)
flow.cost(t(mysol)) # 8.00148
+3
source to share
No one has answered this question yet
Check out similar questions: