Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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()
# 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)
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()
# 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))
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')
In order to make this process easier, we present a mathematical
formulation that models the seating chart problem. This model can
be solved to find the optimal arrangement of guests at tables.
At the very least, it can provide a starting point and hopefully
minimize stress and arguments.
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
class WeddingChartPrinter(cp_model.CpSolverSolutionCallback):
"""Print intermediate solutions."""
def __init__(self, seats, names, num_tables, num_guests):
cp_model.CpSolverSolutionCallback.__init__(self)
self.__solution_count = 0
self.__start_time = time.time()
self.__seats = seats
self.__names = names
self.__num_tables = num_tables
self.__num_guests = num_guests
def on_solution_callback(self):
current_time = time.time()
objective = self.ObjectiveValue()
print("Solution %i, time = %f s, objective = %i" %
(self.__solution_count, current_time - self.__start_time,
def main():
bounds = []
s = pywraplp.Solver('',pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
a = [[2],[-2]]
b = [3,-12]
x = s.NumVar(2,5,'x')
z,l = maximax(s,a,[x],b)
rc = s.Solve()
print('x = ',SolVal(x))
print('z = ',SolVal(z))
print('delta = ', SolVal(l))
main()
def __init__(self, seats, names, num_tables, num_guests):
cp_model.CpSolverSolutionCallback.__init__(self)
self.__solution_count = 0
self.__start_time = time.time()
self.__seats = seats
self.__names = names
self.__num_tables = num_tables
self.__num_guests = num_guests
def main(problem_str="SEND+MORE=MONEY", base=10):
# Create the solver.
solver = pywrapcp.Solver("Send most money")
# data
print("\nproblem:", problem_str)
# convert to array.
problem = re.split("[\s+=]", problem_str)
p_len = len(problem)
print("base:", base)
# create the lookup table: list of (digit : ix)
a = sorted(set("".join(problem)))
n = len(a)
lookup = dict(list(zip(a, list(range(n)))))
# length of each number
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