How to use the ortools.sat.python.cp_model.OPTIMAL 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 / tasks_and_workers_assignment_sat.py View on Github external
# All workers are assigned.
    model.Add(sum(num_workers_in_group) == num_workers)

    # Objective.
    obj = model.NewIntVar(0, sum_of_costs * scaling, 'obj')
    model.AddMaxEquality(obj, averages)
    model.Minimize(obj)

    # Solve and print out the solution.
    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = 60 * 60 * 2
    objective_printer = ObjectivePrinter()
    status = solver.SolveWithSolutionCallback(model, objective_printer)
    print(solver.ResponseStats())

    if status == cp_model.OPTIMAL:
        for j in all_groups:
            print('Group %i' % j)
            for i in all_workers:
                if solver.BooleanValue(x[i, j]):
                    print('  - worker %i' % i)
            for k in all_tasks:
                if solver.BooleanValue(y[k, j]):
                    print('  - task %i with cost %i' % (k, task_cost[k]))
            print('  - sum_of_costs = %i' %
                  (solver.Value(scaled_sum_of_costs_in_group[j]) // scaling))
            print('  - average cost = %f' %
                  (solver.Value(averages[j]) * 1.0 / scaling))
github google / or-tools / examples / python / balance_group_sat.py View on Github external
max_color = num_items_per_group // min_items_of_same_color_per_group
    # Redundant contraint: The problem does not solve in reasonable time without it.
    if max_color < num_colors:
        for g in all_groups:
            model.Add(
                sum(color_in_group[(c, g)] for c in all_colors) <= max_color)

    # Minimize epsilon
    model.Minimize(e)

    solver = cp_model.CpSolver()
    solution_printer = SolutionPrinter(values, colors, all_groups, all_items,
                                       item_in_group)
    status = solver.SolveWithSolutionCallback(model, solution_printer)

    if status == cp_model.OPTIMAL:
        print('Optimal epsilon: %i' % solver.ObjectiveValue())
        print('Statistics')
        print('  - conflicts : %i' % solver.NumConflicts())
        print('  - branches  : %i' % solver.NumBranches())
        print('  - wall time : %f s' % solver.WallTime())
    else:
        print('No solution found')
github tensorflow / mesh / mesh_tensorflow / auto_mtf / layout_optimizer.py View on Github external
Args:
      print_solution: An optional boolean indicating whether to print the full
        solution in human-readable format.

    Returns:
      The computed layout (as a string).

    Raises:
      SolverError: the internal solver could not find a solution, or the
          solution found is infeasible.
    """
    # Solve and see how well the solver did.
    self._cp_solver = cp_model.CpSolver()
    status = self._cp_solver.Solve(self._model)
    if status != cp_model.OPTIMAL:
      if status == cp_model.FEASIBLE:
        logging.warning("A potentially suboptimal solution was found.")
      else:
        logging.error("Solver returned status %d.", status)
        raise SolverError("The solver could not solve the problem and returned "
                          "status {}.".format(status))

    # TODO(joshuawang): Verify the solver's solution.
    if print_solution:
      print_cp_model_solution.print_solution(self._model, self._cp_solver)

    # Reconstruct layout from solution.
    layout = []
    for mtf_dimension_name in (
        self._layout_validator.splittable_mtf_dimension_names):
      for mesh_dimension_name in (
github google / or-tools / ortools / sat / samples / no_overlap_sample_sat.py View on Github external
weekend_2 = model.NewIntervalVar(19, 2, 21, 'weekend_2')

    # No Overlap constraint.
    model.AddNoOverlap(
        [task_0, task_1, task_2, weekend_0, weekend_1, weekend_2])

    # Makespan objective.
    obj = model.NewIntVar(0, horizon, 'makespan')
    model.AddMaxEquality(obj, [end_0, end_1, end_2])
    model.Minimize(obj)

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

    if status == cp_model.OPTIMAL:
        # Print out makespan and the start times for all tasks.
        print('Optimal Schedule Length: %i' % solver.ObjectiveValue())
        print('Task 0 starts at %i' % solver.Value(start_0))
        print('Task 1 starts at %i' % solver.Value(start_1))
        print('Task 2 starts at %i' % solver.Value(start_2))
    else:
        print('Solver exited with nonoptimal status: %i' % status)
github google / or-tools / examples / python / worker_schedule_sat.py View on Github external
sum(workers_per_shift[shift] * possible_shifts[shift][slot]
                for shift in all_shifts) >= min_number_of_workers[slot])

    # Create the objective variable.
    objective = model.NewIntVar(0, num_workers, 'objective')

    # Link the objective.
    model.Add(sum(workers_per_shift) == objective)

    # Minimize.
    model.Minimize(objective)

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

    if status == cp_model.OPTIMAL:
        print('Objective value = %i' % solver.ObjectiveValue())

    print('Statistics')
    print('  - conflicts : %i' % solver.NumConflicts())
    print('  - branches  : %i' % solver.NumBranches())
    print('  - wall time : %f s' % solver.WallTime())
github uTensor / utensor_cgen / utensor_cgen / backend / graph_lower / generic_graph_lower.py View on Github external
inter_vars[tensor] = intv_var
      tensor_allocs[tensor] = _VarMemorySpan(var_start, var_end, size)
    for tensor in tensors_to_schedule:
      inter_var = inter_vars[tensor]
      nonoverlap_vars = [inter_vars[t] 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()])
    model.Minimize(var_mempool_size)

    solver = cp_model.CpSolver()
    status = solver.Solve(model)
    alloc_plan = {}
    opt_mempool_size = None
    if status == cp_model.OPTIMAL:
      opt_mempool_size = solver.Value(var_mempool_size)
      for entity, alloc in tensor_allocs.items():
        alloc_plan[entity] = SpaceAllocation(
          offset_start=solver.Value(alloc.start),
          size=alloc.size,
          data_alignment=self.data_alignment,
        )
      logger.info('optimal tensor allocation plan solved, total memory required: %i bytes', opt_mempool_size)
      logger.info('number of tensors allocated: %i' % len(alloc_plan))
    else:
      logger.info('tensor allocation plan not found, status: %s', solver.StatusName(status))
      if status == cp_model.INFEASIBLE:
        logger.info(
          'the optimal plan is infeasible, please set `max_pool_size` a larger value: %s' % self.max_pool_size
        )
    return alloc_plan, opt_mempool_size
github google / or-tools / ortools / sat / samples / ranking_sample_sat.py View on Github external
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 / shift_scheduling_sat.py View on Github external
if output_proto:
        print('Writing proto to %s' % output_proto)
        with open(output_proto, 'w') as text_file:
            text_file.write(str(model))

    # Solve the model.
    solver = cp_model.CpSolver()
    solver.parameters.num_search_workers = 8
    if params:
        text_format.Merge(params, solver.parameters)
    solution_printer = cp_model.ObjectiveSolutionPrinter()
    status = solver.SolveWithSolutionCallback(model, solution_printer)

    # Print solution.
    if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
        print()
        header = '          '
        for w in range(num_weeks):
            header += 'M T W T F S S '
        print(header)
        for e in range(num_employees):
            schedule = ''
            for d in range(num_days):
                for s in range(num_shifts):
                    if solver.BooleanValue(work[e, s, d]):
                        schedule += shifts[s] + ' '
            print('worker %i: %s' % (e, schedule))
        print()
        print('Penalties:')
        for i, var in enumerate(obj_bool_vars):
            if solver.BooleanValue(var):
github google / or-tools / examples / python / jobshop_ft06_distance_sat.py View on Github external
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())