全,
我正在编写一些代码,其中要求买卖至少100,000个数据包。如果不可能,则应将其置零。
为此,我尝试了许多方法,包括:
def objective_rule(model):
return sum(model.Prices[ProductCount]*model.Amount[ProductCount]*(model.Amount[ProductCount]>100000) for ProductCount in model.Products)但这比预期的要慢。我想把一个明确的约束放在适当的地方。类似于:
def minTradesize_Constraint(model):
return ((model.Amount[ProductCount]>=100000)| \
(model.Amount[ProductCount]==0.00) for ProductCount in model.Products)我已经研究了指标函数,但Pyomo连续近似没有帮助。如有任何帮助或指导,我将不胜感激。
发布于 2020-04-06 17:57:06
基本上,您要实现的是使model.Amount[ProductCount]项采用不连续的值(0或大于或等于100,000)。要实现这一点,首先,基本上需要定义一个二进制变量:model.y = pyomo.Var(model.Products, within=pyomo.Binary)。
然后,您需要添加以下约束:
def minTradesize_Constraint1(model):
return (model.Amount[ProductCount] >= 100000 * y[ProductCount] for ProductCount in model.Products)
def minTradesize_Constraint2(model):
return (model.Amount[ProductCount] <= M * y[ProductCount] for ProductCount in model.Products)其中M是一个足够大的数字(可以是model.Amount[ProductCount]变量的实际上限)。
作为此公式的结果,如果y[ProductCount]为零,则model.Amount[ProductCount]项也将为零。如果模型现在想让model.Amount[ProductCount]变量取正值,它必须将二进制y[ProductCount]设置为1,从而强制model.Amount[ProductCount]变得更大或等于100,000。
注意:我已经用与您在答案中相同的方式阐述了约束。但是,如果我正确理解了您的模型,我会说第一个约束,例如,应该是:
def minTradesize_Constraint1(model, ProductCount):
return (model.Amount[ProductCount] >= 100000 * y[ProductCount]当您创建Pyomo约束时,应该添加for ProductCount in model.Products部件。
发布于 2021-06-22 21:43:15
来进一步简化解决方案。我添加了一个名为route_selected的变量
model.route_selected = pe.Var(<a set, for me its routes == r>, domain=pe.Binary, initialize=0, within=pe.Binary)
model.route_selected = pe.Var(model.R, domain=pe.Binary, initialize=0, within=pe.Binary)这就是我的依赖变量
# Variable to solve, this is the variable that will be changed by solver to find a solution
# for each route, port, cust, year combination what should be supplied amount
model.x_rpcy = pe.Var(self.model.R, self.model.P, self.model.C, self.model.Y, domain=pe.NonNegativeIntegers, initialize=0)然后添加了这个约束
for y in self.model.Y:
for r in self.model.R:
lhs = sum(self.model.x_rpcy[r, p, c, y] for p in self.model.P for c in self.model.C)
vessel_size = 1000
self.model.const_route.add(lhs == vessel_size * self.model.route_selected[r])
model.const_route.add(lhs == vessel_size * model.route_selected[r]) https://stackoverflow.com/questions/61041490
复制相似问题