gurobi 基于python的gurobipy库使用,具有一维变量和二维变量的复杂模型求解

写在前面

可以参考下pulp和scip两篇的,比较详细,尤其pulp篇。举一反三,很好入门。

步骤

定义问题:m = Model(name)
定义变量:x = m.addVars(range(len), vtype=GRB.BINARY)
定义目标函数:m.setObjective(目标函数)
设置约束条件:m.addConstr(约束条件)
求解:m.optimize()#求解
m.objVal#目标函数结果

导入

from gurobipy import *

栗子 复杂模型 一维、二维变量

gurobi 基于python的gurobipy库使用,具有一维变量和二维变量的复杂模型求解_第1张图片

from gurobipy import *
import numpy as np
import csv
import os
import pandas as pd
import altair as alt

n = 200 #residential areas -变量i居民区数量
m = 40 # shelters-变量j庇护所数量
areas = range(n)
shelters = range(m)
print(areas,shelters)

path = 'Pb2_areas.csv'
areas_matrix = np.genfromtxt(path, dtype=float, delimiter=',', encoding='utf-8-sig')
path = 'Pb2_shelters.csv'
shelters_matrix = np.genfromtxt(path, dtype=float, delimiter=',', encoding='utf-8-sig')

R = areas_matrix[:,2]#第三列的居民区居民数量-变量R_i
C = shelters_matrix[:,2]#第三列的庇护所能庇护的容量-变量C_j

#计算居民到庇护所的距离
D = np.zeros((n,m))#-变量D_ij距离
for i in areas:
    for j in shelters:
        D[i,j] = abs(areas_matrix[i,0] - shelters_matrix[j,0]) + abs(areas_matrix[i,1] - shelters_matrix[j,1])


#定义问题
m = Model("assignment")

#定义变量
x = m.addVars(shelters, vtype=GRB.BINARY)#一维变量
y_ij = m.addVars(areas, shelters, vtype=GRB.BINARY)#二维变量


#定义目标函数
m.setObjective(sum(sum(D[i,j] * y_ij[i,j] for i in areas) for j in shelters), GRB.MINIMIZE)

#设置约束
# shelter constraint
m.addConstr(sum(x[j] for j in shelters) == 10)

# resident constraint
for i in areas:
    m.addConstr(sum(y_ij[i, j] for j in shelters) == 1)

# capacity constraint
for j in shelters:
    m.addConstr(sum(R[i] * y_ij[i, j] for i in areas) <= C[j] * x[j])

m.Params.TimeLimit = 60 # seconds
m.optimize()
print("Retrieve Optimal Solution.")

# Print objective value
print("Objective value =", m.objVal)


你可能感兴趣的:(运筹学,Python,python)