How to use the ortools.sat.python.cp_model.CpSolver function in ortools

To help you get started, we’ve selected a few ortools examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / or-tools / examples / python / clustering_sat.py View on Github external
# Enforce transivity on all triplets.
    for n1 in range(num_nodes - 2):
        for n2 in range(n1 + 1, num_nodes - 1):
            for n3 in range(n2 + 1, num_nodes):
                model.Add(
                    neighbors[n1, n3] + neighbors[n2, n3] + neighbors[n1, n2] != 2)

    # Redundant constraints on total sum of neighborss.
    model.Add(sum(obj_vars) == num_groups * group_size * (group_size - 1) // 2)

    # Minimize weighted sum of arcs.
    model.Minimize(
        sum(obj_vars[i] * obj_coeffs[i] for i in range(len(obj_vars))))

    # Solve and print out the solution.
    solver = cp_model.CpSolver()
    solver.parameters.log_search_progress = True
    solver.parameters.num_search_workers = 8

    status = solver.Solve(model)
    print(solver.ResponseStats())

    visited = set()
    for g in range(num_groups):
        for n in range(num_nodes):
            if not n in visited:
                visited.add(n)
                output = str(n)
                for o in range(n + 1, num_nodes):
                    if solver.BooleanValue(neighbors[n, o]):
                        visited.add(o)
                        output += ' ' + str(o)
github google / or-tools / examples / python / jobshop_ft06_distance_sat.py View on Github external
model.AddCircuit(arcs)

    # Precedences inside a job.
    for i in all_jobs:
        for j in range(0, machines_count - 1):
            model.Add(all_tasks[(i, j + 1)].start >= all_tasks[(i, j)].end)

    # Makespan objective.
    obj_var = model.NewIntVar(0, horizon, 'makespan')
    model.AddMaxEquality(
        obj_var, [all_tasks[(i, machines_count - 1)].end for i in all_jobs])
    model.Minimize(obj_var)

    # Solve model.
    solver = cp_model.CpSolver()
    status = solver.Solve(model)

    # Output solution.
    if status == cp_model.OPTIMAL:
        print('Optimal makespan: %i' % solver.ObjectiveValue())
github google / or-tools / examples / python / nqueens_sat.py View on Github external
# No two queens can be on the same diagonal.
    diag1 = []
    diag2 = []
    for i in range(board_size):
        q1 = model.NewIntVar(0, 2 * board_size, 'diag1_%i' % i)
        q2 = model.NewIntVar(-board_size, board_size, 'diag2_%i' % i)
        diag1.append(q1)
        diag2.append(q2)
        model.Add(q1 == queens[i] + i)
        model.Add(q2 == queens[i] - i)
    model.AddAllDifferent(diag1)
    model.AddAllDifferent(diag2)

    ### Solve model.
    solver = cp_model.CpSolver()
    solution_printer = NQueenSolutionPrinter(queens)
    status = solver.SearchForAllSolutions(model, solution_printer)

    print()
    print('Statistics')
    print('  - conflicts       : %i' % solver.NumConflicts())
    print('  - branches        : %i' % solver.NumBranches())
    print('  - wall time       : %f s' % solver.WallTime())
    print('  - solutions found : %i' % solution_printer.solution_count())
github google / or-tools / examples / python / bus_driver_scheduling_flow_sat.py View on Github external
incoming_literals[other].append(lit)

    # Create dag constraint.
    for shift in range(num_shifts):
        model.Add(sum(outgoing_literals[shift]) == 1)
        model.Add(sum(incoming_literals[shift]) == 1)

    # Num drivers
    num_drivers = model.NewIntVar(min_num_drivers, min_num_drivers * 3, 'num_drivers')
    model.Add(sum(incoming_sink_literals) == num_drivers)
    model.Add(sum(outgoing_source_literals) == num_drivers)

    model.Minimize(num_drivers)      

    # Solve model.
    solver = cp_model.CpSolver()
    solver.parameters.log_search_progress = True
    #solver.parameters.num_search_workers = 16
    # solver.parameters.boolean_encoding_level = 0
    # solver.parameters.lns_focus_on_decision_variables = True
    status = solver.Solve(model)

    if status != cp_model.OPTIMAL and status != cp_model.FEASIBLE:
        return -1

    # Display solution
    optimal_num_drivers = int(solver.ObjectiveValue())
    print('minimal number of drivers =', optimal_num_drivers)
    return optimal_num_drivers
github google / or-tools / ortools / sat / samples / simple_solve_sample_sat.py View on Github external
def SimpleSolveSampleSat():
    """Minimal CP-SAT example to showcase calling the solver."""
    # Creates the model.
    model = cp_model.CpModel()
    # Creates the variables.
    num_vals = 3
    x = model.NewIntVar(0, num_vals - 1, 'x')
    y = model.NewIntVar(0, num_vals - 1, 'y')
    z = model.NewIntVar(0, num_vals - 1, 'z')
    # Creates the constraints.
    model.Add(x != y)

    # Creates a solver and solves the model.
    solver = cp_model.CpSolver()
    status = solver.Solve(model)

    if status == cp_model.FEASIBLE:
        print('x = %i' % solver.Value(x))
        print('y = %i' % solver.Value(y))
        print('z = %i' % solver.Value(z))
github google / or-tools / ortools / sat / samples / ranking_sample_sat.py View on Github external
# Creates makespan variable.
    makespan = model.NewIntVar(0, horizon, 'makespan')
    for t in all_tasks:
        if presences[t] == 1:
            model.Add(ends[t] <= makespan)
        else:
            model.Add(ends[t] <= makespan).OnlyEnforceIf(presences[t])

    # Minimizes makespan - fixed gain per tasks performed.
    # As the fixed cost is less that the duration of the last interval,
    # the solver will not perform the last interval.
    model.Minimize(2 * makespan - 7 * sum(presences[t] for t in all_tasks))

    # Solves the model model.
    solver = cp_model.CpSolver()
    status = solver.Solve(model)

    if status == cp_model.OPTIMAL:
        # Prints out the makespan and the start times and ranks of all tasks.
        print('Optimal cost: %i' % solver.ObjectiveValue())
        print('Makespan: %i' % solver.Value(makespan))
        for t in all_tasks:
            if solver.Value(presences[t]):
                print('Task %i starts at %i with rank %i' %
                      (t, solver.Value(starts[t]), solver.Value(ranks[t])))
            else:
                print('Task %i in not performed and ranked at %i' %
                      (t, solver.Value(ranks[t])))
    else:
        print('Solver exited with nonoptimal status: %i' % status)
github google / or-tools / examples / python / sudoku_sat.py View on Github external
one_cell = []
            for di in cell:
                for dj in cell:
                    one_cell.append(grid[(i * cell_size + di,
                                          j * cell_size + dj)])

            model.AddAllDifferent(one_cell)

    # Initial values.
    for i in line:
        for j in line:
            if initial_grid[i][j]:
                model.Add(grid[(i, j)] == initial_grid[i][j])

    # Solve and print out the solution.
    solver = cp_model.CpSolver()
    status = solver.Solve(model)
    if status == cp_model.FEASIBLE:
        for i in line:
            print([int(solver.Value(grid[(i, j)])) for j in line])
github google / or-tools / examples / python / gate_scheduling_sat.py View on Github external
model.AddCumulative(intervals, demands, max_length)

    # Choose which machine to perform the jobs on.
    model.AddNoOverlap(intervals0)
    model.AddNoOverlap(intervals1)

    # Objective variable.
    makespan = model.NewIntVar(0, horizon, 'makespan')
    model.AddMaxEquality(makespan, ends)
    model.Minimize(makespan)

    # Symmetry breaking.
    model.Add(performed[0] == 0)

    # Solve model.
    solver = cp_model.CpSolver()
    solver.Solve(model)

    # Output solution.
    if visualization.RunFromIPython():
        output = visualization.SvgWrapper(solver.ObjectiveValue(), max_length,
                                          40.0)
        output.AddTitle('Makespan = %i' % solver.ObjectiveValue())
        color_manager = visualization.ColorManager()
        color_manager.SeedRandomColor(0)

        for i in all_jobs:
            performed_machine = 1 - solver.Value(performed[i])
            start = solver.Value(starts[i])
            d_x = jobs[i][0]
            d_y = jobs[i][1]
            s_y = performed_machine * (max_length - d_y)
github google / or-tools / ortools / sat / samples / rabbits_and_pheasants_sat.py View on Github external
def RabbitsAndPheasantsSat():
    """Solves the rabbits + pheasants problem."""
    model = cp_model.CpModel()

    r = model.NewIntVar(0, 100, 'r')
    p = model.NewIntVar(0, 100, 'p')

    # 20 heads.
    model.Add(r + p == 20)
    # 56 legs.
    model.Add(4 * r + 2 * p == 56)

    # Solves and prints out the solution.
    solver = cp_model.CpSolver()
    status = solver.Solve(model)

    if status == cp_model.FEASIBLE:
        print('%i rabbits and %i pheasants' %
              (solver.Value(r), solver.Value(p)))