Creating a Model that Contains Variables and Constraints from another Model
AnsweredHi
I am using gurobipy and I want to create a model that contains the constraints and variables from two other models:
model3_constraints = constraints_from_model_1 + constraints_from_model_2
model3_variables = variables_from_model_1 + variables_from_model_2
Is there a way to do this?
Thanks,
Kenan
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi Kenan,
If you built the first two models using the Python API, the easiest way would be to copy the code to add variables and constraints (or better: wrap it into functions that you can then call multiple times on different models). If you're using custom names, you should make sure not to use the same name multiple times.
If you only have the "finished" models but no code, I assume you'd have to iterate over the variables and constraints and replicate them for model3. E.g. to replicate the variables from model1 in model3:
for v in model1.getVars():
model3.addVar(lb=v.lb, ub=v.ub, obj=v.obj, vtype=v.vtype, name="model1_"+v.varname)For constraints, this will be more complicated. To "copy" a constraint, you'd need to iterate over all its terms, find the right variables in the new model and combine them with the coefficients. It makes sense to save the variables to a dictionary "varDict" based on their names when you create them. Then you could recreate the constraints as follows:
for c in model1.getConstrs():
expr = model1.getRow(c)
newexpr = LinExpr()
for i in range(expr.size()):
v = expr.getVar(i)
coeff = expr.getCoeff(i)
newv = varDict["model1_"+v.Varname]
newexpr.add(newv, coeff)
model3.addConstr(newexpr, c.Sense, c.RHS, name="model1_"+c.ConstrName)If the variables in both models have distinct names, you could also consider writing the models to files and then merging the files.
0 -
Perfect! Thank you so much.
Kind Regards,
Kenan
0
Post is closed for comments.
Comments
3 comments