Here's an example that we can use to illustrate ui
and ci
, with some extraneous output removed for brevity. It's maximizing the log likelihood of a normal distribution. In the first part, we use the optim function with box constraints, and in the second part, we use the constrOptim function with its version of the same box constraints.
# function to be optimized
> foo.unconstr <- function(par, x) -sum(dnorm(x, par[1], par[2], log=TRUE))
> x <- rnorm(100,1,1)
> optim(c(1,1), foo.unconstr, lower=c(0,0), upper=c(5,5), method="L-BFGS-B", x=x)
$par
[1] 1.147652 1.077654
$value
[1] 149.3724
>
> # constrOptim example
>
> ui <- cbind(c(1,-1,0,0),c(0,0,1,-1))
> ui
[,1] [,2]
[1,] 1 0
[2,] -1 0
[3,] 0 1
[4,] 0 -1
> ci <- c(0, -5, 0, -5)
>
> constrOptim(c(1,1), foo.unconstr, grad=NULL, ui=u1, ci=c1, x=x)
$par
[1] 1.147690 1.077712
$value
[1] 149.3724
... blah blah blah ...
outer.iterations
[1] 2
$barrier.value
[1] -0.001079475
>
If you look at the ui matrix and imagine multiplying by the parameter vector to be optimized, call it $\theta$, you'll see that the result has four rows, the first of which is $\theta_1$, the second $-\theta_1$, the third $\theta_2$, and the fourth $-\theta_2$. Subtracting off the ci vector and enforcing the $\ge 0$ constraint on each row results in $\theta_1 \ge 0$, $-\theta_1 + 5 \ge 0$, $\theta_2 \ge 0$ and $-\theta_2 + 5 \ge 0$. Obviously, multiplying the second and fourth constraints by -1 and moving the constant to the right hand side gets you to $\theta_1 \le 5$ and $\theta_2 \le 5$, the upper bound constraints.
Just substitute your own values into the ci vector and add appropriate columns (if any) to the ui vector to get the box constraint set you want.