我希望建立一个库存政策的模型,并在如何建模一个结束的库存,不能是负面的困惑。我希望使用像numpy.maximum()这样的函数将任何负数设置为0,但这似乎不适用于ortools。
下面是一个简化的例子。谢谢你的建议!
from ortools.linear_solver import pywraplp
import numpy as np
import pandas as pd
day = [1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2]
item_id = [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3]
increase = [4, 0, 4, 0, 3, 3, 0, 3, 3, 3, 3]
decrease = [2, 2, 2, 5, 0, 0, 5, 1, 1, 1, 1]
my_df = pd.DataFrame(list(zip(day, item_id, increase, decrease)),
columns=['day', 'item_id', 'increase', 'decrease'])
my_df['change'] = my_df.increase - my_df.decrease
my_df = my_df.set_index(['item_id', 'day'])
index_item_day = list(zip(my_df.reset_index().item_id, my_df.reset_index().day))
change = {(i, d): my_df.loc[i, d]['change'] for i, d in index_item_day}
solver = pywraplp.Solver.CreateSolver('SCIP') # or ('GLOP')
percent_var = solver.NumVar(0, 1, 'percent_var')
end_inv = {}
for i, d in index_item_day:
end_inv[i, d] = solver.NumVar(-solver.infinity(), solver.infinity(), 'end_inv')
for i, d in index_item_day:
# if d==1:
solver.Add(end_inv[i, d] == change[i, d] * percent_var)
# solver.Add(end_inv[i, d] == np.maximum(end_inv[i, d-1] + change[i, d] * percent_var, 0))
# else:
# solver.Add(end_inv[i, d] == np.maximum(0, change[i, d] * percent_var))
# The objective function is to maximize the % given the ending inventory constraint
solver.Maximize(percent_var)
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL or status == pywraplp.Solver.FEASIBLE:
print('Maximum % = ', solver.Objective().Value())
else:
print('There was not an optimal solution')
item = []
day = []
actual_change = []
e_inv = []
# pos = []
for i, d in index_item_day:
item.append(i)
day.append(d)
actual_change.append(change[i, d] * percent_var.solution_value())
e_inv.append(end_inv[i, d].solution_value())
supply_results_df = pd.DataFrame(list(zip(item, day, actual_change, e_inv)),
columns=['item', 'day', 'actual_change', 'ending_inventory'])
supply_results_df
这里的结果是负ending_inventory:
但是,如果我试图添加numpy.maximum(0,原始方程),通过注释出原始行并引入这一行,这不会将负ending_inventory值更改为0:
solver.Add(end_inv[i, d] == change[i, d] * percent_var)
# solver.Add(end_inv[i, d] == np.maximum(change[i, d] * percent_var, 0))
如果我移动np.maximum()中的第一个位置而不是第二个位置,那么所有的ending_inventory值都是0。
solver.Add(end_inv[i, d] == np.maximum(0, change[i, d] * percent_var))
发布于 2022-05-27 18:03:06
添加一个松弛变量似乎有效!如果我有任何问题将其扩展到更大的模型,我将在这里发布一个更新。
for i, d in index_item_day:
if d==1:
solver.Add(end_inv[i, d] == change[i, d] * percent_var + slack[i, d])
else:
solver.Add(end_inv[i, d] == end_inv[i, d-1] + change[i, d] * percent_var + slack[i, d])
发布于 2022-05-27 17:35:23
不,OR-Tools线性表达式之间的比较运算符(变量、常数、和.)创建python对象,而不是布尔值。
在它们上调用__bool__
将在CP对象上调用时引发错误,或者将在pywraplp对象上默默地返回True
。
如果您使用CP,则必须使用AddMaximumEquality()
。在吡咯烷酮中没有max方法。
https://stackoverflow.com/questions/72408868
复制相似问题