I'm trying to solve the following optimization problem :
I'm using R's quadprog library, here's my code :
library(quadprog)
# Objective function
D <- 21
mu <- c(Si = 0.264586858634721, Ti = 0.00499189368685614, Al = 0.100673272036359,
Fe = 0.0503031611874183, Mn = 0.00115843519022562, Mg = 0.00639267669445844,
Ca = 0.0251667718328268, Na = 0.0480017900217078, K = 0.0310635277333163,
P = 0.00257139262180236, O = 0.46003556883976, Ba = 0.000977541832343879,
Sr = 0.000495374012720138, Zr = 0.000181322238234176, Ce = 0.000136826980378246,
F = 0.000136033570672977, Cr = 0.000101343391176557, Nb = 7.44163264676416e-05,
Zn = 6.81377448074708e-05, S = 6.65357669501474e-05, Rb = 0.00122291858758587
)
Dmat <- diag(D)
dvec <- -2 * mu
f <- function(x) {
t(x - mu) %*% (x - mu)
}
# Inequality constraints
Amat <- -diag(D)
bvec <- rep(0, D)
# Equality constraint
Cmat <- rep(1, D)
dvec2 <- 1
# Optimization using solve.QP
sol <- solve.QP(Dmat, dvec, Amat, bvec, Cmat, dvec2)
x <- sol$solution
However the solution proposed by the solver is :
x = c(0, -0.00998378737371228, -0.201346544072718, -0.100606322374837,
-0.00231687038045124, -0.0127853533889169, -0.0503335436656537,
-0.0960035800434156, -0.0621270554666326, -0.00514278524360472,
-0.92007113767952, -0.00195508366468776, -0.000990748025440275,
-0.000362644476468351, -0.000273653960756493, -0.000272067141345954,
-0.000202686782353113, -0.000148832652935283, -0.000136275489614942,
-0.000133071533900295, -0.00244583717517173)
Which is unfeasible since it contains negative values. What am I doing wrong ?
From ?solve.QP
you can see form of the minimization function. Also it seems that constraints should be column-wise matrix.
Dmat <- 2 * diag(D)
dvec <- 2 * mu
Amat <- cbind(rep(1, D), diag(D))
bvec <- c(1, rep(0, D))
sol <- solve.QP(Dmat, dvec, Amat, bvec, meq = 1)
x <- sol$solution