update python code, remove __future__ imports, remove six, use absl-py for flags, update examples

This commit is contained in:
Laurent Perron
2020-11-18 10:50:14 +01:00
parent c1b23ffd92
commit 4ececbe448
99 changed files with 246 additions and 340 deletions

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""Generates possible daily schedules for workers."""
from __future__ import print_function
from __future__ import division
import argparse
from ortools.sat.python import cp_model

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Cutting stock problem with the objective to minimize wasted space."""
from __future__ import print_function
import argparse
import collections

View File

@@ -11,7 +11,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Solve an assignment problem with combination constraints on workers."""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -18,8 +18,6 @@ Furthermore, if one color is an a group, at least k items with this color must
be in that group.
"""
from __future__ import print_function
from __future__ import division
from ortools.sat.python import cp_model

View File

@@ -21,7 +21,6 @@ Constraints:
- 15 min cleaning time after the last shift
- 2 min waiting time after each shift for passenger boarding and alighting
"""
from __future__ import print_function
import argparse
import collections

View File

@@ -21,13 +21,23 @@ Constraints:
- 15 min cleaning time after the last shift
- 2 min waiting time after each shift for passenger boarding and alighting
"""
from __future__ import print_function
import collections
import math
from google.protobuf import text_format
from absl import app
from absl import flags
from ortools.sat.python import cp_model
FLAGS = flags.FLAGS
flags.DEFINE_string('output_proto', '',
'Output file to write the cp_model proto to.')
flags.DEFINE_string('params', 'num_search_workers:8,log_search_progress:true',
'Sat solver parameters.')
flags.DEFINE_integer('instance', 1, 'Instance to select (1, 2, 3).', 1, 3)
SAMPLE_SHIFTS_SMALL = [
#
# column description:
@@ -1652,22 +1662,39 @@ SAMPLE_SHIFTS_LARGE = [
[1355, '00:57', '01:07', 1497, 1507, 10]
] # yapf:disable
SAMPLE_SHIFTS = SAMPLE_SHIFTS_MEDIUM
# pytype: disable=wrong-arg-types
def bus_driver_scheduling(minimize_drivers, max_num_drivers):
"""Optimize the bus driver scheduling problem.
This model has two modes.
This model has two modes.
If minimize_drivers == True, the objective will be to find the minimal
number of drivers, independently of the working times of each drivers.
If minimize_drivers == True, the objective will be to find the minimal
number of drivers, independently of the working times of each drivers.
Otherwise, will will create max_num_drivers non optional drivers, and
minimize the sum of working times of these drivers.
"""
num_shifts = len(SAMPLE_SHIFTS)
Otherwise, will will create max_num_drivers non optional drivers, and
minimize the sum of working times of these drivers.
Args:
minimize_drivers: A Boolean parameter specifying the objective of the
problem. If True, it tries to minimize the number of used drivers. If
false, it minimizes the sum of working times per workers.
max_num_drivers: This number specifies the exact number of non optional
drivers to use. This is only used if 'minimize_drivers' is False.
Returns:
The objective value of the model.
"""
shifts = None
if FLAGS.instance == 1:
shifts = SAMPLE_SHIFTS_SMALL
elif FLAGS.instance == 2:
shifts = SAMPLE_SHIFTS_MEDIUM
elif FLAGS.instance == 3:
shifts = SAMPLE_SHIFTS_LARGE
num_shifts = len(shifts)
# All durations are in minutes.
max_driving_time = 540 # 8 hours.
@@ -1680,12 +1707,12 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
cleanup_time = 15
# Computed data.
total_driving_time = sum(shift[5] for shift in SAMPLE_SHIFTS)
min_num_drivers = int(
math.ceil(total_driving_time * 1.0 / max_driving_time))
total_driving_time = sum(shift[5] for shift in shifts)
min_num_drivers = int(math.ceil(total_driving_time * 1.0 /
max_driving_time))
num_drivers = 2 * min_num_drivers if minimize_drivers else max_num_drivers
min_start_time = min(shift[3] for shift in SAMPLE_SHIFTS)
max_end_time = max(shift[4] for shift in SAMPLE_SHIFTS)
min_start_time = min(shift[3] for shift in shifts)
max_end_time = max(shift[4] for shift in shifts)
print('Bus driver scheduling')
print(' num shifts =', num_shifts)
@@ -1760,7 +1787,7 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
performed[d, s] = model.NewBoolVar('performed_%i_%i' % (d, s))
for s in range(num_shifts):
shift = SAMPLE_SHIFTS[s]
shift = shifts[s]
duration = shift[5]
# Arc from source to shift.
@@ -1772,10 +1799,9 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
shared_incoming_literals[s].append(source_lit)
model.Add(start_times[d] == shift[3] -
setup_time).OnlyEnforceIf(source_lit)
model.Add(
total_driving[d, s] == duration).OnlyEnforceIf(source_lit)
model.Add(
no_break_driving[d, s] == duration).OnlyEnforceIf(source_lit)
model.Add(total_driving[d, s] == duration).OnlyEnforceIf(source_lit)
model.Add(no_break_driving[d,
s] == duration).OnlyEnforceIf(source_lit)
starting_shifts[d, s] = source_lit
# Arc from shift to sink
@@ -1787,14 +1813,15 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
incoming_sink_literals.append(sink_lit)
model.Add(end_times[d] == shift[4] +
cleanup_time).OnlyEnforceIf(sink_lit)
model.Add(driving_times[d] == total_driving[d, s]).OnlyEnforceIf(
sink_lit)
model.Add(
driving_times[d] == total_driving[d, s]).OnlyEnforceIf(sink_lit)
# Node not performed
# - set both driving times to 0
# - add a looping arc on the node
model.Add(total_driving[d, s] == 0).OnlyEnforceIf(
performed[d, s].Not())
model.Add(total_driving[d,
s] == 0).OnlyEnforceIf(performed[d,
s].Not())
model.Add(no_break_driving[d, s] == 0).OnlyEnforceIf(
performed[d, s].Not())
incoming_literals[s].append(performed[d, s].Not())
@@ -1811,7 +1838,7 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
performed[d, s])
for o in range(num_shifts):
other = SAMPLE_SHIFTS[o]
other = shifts[o]
delay = other[3] - shift[4]
if delay < min_delay_between_shifts:
continue
@@ -1826,9 +1853,8 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
model.Add(
no_break_driving[d, o] == other[5]).OnlyEnforceIf(lit)
else:
model.Add(
no_break_driving[d, o] == no_break_driving[d, s] +
other[5]).OnlyEnforceIf(lit)
model.Add(no_break_driving[d, o] == no_break_driving[d, s] +
other[5]).OnlyEnforceIf(lit)
# Add arc
outgoing_literals[s].append(lit)
@@ -1890,26 +1916,32 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
working_drivers[d + 1].Not())
# Redundant constraints: sum of driving times = sum of shift driving times
model.Add(sum(driving_times) == total_driving_time)
model.Add(cp_model.LinearExpr.Sum(driving_times) == total_driving_time)
if not minimize_drivers:
model.Add(
sum(working_times) == total_driving_time +
cp_model.LinearExpr.Sum(working_times) == total_driving_time +
num_drivers * (setup_time + cleanup_time) +
cp_model.LinearExpr.ScalProd(delay_literals, delay_weights))
if minimize_drivers:
# Minimize the number of working drivers
model.Minimize(sum(working_drivers))
model.Minimize(cp_model.LinearExpr.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))
if not minimize_drivers and FLAGS.output_proto:
print('Writing proto to %s' % FLAGS.output_proto)
with open(FLAGS.output_proto, 'w') as text_file:
text_file.write(str(model))
# Solve model.
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True # not minimize_drivers
solver.parameters.num_search_workers = 8
if FLAGS.params:
text_format.Parse(FLAGS.params, solver.parameters)
status = solver.Solve(model)
if status != cp_model.OPTIMAL and status != cp_model.FEASIBLE:
@@ -1929,7 +1961,7 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
first = True
for s in range(num_shifts):
shift = SAMPLE_SHIFTS[s]
shift = shifts[s]
if not solver.BooleanValue(performed[d, s]):
continue
@@ -1939,18 +1971,22 @@ def bus_driver_scheduling(minimize_drivers, max_num_drivers):
# no_break_driving which was reinitialized in that case.
if solver.Value(no_break_driving[d, s]) == shift[5] and not first:
print(' **break**')
print(' shift ', shift[0], ':', shift[1], "-", shift[2])
print(' shift ', shift[0], ':', shift[1], '-', shift[2])
first = False
return int(solver.ObjectiveValue())
def optimize_bus_driver_allocation():
def main(_):
"""Optimize the bus driver allocation in two passes."""
print('----------- first pass: minimize the number of drivers')
num_drivers = bus_driver_scheduling(True, -1)
print('----------- second pass: minimize the sum of working times')
bus_driver_scheduling(False, num_drivers)
if num_drivers == -1:
print('no solution found, skipping the final step')
else:
print('----------- second pass: minimize the sum of working times')
bus_driver_scheduling(False, num_drivers)
optimize_bus_driver_allocation()
if __name__ == '__main__':
app.run(main)

View File

@@ -17,8 +17,6 @@
# Furthermore, if one color is an a group, at least k items with this color must
# be in that group.
from __future__ import print_function
from __future__ import division
from ortools.linear_solver import pywraplp

View File

@@ -17,8 +17,6 @@
# Furthermore, if one color is an a group, at least k items with this color must
# be in that group.
from __future__ import print_function
from __future__ import division
from ortools.sat.python import cp_model
import math

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""Cluster 40 cities in 4 equal groups to minimize sum of crossed distances."""
from __future__ import print_function
from __future__ import division
from ortools.sat.python import cp_model

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""Fill a 72x37 rectangle by a minimum number of non-overlapping squares."""
from __future__ import print_function
from __future__ import division
from ortools.sat.python import cp_model

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Solves a flexible jobshop problems with the CP-SAT solver."""
from __future__ import print_function
import collections
from ortools.sat.python import cp_model

View File

@@ -20,14 +20,18 @@ between all marks are all different. The objective is to minimize the length
of the rule.
"""
from absl import app
from absl import flags
from ortools.constraint_solver import pywrapcp
FLAGS = flags.FLAGS
# We disable the following warning because it is a false positive on constraints
# like: solver.Add(x == 0)
# pylint: disable=g-explicit-bool-comparison
def main():
def main(_):
# Create the solver.
solver = pywrapcp.Solver('golomb ruler')
@@ -40,11 +44,13 @@ def main():
objective = solver.Minimize(marks[size - 1], 1)
solver.Add(marks[0] == 0)
solver.Add(
solver.AllDifferent([
marks[j] - marks[i]
for i in range(0, size - 1) for j in range(i + 1, size)
]))
# We expand the creation of the diff array to avoid a pylint warning.
diffs = []
for i in range(0, size - 1):
for j in range(i + 1, size):
diffs.append(marks[j] - marks[i])
solver.Add(solver.AllDifferent(diffs))
solver.Add(marks[size - 1] - marks[size - 2] > marks[1] - marks[0])
for i in range(0, size - 2):
@@ -72,4 +78,4 @@ def main():
if __name__ == '__main__':
main()
app.run(main)

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""Solves the Hidato problem with the CP-SAT solver."""
from __future__ import print_function
from ortools.sat.python import visualization
from ortools.sat.python import cp_model
@@ -31,13 +29,16 @@ def build_pairs(rows, cols):
rows: the number of rows in the grid
cols: the number of columns in the grid
"""
return [
(x * cols + y, (x + dx) * cols + (y + dy)) for x in range(rows)
for y in range(cols) for dx in (-1, 0, 1)
for dy in (-1, 0, 1)
if (x + dx >= 0 and x + dx < rows and y + dy >= 0 and y + dy < cols and
(dx != 0 or dy != 0))
]
result = []
for x in range(rows):
for y in range(cols):
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if (x + dx >= 0 and x + dx < rows and y + dy >= 0 and
y + dy < cols and (dx != 0 or dy != 0)):
result.append(
(x * cols + y, (x + dx) * cols + (y + dy)))
return result
def print_solution(positions, rows, cols):
@@ -83,8 +84,8 @@ def build_puzzle(problem):
elif problem == 2:
puzzle = [[0, 44, 41, 0, 0, 0, 0], [0, 43, 0, 28, 29, 0, 0],
[0, 1, 0, 0, 0, 33, 0], [0, 2, 25, 4, 34, 0, 36],
[49, 16, 0, 23, 0, 0, 0], [0, 19, 0, 0, 12, 7,
0], [0, 0, 0, 14, 0, 0, 0]]
[49, 16, 0, 23, 0, 0, 0], [0, 19, 0, 0, 12, 7, 0],
[0, 0, 0, 14, 0, 0, 0]]
elif problem == 3:
# Problems from the book:
@@ -106,10 +107,9 @@ def build_puzzle(problem):
elif problem == 6:
# Problem 15 (Intermediate)
puzzle = [[64, 0, 0, 0, 0, 0, 0, 0], [1, 63, 0, 59, 15, 57, 53, 0],
[0, 4, 0, 14, 0, 0, 0, 0], [3, 0, 11, 0, 20, 19, 0,
50], [0, 0, 0, 0, 22, 0, 48, 40],
[9, 0, 0, 32, 23, 0, 0, 41], [27, 0, 0, 0, 36, 0, 46,
0], [28, 30, 0, 35, 0, 0, 0, 0]]
[0, 4, 0, 14, 0, 0, 0, 0], [3, 0, 11, 0, 20, 19, 0, 50],
[0, 0, 0, 0, 22, 0, 48, 40], [9, 0, 0, 32, 23, 0, 0, 41],
[27, 0, 0, 0, 36, 0, 46, 0], [28, 30, 0, 35, 0, 0, 0, 0]]
return puzzle
@@ -172,8 +172,8 @@ def solve_hidato(puzzle, index):
output.AddRectangle(x, r - y - 1, 1, 1, color, 'black',
str(i + 1))
output.AddTitle('Puzzle %i solved in %f s' % (index,
solver.WallTime()))
output.AddTitle('Puzzle %i solved in %f s' %
(index, solver.WallTime()))
output.Display()
else:
print_solution(

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""Integer programming examples that show how to use the APIs."""
from __future__ import print_function
from ortools.linear_solver import pywraplp

View File

@@ -24,8 +24,6 @@ This variation introduces a minimum distance between all the jobs on each
machine.
"""
from __future__ import print_function
import collections
from ortools.sat.python import cp_model
@@ -66,8 +64,9 @@ def jobshop_ft06_distance():
end_var = model.NewIntVar(0, horizon, 'end_%i_%i' % (i, j))
interval_var = model.NewIntervalVar(start_var, duration, end_var,
'interval_%i_%i' % (i, j))
all_tasks[(i, j)] = task_type(
start=start_var, end=end_var, interval=interval_var)
all_tasks[(i, j)] = task_type(start=start_var,
end=end_var,
interval=interval_var)
# Create disjuctive constraints.
for i in all_machines:
@@ -102,8 +101,8 @@ def jobshop_ft06_distance():
# We add the reified precedence to link the literal with the
# times of the two tasks.
min_distance = distance_between_jobs(j1, j2)
model.Add(job_starts[j2] >=
job_ends[j1] + min_distance).OnlyEnforceIf(lit)
model.Add(job_starts[j2] >= job_ends[j1] +
min_distance).OnlyEnforceIf(lit)
model.AddCircuit(arcs)

View File

@@ -20,7 +20,6 @@ machine is task_type dependent.
The objective is to minimize the maximum completion time of all
jobs. This is called the makespan.
"""
from __future__ import print_function
import collections
@@ -58,8 +57,9 @@ def jobshop_ft06():
end_var = model.NewIntVar(0, horizon, 'end_%i_%i' % (i, j))
interval_var = model.NewIntervalVar(start_var, duration, end_var,
'interval_%i_%i' % (i, j))
all_tasks[(i, j)] = task_type(
start=start_var, end=end_var, interval=interval_var)
all_tasks[(i, j)] = task_type(start=start_var,
end=end_var,
interval=interval_var)
# Create disjuctive constraints.
machine_to_jobs = {}

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""Jobshop with maintenance tasks using the CP-SAT solver."""
from __future__ import absolute_import
from __future__ import print_function
import collections

View File

@@ -16,14 +16,13 @@
http://www.ee.oulu.fi/~mpa/matreng/eem1_2-1.htm with kCost[0][1]
modified so the optimum solution is unique.
"""
from __future__ import print_function
from absl import app
from ortools.graph import pywrapgraph
def RunAssignmentOn4x4Matrix():
"""Test linear sum assignment on a 4x4 matrix.
"""
"""Test linear sum assignment on a 4x4 matrix."""
num_sources = 4
num_targets = 4
cost = [[90, 76, 75, 80], [35, 85, 55, 65], [125, 95, 90, 105],
@@ -49,9 +48,9 @@ def RunAssignmentOn4x4Matrix():
'Some input costs are too large and may cause an integer overflow.')
def main():
def main(_):
RunAssignmentOn4x4Matrix()
if __name__ == '__main__':
main()
app.run(main)

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""Linear programming examples that show how to use the APIs."""
from __future__ import print_function
from ortools.linear_solver import pywraplp

View File

@@ -16,21 +16,31 @@ This models aims at building a sequence of numbers such that the number of
occurrences of i in this sequence is equal to the value of the ith number.
It uses an aggregated formulation of the count expression called
distribute().
"""
from __future__ import print_function
Usage: python magic_sequence_distribute.py NUMBER
"""
from absl import app
from absl import flags
from ortools.constraint_solver import pywrapcp
FLAGS = flags.FLAGS
def main():
def main(argv):
# Create the solver.
solver = pywrapcp.Solver('magic sequence')
size = 100
# Create an array of IntVars to hold the answers.
size = int(argv[1]) if len(argv) > 1 else 100
all_values = list(range(0, size))
all_vars = [solver.IntVar(0, size, 'vars_%d' % i) for i in all_values]
# The number of variables equal to j shall be the value of all_vars[j].
solver.Add(solver.Distribute(all_vars, all_values, all_vars))
# The sum of all the values shall be equal to the size.
# (This constraint is redundant, but speeds up the search.)
solver.Add(solver.Sum(all_vars) == size)
solver.NewSearch(
@@ -42,4 +52,4 @@ def main():
if __name__ == '__main__':
main()
app.run(main)

View File

@@ -11,7 +11,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""OR-tools solution to the N-queens problem."""
from __future__ import print_function
import time
import sys
from ortools.sat.python import cp_model

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Simple travelling salesman problem between cities."""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,7 +12,7 @@
# limitations under the License.
"""MaxFlow and MinCostFlow examples."""
from __future__ import print_function
from absl import app
from ortools.graph import pywrapgraph
@@ -29,9 +29,9 @@ def MaxFlow():
if max_flow.Solve(0, 5) == max_flow.OPTIMAL:
print('Total flow', max_flow.OptimalFlow(), '/', expected_total_flow)
for i in range(max_flow.NumArcs()):
print(('From source %d to target %d: %d / %d' %
(max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i),
max_flow.Capacity(i))))
print('From source %d to target %d: %d / %d' %
(max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i),
max_flow.Capacity(i)))
print('Source side min-cut:', max_flow.GetSourceSideMinCut())
print('Sink side min-cut:', max_flow.GetSinkSideMinCut())
else:
@@ -53,8 +53,9 @@ def MinCostFlow():
min_cost_flow = pywrapgraph.SimpleMinCostFlow()
for source in range(0, num_sources):
for target in range(0, num_targets):
min_cost_flow.AddArcWithCapacityAndUnitCost(
source, num_sources + target, 1, costs[source][target])
min_cost_flow.AddArcWithCapacityAndUnitCost(source,
num_sources + target, 1,
costs[source][target])
for node in range(0, num_sources):
min_cost_flow.SetNodeSupply(node, 1)
min_cost_flow.SetNodeSupply(num_sources + node, -1)
@@ -64,17 +65,16 @@ def MinCostFlow():
for i in range(0, min_cost_flow.NumArcs()):
if min_cost_flow.Flow(i) > 0:
print('From source %d to target %d: cost %d' %
(min_cost_flow.Tail(i),
min_cost_flow.Head(i) - num_sources,
min_cost_flow.UnitCost(i)))
(min_cost_flow.Tail(i), min_cost_flow.Head(i) -
num_sources, min_cost_flow.UnitCost(i)))
else:
print('There was an issue with the min cost flow input.')
def main():
def main(_):
MaxFlow()
MinCostFlow()
if __name__ == '__main__':
main()
app.run(main)

View File

@@ -1,6 +1,5 @@
"""Solves a Qubo program using the CP-SAT solver."""
from __future__ import print_function
import time

View File

@@ -12,27 +12,24 @@
# limitations under the License.
"""Sat based solver for the RCPSP problems (see rcpsp.proto)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import collections
import time
from google.protobuf import text_format
from absl import app
from absl import flags
from ortools.data import pywraprcpsp
from ortools.sat.python import cp_model
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
'--input', default="", help='Input file to parse and solve.')
PARSER.add_argument(
'--output_proto',
default="",
help='Output file to write the cp_model'
'proto to.')
PARSER.add_argument('--params', default="", help='Sat solver parameters.')
FLAGS = flags.FLAGS
flags.DEFINE_string('input', '', 'Input file to parse and solve.')
flags.DEFINE_string('output_proto', '',
'Output file to write the cp_model proto to.')
flags.DEFINE_string('params', '', 'Sat solver parameters.')
flags.DEFINE_bool('use_interval_makespan', True,
'Whether we encode the makespan using an interval or not.')
flags.DEFINE_integer('horizon', -1, 'Force horizon.')
class SolutionPrinter(cp_model.CpSolverSolutionCallback):
@@ -52,7 +49,7 @@ class SolutionPrinter(cp_model.CpSolverSolutionCallback):
self.__solution_count += 1
def solve_rcpsp(problem, proto_file, params):
def SolveRcpsp(problem, proto_file, params):
"""Parse and solve a given RCPSP problem in proto format."""
# Determine problem type.
@@ -80,6 +77,8 @@ def solve_rcpsp(problem, proto_file, params):
all_resources = range(num_resources)
horizon = problem.deadline if problem.deadline != -1 else problem.horizon
if FLAGS.horizon > 0:
horizon = FLAGS.horizon
if horizon == -1: # Naive computation.
horizon = sum(max(r.duration for r in t.recipes) for t in problem.tasks)
if problem.is_rcpsp_max:
@@ -189,6 +188,9 @@ def solve_rcpsp(problem, proto_file, params):
# Create makespan variable
makespan = model.NewIntVar(0, horizon, 'makespan')
interval_makespan = model.NewIntervalVar(
makespan, model.NewIntVar(1, horizon, 'interval_makespan_size'),
model.NewConstant(horizon + 1), 'interval_makespan')
# Add precedences.
if problem.is_rcpsp_max:
@@ -217,6 +219,8 @@ def solve_rcpsp(problem, proto_file, params):
for t in all_active_tasks:
for n in problem.tasks[t].successors:
if n == num_tasks - 1:
# TODO(user): I guess these are still useful, but we might want to
# experiment with removing them.
model.Add(task_ends[t] <= makespan)
else:
model.Add(task_ends[t] <= task_starts[n])
@@ -241,13 +245,19 @@ def solve_rcpsp(problem, proto_file, params):
max_cost += c * resource.unit_cost
elif resource.renewable:
if intervals_per_resource[r]:
model.AddCumulative(intervals_per_resource[r],
demands_per_resource[r], c)
if FLAGS.use_interval_makespan:
model.AddCumulative(
intervals_per_resource[r] + [interval_makespan],
demands_per_resource[r] + [c], c)
else:
model.AddCumulative(intervals_per_resource[r],
demands_per_resource[r], c)
elif presences_per_resource[r]: # Non empty non renewable resource.
if problem.is_consumer_producer:
model.AddReservoirConstraint(
starts_per_resource[r], demands_per_resource[r],
resource.min_capacity, resource.max_capacity)
model.AddReservoirConstraint(starts_per_resource[r],
demands_per_resource[r],
resource.min_capacity,
resource.max_capacity)
else:
model.Add(
sum(presences_per_resource[r][i] *
@@ -257,8 +267,9 @@ def solve_rcpsp(problem, proto_file, params):
# Objective.
if problem.is_resource_investment:
objective = model.NewIntVar(0, max_cost, 'capacity_costs')
model.Add(objective == sum(problem.resources[i].unit_cost * capacities[
i] for i in range(len(capacities))))
model.Add(objective == sum(problem.resources[i].unit_cost *
capacities[i]
for i in range(len(capacities))))
else:
objective = makespan
@@ -272,17 +283,17 @@ def solve_rcpsp(problem, proto_file, params):
# Solve model.
solver = cp_model.CpSolver()
if params:
text_format.Merge(params, solver.parameters)
text_format.Parse(params, solver.parameters)
solution_printer = SolutionPrinter()
solver.SolveWithSolutionCallback(model, solution_printer)
print(solver.ResponseStats())
def main(args):
def main(_):
rcpsp_parser = pywraprcpsp.RcpspParser()
rcpsp_parser.ParseFile(args.input)
solve_rcpsp(rcpsp_parser.Problem(), args.output_proto, args.params)
rcpsp_parser.ParseFile(FLAGS.input)
SolveRcpsp(rcpsp_parser.Problem(), FLAGS.output_proto, FLAGS.params)
if __name__ == '__main__':
main(PARSER.parse_args())
app.run(main)

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Reallocate production to smooth it over years."""
from __future__ import print_function
import collections

View File

@@ -12,21 +12,17 @@
# limitations under the License.
"""Creates a shift scheduling problem and solves it."""
from __future__ import print_function
import argparse
from ortools.sat.python import cp_model
from google.protobuf import text_format
from absl import app
from absl import flags
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
'--output_proto',
default="",
help='Output file to write the cp_model'
'proto to.')
PARSER.add_argument('--params', default="", help='Sat solver parameters.')
FLAGS = flags.FLAGS
flags.DEFINE_string('output_proto', '',
'Output file to write the cp_model proto to.')
flags.DEFINE_string('params', '', 'Sat solver parameters.')
def negated_bounded_span(works, start, length):
@@ -92,13 +88,13 @@ def add_soft_sequence_constraint(model, works, hard_min, soft_min, min_cost,
# Forbid sequences that are too short.
for length in range(1, hard_min):
for start in range(len(works) - length + 1):
for start in range(len(works) - length - 1):
model.AddBoolOr(negated_bounded_span(works, start, length))
# Penalize sequences that are below the soft limit.
if min_cost > 0:
for length in range(hard_min, soft_min):
for start in range(len(works) - length + 1):
for start in range(len(works) - length - 1):
span = negated_bounded_span(works, start, length)
name = ': under_span(start=%i, length=%i)' % (start, length)
lit = model.NewBoolVar(prefix + name)
@@ -112,7 +108,7 @@ def add_soft_sequence_constraint(model, works, hard_min, soft_min, min_cost,
# Penalize sequences that are above the soft limit.
if max_cost > 0:
for length in range(soft_max + 1, hard_max + 1):
for start in range(len(works) - length + 1):
for start in range(len(works) - length - 1):
span = negated_bounded_span(works, start, length)
name = ': over_span(start=%i, length=%i)' % (start, length)
lit = model.NewBoolVar(prefix + name)
@@ -123,7 +119,7 @@ def add_soft_sequence_constraint(model, works, hard_min, soft_min, min_cost,
cost_coefficients.append(max_cost * (length - soft_max))
# Just forbid any sequence of true variables with length hard_max + 1
for start in range(len(works) - hard_max):
for start in range(len(works) - hard_max - 1):
model.AddBoolOr(
[works[i].Not() for i in range(start, start + hard_max + 1)])
return cost_literals, cost_coefficients
@@ -221,7 +217,7 @@ def solve_shift_scheduling(params, output_proto):
(3, 0, 5, -2),
# Employee 5 wants a night shift on the second Thursday.
(5, 3, 10, -2),
# Employee 2 does not want a night shift on the first Friday.
# Employee 2 does not want a night shift on the third Friday.
(2, 3, 4, 4)
]
@@ -308,8 +304,8 @@ def solve_shift_scheduling(params, output_proto):
works = [work[e, shift, d] for d in range(num_days)]
variables, coeffs = add_soft_sequence_constraint(
model, works, hard_min, soft_min, min_cost, soft_max, hard_max,
max_cost, 'shift_constraint(employee %i, shift %i)' % (e,
shift))
max_cost,
'shift_constraint(employee %i, shift %i)' % (e, shift))
obj_bool_vars.extend(variables)
obj_bool_coeffs.extend(coeffs)
@@ -332,8 +328,8 @@ def solve_shift_scheduling(params, output_proto):
for e in range(num_employees):
for d in range(num_days - 1):
transition = [
work[e, previous_shift, d].Not(),
work[e, next_shift, d + 1].Not()
work[e, previous_shift, d].Not(), work[e, next_shift,
d + 1].Not()
]
if cost == 0:
model.AddBoolOr(transition)
@@ -367,9 +363,9 @@ def solve_shift_scheduling(params, output_proto):
# Objective
model.Minimize(
sum(obj_bool_vars[i] * obj_bool_coeffs[i]
for i in range(len(obj_bool_vars)))
+ sum(obj_int_vars[i] * obj_int_coeffs[i]
for i in range(len(obj_int_vars))))
for i in range(len(obj_bool_vars))) +
sum(obj_int_vars[i] * obj_int_coeffs[i]
for i in range(len(obj_int_vars))))
if output_proto:
print('Writing proto to %s' % output_proto)
@@ -378,9 +374,8 @@ def solve_shift_scheduling(params, output_proto):
# Solve the model.
solver = cp_model.CpSolver()
solver.parameters.num_search_workers = 8
if params:
text_format.Merge(params, solver.parameters)
text_format.Parse(params, solver.parameters)
solution_printer = cp_model.ObjectiveSolutionPrinter()
status = solver.SolveWithSolutionCallback(model, solution_printer)
@@ -414,13 +409,16 @@ def solve_shift_scheduling(params, output_proto):
(var.Name(), solver.Value(var), obj_int_coeffs[i]))
print()
print(solver.ResponseStats())
print('Statistics')
print(' - status : %s' % solver.StatusName(status))
print(' - conflicts : %i' % solver.NumConflicts())
print(' - branches : %i' % solver.NumBranches())
print(' - wall time : %f s' % solver.WallTime())
def main(args):
"""Main."""
solve_shift_scheduling(args.params, args.output_proto)
def main(_):
solve_shift_scheduling(FLAGS.params, FLAGS.output_proto)
if __name__ == '__main__':
main(PARSER.parse_args())
app.run(main)

View File

@@ -11,9 +11,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single machine jobshop with setup times, release dates and due dates."""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import argparse

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Solves the Stell Mill Slab problem with 4 different techniques."""
from __future__ import print_function
import argparse
import collections

View File

@@ -14,8 +14,6 @@
# limitations under the License.
"""Stigler diet example"""
from __future__ import print_function
from six.moves import xrange
from ortools.linear_solver import pywraplp

View File

@@ -12,8 +12,6 @@
# limitations under the License.
"""This model implements a sudoku solver."""
from __future__ import print_function
from ortools.sat.python import cp_model
@@ -28,10 +26,10 @@ def solve_sudoku():
cell = list(range(0, cell_size))
initial_grid = [[0, 6, 0, 0, 5, 0, 0, 2, 0], [0, 0, 0, 3, 0, 0, 0, 9, 0],
[7, 0, 0, 6, 0, 0, 0, 1, 0], [0, 0, 6, 0, 3, 0, 4, 0, 0], [
0, 0, 4, 0, 7, 0, 1, 0, 0
], [0, 0, 5, 0, 9, 0, 8, 0, 0], [0, 4, 0, 0, 0, 1, 0, 0, 6],
[0, 3, 0, 0, 0, 8, 0, 0, 0], [0, 2, 0, 0, 4, 0, 0, 5, 0]]
[7, 0, 0, 6, 0, 0, 0, 1, 0], [0, 0, 6, 0, 3, 0, 4, 0, 0],
[0, 0, 4, 0, 7, 0, 1, 0, 0], [0, 0, 5, 0, 9, 0, 8, 0, 0],
[0, 4, 0, 0, 0, 1, 0, 0, 6], [0, 3, 0, 0, 0, 8, 0, 0, 0],
[0, 2, 0, 0, 4, 0, 0, 5, 0]]
grid = {}
for i in line:
@@ -68,14 +66,7 @@ def solve_sudoku():
status = solver.Solve(model)
if status == cp_model.OPTIMAL:
for i in line:
output = ''
for j in line:
output += str(int(solver.Value(grid[(i, j)]))) + ' '
if j == 2 or j == 5:
output += '| '
print(output)
if i == 2 or i == 5:
print('------|-------|-------')
print([int(solver.Value(grid[(i, j)])) for j in line])
solve_sudoku()

View File

@@ -15,7 +15,6 @@ see
http://yetanothermathprogrammingconsultant.blogspot.com/2018/09/minizinc-cpsat-vs-mip.html
"""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Tasks and workers to group assignment to average sum(cost) / #workers"""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -21,8 +21,6 @@
here we use: 114m x 80m city block
"""
from __future__ import print_function
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
@@ -173,9 +171,9 @@ class CreateTimeEvaluator(object):
"""Initializes the total time matrix."""
self._total_time = {}
# precompute total time to have time callback in O(1)
for from_node in xrange(data.num_locations):
for from_node in range(data.num_locations):
self._total_time[from_node] = {}
for to_node in xrange(data.num_locations):
for to_node in range(data.num_locations):
if from_node == to_node:
self._total_time[from_node][to_node] = 0
else:

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Simple travelling salesman problem between cities."""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Solves a simple shift scheduling problem."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -36,7 +36,6 @@ Adapted from
https://github.com/google/or-tools/blob/master/examples/csharp/wedding_optimal_chart.cs
"""
from __future__ import print_function
import time
from ortools.sat.python import cp_model

View File

@@ -10,7 +10,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -31,7 +31,6 @@ The Norwegian lives next to the blue house.
Who owns a zebra and who drinks water?
"""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -13,7 +13,6 @@
"""A simple knapsack problem."""
# [START program]
# [START import]
from __future__ import print_function
from ortools.algorithms import pywrapknapsack_solver
# [END import]

View File

@@ -13,7 +13,6 @@
# [START program]
"""A simple knapsack problem."""
# [START import]
from __future__ import print_function
from ortools.algorithms import pywrapknapsack_solver
# [END import]

View File

@@ -23,10 +23,8 @@
Distances are in meters.
"""
from __future__ import print_function
from functools import partial
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
@@ -84,9 +82,9 @@ def create_distance_evaluator(data):
"""Creates callback to return distance between points."""
_distances = {}
# precompute distance between location to have distance callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_distances[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_distances[from_node][to_node] = 0
else:
@@ -132,7 +130,7 @@ def print_solution(data, routing, manager, assignment): # pylint:disable=too-ma
total_distance = 0
total_load = 0
capacity_dimension = routing.GetDimensionOrDie('Capacity')
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
distance = 0

View File

@@ -23,10 +23,8 @@
Distances are in meters.
"""
from __future__ import print_function
from functools import partial
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
@@ -122,9 +120,9 @@ def create_distance_evaluator(data):
"""Creates callback to return distance between points."""
_distances = {}
# precompute distance between location to have distance callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_distances[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_distances[from_node][to_node] = 0
else:
@@ -204,9 +202,9 @@ def create_time_evaluator(data):
_total_time = {}
# precompute total time to have time callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_total_time[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_total_time[from_node][to_node] = 0
else:
@@ -243,7 +241,7 @@ def add_time_window_constraints(routing, manager, data, time_evaluator):
routing.AddToAssignment(time_dimension.SlackVar(index))
# Add time window constraints for each vehicle start node
# and 'copy' the slack var in the solution object (aka Assignment) to print it
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0],
data['time_windows'][0][1])
@@ -264,13 +262,13 @@ def print_solution(data, manager, routing, assignment): # pylint:disable=too-ma
capacity_dimension = routing.GetDimensionOrDie('Capacity')
time_dimension = routing.GetDimensionOrDie('Time')
dropped = []
for order in xrange(0, routing.nodes()):
for order in range(0, routing.nodes()):
index = manager.NodeToIndex(order)
if assignment.Value(routing.NextVar(index)) == index:
dropped.append(order)
print('dropped orders: {}'.format(dropped))
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
distance = 0

View File

@@ -23,10 +23,8 @@
Distances are in meters and time in minutes.
"""
from __future__ import print_function
from functools import partial
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
@@ -96,9 +94,9 @@ def create_distance_evaluator(data):
"""Creates callback to return distance between points."""
_distances = {}
# precompute distance between location to have distance callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_distances[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_distances[from_node][to_node] = 0
else:
@@ -153,9 +151,9 @@ def create_time_evaluator(data):
_total_time = {}
# precompute total time to have time callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_total_time[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_total_time[from_node][to_node] = 0
else:
@@ -192,7 +190,7 @@ def add_time_window_constraints(routing, manager, data, time_evaluator_index):
routing.AddToAssignment(time_dimension.SlackVar(index))
# Add time window constraints for each vehicle start node
# and 'copy' the slack var in the solution object (aka Assignment) to print it
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0],
data['time_windows'][0][1])
@@ -212,7 +210,7 @@ def print_solution(data, manager, routing, assignment): # pylint:disable=too-ma
total_time = 0
capacity_dimension = routing.GetDimensionOrDie('Capacity')
time_dimension = routing.GetDimensionOrDie('Time')
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
distance = 0

View File

@@ -23,10 +23,8 @@
Distances are in meters and time in minutes.
"""
from __future__ import print_function
from functools import partial
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
@@ -97,9 +95,9 @@ def create_distance_evaluator(data):
"""Creates callback to return distance between points."""
_distances = {}
# precompute distance between location to have distance callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_distances[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_distances[from_node][to_node] = 0
else:
@@ -154,9 +152,9 @@ def create_time_evaluator(data):
_total_time = {}
# precompute total time to have time callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_total_time[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_total_time[from_node][to_node] = 0
else:
@@ -193,7 +191,7 @@ def add_time_window_constraints(routing, manager, data, time_evaluator_index):
routing.AddToAssignment(time_dimension.SlackVar(index))
# Add time window constraints for each vehicle start node
# and 'copy' the slack var in the solution object (aka Assignment) to print it
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0],
data['time_windows'][0][1])
@@ -211,7 +209,7 @@ def print_solution(data, manager, routing, assignment): # pylint:disable=too-ma
print('Breaks:')
intervals = assignment.IntervalVarContainer()
for i in xrange(intervals.Size()):
for i in range(intervals.Size()):
brk = intervals.Element(i)
if brk.PerformedValue() == 1:
print('{}: Start({}) Duration({})'.format(
@@ -226,7 +224,7 @@ def print_solution(data, manager, routing, assignment): # pylint:disable=too-ma
total_time = 0
capacity_dimension = routing.GetDimensionOrDie('Capacity')
time_dimension = routing.GetDimensionOrDie('Time')
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
distance = 0
@@ -298,7 +296,7 @@ def main():
# Add breaks
time_dimension = routing.GetDimensionOrDie("Time")
node_visit_transit = {}
for n in xrange(routing.Size()):
for n in range(routing.Size()):
if n >= data['num_locations']:
node_visit_transit[n] = 0
else:
@@ -306,7 +304,7 @@ def main():
data['demands'][n] * data['time_per_demand_unit'])
break_intervals = {}
#for v in xrange(data['num_vehicles']):
#for v in range(data['num_vehicles']):
for v in [0]:
vehicle_break = data['breaks'][v]
break_intervals[v] = [

View File

@@ -14,7 +14,6 @@
"""Simple Constraint optimization example."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Vehicle Routing example."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -18,7 +18,6 @@ http://en.wikipedia.org/wiki/Travelling_salesman_problem.
"""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Simple travelling salesman problem on a circuit board."""
# [START import]
from __future__ import print_function
import math
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

View File

@@ -14,7 +14,6 @@
"""Simple travelling salesman problem between cities."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

View File

@@ -14,7 +14,6 @@
"""Simple Travelling Salesman Problem."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Simple Vehicles Routing Problem."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Capacited Vehicles Routing Problem (CVRP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Capacited Vehicles Routing Problem (CVRP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Vehicles Routing Problem (VRP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Vehicles Routing Problem (VRP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Simple Pickup Delivery Problem (PDP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Simple Pickup Delivery Problem (PDP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Simple Pickup Delivery Problem (PDP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Vehicles Routing Problem (VRP) with Resource Constraints."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Simple Vehicles Routing Problem."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Vehicles Routing Problem (VRP) with Time Windows."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -14,7 +14,6 @@
"""Vehicles Routing Problem (VRP)."""
# [START import]
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# [END import]

View File

@@ -23,10 +23,8 @@
Distances are in meters.
"""
from __future__ import print_function
from functools import partial
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
@@ -73,9 +71,9 @@ def create_distance_evaluator(data):
"""Creates callback to return distance between points."""
_distances = {}
# precompute distance between location to have distance callback in O(1)
for from_node in xrange(data['num_locations']):
for from_node in range(data['num_locations']):
_distances[from_node] = {}
for to_node in xrange(data['num_locations']):
for to_node in range(data['num_locations']):
if from_node == to_node:
_distances[from_node][to_node] = 0
else:
@@ -112,7 +110,7 @@ def print_solution(data, routing, manager, assignment): # pylint:disable=too-ma
"""Prints assignment on console"""
print('Objective: {}'.format(assignment.ObjectiveValue()))
total_distance = 0
for vehicle_id in xrange(data['num_vehicles']):
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
distance = 0

View File

@@ -13,7 +13,6 @@
# [START program]
"""From Taha 'Introduction to Operations Research', example 6.4-2."""
# [START import]
from __future__ import print_function
from ortools.graph import pywrapgraph
# [END import]

View File

@@ -13,7 +13,6 @@
# [START program]
"""From Bradley, H. and M., 'Applied Mathematical Programming', figure 8.1."""
# [START import]
from __future__ import print_function
from ortools.graph import pywrapgraph
# [END import]

View File

@@ -41,7 +41,7 @@ void BinPackingMip() {
// [START solver]
// Create the mip solver with the CBC backend.
MPSolver solver("bin_packing_mip", MPSolver::CBC_MIXED_INTEGER_PROGRAMMING);
MPSolver solver("bin_packing_mip", MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING);
// [END solver]
// [START program_part2]

View File

@@ -13,7 +13,6 @@
"""Solve a simple bin packing problem using a MIP solver."""
# [START program]
# [START import]
from __future__ import print_function
from ortools.linear_solver import pywraplp
# [END import]

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Small example to illustrate solving a MIP problem."""
# [START program]
from __future__ import print_function
# [START import]
from ortools.linear_solver import pywraplp
# [END import]

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Linear optimization example."""
# [START program]
from __future__ import print_function
# [START import]
from ortools.linear_solver import pywraplp

View File

@@ -13,7 +13,6 @@
"""MIP example that uses a variable array."""
# [START program]
# [START import]
from __future__ import print_function
from ortools.linear_solver import pywraplp
# [END import]

View File

@@ -45,7 +45,7 @@ void MultipleKnapsackMip() {
// [START solver]
// Create the mip solver with the CBC backend.
MPSolver solver("multiple_knapsack_mip",
MPSolver::CBC_MIXED_INTEGER_PROGRAMMING);
MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING);
// [END solver]
// [START program_part2]

View File

@@ -13,7 +13,6 @@
"""Solve a multiple knapsack problem using a MIP solver."""
# [START program]
# [START import]
from __future__ import print_function
from ortools.linear_solver import pywraplp
# [END import]

View File

@@ -13,7 +13,6 @@
"""Minimal example to call the GLOP solver."""
# [START program]
# [START import]
from __future__ import print_function
from ortools.linear_solver import pywraplp
# [END import]

View File

@@ -13,7 +13,6 @@
"""Integer programming examples that show how to use the APIs."""
# [START program]
# [START import]
from __future__ import print_function
from ortools.linear_solver import pywraplp
# [END import]

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Solves a binpacking problem using the CP-SAT solver."""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample to demonstrates a simple Boolean constraint."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample that encodes the product of two Boolean variables."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Link integer constraints together."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -20,7 +20,6 @@ This problem has 72 different solutions in base 10.
"""
# [START program]
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Encodes an convex piecewise linear function."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample to demonstrates how to build an interval."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample to demonstrate Boolean variable and literals."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -13,7 +13,6 @@
"""Minimal jobshop example."""
# [START program]
from __future__ import print_function
import collections

View File

@@ -14,9 +14,6 @@
"""Solves a multiple knapsack problem using the CP-SAT solver."""
# [START import]
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample to demonstrate how to build a NoOverlap constraint."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample to demonstrates how to build an optional interval."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Rabbits and Pheasants quizz."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,7 +12,6 @@
# limitations under the License.
"""Code sample to demonstrates how to rank intervals."""
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Simple model with a reified constraint."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample to demonstrate how an interval can span across a break."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -13,9 +13,6 @@
"""Code sample that solves a model and displays all solutions."""
# [START program]
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -13,9 +13,6 @@
"""Simple solve."""
# [START program]
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -13,9 +13,6 @@
"""Code sample that solves a model using solution hinting."""
# [START program]
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -13,9 +13,6 @@
"""Solves an optimization problem and displays all intermediate solutions."""
# [START program]
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Solves a problem with a time limit."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Implements a step function."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model

View File

@@ -12,9 +12,6 @@
# limitations under the License.
"""Code sample that solves a model and displays a small number of solutions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model