44、动态规划-生产与存储问题

import random as rd
from pyscipopt import Model, quicksum

def Planning(s, K, a, b, v0, vn, time_limit):

    n = len(s)

    M = max(s)*10

    model = Model("Production_and_storage")
    x = [model.addVar(vtype="I", name="x[%s]" % (i)) for i in range(n)]
    y = [model.addVar(vtype="B", name="y[%s]" % (i)) for i in range(n)]

    # 以总成本最小为目标
    model.setObjective(quicksum(a*x[i]+K*y[i] for i in range(n)) + b * quicksum(v0 + quicksum(x[j] for j in range(i+1)) - quicksum(s[j] for j in range(i+1)) for i in range(n-1)) , "minimize")

    # 有的量大于等于卖的量
    for i in range(n):
        model.addCons(v0 + quicksum(x[j] for j in range(i + 1)) - quicksum(s[j] for j in range(i + 1)) >= 0)

    # 有生产时必须有准备费用
    for i in range(n):
        model.addCons(x[i] - M*y[i] <= 0)

    # 设置求解时间
    model.setRealParam("limits/time", time_limit)
    model.optimize()
    print("\ngap:",model.getGap())

    # 拿结果
    p = [round(model.getVal(x[i])) for i in range(n)]

    return p

if __name__ == "__main__":

    #月数
    n = 4
    print("\nn:\n", n)

    #销量、生产准备成本、生产产品成本、存储费用、起始量、最终量
    s = [int(rd.random() * 1000) for i in range(n)]
    # s = [400, 500, 300, 200]
    print("\ns:\n", s)

    K, a, b = 500, 1, 1
    print("\nK a b:\n", K, a, b)

    v0, vn = 100, 0
    print("\nv0, vn:\n", v0, vn)

    # 开始计算
    p = Planning(s, K, a, b, v0, vn, 10)
    print("\np:\n", p)

 

你可能感兴趣的:(44、动态规划-生产与存储问题)