基础知识

导入库

from pyscipopt import Model,quicksum

栗子1 单个变量+简单模型

基于python的scip库使用,从基础模型到复杂模型,从一维变量到二位变量-LMLPHP

def prumen1():
    #创建模型
    model=Model("remen")

    #创建变量
    x=model.addVar(vtype="I",name="x",lb=0)
    y = model.addVar(vtype="I", name="y", lb=0)
    z = model.addVar(vtype="I", name="z", lb=0)
    w = model.addVar(vtype="I", name="w", lb=0)

    #创建目标函数
    model.setObjective(5 * x + 6 * y + 7 * z + 8 * w , "minimize")

    #创建约束条件
    model.addCons(x + y + z + w == 100)
    model.addCons(5 * x + 4 * y + 5 * z + 6 * w >= 530)
    model.addCons(2 * x + y + z + 2 * w <= 160)

    #求解
    model.optimize()
    sol = model.getBestSol()

    print("x: {}".format(sol[x]))
    print("y: {}".format(sol[y]))
    print("z: {}".format(sol[z]))
    print("w: {}".format(sol[w]))
    print(model.getObjVal())

栗子2 一维变量+二维变量+复杂模型

模型感谢Cathy友情提供
基于python的scip库使用,从基础模型到复杂模型,从一维变量到二位变量-LMLPHP

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

    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])

    # 定义问题
    model=Model("Cathy_exp")

    # 定义变量
   for i in range(n):
        x = model.addVar(vtype="B", name="x")#一维变量
    for i in range(n):
        for j in range(m):
            y_ij=model.addVar(vtype="B", name="y")#二维变量

    # 目标函数
    ansa=0.0
    for j in range(m):
        for i in range(n):
            ansa+=(D[i, j] * y_ij[i,j])
    model.setObjective(ansa, "minimize")

    # 约束条件
    model.addCons(quicksum(x[j] for j in shelters)==10)
    for i in areas:
        model.addCons(quicksum(y_ij[i,j] for j in shelters)==1)
    for j in shelters:
        model.addCons(quicksum(R[i]*y_ij[i,j] for i in areas)<=C[j]*x[j])


    model.optimize()
    print(model.getObjVal())
    # print(m)

不完整栗子 三维变量

这个的完整代码就不透露了~~~

    # 创建决策变量
    x, y, h = {}, {}, {}
    for i in range(n):
        for j in range(m):
            x[i, j] = model.addVar(vtype="B", name="x(%s,%s)" % (i, j)) #二维变量定义
    y = [[[model.addVar(vtype="I", name="y(%s,%s,%s)" % (i, j, k), lb=0) for k in range(t)] for j in range(m)] for i in
         range(n)] #三维变量定义

     #输出
     sol = model.getBestSol()      
     for i in range(n):
        for j in range(m):
            print(x[i, j], "=", sol[x[i, j]])#二维变量输出
            for k in range(t):
                print(y[i, j, k], "=", sol[y[i, j, k]])#三维变量输出
11-30 10:39