Question

import numpy 
from numpy import asarray

Initial = numpy.asarray [2.0, 4.0, 5.0, 3.0, 5.0, 6.0]       # Initial values to start with


bounds = [(1, 5000), (1, 6000), (2, 100000), (1, 50000), (1.0, 5000), (2, 1000000)] 

# actual passed bounds

b1 = lambda x: numpy.asarray([1.4*x[0] - x[0]])  
b2 = lambda x: numpy.asarray([1.4*x[1] - x[1]])  
b3 = lambda x: numpy.asarray([x[2] - x[3]])     
constraints = numpy.asarray([b1, b2, b3])

opt= optimize.fmin_slsqp(func,Initial,ieqcons=constraints,bounds=bounds, full_output=True,iter=200,iprint=2, acc=0.01)

Problem: I want to pass in inequality constraints. Consider that I have 6 parameters

[ a, b, c, d, e, f]

in the Initial values, and my constraints are:

a<=e<=1.4*a   ('e' varies from a to 1.4*a)
b<=f<=1.4*b   ('f' varies from b to 1.4*b)
c>d           ('c' must always be greater than d)

But this is not working properly. I don't know what the mistake is. Is there any better way to pass my constraints as a function? Please help me.

Was it helpful?

Solution

Based on the comment from Robert Kern, I have removed my previous answer. Here are the constraints as continuous functions:

b1 = lambda x: x[4]-x[0] if x[4]<1.2*x[0] else 1.4*x[0]-x[4]
b2 = lambda x: x[5]-x[1] if x[5]<1.2*x[1] else 1.4*x[1]-x[5]
b3 = lambda x: x[2]-x[3]

Note: Python 2.5 or greater is required for this syntax.1

To get the constraint a<=e<=1.4*a, note that 1.2*a is the halfway point between a and 1.4*a.

Below this point, that is, all e<1.2*a, we use the continuous function e-a. Thus the overall constraint function is negative when e<a, handling the lower out-of-bounds condition, zero on the lower boundary e==a, and then positive for e>a up to the halfway point.

Above the halfway point, that is, all e>1.2*a, we use instead the continuous function 1.4*a-e. This means the overall constraint function is is negative when e>1.4*a, handling the upper out-of-bounds condition, zero on the upper boundary e==1.4*a, and then positive when e<1.4*a, down to the halfway point.

At the halfway point, where e==1.2*a, both functions have the same value. This means that the overall function is continuous.

Reference: documentation for ieqcons.

1 - Here is pre-Python 2.5 syntax: b1 = lambda x: (1.4*x[0]-x[4], x[4]-x[0])[x[4]<1.2*x[0]]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top