I am building a model using mathopt library of or tools, and I want to save the model object as a pickle file (or any other suitable alternative). The use case for doing this is - underlying data behind the model build is huge, and it takes some time to build the model, however, when user interacts with the model, he/she will change only a couple of constraints at the maximum. So, I wanted to a) save the model object, and then b) load it back in memory, c) identify the constraint the user wants to change, and then update only that constraint, d) run the revised model and solve. Do the same process for multiple calls by user
However, pickling somehow is not working with mathopt:
from ortools.math_opt.python import mathopt
model = mathopt.Model(name="getting_started_lp")
x = model.add_variable(lb=0.0, ub=1.5, name="x")
y = model.add_variable(lb=0.0, ub=1.0, name="y")
model.add_linear_constraint(x + y <= 2)
model.maximize(x + 2 * y)
# try to pickle the model object
pickle.dumps(model)
# get the below error
AttributeError: Can't pickle local object 'WeakSet.__init__.<locals>._remove'
Pickle seems to work with cp-sat solver though:
model = cp_model.CpModel()
x = model.new_int_var(0, 10, "x")
y = model.new_int_var(0, 10, "y")
model.add(2 * x + 7 * y <= 20)
model.maximize(2 * x + 2 * y)
b = pickle.dumps(model)
# runs without any errors
Is there any way out - any alternative to saving the model for later use with mathopt ?
------ BELOW IS MY ATTEMPT TO SAVE THE MATHOPT MODEL -------- But does not work
from google.protobuf import text_format
from ortools.math_opt.python import mathopt
model = mathopt.Model(name="getting_started_lp")
x = model.add_variable(lb=0.0, ub=1.5, name="x")
y = model.add_variable(lb=0.0, ub=1.0, name="y")
model.add_linear_constraint(x + y <= 2)
model.maximize(x + 2 * y)
def export_model(model, filename):
with open(filename, "w") as file:
file.write(text_format.MessageToString(model.export_model()))
def import_model(filename):
model = mathopt.Model()
with open(filename, "r") as file:
text_format.Parse(file.read(), model.export_model())
return model
# runs fine -- exports model
export_model(model, "mdl")
# fails
import_model("mdl")
# ParseError: 1:11 : Message type # "operations_research.math_opt.ModelProto" should not have # multiple "objective" fields.
mathoptmodel, but clearly I am missing something. Hoping for your able guidance.mathoptmodel to a file, which I can later import back. Could you please help me with themathoptmodel pls. I tried to do in my code, but does not work. Thanks.