0

I have OR-Tools running in a Python on Linux Azure Function.

I'd like to make this an API end point where I can post a JSON representation of an Integer Programming problem and receive a solution back.

# Grab the POST data as an object
req_json = req.get_json()

# Create the MIP solver BOP/SAT/CBC
solver = pywraplp.Solver.CreateSolver('BOP')

# Create the variables
x = {}
for i in range(len(req_json['Variables'])):
    x[i] = solver.IntVar(0, req_json['Variables'][i]['UpperBound'], req_json['Variables'][i]['Name'])
print('Number of variables =', solver.NumVariables())

# Create the constraints
for j in range(len(req_json['Constraints'])):
    solver.Add(req_json['Constraints'][j]['Formula'])
print('Number of constraints =', solver.NumConstraints())

However it seems like solver.Add() does not support a string representation of the formula, it's expecting an object like solver.Add(x + y < 5), so is there another way to do this?

My variables and constraint formulas are dynamic and will be provided by another system. I've had a look at using Arrays to define the model instead, but my formulas are quite complex and I'm not sure I'd be able to reduce them to an array of constraint coefficients.

Josh
  • 3,442
  • 2
  • 23
  • 24
  • A solution was answered on another thread [here](https://stackoverflow.com/questions/65754900/convert-string-representation-of-a-comparison-formula-back-to-formula/65768409#65768409) specifically for Python. – Josh Jan 19 '21 at 02:25

1 Answers1

3

You have to parse the constraint yourself, a dirty way would be something like:

formula = "x + y + z == 0"
formula = re.sub(
    r"[^\s]+",
    lambda m: f'x["{m.group(0)}"]' if m.group(0).isalpha() else m.group(0),
    formula,
)
solver.Add(eval(formula))

But eval isn't recommended.

Look up each term in the variables dict and do the same for the operators (Turn string into operator) or maybe try something like LoadModelFromProto+ExportModelToProto or ExportModelAsMpsFormat.

Stradivari
  • 2,626
  • 1
  • 9
  • 21
  • Thanks, I looked at `eval()` but that actually tries to execute/calculate the formula. `solver.Add()` is expecting a formula object. I'll edit the question to include an accurate example. – Josh Jan 17 '21 at 19:48
  • I'll have a look at the Export/Import options though thanks. – Josh Jan 17 '21 at 19:51
  • This was the right track. I just wasn't familiar enough with Python to execute. – Josh Jan 19 '21 at 02:24