为节省存储空间,采用稀疏矩阵来表示约束条件的系数矩阵
例如,求解下列MIP模型,采用稀疏矩阵来表示约束条件
# This example formulates and solves the following simple MIP model # using the matrix API: # maximize # x + y + 2 z # subject to # x + 2 y + 3 z <= 4 # x + y >= 1 # x, y, z binary
import gurobipy as gb
from gurobipy import GRB
import numpy as np
import scipy.sparse as sp # scipy库中存储稀疏矩阵的函数
try:
# creat a new model
m=gb.Model("matrix_model")
# creat variables
x=m.addMVar(shape=3, vtype=GRB.BINARY, name ="x")
# set objective
obj = np.array([1.0, 1.0, 2.0])
m.setObjective(obj@x, GRB.MAXIMIZE)
# build sparse constraint matrix
val = np.array([1.0, 2.0, 3.0, -1.0, -1.0]) # 按行罗列约束中的变量系数
row = np.array([0, 0, 0, 1, 1]) # 非0系数的行索引
col = np.array([0, 1, 2, 0, 1]) # 非0系数的列索引
A=sp.csr_matrix((val, (row, col)), shape =(2,3))
# build rhs vector
rhs = np.array([4.0, -1.0])
# add constraints
m.addConstr(A@x<=rhs, name="c")
m.optimize()
for v in m.getVars():
print(f"{v.VarName} {v.X:g}")
print(f"Objective: {m.ObjVal:g}")
except gb.GurobiError as e:
print(f"Error code {e.errno}: {e}")
except AttributeError:
print("Encountered an attribute error")
稀疏矩阵是如何创建的
csr_matrix (compress sparse row): 按行压缩的稀疏矩阵
csc_matrix(compress sparse column):按列压缩的稀疏矩阵
可以看到,在将 CSR(Compressed Sparse Row)格式的稀疏矩阵转换为 CSC(Compressed Sparse Column)格式后,矩阵的结构本身并没有改变,仅是数据的存储方式不同。
另,稀疏矩阵的常见用法可以参考这个连接:SciPy 稀疏矩阵 | 菜鸟教程 (runoob.com)