社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

0-1规划问题的python求解

格栅的所见所思 • 1 年前 • 453 次点击  
在网上找到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()

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/177058