tgordon18
tgordon18

Reputation: 1859

PULP: Check variable setting against constraints

I'm looking to set up a constraint-check in Python using PULP. Suppose I had variables A1,..,Xn and a constraint (AffineExpression) A1X1 + ... + AnXn <= B, where A1,..,An and B are all constants.

Given an assignment for X (e.g. X1=1, X2=4,...Xn=2), how can I check if the constraints are satisfied? I know how to do this with matrices using Numpy, but wondering if it's possible to do using PULP to let the library handle the work.

My hope here is that I can check specific variable assignments. I do not want to run an optimization algorithm on the problem (e.g. prob.solve()).

Can PULP do this? Is there a different Python library that would be better? I've thought about Google's OR-Tools but have found the documentation is a little bit harder to parse through than PULP's.

Upvotes: 1

Views: 1620

Answers (2)

tgordon18
tgordon18

Reputation: 1859

It looks like this is possible doing the following:

  1. Define PULP variables and constraints and add them to an LpProblem
  2. Make a dictionary of your assignments in the form {'variable name': value}
  3. Use LpProblem.assignVarsVals(your_assignment_dict) to assign those values
  4. Run LpProblem.valid() to check that your assignment meets all constraints and variable restrictions

Note that this will almost certainly be slower than using numpy and Ax <= b. Formulating the problem might be easier, but performance will suffer due to how PULP runs these checks.

Upvotes: 2

PatientOtter
PatientOtter

Reputation: 2298

You can stay in numpy and accomplish this. Looking at a single line from a matrix you can set your row of A equal to a vector and then create a row sum that allows you to check the index and find if it is true. For example:

a = A[0, :]
row_sum = a*x
sum(row_sum) <= B[0]

The last line will return just True or False. Then if you want to change a single index you could update your row_sum array by using

row_sum[3] = a[3]*new_val

and run your analysis again.

Upvotes: 0

Related Questions