Qaekwy,一个崭新的Python运筹优化库

今天给大家介绍一下Qaekwy,一个Python运筹优化库,该优化库是2023年才建立的,但文档方面介绍的比较齐全,建模和求解过程简单适用,本文介绍这个优化库的基本使用。

安装

pip install Qaekwy

案例

先看看官方基础案例。(从这个案例入门很简单,看完就能实现基础建模操作。)

  
from qaekwy.engine import DirectEngine  
from qaekwy.model.constraint.relational import RelationalExpression  
from qaekwy.model.specific import SpecificMaximum  
from qaekwy.model.variable.integer import IntegerVariable  
from qaekwy.model.modeller import Modeller  
from qaekwy.model.searcher import SearcherType  
  
# Define the optimization problem using Qaekwy Python Client  
class SimpleOptimizationProblem(Modeller):  
    def __init__(self):  
        super().__init__()  
  
        # Create a integer variables  
        x = IntegerVariable(var_name="x", domain_low=0, domain_high=100)  
        y = IntegerVariable(var_name="y", domain_low=0, domain_high=10)  
        z = IntegerVariable(var_name="z", domain_low=0, domain_high=10)  
  
        # Constraints  
        constraint_1 = RelationalExpression(y > 2*x)  
        constraint_2 = RelationalExpression(x >= 4)  
        constraint_3 = RelationalExpression(z == y - x)  
  
        # Objective: Maximize z  
        self.add_objective(  
            SpecificMaximum(variable=z)  
        )  
  
        # Add variable and constraint to the problem  
        self.add_variable(x)  
        self.add_variable(y)  
        self.add_variable(z)  
        self.add_constraint(constraint_1)  
        self.add_constraint(constraint_2)  
        self.add_constraint(constraint_3)  
  
        # Set the search strategy  
        self.set_searcher(SearcherType.BAB)  
  
# Create a Qaekwy engine for interaction with the freely-available Cloud instance  
qaekwy_engine = DirectEngine()  
  
# Create the optimization problem instance  
optimization_problem = SimpleOptimizationProblem()  
  
# Request the Qaekwy engine to solve the problem  
response = qaekwy_engine.model(model=optimization_problem)  
  
# Retrieve the list of solutions from the response  
list_of_solutions = response.get_solutions()  
  
# Print the solution(s) obtained  
for solution in list_of_solutions:  
    print(f"Optimal solution: x = {solution.x}")  
    print(f"Optimal solution: y = {solution.y}")  
    print(f"Optimal solution: z = {solution.z}")  

整体的思路是先进行建模,建模过程中把模型变量、目标、使用的搜索策略都设置好,然后再求解。

Qaekwy建模及求解框架

Qaekwy建模框架很清晰,主要有以下几个步骤。

设计模型

这里先设立模型框架,比如基础案例中,设定的是一个线性规划问题。

# Create the optimization problem instance  
optimization_problem = SimpleOptimizationProblem()

定义问题

对问题进行定义,加上约束和目标各种函数。

  # Create a integer variables  
        x = IntegerVariable(var_name="x", domain_low=0, domain_high=100)  
        y = IntegerVariable(var_name="y", domain_low=0, domain_high=10)  
        z = IntegerVariable(var_name="z", domain_low=0, domain_high=10)  
  
        # Constraints  
        constraint_1 = RelationalExpression(y > 2*x)  
        constraint_2 = RelationalExpression(x >= 4)  
        constraint_3 = RelationalExpression(z == y - x)  
  
        # Objective: Maximize z  
        self.add_objective(  
            SpecificMaximum(variable=z)  
        )  
  
        # Add variable and constraint to the problem  
        self.add_variable(x)  
        self.add_variable(y)  
        self.add_variable(z)  
        self.add_constraint(constraint_1)  
        self.add_constraint(constraint_2)  
        self.add_constraint(constraint_3)

设定求解方法

本环节是设定求解的方法,Qaekwy内部封装了许多求解方法。

 # Set the search strategy  
 self.set_searcher(SearcherType.BAB)

这里使用的是BAB方法,从文档介绍来看,应该是使用分支定界法求解最优解,也是比较常用的方法。

实例化 Qaekwy 引擎

这里用了自带的免费实例化引擎,官网文档介绍,中小规模可以用自带免费引擎求解。当然,可以换更牛的引擎(估计需要更高的算力,可能需要自己买算力。)

qaekwy_engine = DirectEngine()

解决问题

前面搭建好了以后,就可以求解了。

# Request the Qaekwy engine to solve the problem  
response = qaekwy_engine.model(model=optimization_problem)  
  
# Retrieve the list of solutions from the response  
list_of_solutions = response.get_solutions()  
  
# Print the solution(s) obtained  
for solution in list_of_solutions:  
    print(f"Optimal solution: x = {solution.x}")  
    print(f"Optimal solution: y = {solution.y}")  
    print(f"Optimal solution: z = {solution.z}")

更多案例-背包问题

为了方便大家理解建模及求解过程,再给一个背包问题的案例给大家参考学习。

from qaekwy.engine import DirectEngine  
from qaekwy.model.constraint.relational import RelationalExpression  
from qaekwy.model.specific import SpecificMaximum  
from qaekwy.model.variable.branch import BranchIntegerVal  
from qaekwy.model.variable.integer import IntegerVariable, IntegerExpressionVariable  
from qaekwy.model.modeller import Modeller  
from qaekwy.model.searcher import SearcherType  
  
import json  
  
  
class KnapsackProblem(Modeller):  
    """  
    KnapsackProblem  
    """  
  
    def __init__(self, weights, values, weight_limit):  
        super().__init__()  
  
        num_items = len(weights)  
        selected_items = [  
            IntegerVariable(  
                var_name=f"item_{i}",  
                domain_low=0,  
                domain_high=1,  
                branch_val=BranchIntegerVal.VAL_MIN,  
            )  
            for i in range(num_items)  
        ]  
  
        # Constraint: Total weight of selected items should be less than or equal  
        # to the weight limit  
        weight_constraint = RelationalExpression(  
            sum(weights[i] * selected_items[i] for i in range(num_items))  
            <= weight_limit  
        )  
  
        # Add variables and constraints to the problem  
        for item_var in selected_items:  
            self.add_variable(item_var)  
  
        self.add_constraint(weight_constraint)  
  
        # Maximize the total value  
        total_value = IntegerExpressionVariable(  
            var_name="total_value",  
            expression=sum(values[i] * selected_items[i] for i in range(num_items)),  
            branch_val=BranchIntegerVal.VAL_MIN,  
        )  
  
        self.add_variable(total_value)  
        self.add_objective(SpecificMaximum(total_value))  
  
        # Set the search strategy to Branch-and-bound Search (BAB)  
        self.set_searcher(SearcherType.BAB)  
  
  
if __name__ == "__main__":  
    # Create a Qaekwy engine for direct interaction  
    qaekwy_engine = DirectEngine()  
  
    # Define the items' weights, values, and knapsack weight limit  
    weights = [2, 3, 4, 5,1,2,4,4,1,1]  
    values = [3, 4, 5, 6,120,3,4,5,1,2]  
    knapsack_weight_limit = 3  
  
    # Create the knapsack problem instance  
    knapsack_problem = KnapsackProblem(weights, values, knapsack_weight_limit)  
  
    # Request the Qaekwy engine to solve the knapsack problem  
    response = qaekwy_engine.model(model=knapsack_problem)  
  
    # Retrieve the list of solutions from the response  
    list_of_solutions = response.get_solutions()  
  
    solution = list_of_solutions[0]  
    for solution_item, solution_value in solution.items():  
        if "item" in str(solution_item).lower():  
            idx = int(solution_item.split("_")[1])  
            item_weight, item_value = weights[idx], values[idx]  
            print(  
                f"Item {idx}: Weight = {item_weight}; Value = {item_value}; Packed = {solution_value}"  
            )  
  
    print(f"Total Value: {solution.total_value}")

官方文档已经把求解过程、变量设定、目标设定等规则介绍的非常详细。感兴趣的可以查阅本文的参考资料链接。

参考资料:

https://docs.qaekwy.io/

点击下方安全链接前往获取

CSDN大礼包:《Python入门&进阶学习资源包》免费分享

👉Python实战案例👈

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

图片

图片

👉Python书籍和视频合集👈

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。

图片

👉Python副业创收路线👈

图片

这些资料都是非常不错的,朋友们如果有需要《Python学习路线&学习资料》,点击下方安全链接前往获取

CSDN大礼包:《Python入门&进阶学习资源包》免费分享

本文转自网络,如有侵权,请联系删除。

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
运筹优化Python是使用Python编程语言进行运筹优化问题建模和求解的过程。运筹优化是一种数学方法,用于优化决策问题,例如最大化利润或最小化成本。Python是一种功能强大的编程语言,具有丰富的和工具,可以帮助我们在运筹优化中进行问题建模和求解。 通过使用Python,您可以使用线性规划来解决线性规划问题。这些包装了本机求解器,可以提供解决方案状态、决策变量值、松弛变量、目标函数等结果信息。一些常用的Python线性规划包括GLPK、LP Solve、CBC、CVXOPT、SciPy等。 此外,还有一些商业求解器提供了Python API,如Gurobi Optimization。Gurobi是一家提供快速商业求解器的公司,他们还提供关于线性规划和混合整数线性规划的宝贵资源,包括基础知识、教程和如何选择数学规划求解器的指南。 总之,运筹优化Python是指使用Python编程语言进行运筹优化问题建模和求解的过程,可以通过使用线性规划或商业求解器的Python API来解决问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [运筹优化学习26:Python求解线性规划问题入门手册](https://blog.csdn.net/m1m2m3mmm/article/details/112579384)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值