0

I am trying to formulate and solve an optimization problem using IBM CPLEX framework using python API.

My objective function is as follows:

enter image description here

where enter image description here and enter image description here are my integer variables. I define the variables as follows in my code:

enter image description here

function f is as follows:

def f(p,n):
   if p==4 and n ==4:
        return 0.8
   elif p==4 and n ==8:
        return 0.9
   elif p==6. and n==4:
        return 0.88
   .
   .
   .

My problem:

The problem that I have is about calling function f and using the variable n in that function. Nore specifically, I can not compare this variable to a number suhc as 4 or 8 or I can not use this varibale as the index of a dictionary. The error I get is: enter image description here

I tried to implement function f as bellow:

def f (p,n):
   my_dictionary = {4:{4:0.8,8:0.9},6:{4:0.88,8:0.92}
   return    my_dictionary[p][n]

I get the error of "keyerror exception" meaning that there is no key as n in my dictionary.

How can I pass the value of my variable to a function and use that value there?

1 Answers1

1

You could use logical constraints:

from docplex.mp.model import Model

mdl = Model(name='test')


n = mdl.integer_var(name='n')
p = mdl.integer_var(name='p')
restimes100=mdl.integer_var(name='restimes100')
res=mdl.continuous_var(name='res')

def f(p,n):
   if p==4 and n ==4:
        return 0.8
   elif p==4 and n ==8:
        return 0.9
   elif p==6. and n==4:
        return 0.88

mdl.add( mdl.logical_and(p==4,n ==4)==(restimes100==80))
mdl.add( mdl.logical_and(p==4,n ==8)==(restimes100==90))
mdl.add( mdl.logical_and(p==6,n ==4)==(restimes100==88))

mdl.add(p==6)
mdl.add(n==4)

mdl.add(res==restimes100*0.01)

mdl.solve()

print("res in cplex = ",res.solution_value)
print("res with f = ",f(6,4))

gives

res in cplex =  0.88
res with f =  0.88
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15
  • would you please add one objective also to your example? It would be clear to me how to use it in my context and for my problem. If you want to use my objective goal, you can set the value of lists T, K, and P as T= [0,1], K = [0,1], and P = [4,6]. I would really appreciate your help. – Shahrooz Pooryousef Mar 14 '22 at 19:46
  • I have a hard time understanding your solution :) the variable n is my decision variable. but here in your example, you have hardcoded the value of n to 4. And also what is the objective command here? Would you please use an objective function similar to mine? Also "p" is not a variable. – Shahrooz Pooryousef Mar 14 '22 at 20:34