簡體   English   中英

如何在紙漿優化中限制變量?

[英]How to cap a variable in Pulp optimization?

我正在嘗試使用預測的成本和銷售額來優化產品的整體銷售額(為期 3 個月)。 我當前的數據如下所示

>     Month |    sales quantity  | discount % | Total inventory
      1     |         12         |    5       |      45
      1     |         23         |    9       |      45
      1     |         40         |    15      |      45
      2     |         23         |    5       |      45

根據預測的銷售額,每個月都有一些折扣。 Total inventory是所有月份的庫存總和。 我正在嘗試使用紙漿最大化整體銷售額,但優化結果總是選擇每個月的最高sales quantity ,大部分時間超過Total inventory

當總銷售額超過Total inventory時,我需要限制sales quantity值(為零)。

保持像lpSum(x[i]*sales_quantity[i] for i in unique_months) < total_inventory的約束會導致不可行的解決方案。 我的一小段代碼:

import pulp as lp 

# `data` is a DataFrame contains above data
x = LpVariable.dicts("x", range(0, len(data)), 0, 1, LpBinary) 

prob = lp.LpProblem("test problem", lp.LpMaximize)

# obj function
prob += lpSum(x[i] * data.loc[i, 'sales quantity'] for i in range(0, len(data)))

# constraints
prob += lpSum(x[i] * data.loc[i, 'sales quantity'] for i in range(0, len(data))) >= threshold_inventory_to_clear

# constraints to select each month(without missing any)
for j in list(data['Month'].unique()):
    if j == data['Month'].max():
       break
    sub_idx_current = data[data['Month'] == j].index
    sub_idx_next = data[data['Month'] == j + 1].index
    prob += lpSum(x[idx_current] * data.loc[idx_current, 'Month'] for idx_current in sub_idx_current) \
                        <= lpSum(x[idx_next] * data.loc[idx_next, 'Month'] for idx_next in sub_idx_next)

# Need to replace this constraints with some calling logic
prob += lpSum(x[i]*data.loc[i, 'sales quantity'] for i in range(0, len(data)) < total_inventory

如果我正確理解您的問題,您可以選擇每月出售或不出售? 並且您希望最大化您的收入,這樣您的銷售量不會超過您的庫存。 我不確定您是否正在處理多種產品。

如果我正確理解了您的問題,那么以下內容應該可以在 4 個不同的時間段內為單個產品解決問題。

import pulp
import pandas as pd

max_quantity = 45
df = pd.DataFrame({
    "sales_quantity": [12,23,40,23],
    "discount": [5,9,15,5]
})

prob = pulp.LpProblem("MaxSales", pulp.LpMaximize)

X = [pulp.LpVariable('var_'+str(i), 0, 1, pulp.LpBinary) for i, sq in enumerate(df['sales_quantity'])]
prob += pulp.LpAffineExpression({X[i]: (100-df['discount'][i])*df['sales_quantity'][i] 
                                 for i in range(0,len(df))}, name='Objective')
prob += pulp.LpAffineExpression({X[i]: df['sales_quantity'][i] for i in range(0,len(df))})<=max_quantity, "Max Inventory"
prob.solve()
print(prob)
print("Revenue: " + str(pulp.value(prob.objective)))
print([pulp.value(x) for x in X])

Output:

MaxSales:
MAXIMIZE
1140*var_0 + 2093*var_1 + 3400*var_2 + 2185*var_3 + 0
SUBJECT TO
Max_Inventory: 12 var_0 + 23 var_1 + 40 var_2 + 23 var_3 <= 45

VARIABLES
0 <= var_0 <= 1 Integer
0 <= var_1 <= 1 Integer
0 <= var_2 <= 1 Integer
0 <= var_3 <= 1 Integer

Revenue: 3400.0
[0.0, 0.0, 1.0, 0.0]

如果我誤解了什么,請告訴我。 我無權發表評論,因此無法事先要求澄清。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM