Python 中 Excel 求解器和 PuLP 求解器之间的差异,

问题描述 投票:0回答:1

excel中的Solver比PuLP Solver更高效,或者我犯了一些错误。请问你能帮我吗?

Python PuLP(不正确的结果):

from pulp import *
p = (120, 72, 80)
o = (0.85, 0.85, 0.80)

lp= LpProblem("Linka1_2_3", LpMaximize)
print("OBJECTIVE1: ",lp.objective)

x1 = LpVariable(name="Time:Line1Ref1",lowBound=0)
x2 = LpVariable(name='Time:Line2Ref1',lowBound=0)

print("Constrains: ",lp.constraints)

# Objective function
lp += lpSum(102*x1 + 61.2*x2)

# Constrains
lp += 102*x1 <= 500
lp += 61.2 *x2  <=500
lp += 102*x1 + 61.2*x2  <=500
lp += x1 <= 3.5
lp += x2 <= 3.5

status = lp.solve()
print("Status:", status, "   ---1:optimal, 2:not solved, 3:infeasible, 4:unbounded, 5:undef")

#Print solution
i=0
for var in lp.variables():
    print(f" ",var, "=", value(var), "Tzn. ",((p[i]*o[i]))," PxO a cas straveny", value(var)*(p[i]*o[i])," pcs")
    i += 1
print("OPT =", value(lp.objective))
Result:
Time:Line1Ref1 = 2.8019608 Tzn.  102.0  PxO a cas straveny 285.8000016  pcs
Time:Line2Ref1 = 3.5 Tzn.  61.199999999999996  PxO a cas straveny 214.2  pcs

Time X1 + X2 = 6.3019....

正确的结果应该是:

5.836601
,就像在 Excel 中一样(6.3 太高,不是正确的解决方案)

我的代码哪里有问题?

这是带有公式的 XLSX 表:

python solver pulp
1个回答
0
投票

您的问题是不确定的,因此有多种解决方案可以在其边界处产生最佳值 500。 PuLP 完全有能力提供这样的解决方案。

import pandas as pd
import pulp

idx = ['Lin1Ref1', 'Lin2Ref1']
ConstrainsX12 = (3.5, 3.5)
ConstrainsX = (*ConstrainsX12, max(ConstrainsX12))
X12 = [
    pulp.LpVariable(
        name=f'X_{i}', cat=pulp.LpContinuous,
        lowBound=0, upBound=bound)
    for i, bound in zip(idx, ConstrainsX12)
]
X = (*X12, pulp.lpSum(X12))
P = (120, 72)
O = (0.85, 0.85)
PxO = [pi*ji for pi, ji in zip(P, O)]
XxPxO12 = [xi*poi for xi, poi in zip(X, PxO)]
XxPxO = [*XxPxO12, pulp.lpSum(XxPxO12)]
Constrains_formula = (500,)*3

lp = pulp.LpProblem(name='Line1_2_3', sense=pulp.LpMaximize)
lp.setObjective(XxPxO[-1])

for fi, constraint in zip(XxPxO, Constrains_formula):
    lp.addConstraint(fi <= constraint)

print(lp)
status = lp.solve()
assert status == pulp.LpStatusOptimal

df = pd.DataFrame(
    index=['Lin1Ref1', 'Lin2Ref1', 'B4 + B5:'],
    data={
        'X': [pulp.value(x) for x in X],
        'P': (*P, ''),
        'O': (*O, 'SUMRef1:'),
        'PxO': (*PxO, ''),
        'Solv: XxPxO': [pulp.value(p) for p in XxPxO],
        'Constrains formula': Constrains_formula,
        'Constrains[X]': ConstrainsX,
    },
)
pd.options.display.width = 200
pd.options.display.max_columns = 9
print(df)
                 X    P         O    PxO  Solv: XxPxO  Constrains formula  Constrains[X]
Lin1Ref1  2.801961  120      0.85  102.0   285.800002                 500            3.5
Lin2Ref1  3.500000   72      0.85   61.2   214.200000                 500            3.5
B4 + B5:  6.301961       SUMRef1:          500.000002                 500            3.5
© www.soinside.com 2019 - 2024. All rights reserved.