本文将详细介绍如何在Python中安装、配置和使用高性能求解器Mosek。
Mosek求解器介绍
Mosek是一种高性能的优化求解器,该求解器已经广泛应用于工业界和学术界,用于解决线性规划、整数规划、二次规划、二次锥规划等各种优化问题。
Mosek主要功能
高效的求解算法:Mosek针对各种不同类型的数学优化问题提供了高效且优化的求解算法。它使用了内部的优化技术和数据结构,以最小化求解时间,并提供与解决器的准确性和鲁棒性。
并行处理:Mosek支持多线程和多核处理,能极大程度地利用计算机硬件提高求解效率。
灵活性和可扩展性:允许用户根据自己的需求进行自定义。用户可以自定义线性和二次优化问题的约束条件和目标函数,并添加自定义的优化算法。
接口丰富:Mosek提供了多种编程语言接口,包括Python、MATLAB、C++等。通过这些接口,用户可以方便调用Mosek求解器。
Python中使用Mosek
安装软件包
可以通过pip安装mosek软件包:
pip install mosek
下载许可证(重要)
仅pip安装mosek,在python是无法调用求解器的。还需要下载一个许可证,才能正常调用mosek求解器。
试用许可证地址:30天
https://www.mosek.com/try/
学术许可证地址:365天
https://www.mosek.com/products/academic-licenses/
激活许可证(重要)
申请完许可证后,可以根据邮件上地址激活。激活后会收到许可证文件。
许可证存放指定位置(重要)
/home/YOUR_USER_NAME/mosek/mosek.lic (Linux)
/Users/YOUR_USER_NAME/mosek/mosek.lic (OSX)
C:\Users\YOUR_USER_NAME\mosek\mosek.lic (Windows)
Where YOUR_USER_NAME is your user ID on the computer.
注意不同的操作系统指定位置不一样。我用的是windows,文件放置在
C:\Users\User\mosek\mosek.lic
使用案例
线性规划案例
from mosek.fusion import *
A = [[3.0, 1.0, 2.0, 0.0],
[2.0, 1.0, 3.0, 1.0],
[0.0, 2.0, 0.0, 3.0]]
c = [3.0, 1.0, 5.0, 1.0]
# Create a model with the name 'lo1'
with Model("lo1") as M:
# Create variable 'x' of length 4
x = M.variable("x", 4, Domain.greaterThan(0.0))
# Create constraints
M.constraint(x.index(1), Domain.lessThan(10.0))
M.constraint("c1", Expr.dot(A[0], x), Domain.equalsTo(30.0))
M.constraint("c2", Expr.dot(A[1], x), Domain.greaterThan(15.0))
M.constraint("c3", Expr.dot(A[2], x), Domain.lessThan(25.0))
# Set the objective function to (c^t * x)
M.objective("obj", ObjectiveSense.Maximize, Expr.dot(c, x))
# Solve the problem
M.solve()
# Get the solution values
sol = x.level()
print('\n'.join(["x[%d] = %f" % (i, sol[i]) for i in range(4)]))
TSP案例
def tsp(n, A, C, remove_selfloops, remove_2_hop_loops):
with Model() as M:
M.setLogHandler(sys.stdout)
x = M.variable([n,n], Domain.binary())
M.constraint(Expr.sum(x,0), Domain.equalsTo(1.0))
M.constraint(Expr.sum(x,1), Domain.equalsTo(1.0))
M.constraint(x, Domain.lessThan( A ))
M.objective(ObjectiveSense.Minimize, Expr.dot(C ,x))
if remove_2_hop_loops:
M.constraint(Expr.add(x, x.transpose()), Domain.lessThan(1.0))
if remove_selfloops:
M.constraint(x.diag(), Domain.equalsTo(0.))
it = 1
M.writeTask("tsp-0-%s-%s.ptf" % ('t' if remove_selfloops else 'f', 't' if remove_2_hop_loops else 'f'))
while True:
print("\n\n--------------------\nIteration",it)
M.solve()
print('\nsolution cost:', M.primalObjValue())
print('\nsolution:')
cycles = []
for i in range(n):
xi = x.slice([i,0],[i+1,n])
print(xi.level())
for j in range(n):
if xi.level()[j] <= 0.5 : continue
found = False
for c in cycles:
if len( [ a for a in c if i in a or j in a ] )> 0:
c.append( [i,j] )
found = True
break
if not found:
cycles.append([ [ i,j ]])
print('\ncycles:')
print([c for c in cycles])
if len(cycles)==1:
break;
for c in cycles:
M.constraint(Expr.sum(x.pick(c)), Domain.lessThan( 1.0 * len(c) - 1 ))
it = it +1
return x.level(), c
return [],[]
def main():
A_i = [0,1,2,3,1,0,2,0]
A_j = [1,2,3,0,0,2,1,3]
C_v = [1.,1.,1.,1.,0.1,0.1,0.1,0.1]
n = max(max(A_i),max(A_j))+1
costs = Matrix.sparse(n,n,A_i,A_j,C_v)
x,c = tsp(n, Matrix.sparse(n,n,A_i,A_j,1.), costs , True, True)
x,c = tsp(n, Matrix.sparse(n,n,A_i,A_j,1.), costs , True, False)
main()
输出结果
Open file 'tsp-0-t-t.ptf'
Writing started.
Writing terminated. Time: 0.00
--------------------
Iteration 1
Problem
Name :
Objective sense : minimize
Type : LO (linear optimization problem)
Constraints : 44
Affine conic cons. : 0
Disjunctive cons. : 0
Cones : 0
Scalar variables : 17
Matrix variables : 0
Integer variables : 16
Optimizer started.
Mixed integer optimizer started.
Threads used: 8
Presolve started.
Presolve terminated. Time = 0.00, probing time = 0.00
Presolved problem: 0 variables, 0 constraints, 0 non-zeros
Presolved problem: 0 general integer, 0 binary, 0 continuous
Clique table size: 0
BRANCHES RELAXS ACT_NDS DEPTH BEST_INT_OBJ BEST_RELAX_OBJ REL_GAP(%) TIME
0 0 1 0 4.0000000000e+00 NA NA 0.0
0 1 1 0 4.0000000000e+00 4.0000000000e+00 0.00e+00 0.0
An optimal solution satisfying the relative gap tolerance of 1.00e-02(%) has been located.
The relative gap is 0.00e+00(%).
An optimal solution satisfying the absolute gap tolerance of 0.00e+00 has been located.
The absolute gap is 0.00e+00.
Objective of best integer solution : 4.000000000000e+00
Best objective bound : 4.000000000000e+00
Initial feasible solution objective: Undefined
Construct solution objective : Not employed
User objective cut value : Not employed
Number of cuts generated : 0
Number of branches : 0
Number of relaxations solved : 1
Number of interior point iterations: 0
Number of simplex iterations : 0
Time spend presolving the root : 0.00
Time spend optimizing the root : 0.00
Mixed integer optimizer terminated. Time: 0.03
Optimizer terminated. Time: 0.09
Integer solution solution summary
Problem status : PRIMAL_FEASIBLE
Solution status : INTEGER_OPTIMAL
Primal. obj: 4.0000000000e+00 nrm: 1e+00 Viol. con: 0e+00 var: 0e+00 itg: 0e+00
solution cost: 4.0
solution:
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[1. 0. 0. 0.]
cycles:
[[[0, 1], [1, 2], [2, 3], [3, 0]]]
Open file 'tsp-0-t-f.ptf'
Writing started.
Writing terminated. Time: 0.00
--------------------
Iteration 1
Problem
Name :
Objective sense : minimize
Type : LO (linear optimization problem)
Constraints : 28
Affine conic cons. : 0
Disjunctive cons. : 0
Cones : 0
Scalar variables : 17
Matrix variables : 0
Integer variables : 16
Optimizer started.
Mixed integer optimizer started.
Threads used: 8
Presolve started.
Presolve terminated. Time = 0.00, probing time = 0.00
Presolved problem: 0 variables, 0 constraints, 0 non-zeros
Presolved problem: 0 general integer, 0 binary, 0 continuous
Clique table size: 0
BRANCHES RELAXS ACT_NDS DEPTH BEST_INT_OBJ BEST_RELAX_OBJ REL_GAP(%) TIME
0 0 1 0 2.2000000000e+00 NA NA 0.0
0 1 1 0 2.2000000000e+00 2.2000000000e+00 0.00e+00 0.0
An optimal solution satisfying the relative gap tolerance of 1.00e-02(%) has been located.
The relative gap is 0.00e+00(%).
An optimal solution satisfying the absolute gap tolerance of 0.00e+00 has been located.
The absolute gap is 0.00e+00.
Objective of best integer solution : 2.200000000000e+00
Best objective bound : 2.200000000000e+00
Initial feasible solution objective: Undefined
Construct solution objective : Not employed
User objective cut value : Not employed
Number of cuts generated : 0
Number of branches : 0
Number of relaxations solved : 1
Number of interior point iterations: 0
Number of simplex iterations : 0
Time spend presolving the root : 0.00
Time spend optimizing the root : 0.00
Mixed integer optimizer terminated. Time: 0.02
Optimizer terminated. Time: 0.06
Integer solution solution summary
Problem status : PRIMAL_FEASIBLE
Solution status : INTEGER_OPTIMAL
Primal. obj: 2.2000000000e+00 nrm: 1e+00 Viol. con: 0e+00 var: 0e+00 itg: 0e+00
solution cost: 2.2
solution:
[0. 0. 0. 1.]
[0. 0. 1. 0.]
[0. 1. 0. 0.]
[1. 0. 0. 0.]
cycles:
[[[0, 3], [3, 0]], [[1, 2], [2, 1]]]
--------------------
Iteration 2
Problem
Name :
Objective sense : minimize
Type : LO (linear optimization problem)
Constraints : 30
Affine conic cons. : 0
Disjunctive cons. : 0
Cones : 0
Scalar variables : 17
Matrix variables : 0
Integer variables : 16
Optimizer started.
Mixed integer optimizer started.
Threads used: 8
Presolve started.
Presolve terminated. Time = 0.00, probing time = 0.00
Presolved problem: 0 variables, 0 constraints, 0 non-zeros
Presolved problem: 0 general integer, 0 binary, 0 continuous
Clique table size: 0
BRANCHES RELAXS ACT_NDS DEPTH BEST_INT_OBJ BEST_RELAX_OBJ REL_GAP(%) TIME
0 0 1 0 4.0000000000e+00 NA NA 0.0
0 1 1 0 4.0000000000e+00 4.0000000000e+00 0.00e+00 0.0
An optimal solution satisfying the relative gap tolerance of 1.00e-02(%) has been located.
The relative gap is 0.00e+00(%).
An optimal solution satisfying the absolute gap tolerance of 0.00e+00 has been located.
The absolute gap is 0.00e+00.
Objective of best integer solution : 4.000000000000e+00
Best objective bound : 4.000000000000e+00
Initial feasible solution objective: Undefined
Construct solution objective : Not employed
User objective cut value : Not employed
Number of cuts generated : 0
Number of branches : 0
Number of relaxations solved : 1
Number of interior point iterations: 0
Number of simplex iterations : 0
Time spend presolving the root : 0.00
Time spend optimizing the root : 0.00
Mixed integer optimizer terminated. Time: 0.00
Optimizer terminated. Time: 0.06
Integer solution solution summary
Problem status : PRIMAL_FEASIBLE
Solution status : INTEGER_OPTIMAL
Primal. obj: 4.0000000000e+00 nrm: 1e+00 Viol. con: 0e+00 var: 0e+00 itg: 0e+00
solution cost: 4.0
solution:
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[1. 0. 0. 0.]
cycles:
[[[0, 1], [1, 2], [2, 3], [3, 0]]]
参考文献mosek官网:
https://www.mosek.com/
微信公众号后台回复
加群:加入全球华人OR|AI|DS社区硕博微信学术群
资料:免费获得大量运筹学相关学习资料
人才库:加入运筹精英人才库,获得独家职位推荐
电子书:免费获取平台小编独家创作的优化理论、运筹实践和数据科学电子书,持续更新中ing...
加入我们:加入「运筹OR帷幄」,参与内容创作平台运营
知识星球:加入「运筹OR帷幄」数据算法社区,免费参与每周「领读计划」、「行业inTalk」、「OR会客厅」等直播活动,与数百位签约大V进行在线交流
文章须知
文章作者:用户007
微信编辑:疑疑
文章转载自『Python学习杂记』公众号,原文链接:Mosek求解器在Python中安装、配置及使用
关注我们
FOLLOW US