remove mypy issues

This commit is contained in:
Laurent Perron
2024-07-24 14:54:57 -07:00
parent 1cedb55d6e
commit ad3e00e441
11 changed files with 1868 additions and 1735 deletions

View File

@@ -39,17 +39,143 @@ _SOLVER = flags.DEFINE_string("solver", "sat", "Method used to solve: sat, mip."
DESIRED_LENGTHS = [
2490, 3980, 2490, 3980, 2391, 2391, 2391, 596, 596, 596, 2456, 2456, 3018,
938, 3018, 938, 943, 3018, 943, 3018, 2490, 3980, 2490, 3980, 2391, 2391,
2391, 596, 596, 596, 2456, 2456, 3018, 938, 3018, 938, 943, 3018, 943,
3018, 2890, 3980, 2890, 3980, 2391, 2391, 2391, 596, 596, 596, 2856, 2856,
3018, 938, 3018, 938, 943, 3018, 943, 3018, 3290, 3980, 3290, 3980, 2391,
2391, 2391, 596, 596, 596, 3256, 3256, 3018, 938, 3018, 938, 943, 3018,
943, 3018, 3690, 3980, 3690, 3980, 2391, 2391, 2391, 596, 596, 596, 3656,
3656, 3018, 938, 3018, 938, 943, 3018, 943, 3018, 2790, 3980, 2790, 3980,
2391, 2391, 2391, 596, 596, 596, 2756, 2756, 3018, 938, 3018, 938, 943,
3018, 943, 3018, 2790, 3980, 2790, 3980, 2391, 2391, 2391, 596, 596, 596,
2756, 2756, 3018, 938, 3018, 938, 943
2490,
3980,
2490,
3980,
2391,
2391,
2391,
596,
596,
596,
2456,
2456,
3018,
938,
3018,
938,
943,
3018,
943,
3018,
2490,
3980,
2490,
3980,
2391,
2391,
2391,
596,
596,
596,
2456,
2456,
3018,
938,
3018,
938,
943,
3018,
943,
3018,
2890,
3980,
2890,
3980,
2391,
2391,
2391,
596,
596,
596,
2856,
2856,
3018,
938,
3018,
938,
943,
3018,
943,
3018,
3290,
3980,
3290,
3980,
2391,
2391,
2391,
596,
596,
596,
3256,
3256,
3018,
938,
3018,
938,
943,
3018,
943,
3018,
3690,
3980,
3690,
3980,
2391,
2391,
2391,
596,
596,
596,
3656,
3656,
3018,
938,
3018,
938,
943,
3018,
943,
3018,
2790,
3980,
2790,
3980,
2391,
2391,
2391,
596,
596,
596,
2756,
2756,
3018,
938,
3018,
938,
943,
3018,
943,
3018,
2790,
3980,
2790,
3980,
2391,
2391,
2391,
596,
596,
596,
2756,
2756,
3018,
938,
3018,
938,
943,
]
POSSIBLE_CAPACITIES = [4000, 5000, 6000, 7000, 8000]

View File

@@ -19,8 +19,10 @@ be as close to the average as possible.
Furthermore, if one color is an a group, at least k items with this color must
be in that group.
"""
from typing import Sequence
from typing import Dict, Sequence
from absl import app
from ortools.sat.python import cp_model
@@ -88,18 +90,15 @@ def main(argv: Sequence[str]) -> None:
num_items_per_group = num_items // num_groups
# Collect all items in a given color.
items_per_color = {}
for c in all_colors:
items_per_color[c] = []
items_per_color: Dict[int, list[int]] = {}
for color in all_colors:
items_per_color[color] = []
for i in all_items:
if colors[i] == c:
items_per_color[c].append(i)
if colors[i] == color:
items_per_color[color].append(i)
print(
"Model has %i items, %i groups, and %i colors"
% (num_items, num_groups, num_colors)
)
print(" average sum per group = %i" % average_sum_per_group)
print(f"Model has {num_items} items, {num_groups} groups, and {num_colors} colors")
print(f" average sum per group = {average_sum_per_group}")
# Model.

File diff suppressed because it is too large Load Diff

View File

@@ -90,7 +90,7 @@ def flexible_jobshop() -> None:
intervals_per_resources = collections.defaultdict(list)
starts = {} # indexed by (job_id, task_id).
presences = {} # indexed by (job_id, task_id, alt_id).
job_ends = []
job_ends: list[cp_model.IntVar] = []
# Scan the jobs and create the relevant variables and intervals.
for job_id in all_jobs:
@@ -161,7 +161,8 @@ def flexible_jobshop() -> None:
intervals_per_resources[task[0][1]].append(interval)
presences[(job_id, task_id, 0)] = model.new_constant(1)
job_ends.append(previous_end)
if previous_end is not None:
job_ends.append(previous_end)
# Create machines constraints.
for machine_id in all_machines:
@@ -181,28 +182,27 @@ def flexible_jobshop() -> None:
# Print final solution.
for job_id in all_jobs:
print("Job %i:" % job_id)
print(f"Job {job_id}")
for task_id in range(len(jobs[job_id])):
start_value = solver.value(starts[(job_id, task_id)])
machine = -1
duration = -1
selected = -1
machine: int = -1
task_duration: int = -1
selected: int = -1
for alt_id in range(len(jobs[job_id][task_id])):
if solver.value(presences[(job_id, task_id, alt_id)]):
duration = jobs[job_id][task_id][alt_id][0]
if solver.boolean_value(presences[(job_id, task_id, alt_id)]):
task_duration = jobs[job_id][task_id][alt_id][0]
machine = jobs[job_id][task_id][alt_id][1]
selected = alt_id
print(
" task_%i_%i starts at %i (alt %i, machine %i, duration %i)"
% (job_id, task_id, start_value, selected, machine, duration)
f" task_{job_id}_{task_id} starts at {start_value} (alt {selected}, machine {machine}, duration {task_duration})"
)
print("solve status: %s" % solver.status_name(status))
print("Optimal objective value: %i" % solver.objective_value)
print(f"solve status: {solver.status_name(status)}")
print(f"Optimal objective value: {solver.objective_value}")
print("Statistics")
print(" - conflicts : %i" % solver.num_conflicts)
print(" - branches : %i" % solver.num_branches)
print(" - wall time : %f s" % solver.wall_time)
print(f" - conflicts : {solver.num_conflicts}")
print(f" - branches : {solver.num_branches}")
print(f" - wall time : {solver.wall_time} s")
flexible_jobshop()

View File

@@ -67,34 +67,34 @@ def main(_) -> None:
for i in all_jobs:
# Create main interval.
start = model.new_int_var(0, horizon, "start_%i" % i)
start = model.new_int_var(0, horizon, f"start_{i}")
duration = jobs[i][0]
end = model.new_int_var(0, horizon, "end_%i" % i)
interval = model.new_interval_var(start, duration, end, "interval_%i" % i)
end = model.new_int_var(0, horizon, f"end_{i}")
interval = model.new_interval_var(start, duration, end, f"interval_{i}")
starts.append(start)
intervals.append(interval)
ends.append(end)
demands.append(jobs[i][1])
# Create an optional copy of interval to be executed on machine 0.
performed_on_m0 = model.new_bool_var("perform_%i_on_m0" % i)
performed_on_m0 = model.new_bool_var(f"perform_{i}_on_m0")
performed.append(performed_on_m0)
start0 = model.new_int_var(0, horizon, "start_%i_on_m0" % i)
end0 = model.new_int_var(0, horizon, "end_%i_on_m0" % i)
start0 = model.new_int_var(0, horizon, f"start_{i}_on_m0")
end0 = model.new_int_var(0, horizon, f"end_{i}_on_m0")
interval0 = model.new_optional_interval_var(
start0, duration, end0, performed_on_m0, "interval_%i_on_m0" % i
start0, duration, end0, performed_on_m0, f"interval_{i}_on_m0"
)
intervals0.append(interval0)
# Create an optional copy of interval to be executed on machine 1.
start1 = model.new_int_var(0, horizon, "start_%i_on_m1" % i)
end1 = model.new_int_var(0, horizon, "end_%i_on_m1" % i)
start1 = model.new_int_var(0, horizon, f"start_{i}_on_m1")
end1 = model.new_int_var(0, horizon, f"end_{i}_on_m1")
interval1 = model.new_optional_interval_var(
start1,
duration,
end1,
~performed_on_m0,
"interval_%i_on_m1" % i,
f"interval_{i}_on_m1",
)
intervals1.append(interval1)
@@ -124,18 +124,24 @@ def main(_) -> None:
# Output solution.
if visualization.RunFromIPython():
output = visualization.SvgWrapper(solver.objective_value, max_width, 40.0)
output.AddTitle("Makespan = %i" % solver.objective_value)
output.AddTitle(f"Makespan = {solver.objective_value}")
color_manager = visualization.ColorManager()
color_manager.SeedRandomColor(0)
for i in all_jobs:
performed_machine = 1 - solver.value(performed[i])
start = solver.value(starts[i])
start_of_task = solver.value(starts[i])
d_x = jobs[i][0]
d_y = jobs[i][1]
s_y = performed_machine * (max_width - d_y)
output.AddRectangle(
start, s_y, d_x, d_y, color_manager.RandomColor(), "black", "j%i" % i
start_of_task,
s_y,
d_x,
d_y,
color_manager.RandomColor(),
"black",
f"j{i}",
)
output.AddXScale()
@@ -143,17 +149,17 @@ def main(_) -> None:
output.Display()
else:
print("Solution")
print(" - makespan = %i" % solver.objective_value)
print(f" - makespan = {solver.objective_value}")
for i in all_jobs:
performed_machine = 1 - solver.value(performed[i])
start = solver.value(starts[i])
start_of_task = solver.value(starts[i])
print(
" - Job %i starts at %i on machine %i" % (i, start, performed_machine)
f" - Job {i} starts at {start_of_task} on machine {performed_machine}"
)
print("Statistics")
print(" - conflicts : %i" % solver.num_conflicts)
print(" - branches : %i" % solver.num_branches)
print(" - wall time : %f s" % solver.wall_time)
print(f" - conflicts : {solver.num_conflicts}")
print(f" - branches : {solver.num_branches}")
print(f" - wall time : {solver.wall_time} s")
if __name__ == "__main__":

View File

@@ -54,7 +54,7 @@ def jobshop_with_maintenance() -> None:
horizon = sum(task[1] for job in jobs_data for task in job)
# Named tuple to store information about created variables.
task_type = collections.namedtuple("Task", "start end interval")
task_type = collections.namedtuple("task_type", "start end interval")
# Named tuple to manipulate solution information.
assigned_task_type = collections.namedtuple(
"assigned_task_type", "start job index duration"
@@ -69,7 +69,7 @@ def jobshop_with_maintenance() -> None:
task_id, task = entry
machine = task[0]
duration = task[1]
suffix = "_%i_%i" % (job_id, task_id)
suffix = f"_{job_id}_{task_id}"
start_var = model.new_int_var(0, horizon, "start" + suffix)
end_var = model.new_int_var(0, horizon, "end" + suffix)
interval_var = model.new_interval_var(

View File

@@ -20,7 +20,7 @@ visit all boxes in order, and walk on each block in a 4x4x4 map exactly once.
Admissible moves are one step in one of the 6 directions:
x+, x-, y+, y-, z+(up), z-(down)
"""
from typing import Sequence
from typing import Sequence, Tuple
from absl import app
from absl import flags
@@ -91,7 +91,7 @@ def escape_the_maze(params, output_proto) -> None:
# Circuit constraint: visit all blocks exactly once, and maintains the rank
# of each block.
arcs = []
arcs: list[Tuple[int, int, cp_model.LiteralT]] = []
for x in range(size):
for y in range(size):
for z in range(size):

View File

@@ -54,8 +54,10 @@ def solve_hard_model(output_proto: str, params: str) -> bool:
y_starts: List[cp_model.IntVar] = []
y_intervals: List[cp_model.IntervalVar] = []
for start, end, demand, unused_alignment in DEMANDS:
x_interval = model.new_fixed_size_interval_var(start, end - start + 1, "")
for start_time, end_time, demand, _ in DEMANDS:
x_interval = model.new_fixed_size_interval_var(
start_time, end_time - start_time + 1, ""
)
y_start = model.new_int_var(0, CAPACITY - demand, "")
y_interval = model.new_fixed_size_interval_var(y_start, demand, "")
@@ -74,9 +76,9 @@ def solve_hard_model(output_proto: str, params: str) -> bool:
status = solver.solve(model)
print(solver.response_stats())
if status == cp_model.FEASIBLE or status == cp_model.OPTIMAL:
for index, start in enumerate(y_starts):
print(f"task {index} buffer starts at {solver.value(start)}")
if status in (cp_model.FEASIBLE, cp_model.OPTIMAL):
for index, start_var in enumerate(y_starts):
print(f"task {index} buffer starts at {solver.value(start_var)}")
return status != cp_model.INFEASIBLE

View File

@@ -19,7 +19,6 @@ from ortools.sat.python import cp_model
def main():
# Data
data_0 = [
[107, 107, 107, 0, 0], # pr1
@@ -35,7 +34,7 @@ def main():
[298836792, 0, 0, 0],
[3713428, 4118530, 4107277, 3072018],
[6477273, 7183884, 5358471, 0],
[1485371, 1647412, 1642911, 1228807]
[1485371, 1647412, 1642911, 1228807],
]
data_2 = [
@@ -45,7 +44,7 @@ def main():
[2988367, 0, 0, 0],
[37134, 41185, 41072, 30720],
[64772, 71838, 53584, 0],
[14853, 16474, 16429, 12288]
[14853, 16474, 16429, 12288],
]
pr = data_0
@@ -59,7 +58,7 @@ def main():
model = cp_model.CpModel()
# Variables
delta = model.NewIntVar(0, total, 'delta')
delta = model.NewIntVar(0, total, "delta")
contributions_per_years = collections.defaultdict(list)
contributions_per_prs = collections.defaultdict(list)
@@ -68,14 +67,12 @@ def main():
for p, inner_l in enumerate(pr):
for y, item in enumerate(inner_l):
if item != 0:
contrib = model.NewIntVar(0, total, 'r%d c%d' % (p, y))
contrib = model.NewIntVar(0, total, "r%d c%d" % (p, y))
contributions_per_years[y].append(contrib)
contributions_per_prs[p].append(contrib)
all_contribs[p, y] = contrib
year_var = [
model.NewIntVar(0, total, 'y[%i]' % i) for i in range(num_years)
]
year_var = [model.NewIntVar(0, total, "y[%i]" % i) for i in range(num_years)]
# Constraints
@@ -103,34 +100,34 @@ def main():
# Output solution.
if status == cp_model.OPTIMAL:
print('Data')
print(' - total = ', total)
print(' - year_average = ', avg)
print(' - number of projects = ', num_pr)
print(' - number of years = ', num_years)
print("Data")
print(" - total = ", total)
print(" - year_average = ", avg)
print(" - number of projects = ", num_pr)
print(" - number of years = ", num_years)
print(' - input production')
print(" - input production")
for p in range(num_pr):
for y in range(num_years):
if pr[p][y] == 0:
print(' ', end='')
print(" ", end="")
else:
print('%10i' % pr[p][y], end='')
print("%10i" % pr[p][y], end="")
print()
print('Solution')
print("Solution")
for p in range(num_pr):
for y in range(num_years):
if pr[p][y] == 0:
print(' ', end='')
print(" ", end="")
else:
print('%10i' % solver.Value(all_contribs[p, y]), end='')
print("%10i" % solver.Value(all_contribs[p, y]), end="")
print()
for y in range(num_years):
print('%10i' % solver.Value(year_var[y]), end='')
print("%10i" % solver.Value(year_var[y]), end="")
print()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View File

@@ -503,7 +503,7 @@ def single_machine_scheduling():
if parameters:
text_format.Parse(parameters, solver.parameters)
solution_printer = SolutionPrinter()
solver.best_bound_callback = lambda a : print(f"New objective lower bound: {a}")
solver.best_bound_callback = lambda a: print(f"New objective lower bound: {a}")
solver.solve(model, solution_printer)
for job_id in all_jobs:
print(

View File

@@ -44,7 +44,7 @@ _PARAMS = flags.DEFINE_string(
)
def build_data() -> tuple[pd.DataFrame, pd.Series, pd.Series]:
def build_data() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
"""Build the data frame."""
tests_str = """
Name Operator TestTime AveragePower
@@ -76,7 +76,7 @@ def build_data() -> tuple[pd.DataFrame, pd.Series, pd.Series]:
def solve(
tests_data: pd.DataFrame, operator_data: pd.Series, supplies_data: pd.Series
tests_data: pd.DataFrame, operator_data: pd.DataFrame, supplies_data: pd.DataFrame
) -> None:
"""Solve the scheduling of tests problem."""
@@ -153,6 +153,7 @@ def solve(
def main(argv: Sequence[str]) -> None:
"""Builds the data and solve the scheduling problem."""
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")