在网上找到python求解0-1规划的python代码,将其中的数学公式表达采取了更方便用代码来表示的方式。特别是,当变量很多的时候,不可能逐一手工在代码中输入约束条件。1# -*- coding: utf-8 -*-
2""" Solving 0-1 binary programming with PuLP using DataFrame
3Created on Mon Dec 16 21:47:01 2024
4"""
5
6import pulp # 导入 pulp 库
7import pandas as pd
8
9
10def main():
11 # 投资决策问题:
12 # 公司现有 5个拟投资项目,根据投资额、投资收益和限制条件,问如何决策使收益最大。
13 """
14 问题建模:
15 决策变量:
16 x1~x5:0/1 变量,1 表示选择第 i 个项目, 0 表示不选择第 i 个项目
17 目标函数:
18 max fx = 150*x1 + 210*x2 + 60*x3 + 80*x4 + 180*x5
19 约束条件:
20 210*x1 + 300*x2 + 100*x3 + 130*x4 + 260*x5 <= 600
21 x1 + x2 + x3 = 1
22 x3 + x4 <= 1
23 x5 <= x1
24 x1,...,x5 = 0, 1
25 """
26
27 # 定义数据
28 data = {
29 'Project': ['A', 'B', 'C', 'D', 'E'],
30 'Profit': [150, 210, 60, 80, 180], # 目标函数系数
31 'Cost': [210, 300, 100, 130, 260], # 约束条件系数
32 'C1': [1, 1, 1, 0, 0],
33 'C2': [0, 0,
1, 1, 0],
34 'C3': [-1, 0, 0, 0, 1],
35 }
36 df = pd.DataFrame(data)
37
38 constraints = {
39 'Cost': '<=600',
40 'C1': '==1',
41 'C2': '<=1',
42 'C3': '<=0',
43 }
44
45 # 定义问题,求最大值
46 InvestLP = pulp.LpProblem("Invest decision problem", sense=pulp.LpMaximize)
47
48 # 创建决策变量(0/1)
49 decision_vars = {row.Project: pulp.LpVariable(
50 row.Project, cat='Binary') for row in
df.itertuples()}
51
52 # 设置目标函数
53 InvestLP += pulp.lpSum(row.Profit * decision_vars[row.Project]
54 for row in df.itertuples()), "Total Profit"
55
56 # 设置约束条件,定义总预算和其他约束条件,
57 for index, (key, value) in enumerate(constraints.items(), 1):
58 # 判断 value 的类型并构建正确的约束
59 if '<=' in value:
60 constraint_expr = pulp.lpSum(getattr(
61 row, key) * decision_vars[row.Project] for row in df.itertuples()) <= float(value.split('<=')[1])
62 elif '==' in value:
63 constraint_expr = pulp.lpSum(getattr(
64 row, key) * decision_vars[row.Project] for row in df.itertuples()) == float(value.split('==')[1])
65 elif
'>=' in value:
66 constraint_expr = pulp.lpSum(getattr(
67 row, key) * decision_vars[row.Project] for row in df.itertuples()) >= float(value.split('>=')[1])
68 else:
69 continue # 如果没有识别到合适的符号,则跳过
70
71 # 添加约束到 InvestLP
72 InvestLP += constraint_expr, f"Constraint {index} ({key} {value})"
73
74 # 求解问题
75 InvestLP.solve()
76
77 # 输出结果
78 print("Status:", pulp.LpStatus[InvestLP.status]) # 输出求解状态
79 for v in InvestLP.variables():
80 print(f"{v.name} = {v.varValue}") # 输出每个变量的最优值
81 print(
"\nMax f(x) =", pulp.value(InvestLP.objective)) # 输出最优解的目标函数值
82
83
84if __name__ == '__main__':
85 main()