0

I am using Docplex (Cplex python version) with a minimization objective. As it takes a long time to find the optimum I would like to set a timelimit and receive the found solution at that time. To limit the time I have tried the following but it does not work. Can anyone give me a hint on how to implement it?

import docplex.cp.parameters as params
 
def solve_model():
     params.timelimit = 1
     result = model.solve()     

Also I have tried model.parameters.timelimit = 1

I do not get any errors. The model is solved correctly but the timelimit is exceeded.

Philippe Couronne
  • 826
  • 1
  • 5
  • 6
Mado_xx
  • 1
  • 2

2 Answers2

1

in optimization simple in python

See https://github.com/AlexFleischerParis/zoodocplex/blob/master/zoosettings.py

from docplex.mp.model import Model

mdl = Model(name='buses')

mdl.parameters.timelimit=20;
mdl.set_time_limit(20) #The same

nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

mdl.export("c:\\temp\\buses.lp")

print("time limit = ",mdl.parameters.timelimit.get())
print("time limit = ",mdl.get_time_limit()) #The same

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15
0

I hope you find it usefull.

def main():
    # Create the model
    model = Model(name='buses')

    # Create decision variables
    x = {(i, j): model.binary_var(name='x_{0}_{1}'.format(i, j)) for i in range(n) for j in range(n)}

    # Create objective
    obj = model.sum(c[i][j] * x[i, j] for i in range(n) for j in range(n))
    model.minimize(obj)

    # Add constraints
    for i in range(n):
        model.add_constraint(model.sum(x[i, j] for j in range(n)) == 1)
        model.add_constraint(model.sum(x[j, i] for j in range(n)) == 1)

    # Add time limit
    model.context.solver.time_limit = 30

    # Solve the model
    solution = model.solve()

    # Print solution
    if solution:
        print_solution(solution, x)


def print_solution(solution, x):
    print('Total cost = ', solution.objective_value)
    for i in range(n):
        for j in range(n):
            if solution[x[i, j]] > 0:
                print('x{0}_{1} = '.format(i, j), solution[x[i, j]])


if __name__ == '__main__':
    main()
Mahi
  • 332
  • 3
  • 11
  • Thank you for the quick response! I implemented it this way but unfortunately the time limit is still exceeded when solving the model. Do I have to add / import something else? – Mado_xx Oct 06 '21 at 10:59
  • Sorry, it's been a while I can't remember exactly. :/ – Mahi Oct 06 '21 at 11:02