How to use the ortools.sat.python.cp_model.FEASIBLE 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 samsquire / devops-pipeline / devops_pipeline / component_scheduler / scheduler.py View on Github external
for ancestor in component["ancestors"]:
            model.Add(component_vars[ancestor].start < this_var.start)
        for successor in component["successors"]:
            model.Add(component_vars[successor].start > this_var.start)
        successor_lookup[component["name"]] = component["successors"]

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

    orderings = collections.defaultdict(list)
    positions = {}
    roots = []
    threads = []
    thread_list = []
    if status == cp_model.FEASIBLE or status == cp_model.OPTIMAL:
        for component in component_data:
            position = solver.Value(component_vars[component["name"]].start)
            positions[component["name"]] = position
            component["position"] = position
            orderings[position].append(component["name"])

        highest = max(positions.values())
        items = list(orderings.keys())
        results = []

        pprint(results)

    return list(sorted(component_data, key=lambda item: item["position"])), orderings
github google / or-tools / examples / python / cover_rectangle_sat.py View on Github external
model.Add(sizes[i] < sizes[i + 1]).OnlyEnforceIf(same.Not())

        # Tie break with starts.
        model.Add(x_starts[i] <= x_starts[i + 1]).OnlyEnforceIf(same)

    # Symmetry breaking 2: first square in one quadrant.
    model.Add(x_starts[0] < 36)
    model.Add(y_starts[0] < 19)

    # Creates a solver and solves.
    solver = cp_model.CpSolver()
    status = solver.Solve(model)
    print('%s found in %0.2fs' % (solver.StatusName(status), solver.WallTime()))

    # Prints solution.
    if status == cp_model.FEASIBLE:
        display = [[' ' for _ in range(size_x)] for _ in range(size_y)]
        for i in range(num_squares):
            sol_x = solver.Value(x_starts[i])
            sol_y = solver.Value(y_starts[i])
            sol_s = solver.Value(sizes[i])
            char = format(i, '01x')
            for j in range(sol_s):
                for k in range(sol_s):
                    if display[sol_y + j][sol_x + k] != ' ':
                        print('ERROR between %s and %s' %
                              (display[sol_y + j][sol_x + k], char))
                    display[sol_y + j][sol_x + k] = char

        for line in range(size_y):
            print(' '.join(display[line]))
    return status == cp_model.FEASIBLE
github google / or-tools / examples / python / bus_driver_scheduling_sat.py View on Github external
if minimize_drivers:
        # Minimize the number of working drivers
        model.Minimize(sum(working_drivers))
    else:
        # Minimize the sum of delays between tasks, which in turns minimize the
        # sum of working times as the total driving time is fixed
        model.Minimize(
            cp_model.LinearExpr.ScalProd(delay_literals, delay_weights))

    # Solve model.
    solver = cp_model.CpSolver()
    solver.parameters.log_search_progress = True # not minimize_drivers
    solver.parameters.num_search_workers = 8
    status = solver.Solve(model)

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

    # Display solution
    if minimize_drivers:
        max_num_drivers = int(solver.ObjectiveValue())
        print('minimal number of drivers =', max_num_drivers)
        return max_num_drivers

    for d in range(num_drivers):
        print('Driver %i: ' % (d + 1))
        print('  total driving time =', solver.Value(driving_times[d]))
        print('  working time =',
              solver.Value(working_times[d]) + setup_time + cleanup_time)

        first = True
        for s in range(num_shifts):
github google / or-tools / examples / python / scheduling_with_transitions_sat.py View on Github external
print('Writing proto to %s' % output_proto)
    with open(output_proto, 'w') as text_file:
      text_file.write(str(model))

  #----------------------------------------------------------------------------
  # Solve.
  solver = cp_model.CpSolver()
  solver.parameters.max_time_in_seconds = 60 * 60 * 2
  if parameters:
    text_format.Merge(parameters, solver.parameters)
  solution_printer = SolutionPrinter(makespan)
  status = solver.SolveWithSolutionCallback(model, solution_printer)

  #----------------------------------------------------------------------------
  # Print solution.
  if status == cp_model.FEASIBLE or status == cp_model.OPTIMAL:
    for job_id in all_jobs:
      for task_id in range(len(jobs[job_id])):
        start_value = solver.Value(job_starts[(job_id, task_id)])
        machine = 0
        duration = 0
        select = 0
        rank = -1

        for alt_id in range(len(jobs[job_id][task_id])):
          if jobs[job_id][task_id][alt_id][0] == -1:
            continue

          if solver.BooleanValue(job_presences[(job_id, task_id, alt_id)]):
            duration = jobs[job_id][task_id][alt_id][0]
            machine = jobs[job_id][task_id][alt_id][1]
            select = alt_id
github google / or-tools / ortools / sat / samples / rabbits_and_pheasants_sat.py View on Github external
"""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 google / or-tools / ortools / sat / samples / simple_sat_program.py View on Github external
y = model.NewIntVar(0, num_vals - 1, 'y')
    z = model.NewIntVar(0, num_vals - 1, 'z')
    # [END variables]

    # Creates the constraints.
    # [START constraints]
    model.Add(x != y)
    # [END constraints]

    # Creates a solver and solves the model.
    # [START solve]
    solver = cp_model.CpSolver()
    status = solver.Solve(model)
    # [END solve]

    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 / examples / python / sudoku_sat.py View on Github external
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 / contrib / scheduling_with_transitions_sat.py View on Github external
print('Writing proto to %s' % output_proto)
    with open(output_proto, 'w') as text_file:
      text_file.write(str(model))

  #----------------------------------------------------------------------------
  # Solve.
  solver = cp_model.CpSolver()
  solver.parameters.max_time_in_seconds = 60 * 60 * 2
  if parameters:
    text_format.Merge(parameters, solver.parameters)
  solution_printer = SolutionPrinter(makespan)
  status = solver.SolveWithSolutionCallback(model, solution_printer)

  #----------------------------------------------------------------------------
  # Print solution.
  if status == cp_model.FEASIBLE or status == cp_model.OPTIMAL:
    for job_id in all_jobs:
      for task_id in range(len(jobs[job_id])):
        start_value = solver.Value(job_starts[(job_id, task_id)])
        machine = 0
        duration = 0
        select = 0
        rank = -1

        for alt_id in range(len(jobs[job_id][task_id])):
          if jobs[job_id][task_id][alt_id][0] == -1:
            continue

          if solver.BooleanValue(job_presences[(job_id, task_id, alt_id)]):
            duration = jobs[job_id][task_id][alt_id][0]
            machine = jobs[job_id][task_id][alt_id][1]
            select = alt_id
github google / or-tools / examples / python / zebra_sat.py View on Github external
diff_horse_kools = model.NewIntVar(-4, 4, 'diff_horse_kools')
    model.Add(diff_horse_kools == horse - kools)
    model.AddAbsEquality(1, diff_horse_kools)

    model.Add(lucky_strike == fruit_juice)
    model.Add(japanese == parliaments)

    diff_norwegian_blue = model.NewIntVar(-4, 4, 'diff_norwegian_blue')
    model.Add(diff_norwegian_blue == norwegian - blue)
    model.AddAbsEquality(1, diff_norwegian_blue)

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

    if status == cp_model.FEASIBLE:
        people = [englishman, spaniard, japanese, ukrainian, norwegian]
        water_drinker = [
            p for p in people if solver.Value(p) == solver.Value(water)
        ][0]
        zebra_owner = [
            p for p in people if solver.Value(p) == solver.Value(zebra)
        ][0]
        print('The', water_drinker.Name(), 'drinks water.')
        print('The', zebra_owner.Name(), 'owns the zebra.')
    else:
        print('No solutions to the zebra problem, this is unusual!')
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 (
          self._layout_validator.mesh_dimension_name_to_size):