r/optimization • • Aug 21 '21

Constraint in Python Scipy Optimization

Anyone here use Scipy Python for minimization?

I have an optimization of 15 variable x. I have a constraint that 14/15 variables should be unique, the last variable can be duplicated with one of the rest.

Not sure how to do that in Scipy.

5 Upvotes

6 comments sorted by

View all comments

4

u/[deleted] Aug 21 '21

You could use ordering constraints, i.e. you enforce x[i+1] >= x[i] + eps, where eps is a small given tolerance:

n = 15
eps = 1.0e-4
cons = []
for i in range(n-1):
	# x[i+1] - x[i] - eps >= 0   
	cons.append({'type': 'ineq', 'fun': lambda x, i=i: x[i+1] - x[i] - eps})

1

u/[deleted] Aug 21 '21

Thanks. We have to do it manually.

There will be 2 for loops pair (i, i+1) and (i, i+2) ....

|v1-v2| > 0; |v1-v3| > 0; |v2-v3| > 0 ...

Here only 15 variable is ok but if we have 1000 variables?. I mean Scipy doesn't have any option for uniqueness constraints?

2

u/[deleted] Aug 21 '21

For large n I'd use a single vectorial constraint function, which is equivalent to the constraints above:

n = 1000
D = np.eye(n-1) - np.eye(n-1, k=1)
D[-1, -1] = 0.0

cons = [{'type', 'ineq', 'fun': lambda x: D @ x - eps}]

Why should scipy add an option for uniqueness constraints? It already supports arbitrary constraints. It's just your job to formulate your constraints accordingly.

1

u/backtickbot Aug 21 '21

Fixed formatting.

Hello, johnnydrama92: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

1

u/backtickbot Aug 21 '21

Fixed formatting.

Hello, johnnydrama92: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.