Search code examples
jupyter-notebookjupyteror-toolscp-sat

How to set both a time and solution limit in OR-Tools?


I am using OR-Tools for some simple solving, but I am really confused on how you used SolveWithTimeLimitSampleSat and StopAfterNSolutionsSampleSat. I want the solver to try and find the 2 solutions, but I want it to stop after x amount of time if it hasn't found 2. The documentation on the google website is not helpful to say the least, it doesn't tell me the parameters for any of these functions nor an example. I tried using VarArraySolutionPrinterWithLimit but jupyter did not recognise this function, nor does my solver recognise either of the first 2 functions. Can anyone explain what I am meant to be placing in between the marked code below to get the aformentioned result?

    solver = cp_model.CpSolver()

    ### Something goes here ###

    status = solver.Solve(model)
    
    if status in [cp_model.OPTIMAL, cp_model.FEASIBLE]:
        for i in range(0, 30):
            print(f'{i + 1} is {solver.Value(Car[i]) + 1}')
    else:
        print('unsat')

Solution

  • Everything is explained in the docs directory.

    Explicitly https://github.com/google/or-tools/blob/stable/ortools/sat/docs/solver.md

    For instance, to set a time limit, just set a parameter after creating the solver and before calling solve:

        # Creates a solver and solves the model.
        solver = cp_model.CpSolver()
    
        # Sets a time limit of 10 seconds.
        solver.parameters.max_time_in_seconds = 10.0
    
        status = solver.Solve(model)