How to use the ortools.sat.python.cp_model.CpModel 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 / appointments.py View on Github external
def find_combinations(durations, load_min, load_max, commute_time):
    """This methods find all valid combinations of appointments.

    This methods find all combinations of appointments such that the sum of
    durations + commute times is between load_min and load_max.

    Args:
        durations: The durations of all appointments.
        load_min: The min number of worked minutes for a valid selection.
        load_max: The max number of worked minutes for a valid selection.
        commute_time: The commute time between two appointments in minutes.

    Returns:
        A matrix where each line is a valid combinations of appointments.
    """
    model = cp_model.CpModel()
    variables = [
        model.NewIntVar(0, load_max // (duration + commute_time), '')
        for duration in durations
    ]
    terms = sum(variables[i] * (duration + commute_time)
                for i, duration in enumerate(durations))
    model.AddLinearConstraint(terms, load_min, load_max)

    solver = cp_model.CpSolver()
    solution_collector = AllSolutionCollector(variables)
    solver.SearchForAllSolutions(model, solution_collector)
    return solution_collector.combinations()
github google / or-tools / ortools / sat / samples / stop_after_n_solutions_sample_sat.py View on Github external
def StopAfterNSolutionsSampleSat():
    """Showcases calling the solver to search for small number of solutions."""
    # 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')

    # Create a solver and solve.
    solver = cp_model.CpSolver()
    solution_printer = VarArraySolutionPrinterWithLimit([x, y, z], 5)
    status = solver.SearchForAllSolutions(model, solution_printer)
    print('Status = %s' % solver.StatusName(status))
    print('Number of solutions found: %i' % solution_printer.solution_count())
    assert solution_printer.solution_count() == 5
github google / or-tools / examples / python / hidato_sat.py View on Github external
def solve_hidato(puzzle, index):
    """Solve the given hidato table."""
    # Create the model.
    model = cp_model.CpModel()

    r = len(puzzle)
    c = len(puzzle[0])
    if not visualization.RunFromIPython():
        print('')
        print('----- Solving problem %i -----' % index)
        print('')
        print(('Initial game (%i x %i)' % (r, c)))
        print_matrix(puzzle)

    #
    # declare variables
    #
    positions = [
        model.NewIntVar(0, r * c - 1, 'p[%i]' % i) for i in range(r * c)
    ]
github google / or-tools / examples / python / assignment_with_constraints_sat.py View on Github external
[0, 1, 0, 1],  # Workers 9, 11
        [0, 1, 1, 0],  # Workers 9, 10
        [1, 0, 1, 0],  # Workers 8, 10
        [1, 0, 0, 1]
    ]  # Workers 8, 11

    sizes = [10, 7, 3, 12, 15, 4, 11, 5]
    total_size_max = 15
    num_workers = len(cost)
    num_tasks = len(cost[1])
    all_workers = range(num_workers)
    all_tasks = range(num_tasks)

    # Model.

    model = cp_model.CpModel()
    # Variables
    selected = [[model.NewBoolVar('x[%i,%i]' % (i, j)) for j in all_tasks]
                for i in all_workers]
    works = [model.NewBoolVar('works[%i]' % i) for i in all_workers]

    # Constraints

    # Link selected and workers.
    for i in range(num_workers):
        model.AddMaxEquality(works[i], selected[i])

    # Each task is assigned to at least one worker.
    for j in all_tasks:
        model.Add(sum(selected[i][j] for i in all_workers) >= 1)

    # Total task size for each worker is at most total_size_max
github google / or-tools / ortools / sat / samples / solve_with_time_limit_sample_sat.py View on Github external
def SolveWithTimeLimitSampleSat():
    """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')
    # Adds an all-different constraint.
    model.Add(x != y)

    # 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)
github google / or-tools / examples / python / task_allocation_sat.py View on Github external
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0
    ]]

    ntasks = len(available)
    nslots = len(available[0])

    # sets
    all_tasks = range(ntasks)
    all_slots = range(nslots)

    # max tasks per time slot
    capacity = 3

    # Model
    model = cp_model.CpModel()
    assign = {}
    for task in all_tasks:
        for slot in all_slots:
            assign[(task, slot)] = model.NewBoolVar('x[%i][%i]' % (task, slot))
    count = model.NewIntVar(0, nslots, 'count')
    slot_used = [model.NewBoolVar('slot_used[%i]' % s) for s in all_slots]

    for task in all_tasks:
        model.Add(
            sum(assign[(task, slot)] for slot in all_slots
                if available[task][slot] == 1) == 1)

    for slot in all_slots:
        model.Add(
            sum(assign[(task, slot)] for task in all_tasks
                if available[task][slot] == 1) <= capacity)
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)))
github uTensor / utensor_cgen / utensor_cgen / transformer / mem_alloc.py View on Github external
def _solve_opt_plan(self, tensors_to_schedule, nonoverlap_map):
    model = cp_model.CpModel()
    inter_vars = {}
    tensor_allocs = {}
    for tensor in tensors_to_schedule:
      var_start = model.NewIntVar(0, self.max_pool_size, '{}_start'.format(tensor.name))
      var_end = model.NewIntVar(0, self.max_pool_size, '{}_end'.format(tensor.name))
      size = tensor.size * tensor.dtype.itemsize
      intv_var = model.NewIntervalVar(var_start, size, var_end, '{}_alloc'.format(tensor.name))
      inter_vars[tensor.name] = intv_var
      tensor_allocs[tensor.name] = MemorySpan(var_start, var_end, size)
    for tensor in tensors_to_schedule:
      inter_var = inter_vars[tensor.name]
      nonoverlap_vars = [inter_vars[t.name] for t in nonoverlap_map[tensor]]
      for other in nonoverlap_vars:
          model.AddNoOverlap([inter_var, other])
    var_mempool_size = model.NewIntVar(0, self.max_pool_size, 'mempool_size')
    model.AddMaxEquality(var_mempool_size, [alloc.end for alloc in tensor_allocs.values()])
github google / or-tools / examples / python / bus_driver_scheduling_flow_sat.py View on Github external
max_end_time = max(shift[4] for shift in shifts)

    print('Bus driver scheduling')
    print('  num shifts =', num_shifts)
    print('  total driving time =', total_driving_time, 'minutes')
    print('  min num drivers =', min_num_drivers)
    print('  min start time =', min_start_time)
    print('  max end time =', max_end_time)

    # We are going to build a flow from a the start of the day to the end
    # of the day.
    #
    # Along the path, we will accumulate driving time, accrued time since the
    # last break, and total working time.

    model = cp_model.CpModel()

    # Per node info
    driving_time = {}
    working_time = {}
    no_break_driving_time = {}

    incoming_literals = collections.defaultdict(list)
    outgoing_literals = collections.defaultdict(list)
    outgoing_source_literals = []
    incoming_sink_literals = []

    all_literals = []

    # Create all the shift variables before iterating on the transitions
    # between these shifts.
    for shift in range(num_shifts):
github google / or-tools / examples / python / code_samples_sat.py View on Github external
def SolvingLinearProblem():
    """CP-SAT linear solver problem."""
    # Create a model.
    model = cp_model.CpModel()

    # x and y are integer non-negative variables.
    x = model.NewIntVar(0, 17, 'x')
    y = model.NewIntVar(0, 17, 'y')
    model.Add(2 * x + 14 * y <= 35)
    model.Add(2 * x <= 7)
    obj_var = model.NewIntVar(0, 1000, 'obj_var')
    model.Add(obj_var == x + 10 * y)
    model.Maximize(obj_var)

    # Create a solver and solve.
    solver = cp_model.CpSolver()
    status = solver.Solve(model)
    if status == cp_model.OPTIMAL:
        print('Objective value: %i' % solver.ObjectiveValue())
        print()