Decision Optimization

Decision Optimization

Delivers prescriptive analytics capabilities and decision intelligence to improve decision-making.


#Analytics
#DecisionOptimization
#DecisionOptimization
 View Only
  • 1.  How to run several input parameter (r2) by using for loop in cplex with python?

    Posted 12/04/22 08:53 AM
    Dear All,

    I would like to run several input parameter for r2 in total_r2 by using CPLEX library.
    I use python with additional numpy and pandas library in pycharm.
    However, I could not get the final result (obj_lambda) for each input parameter.
    The following is the code.
    Can anyone let me know what should I do, please?

    ,,,,
    import cplex
    from docplex.mp.model import Model
    import numpy as np
    import pandas as pd

    mdl = Model(name='Scheduling')
    inf = cplex.infinity
    bigM= 10000

    Total_P = 11 # number of places
    Total_T = 8 # number of transitions

    r1 = 100 #processing time for PM1 (second)
    #r2 = 200 #processing time for PM2 (second)
    r3 = 100

    v = 1 #robot moving time (second)
    w = 1 #loading or unloading time (second)

    M0 = np.array([0,1,0,1,0,1,0,0,0,0,2]).reshape(Total_P,1)
    M0_temp = M0.reshape(1,Total_P)
    M0_final = M0_temp.tolist()*Total_T



    #Parameter
    AT =np.array([[1,-1,0,0,0,0,0,0],
    [0,1,-1,0,0,0,0,0],
    [0,0,1,-1,0,0,0,0],
    [0,0,0,1,-1,0,0,0],
    [0,0,0,0,1,-1,0,0],
    [0,0,0,0,0,1,-1,0],
    [0,0,0,0,0,0,1,-1],
    [0,-1,1,0,0,0,0,0],
    [0,0,0,-1,1,0,0,0],
    [0,0,0,0,0,-1,1,0],
    [-1,1,-1,1,-1,1,-1,1]])
    AT_temp = AT.transpose()

    total_r2 = 5

    storage_PS_one = []
    storage_PS_two = []
    storage_PS_three = []
    storage_lambda = []

    places = np.array(['p1','p2','p3','p4','p5','p6','p7','p8','p9','p10','p11'])
    P_conflict = np.empty((1,Total_P), dtype = object)
    P_zero = np.empty((1,Total_P), dtype = object)

    #Define the place without conflict place
    CP = np.count_nonzero(AT, axis=1, keepdims=True) #calculate the nonzero elements for each row
    P_conflict = []
    P_zero = []

    for a in range(0, len(CP)):
    if CP[a].item(0) > 2:
    P_conflict.append(places[a])
    else:
    P_zero.append(places[a])



    for r2 in range(0,total_r2):
    h = np.array([v + w, w + r1, v + w, w + r2, v + w, w + r3, v + w, 0, 0, 0, 0]).reshape(Total_P, 1)
    obj_lambda = [ ]
    obj_lambda = mdl.integer_var(lb = 0, ub=inf, name='obj_lambda')

    x = np.array(mdl.integer_var_list(Total_T, 0, inf, name='x')).reshape(Total_T,)
    ind_x = np.where(AT[0] == 1)


    def get_index_value(input):
    data = []
    for l in range(len(P_zero)):
    ind_x = np.where(AT[l] == input)
    get_value = x[ind_x]
    data.append(get_value)
    return data


    x_in = get_index_value(1)
    x_out = get_index_value(-1)

    #constraint 16
    for l in range(len(P_zero)): #only for P non conflict
    #if x_in is not None and x_out is not None and obj_lambda is not None:
    mdl.add_constraint(x_out[l][0]-x_in[l][0] >= h[l][0] - M0[l][0]*obj_lambda)

    #Decision Var
    Z = np.empty((Total_T, Total_T), dtype = object)
    for k in range(Total_T):
    for i in range(Total_T):
    Z[k][i] = mdl.binary_var(name='Z' + str(k+1) + str(',') + str(i+1))

    storage_ZAT = []
    for k in range(Total_T):
    ZAT = np.matmul(Z[k].reshape(1,Total_T),AT_temp)
    storage_ZAT.append(ZAT) #storage_ZAT = np.append(storage_ZAT, ZAT, axis=0)

    ZAT_final = np.asarray(storage_ZAT).reshape(Total_T,Total_P)

    M = np.empty((Total_T, Total_P), dtype = object)
    for k in range(0,Total_T):
    for l in range (0,Total_P):
    if k == Total_T-1:
    M[Total_T-1][l] = M0_final[0][l]
    else:
    M[k][l] = mdl.integer_var(name='M' + str(k + 1) + str(',') + str(l + 1))

    M_prev = np.empty((Total_T, Total_P), dtype = object)
    if M is not None:
    for k in range(0,Total_T):
    for l in range (0,Total_P):
    if k is not 0:
    M_prev[k][l] = M[k-1][l]
    else:
    M_prev[0][l] = M0_final[0][l]

    #Constraint 17
    for k in range(Total_T):
    for l in range(Total_P):
    mdl.add_constraint(M[k][l] == M_prev[k][l] + ZAT_final[k][l])


    #Constraint 18
    mdl.add_constraints(mdl.sum(Z[k][i] for k in range(Total_T)) == 1 for i in range(Total_T))

    # Constraint 19
    mdl.add_constraints(mdl.sum(Z[k][i] for i in range(Total_T)) == 1 for k in range(Total_T))


    # # Parameters
    VW_temp = [[v + w]]
    VW_temp = VW_temp*Total_T
    VW = np.array(VW_temp) #eshape(Total_T,)


    #Define S
    S = np.array(mdl.integer_var_list(Total_T, 0, inf, name='S')).reshape(Total_T,1)

    #Constraint 20

    for k in range(Total_T-1):
    mdl.add_constraint(S[k][0] - S[k+1][0] <= -VW[k][0])

    # # Constraint 21
    mdl.add_constraint(S[Total_T-1][0] - (S[0][0] + obj_lambda) <=-VW[Total_T-1][0])

    x_temp = x.reshape(Total_T,1)
    #print('x_temp',x_temp)

    # Constraint 22
    for k in range(Total_T):
    for i in range(Total_T):
    mdl.add_constraint(S[k][0] - x_temp[i][0] <= (1-Z[k][i])*bigM) #why x_temp? because it is the reshape of x

    # Constraint 23
    for k in range(Total_T):
    for i in range(Total_T):
    mdl.add_constraint(S[k][0] - x_temp[i][0] >= (Z[k][i]-1)*bigM)

    mdl.minimize(obj_lambda)
    mdl.print_information()
    solver = mdl.solve() #(log_output=True)
    #if solver is not None:
    mdl.print_solution()
    #else:
    #print("Solver is error")

    storage_PS_one.append(r1)
    storage_PS_two.append(r2)
    storage_PS_three.append(r3)
    storage_lambda.append(obj_lambda)


    df_final = pd.DataFrame(list(zip(storage_PS_one, storage_PS_two, storage_PS_three, storage_lambda)),columns =['PS 1', 'PS 2', 'FS 3', 'Lambda'])

    print(df_final)
    print('storage_lambda', storage_lambda)

    ,,,,

    Thank you in advance.

    Yours sincerely,
    Nicholas​

    ------------------------------
    Nicholas Nicholas
    ------------------------------

    #DecisionOptimization


  • 2.  RE: How to run several input parameter (r2) by using for loop in cplex with python?

    Posted 12/05/22 07:08 AM
    Hi

    See montecarlo example

    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));​


    ------------------------------
    [Alex] [Fleischer]
    [Data and AI Technical Sales]
    [IBM]
    ------------------------------



  • 3.  RE: How to run several input parameter (r2) by using for loop in cplex with python?

    Posted 12/05/22 07:40 AM
    Thank you @ALEX FLEISCHER.

    In addition, do you think is it possible if me to summarize the result from CPLEX into pandas data frame? If yes, do you mind sharing an example on how to consolidate the CPLEX result to pandas data frame, please?
    I tried before, but there is no result in the pandas, thank you.

    ------------------------------
    Nicholas Nicholas
    ------------------------------



  • 4.  RE: How to run several input parameter (r2) by using for loop in cplex with python?

    Posted 12/05/22 10:59 AM
    This is more a pandas question than cplex but you can write

    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
    
    from pandas import *
    
    # Data
    
    dfResults = pandas.DataFrame(columns=['size','cost'])
    
    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)
       newRow={'size': nbKidsOptions[i], 'cost':cost}
       dfResults = dfResults.append(newRow,ignore_index=True)
    
    print()   
    averageCost=1/nbSamples*totalCost
    print("------------------------------");
    print("average cost = ",math.ceil(averageCost));
    
    print(dfResults)​
    that gives

         size    cost
    0   296.0  3800.0
    1   282.0  3700.0
    2   273.0  3500.0
    3   275.0  3500.0
    4   276.0  3500.0
    5   298.0  3800.0
    6   292.0  3800.0
    7   297.0  3800.0
    8   285.0  3700.0
    9   276.0  3500.0
    10  286.0  3700.0
    11  285.0  3700.0
    12  280.0  3500.0
    13  288.0  3700.0
    14  275.0  3500.0
    15  294.0  3800.0
    16  297.0  3800.0
    17  285.0  3700.0
    18  300.0  3800.0
    19  272.0  3500.0​



    ------------------------------
    [Alex] [Fleischer]
    [Data and AI Technical Sales]
    [IBM]
    ------------------------------