mathematical-optimizationcplexmixed-integer-programmingdocplexobjective-function

Objective function definition for MIP using docplex


import numpy as np

rnd = np.random
rnd.seed(0)

n = 6
t = [i for i in range(1, n)] 
V = [0] + [i for i in range(1, n + 1)]  
o = 5  
operator = [o for o in range(1, o)]


precedence = [[1, 2], [1, 3], [3, 5], [2, 4], [4, 5], [4, 6], [5, 7], [6, 7]]
cost = {(1, 2): 0, (1, 3): 0, (3, 5): 4, (2, 4): 8, (4, 5): 6, (4, 6): 10, (5, 7): 0, (6, 7): 0}

arc = [(i, j) for (i, j) in precedence]

from docplex.mp.model import Model

model = Model('EWA')
x = model.binary_var_dict((i,j,o) for i, j in precedence for o in operator)
model.minimize(model.sum(x[i,j,o]*cost.get((i,j), 0) for i, j in precedence))

Traceback (most recent call last):
  File "C:\Users\karaba02\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3369, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-7426e90af4f8>", line 1, in <cell line: 1>
    runfile('C:\\Users\\karaba02\\PycharmProjects\\pythonProject\\ergonomic_work_assignment.py', wdir='C:\\Users\\karaba02\\PycharmProjects\\pythonProject')
  File "C:\Program Files\JetBrains\PyCharm 2022.2.2\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2022.2.2\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\karaba02\PycharmProjects\pythonProject\ergonomic_work_assignment.py", line 37, in <module>
    model.minimize(model.sum(x[i,j,o]*cost.get((i,j), 0) for i in precedence for j in precedence))
  File "C:\Users\karaba02\Anaconda3\lib\site-packages\docplex\mp\model.py", line 3268, in sum
    return self._aggregator.sum(args)
  File "C:\Users\karaba02\Anaconda3\lib\site-packages\docplex\mp\aggregator.py", line 198, in sum
    sum_res = self._sum_with_iter(sum_args)
  File "C:\Users\karaba02\Anaconda3\lib\site-packages\docplex\mp\aggregator.py", line 221, in _sum_with_iter
    for item in args:
  File "C:\Users\karaba02\PycharmProjects\pythonProject\ergonomic_work_assignment.py", line 37, in <genexpr>
    model.minimize(model.sum(x[i,j,o]*cost.get((i,j), 0) for i in precedence for j in precedence))
TypeError: unhashable type: 'list'

I am taking given error because of objective functio as unhashable type: 'list' It could be related to defining cost but I coul not solve it. Could you please define the error on objective function?


Solution

  • You face an out of bounds

    If you turn

    operator = [o for o in range(1, o)]
    

    into

    operator = [o for o in range(1, o+1)]
    

    Then you model works much better