Create different models from "pool" of variables and constraints
回答済みI am coming to Gurobi (more exactly, to the Gurobi/Python API) from a different family of Algebraic Modeling Languages and want to understand how to generate multiple models from a common pool of variables and constraints. Let's say I want to declare, but not yet add to any model, a set of n variables and m constraints and later I want to create different models with subsets of those variables and constraints, based on some conditions. For example (in pseudo-code):
Declare var1(type, ub, lb, obj), var2(type, ub, lb, obj), ..., var10(type, ub, lb, obj)
Declare constr1 = f(var1,...,var5), constr2 = g(var4,...,var8), constr3 = h(var6,...,var10)
model1.Vars = [var1,...,var8]
model1.Constrs = [constr1, constr2]
model2.Vars = [var4,...,var10]
model2.Constrs = [constr2, constr3]
So far, I am able to do something similar to this only for the constraints: I create a Python generator expression (expr) and then add the constraint as needed with model.addConstrs(expr,name="someName"). But I have not been able to figure out a good way to do something similar for the variables yet.
Is there a (better) way to do this? Any advice would be appreciated.
-
正式なコメント
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 try Gurobot, our chatbot interface offering instant, expert-level support. -
Hi Andres,
AFAIK both constraints and variables are specific to each model object in Gurobi.
To get around this, you could for example declare your variables and constraints using only their indices and properties, and then add them to your models as you need.
For example, you could define your "variables" using the following dict:
vars_dict = {1: ["I", 0, 5, 2],
2: ["C", -5, 5, 0]}"constraints" as:
constr_dict = {"A": [1, 2]}and then automate by calling
m = gp.Model()
model_specific_vars = dict()
for index, var_properties in vars_dict.items():
# some if-statement could come here
model_specific_vars[index] = m.addVar(vtype=var_properties[0], lb=var_properties[1], ub=var_properties[2], obj=var_properties[3])
for name, constr in constr_dict.items():
# here also some if-conditions could be used
# here I assume that the constraint is a multiple choice constraint
expr = gp.quicksum(model_specific_vars[i] for i in constr)
m.addLConstr(expr <= 1, name=name)You will find the information about the methods used above here and here.
Hope this gives you some inspiration. Perhaps someone from Gurobi team can offer a better approach?
Best regards
Jonasz1 -
Thanks Jonasz Staszek for the suggestion; it definitely gives me good ideas to try a few things and I think puts me in the right track. I'll try to update the post once I find a solution based on your advice.
0
投稿コメントは受け付けていません。
コメント
3件のコメント