I have a Cplex model with several constraints and a solution pool. One of my constraint is :
R_alt=[i for i in R if i not in SetAlt]
model.add_constraints((model.sum(x[i, j] for j in R2 ) == 2 for i in R_alt),"6C" )
model.add_constraints((x[i, n1-4] ==x[i, n1-2] for i in R_alt ),"7C" )
SetAlt is a set of 2 values that will be removed from R_alt before making the constraint. I need these 2 values to be picked randomly by the cplex for each solution. In other words, I need cplex to change the model on this constraint during solution pool generation.
For example if I have 6C on R_alt=[0,1,2,3,6,7,8] in one solution, I get R_alt=[0,2,3,4,5,6,8] in another solution.
Before, I was using python random for picking this SetAlt but the problem was that I had the same SetAlt in all solutions.
in https://github.com/AlexFleischerParis/zoodocplex/blob/master/zoomontecarlooptimization.py
import random
import math
random.seed(1)
from docplex.mp.model import Model
# original model
nbKids=300
mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
costBus40=500.0;
costBus30=400.0;
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= nbKids, 'kids')
mdl.minimize(nbbus40*costBus40 + nbbus30*costBus30)
nbSamples=20
nbMaxKidsAbsent=30;
nbKidsLess=[random.randint(0,nbMaxKidsAbsent) for i in range(0,nbSamples)]
nbKidsOptions=[nbKids-nbKidsLess[i] for i in range(0,nbSamples)]
#Monte Carlo optimization
totalCost=0.0;
for i in range(0,nbSamples):
mdl.get_constraint_by_name("kids").rhs=nbKidsOptions[i]
mdl.solve()
cost=mdl.solution.get_objective_value()
totalCost+=cost
print("if we need to bring ",nbKidsOptions[i]," kids to the zoo");
print("cost = ",cost)
print()
averageCost=1/nbSamples*totalCost
print("------------------------------");
print("average cost = ",math.ceil(averageCost));
you may find an example of changing a constraint and solving again:
mdl.get_constraint_by_name("kids").rhs=nbKidsOptions[i]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.