我们丢代码吧:
#
# This file is part of the Cardinal Optimizer, all rights reserved.
#
import coptpy as cp
from coptpy import COPT
import math
import itertools
# Optimization data for multicommodity problem
ORIG = ['zhenzhou', 'shanghai', 'tianjin']
DEST = ['xi‘an', 'kunming', 'shenzhen',]
PROD = ['bands',]
supply_list = [19,
20,
12, ]
supply = dict(zip(itertools.product(ORIG, PROD), supply_list))
demand_list = [19,
25,
7,
]
demand = dict(zip(itertools.product(DEST, PROD), demand_list))
limit_list = [625.0] * len(ORIG) * len(DEST)
limit = dict(zip(itertools.product(ORIG, DEST), limit_list))
cost_list = [3500, 13500,10500,
24500, 24000,10500,
17500, 16500,25500,]
cost = dict(zip(itertools.product(ORIG, DEST, PROD), cost_list))
# Create COPT environment
env = cp.Envr()
# Create COPT problem
mmulti = env.createModel()
# Add variables to problem
vtrans = mmulti.addVars(ORIG, DEST, PROD, nameprefix='trans')
# Add constraints to problem
mmulti.addConstrs((vtrans.sum(i, '*', k) == supply[i, k] for i in ORIG for k in PROD), nameprefix='supply')
mmulti.addConstrs((vtrans.sum('*', j, k) == demand[j, k] for j in DEST for k in PROD), nameprefix='demand')
mmulti.addConstrs((vtrans.sum(i, j, '*') <= limit[i, j] for i in ORIG for j in DEST), nameprefix='multi')
# Set objective function
mmulti.setObjective(vtrans.prod(cost), COPT.MINIMIZE)
# Set optimization parameters
mmulti.setParam(COPT.Param.TimeLimit, 100)
# Solve the problem
mmulti.solve()
# Display solution
if mmulti.status == COPT.OPTIMAL:
print('\nObjective value: {}'.format(mmulti.objval))
print('Variable solution: ')
multvars = mmulti.getVars()
for mvar in multvars:
if math.fabs(mvar.x) >= 1e-6:
print(' {0:s} = {1:.6f}'.format(mvar.name, mvar.x))
说明一下,这个案例是可以推广的,比如更复杂一点的。
第一:可以试试看混合调度,就是两个公司调度。
第二:可以试试看加一个天数的约束。
3行3列表示的是对应关系,消耗的情况,其实我个人认为如果没有天数约束,可以直接把天数×在成本里面。可以尝试一下的。
上结果吧:
Cardinal Optimizer v7.1.3. Build date Apr 29 2024
Copyright Cardinal Operations 2024. All Rights Reserved
Setting parameter 'TimeLimit' to 100
Model fingerprint: ab1d09db
Using Cardinal Optimizer v7.1.3 on Windows
Hardware has 4 cores and 8 threads. Using instruction set X86_AVX512_E1 (14)
Minimizing an LP problem
The original problem has:
15 rows, 9 columns and 27 non-zero elements
The presolved problem has:
6 rows, 9 columns and 18 non-zero elements
Starting the simplex solver using up to 8 threads
Method Iteration Objective Primal.NInf Dual.NInf Time
Dual 0 0.0000000000e+00 6 0 0.01s
Dual 4 6.5000612544e+05 0 0 0.01s
Postsolving
Dual 4 6.5000000000e+05 0 0 0.01s
Solving finished
Status: Optimal Objective: 6.5000000000e+05 Iterations: 4 Time: 0.01s
Objective value: 650000.0
Variable solution:
19.000000 =
13.000000 =
7.000000 =
12.000000 =
结果很明显了吧,很典型的混合整数规划,我们终于初步尝试了代码,感谢杉数官方案例。