# [SciPy-User] [SciPy-user] Constrained optimizing - how to setup?

Skipper Seabold jsseabold@gmail....
Thu Nov 18 09:01:14 CST 2010

```On Wed, Nov 17, 2010 at 9:34 PM, bevan j <bevan07@gmail.com> wrote:
>
> Hello,
>
> I have an optimization issue that I cannot get my head around.  I think it
> is likely that i need to reformat/change my functions (in addition to using
> a constrained solver)
>
> The example below is what I currently have, however, I would to constrain
> 'term1','term2', and 'term3' to >= 0.01
>
> def myerr(params,r1,r2,r3,x1,x2,x3,x4):
>    term1 = myfunc(r1, params[0], params[1], x1, x2)
>    term2 = myfunc(r2, params[0], params[1], x1, x3)
>    term3 = myfunc(r3, params[0], params[1], x1, x4)
>    er1 = (term1 - term2)**2
>    er2 = (term2 - term3)**2
>    return er1+er2
>
> v = optimize.fmin(myerr, v0,
> args=(self.r1,self.r2,self.r3,self.x1,self.x2,self.x3,self.x4),maxiter=10000,
> maxfun=10000)
>
> I hope this clear enough, any tips, v. much appreciated.
>

If you could give a working example it would help.  It is not clear
(to me) how you could get this working without knowing more, but I
suspect you could change your objective and use one of the constrained
solvers.

Another approach is to use a penalty function with an unconstrained
optimizer, but I don't know how well it will work in this context.
I've used it mostly for univariate optimization.  Eg., if the
constraint is violated then you return the actual objective function
less (in absolute value) a large nonlinear penalty based on what your
bounds are to move the optimizer away from the bad region.

Also IIUC, you might want to do

r1, r2, f3, x1, x2, x3, x4 =
self.r1,self.r2,self.r3,self.x1,self.x2,self.x3,self.x4

and pass these to the optimizer to avoid what I think will be unneeded
calls to __getattr__ or __getattribute__.  Just a good habit.

Skipper
```