Question

I am using the alabama package to optimize a non-linear constrained optimization problem.

The problem is:

 minimise:  -(0.653*x[1]+ 0.234* x[1]*x[1]+ 0.437 * x[2] + 0.769 * x[3]
 +0.453 * x[4] + 0.744 * x[5] + 0.476 * x[5]* x[5])

The equality constraint is:

x[1]+ x[2]+x[3]+x[4]+x[5] = 2600

The inequality constraints are:

x[1]> 900
x[1] < 1100
x[2] > 400
x[2] < 600
x[3] > 250
x[3] < 350
x[4] > 175
x[4] < 225
x[5] > 295
x[5] < 305

Here is what I am trying:

fn <- function() {
   -(0.653*x[1]+ 0.234* x[1]*x[1]+ 0.437 * x[2] + 0.769 * x[3] +
    0.453 * x[4] + 0.744 * x[5] + 0.476 * x[5]* x[5])
 }



 heq <- function(x) { x[1] + x[2] + x[3] + x[4] +x[5] - 2600  }

hin <- function(x) {
h <- rep(NA, 1)
h[1] <- x[1] - 900
h[2] <- 1100 - x[1]
h[3] <- x[2] - 400
h[4] <- 600 - x[2]
h[5] <- x[3] - 250
h[6] <- 350 - x[3]
h[7] <- x[4] - 175
h[8] <- 225 - x[4]
h[9] <- x[5] - 295
h[10] <- 305 - x[5]
h
}

Here are the various problems I face with different values of par:

Case1:

ans <- auglag(par= NULL,fn=fn, gr=NULL,hin=hin, heq=heq) 
Error in h[1] <- x[1] - 900 : replacement has length zero

Case2:

ans <- auglag(par= c(1,1,1,1,1),fn=fn,hin=hin, heq=heq)
Error in h[1] <- x[1] + x[2] + x[3] + x[4] + x[5] - 2600 : 
  object 'h' not found

Case3:

 ans <- auglag(par= c(1000,500,300,200,300),fn=fn,hin=hin, heq=heq)
Error in h[1] <- x[1] + x[2] + x[3] + x[4] + x[5] - 2600 : 
  object 'h' not found

Case4:

ans <- auglag(par=NULL,fn=fn, gr=NULL,hin=hin,heq=heq) 
Error in h[1] <- x[1] - 900 : replacement has length zero

What is the correct way to apply auglag or constrOptim.nl? I tried solving it through solve.QP but couldn't undestand what parameters to pass.

After the edits made by @Hong Ooi, here are the new errors:

> ans <- auglag(par= NULL,fn=fn, gr=NULL,hin=hin, heq=heq) 
Error in h[1] <- x[1] - 900 : replacement has length zero
> ans <- auglag(par= c(1,1,1,1,1),fn=fn,hin=hin, heq=heq)
Error in fn(par, ...) : unused argument(s) (par)
> ans <- auglag(par= c(1000,500,300,200,300),fn=fn,hin=hin, heq=heq)
Error in fn(par, ...) : unused argument(s) (par)
> ans <- auglag(par=NULL,fn=fn, gr=NULL,hin=hin,heq=heq) 
Error in h[1] <- x[1] - 900 : replacement has length zero
Was it helpful?

Solution

I have got this to work. Thanks to Hao Ooi for guiding me on the same.

My problem was that:

I was using:

fn <- function() {
   -(0.653*x[1]+ 0.234* x[1]*x[1]+ 0.437 * x[2] + 0.769 * x[3] +
    0.453 * x[4] + 0.744 * x[5] + 0.476 * x[5]* x[5])
 }

Instead, I should have used:

fn <- function(x) {
       -(0.653*x[1]+ 0.234* x[1]*x[1]+ 0.437 * x[2] + 0.769 * x[3] +
        0.453 * x[4] + 0.744 * x[5] + 0.476 * x[5]* x[5])
     }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top