您现在的位置是:首页 >技术教程 >【从零开始】源码构建 OR-Tools v9.6与第三方求解器CPLEX等在python中结合使用网站首页技术教程

【从零开始】源码构建 OR-Tools v9.6与第三方求解器CPLEX等在python中结合使用

小猪快跑爱摄影 2024-10-09 12:01:04
简介【从零开始】源码构建 OR-Tools v9.6与第三方求解器CPLEX等在python中结合使用


OR-Tools 是一个用于优化的开源软件套件,专为解决世界上最棘手的车辆路线规划、流程、整数和线性规划以及约束规划问题而调整。
本文将介绍如何源码构建 OR-Tools v9.6与第三方求解器CPLEX等在python中结合使用。

如果您计划将第三方求解器与 OR-Tools 结合使用,则需要从源代码构建 OR-Tools。——@小猪快跑

相关教程

相关文献

安装教程

博主的环境是Ubuntu 22.04 LTS。官网可参考在 Linux 上从源代码 OR-Tools Python 构建 | Google for Developers

C++ tools

如需安装 C++ 工具,请打开终端窗口并输入以下命令:

sudo apt update
sudo apt upgrade -y
sudo apt install -y build-essential cmake lsb-release

SWIG

sudo apt install -y swig

Python(anaconda)

这里我们使用Anaconda | The World’s Most Popular Data Science Platform,官网下载安装即可。这里我们使用静默安装Installing in silent mode — Anaconda documentation

bash Anaconda3-2023.03-1-Linux-x86_64.sh -b

激活conda环境

方法一

如果您希望condabase环境在启动时被激活,将auto_activate_base参数设置为true

conda config --set auto_activate_base true

刷新环境变量

source ~/.bashrc
方法二
# 进入安装目录
cd ~/anaconda3/bin/
# 激活conda base环境
source activate

如果之后需要反激活conda base环境

source deactivate

创建新的conda环境

conda create -n orTools python=3.10 -y

然后进入刚刚创建的环境

conda activate orTools

PIP代理换源(可选)

假如pip的速度比较慢,可以换成国内镜像

pip3 config set global.index-url https://mirrors.aliyun.com/pypi/simple/

之后会提示Writing to /home/user/.config/pip/pip.conf,今后可以在这里修改pip源。

Git换源(可选)

假如git的速度比较慢,可以换成国内镜像

方法一

git config --global url."https://ghproxy.com/".insteadOf https://

方法二(推荐)

vim ~/.gitconfig

然后输入:

[url "https://ghproxy.com/https://github.com/"]
        insteadOf = https://github.com/
[url "https://ghproxy.com/https://raw.githubusercontent.com/"]
        insteadOf = https://raw.githubusercontent.com/
[url "https://ghproxy.com/https://gist.github.com/"]
        insteadOf = https://gist.github.com/
[url "https://ghproxy.com/https://gist.githubusercontent.com/"]
        insteadOf = https://gist.githubusercontent.com/

CPLEX

bash cos_installer_preview-22.1.1.0.R0-M08SWML-linux-x86-64.bin

我个人习惯不用root权限安装,所以把安装路径改成:/home/user/ibm/ILOG/CPLEX_Studio_Community2211

===============================================================================
Choose Install Folder
---------------------

Where would you like to install?

  Default Install Folder: /opt/ibm/ILOG/CPLEX_Studio_Community2211

ENTER AN ABSOLUTE PATH, OR PRESS <ENTER> TO ACCEPT THE DEFAULT
      : /home/user/ibm/ILOG/CPLEX_Studio_Community2211

INSTALL FOLDER IS: /home/user/ibm/ILOG/CPLEX_Studio_Community2211
   IS THIS CORRECT? (Y/N): y

如果想直接安装python版本的CPLEX,如下命令即可(但不能用OR-Tools直接调用):

===============================================================================
Installing the engines in your Python environment
-------------------------------------------------

If you want to use the CPLEX or CP Optimizer engines through their Python
APIs, you need to tell Python where to find them.  To do so, enter the
following command into a terminal :
<<<<<<
python /home/user/ibm/ILOG/CPLEX_Studio_Community2211/python/setup.py install
>>>>>>

OR-Tools

个人建议从GitHub上下载源码压缩包然后解压,我这里用的是最新版Release v9.6 (2023/03) · google/or-tools · GitHub。当然也可以直接:

git clone https://github.com/google/or-tools

进入or-tools目录:

cmake -S. -Bbuild -DBUILD_DEPS=ON -DBUILD_PYTHON=ON -DUSE_CPLEX=ON -DCPLEX_ROOT=/home/user/ibm/ILOG/CPLEX_Studio_Community2211

注意注意,非常重要!!!安装后看到成功界面别激动,网上翻几页去看warning信息

-- CPLEX_ROOT: /home/user/ibm/ILOG/CPLEX_Studio_Community2211
-- Adding proto path: $<BUILD_INTERFACE:/home/user/ClionProjects/or-tools-9.6/build/_deps/protobuf-src/src>
-- Found SWIG: /usr/bin/swig4.0 (found version "4.0.2")
-- Searching python module: "mypy_protobuf"
CMake Warning at cmake/python.cmake:89 (message):
  Can't find python module: "mypy_protobuf", install it using pip...
Call Stack (most recent call first):
  cmake/python.cmake:134 (search_python_module)
  CMakeLists.txt:381 (include)


Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting mypy-protobuf
  Downloading https://mirrors.aliyun.com/pypi/packages/4a/47/5bad06a9546d9b8115b4f8f1e216a6033055ad06bec0bbcbfe3918a27b70/mypy_protobuf-3.4.0-py3-none-any.whl (15 kB)
Collecting types-protobuf>=3.20.4
  Downloading https://mirrors.aliyun.com/pypi/packages/ff/46/eab94a15512a21e9e89df47de5777383977f3da2d5e4df66b19bf7510c68/types_protobuf-4.23.0.1-py3-none-any.whl (61 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.3/61.3 kB 1.2 MB/s eta 0:00:00
Collecting protobuf>=4.21.8
  Downloading https://mirrors.aliyun.com/pypi/packages/14/23/f3b852093f3a7031049313913e04431e7a32bd9752adfaf79d1193cf05b1/protobuf-4.23.2-cp37-abi3-manylinux2014_x86_64.whl (304 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 304.5/304.5 kB 8.9 MB/s eta 0:00:00
Installing collected packages: types-protobuf, protobuf, mypy-protobuf
  WARNING: The scripts protoc-gen-mypy and protoc-gen-mypy_grpc are installed in '/home/user/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed mypy-protobuf-3.4.0 protobuf-4.23.2 types-protobuf-4.23.0.1
-- Searching python module: "virtualenv"
CMake Warning at cmake/python.cmake:89 (message):
  Can't find python module: "virtualenv", install it using pip...
Call Stack (most recent call first):
  cmake/python.cmake:183 (search_python_module)
  CMakeLists.txt:381 (include)


Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting virtualenv
  Downloading https://mirrors.aliyun.com/pypi/packages/f1/0a/18755fa6aec794fd539b050beeaa905fa5c77c64356aa8bdecb62c01581a/virtualenv-20.23.0-py3-none-any.whl (3.3 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.3/3.3 MB 6.2 MB/s eta 0:00:00
Collecting platformdirs<4,>=3.2
  Downloading https://mirrors.aliyun.com/pypi/packages/6d/1a/96efea7b36835ce89911d7813fe68f5b1db7ecae4023bf209a7aeba93017/platformdirs-3.5.3-py3-none-any.whl (15 kB)
Collecting filelock<4,>=3.11
  Downloading https://mirrors.aliyun.com/pypi/packages/e2/88/52dfc8182232b85ac63aaae9d5f0947ecd5d4ff24131bc1b3800c2bf7914/filelock-3.12.1-py3-none-any.whl (10 kB)
Collecting distlib<1,>=0.3.6
  Downloading https://mirrors.aliyun.com/pypi/packages/76/cb/6bbd2b10170ed991cf64e8c8b85e01f2fb38f95d1bc77617569e0b0b26ac/distlib-0.3.6-py2.py3-none-any.whl (468 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 468.5/468.5 kB 6.3 MB/s eta 0:00:00
Installing collected packages: distlib, platformdirs, filelock, virtualenv
  WARNING: The script virtualenv is installed in '/home/user/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed distlib-0.3.6 filelock-3.12.1 platformdirs-3.5.3 virtualenv-20.23.0
-- Python project: ortools

这里最关键的警告是:

WARNING: The script virtualenv is installed in '/home/user/.local/bin' which is not on PATH.

因为默认安装在系统python环境下,而不是conda环境下,我们需要手动安装以上几个安装包。

conda install mypy-protobuf virtualenv -y

构建源代码(如果失败的话把-j去掉,就是不开多线程编译,或者手动指定少一点线程,博主AMD的CPU有时候会有一点点bug)

cmake --build build --config Release --target all -j -v

进入刚才编译后的python目录

cd build/python/dist/

安装.whl文件

pip install ortools-9.6.9999-cp310-cp310-linux_x86_64.whl

例子测试

from ortools.linear_solver import pywraplp


def main():
    # Create the mip solver with the SCIP backend.
    solver = pywraplp.Solver.CreateSolver('CPLEX')
    if not solver:
        return

    infinity = solver.infinity()
    # x and y are integer non-negative variables.
    x = solver.IntVar(0.0, infinity, 'x')
    y = solver.IntVar(0.0, infinity, 'y')

    print('Number of variables =', solver.NumVariables())

    # x + 7 * y <= 17.5.
    solver.Add(x + 7 * y <= 17.5)

    # x <= 3.5.
    solver.Add(x <= 3.5)

    print('Number of constraints =', solver.NumConstraints())

    # Maximize x + 10 * y.
    solver.Maximize(x + 10 * y)

    print(f'Solving with {solver.SolverVersion()}')
    status = solver.Solve()

    if status == pywraplp.Solver.OPTIMAL:
        print('Solution:')
        print('Objective value =', solver.Objective().Value())
        print('x =', x.solution_value())
        print('y =', y.solution_value())
    else:
        print('The problem does not have an optimal solution.')

    print('
Advanced usage:')
    print('Problem solved in %f milliseconds' % solver.wall_time())
    print('Problem solved in %d iterations' % solver.iterations())
    print('Problem solved in %d branch-and-bound nodes' % solver.nodes())


if __name__ == '__main__':
    main()

控制台输出

/home/user/anaconda3/bin/conda run -n orTools --no-capture-output python /home/user/PycharmProjects/orTools_example/main.py 
Number of variables = 2
Number of constraints = 2
Solving with CPLEX library version 22.01.01.00
Solution:
Objective value = 23.0
x = 3.0
y = 2.0

Advanced usage:
Problem solved in 2.000000 milliseconds
Problem solved in 0 iterations
Problem solved in 0 branch-and-bound nodes

Process finished with exit code 0
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。