0

this is a simple example of LP using cvxpy

import cvxpy as cp
x1 = cp.Variable()
x2 = cp.Variable()
objective = cp.Minimize(0.3*x1 + 0.4*x2)
constraints = [
    4.6*x1 + 58.8*x2 >= 300,
    52*x1 + 33*x2 >= 2000,
    152*x1 + 133*x2 >= 5000,
]
linear_program = cp.Problem(objective, constraints)
result = linear_program.solve()

my question is if I have the same constraints in the form of a dataFrame

A = pd.DataFrame([[4.6,58.8],[52,33],[152,133]])
c= [0.3,0.4]
b = [300,2000,5000]

then how do I transform A,b and c to put it through the cvxpy optimiser? i.e. converting the dataFrame A, b to the format

4.6*x1 + 58.8*x2 >= 300,
52*x1 + 33*x2 >= 2000,
152*x1 + 133*x2 >= 5000,

and c to

0.3*x1 + 0.4*x2

Its easy to manually type if the number of constraints and variable are limited (3 and 2 in this case), but my acutal problem has over 50+ variables and over 80+ constraints in the form of dataFrames (and the numbers can keep changing so I cant hardcode the constraints).

#########Edits- updated the shape of the dataFrame A, which was previously incorrect

1 Answer 1

1

Firstly, change your lists to numpy arrays. Then create an array of x variables, instead of one at a time then use it with matrix multiplication to add constraint. Eg

A @ x >= b 

See example here https://www.cvxpy.org/examples/basic/linear_program.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.