File size: 38,336 Bytes
ab849c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 | """Optimization method implementations — baseline, exact, scalable, robust."""
from __future__ import annotations
import math
import random
import time
from abc import ABC, abstractmethod
from typing import Any
from optos.constants import SOLVER_CONFIGS
from optos.models import ProblemInstance, SolveMetrics, SolveResult
class BaseMethod(ABC):
method_id: str = "base"
method_label: str = "Base"
method_category: str = "baseline"
solver_id: str = "heuristic"
def __init__(self, time_limit_sec: float = 10.0) -> None:
self.time_limit_sec = time_limit_sec
self.config = dict(SOLVER_CONFIGS.get(self.solver_id, {}))
@abstractmethod
def solve(self, instance: ProblemInstance) -> SolveResult:
...
def _make_result(
self,
instance: ProblemInstance,
obj: float,
status: str,
elapsed: float,
feasible: bool,
solution: dict[str, Any] | None = None,
bound: float | None = None,
iterations: int = 0,
violations: int = 0,
log: str = "",
t_first: float | None = None,
) -> SolveResult:
gap = 0.0
if bound is not None and feasible and obj > 0:
gap = abs(obj - bound) / max(abs(obj), 1e-9) * 100
elif instance.known_optimum and feasible:
gap = abs(obj - instance.known_optimum) / max(abs(instance.known_optimum), 1e-9) * 100
metrics = SolveMetrics(
objective_value=round(obj, 4) if feasible else 0.0,
best_bound=round(bound or obj, 4),
optimality_gap=round(gap, 4),
elapsed_time_sec=round(elapsed, 4),
iterations=iterations,
constraint_violations=violations,
feasible=feasible,
status=status,
time_to_first_feasible=round(t_first or elapsed, 4),
)
return SolveResult(
method_id=self.method_id,
method_label=self.method_label,
method_category=self.method_category,
solver_id=self.solver_id,
solver_config=self.config,
instance_id=instance.instance_id,
problem_type=instance.problem_type,
metrics=metrics,
solution=solution or {},
log=log,
)
# ---------------------------------------------------------------------------
# Scheduling
# ---------------------------------------------------------------------------
class SptBaseline(BaseMethod):
method_id = "spt_baseline"
method_label = "Shortest Processing Time (SPT)"
method_category = "baseline"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
n_jobs, n_machines = data["n_jobs"], data["n_machines"]
machine_free = [0.0] * n_machines
job_ready = [0.0] * n_jobs
makespan = 0.0
for o in range(n_machines):
order = sorted(range(n_jobs), key=lambda j: data["processing_times"][j][o])
for j in order:
start = max(machine_free[o], job_ready[j])
end = start + data["processing_times"][j][o]
machine_free[o] = end
job_ready[j] = end
makespan = max(makespan, end)
elapsed = time.perf_counter() - t0
return self._make_result(instance, makespan, "heuristic", elapsed, True, {"makespan": makespan})
class CpSatScheduling(BaseMethod):
method_id = "cp_sat_scheduling"
method_label = "CP-SAT Job Shop"
method_category = "exact"
solver_id = "cp_sat"
def solve(self, instance: ProblemInstance) -> SolveResult:
from ortools.sat.python import cp_model
t0 = time.perf_counter()
data = instance.data
n_jobs, n_machines = data["n_jobs"], data["n_machines"]
horizon = sum(max(row) for row in data["processing_times"]) * n_jobs
model = cp_model.CpModel()
starts, ends = {}, {}
for j in range(n_jobs):
for o in range(n_machines):
dur = data["processing_times"][j][o]
starts[j, o] = model.new_int_var(0, horizon, f"s_{j}_{o}")
ends[j, o] = model.new_int_var(0, horizon, f"e_{j}_{o}")
model.add(ends[j, o] == starts[j, o] + dur)
for o in range(n_machines - 1):
model.add(starts[j, o + 1] >= ends[j, o])
for m in range(n_machines):
intervals = []
for j in range(n_jobs):
for o in range(n_machines):
if data["machine_order"][j][o] == m:
dur = data["processing_times"][j][o]
iv = model.new_interval_var(starts[j, o], dur, ends[j, o], f"iv_{j}_{o}_{m}")
intervals.append(iv)
if intervals:
model.add_no_overlap(intervals)
makespan = model.new_int_var(0, horizon, "makespan")
model.add_max_equality(makespan, [ends[j, n_machines - 1] for j in range(n_jobs)])
model.minimize(makespan)
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = self.time_limit_sec
solver.parameters.num_search_workers = self.config.get("num_search_workers", 4)
status = solver.solve(model)
elapsed = time.perf_counter() - t0
feasible = status in (cp_model.OPTIMAL, cp_model.FEASIBLE)
obj = solver.objective_value if feasible else 0.0
bound = solver.best_objective_bound if feasible else 0.0
return self._make_result(
instance, obj, solver.status_name(status), elapsed, feasible,
{"makespan": obj}, bound=bound, iterations=solver.num_branches,
log=f"branches={solver.num_branches}",
)
class GaScheduling(BaseMethod):
method_id = "ga_scheduling"
method_label = "Genetic Algorithm"
method_category = "scalable"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
n_jobs, n_machines = data["n_jobs"], data["n_machines"]
rng = random.Random(42)
pop_size = min(40, max(10, n_jobs * 2))
def eval_perm(perm: list[int]) -> float:
machine_free = [0.0] * n_machines
job_ready = [0.0] * n_jobs
makespan = 0.0
for j in perm:
for o in range(n_machines):
start = max(machine_free[data["machine_order"][j][o]], job_ready[j])
end = start + data["processing_times"][j][o]
machine_free[data["machine_order"][j][o]] = end
job_ready[j] = end
makespan = max(makespan, end)
return makespan
population = [list(range(n_jobs)) for _ in range(pop_size)]
for p in population:
rng.shuffle(p)
best = min(population, key=eval_perm)
best_obj = eval_perm(best)
iterations = 0
deadline = t0 + self.time_limit_sec
while time.perf_counter() < deadline and iterations < 200:
iterations += 1
parent = min(random.sample(population, 2), key=eval_perm)
child = parent[:]
i, j = rng.sample(range(n_jobs), 2)
child[i], child[j] = child[j], child[i]
child_obj = eval_perm(child)
if child_obj < best_obj:
best, best_obj = child, child_obj
population[iterations % pop_size] = child
elapsed = time.perf_counter() - t0
return self._make_result(instance, best_obj, "heuristic", elapsed, True,
{"makespan": best_obj, "permutation": best}, iterations=iterations)
class RollingHorizonScheduling(BaseMethod):
method_id = "rolling_horizon_scheduling"
method_label = "Rolling Horizon"
method_category = "robust"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
sub = ProblemInstance(
problem_type=instance.problem_type,
instance_id=instance.instance_id + "_rh",
label=instance.label,
size=instance.size,
seed=instance.seed,
data=dict(instance.data),
features=instance.features,
)
data = sub.data
window = max(2, data["n_jobs"] // 2)
total_makespan = 0.0
remaining_jobs = list(range(data["n_jobs"]))
machine_free = [0.0] * data["n_machines"]
while remaining_jobs:
batch = remaining_jobs[:window]
remaining_jobs = remaining_jobs[window:]
mini = dict(data)
mini["n_jobs"] = len(batch)
mini["processing_times"] = [data["processing_times"][j] for j in batch]
mini["machine_order"] = [data["machine_order"][j] for j in batch]
mini_inst = ProblemInstance(
problem_type="scheduling", instance_id=sub.instance_id,
label=sub.label, size=sub.size, seed=sub.seed,
data=mini, features=sub.features,
)
res = SptBaseline(self.time_limit_sec / 3).solve(mini_inst)
batch_makespan = res.metrics.objective_value
for m in range(data["n_machines"]):
machine_free[m] += batch_makespan / data["n_machines"]
total_makespan = max(machine_free)
elapsed = time.perf_counter() - t0
return self._make_result(instance, total_makespan, "rolling_horizon", elapsed, True,
{"makespan": total_makespan})
# ---------------------------------------------------------------------------
# Routing
# ---------------------------------------------------------------------------
def _route_distance(depot: tuple, customers: list, route: list[int]) -> float:
total = 0.0
prev = depot
for c in route:
pt = customers[c]
total += math.hypot(pt[0] - prev[0], pt[1] - prev[1])
prev = pt
total += math.hypot(prev[0] - depot[0], prev[1] - depot[1])
return total
class NearestDepotRouting(BaseMethod):
method_id = "nearest_depot"
method_label = "Nearest Warehouse Greedy"
method_category = "baseline"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
depot, customers = data["depot"], data["customers"]
unvisited = set(range(data["n_customers"]))
routes: list[list[int]] = []
total_dist = 0.0
while unvisited:
route, load = [], 0
pos = depot
while unvisited:
nearest = min(unvisited, key=lambda c: math.hypot(
customers[c][0] - pos[0], customers[c][1] - pos[1]))
if load + data["demands"][nearest] > data["vehicle_capacity"]:
break
route.append(nearest)
load += data["demands"][nearest]
unvisited.remove(nearest)
pos = customers[nearest]
if route:
routes.append(route)
total_dist += _route_distance(depot, customers, route)
elapsed = time.perf_counter() - t0
return self._make_result(instance, total_dist, "heuristic", elapsed, True,
{"total_distance": total_dist, "routes": routes})
class CpSatRouting(BaseMethod):
method_id = "cp_sat_routing"
method_label = "CP-SAT Routing"
method_category = "exact"
solver_id = "cp_sat"
def solve(self, instance: ProblemInstance) -> SolveResult:
from ortools.sat.python import cp_model
t0 = time.perf_counter()
data = instance.data
n = data["n_customers"]
if n > 15:
return NearestDepotRouting(self.time_limit_sec).solve(instance)
depot, customers = data["depot"], data["customers"]
dist = [[0.0] * (n + 1) for _ in range(n + 1)]
pts = [depot] + customers
for i in range(n + 1):
for j in range(n + 1):
dist[i][j] = int(math.hypot(pts[i][0] - pts[j][0], pts[i][1] - pts[j][1]) * 10)
model = cp_model.CpModel()
x = {}
for i in range(n + 1):
for j in range(n + 1):
if i != j:
x[i, j] = model.new_bool_var(f"x_{i}_{j}")
for i in range(1, n + 1):
model.add(sum(x[i, j] for j in range(n + 1) if j != i) == 1)
model.add(sum(x[j, i] for j in range(n + 1) if j != i) == 1)
u = [model.new_int_var(0, n, f"u_{i}") for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
if i != j:
model.add(u[i] - u[j] + (n + 1) * x[i, j] <= n)
model.minimize(sum(dist[i][j] * x[i, j] for i in range(n + 1) for j in range(n + 1) if i != j))
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = self.time_limit_sec
status = solver.solve(model)
elapsed = time.perf_counter() - t0
feasible = status in (cp_model.OPTIMAL, cp_model.FEASIBLE)
obj = solver.objective_value / 10.0 if feasible else 0.0
return self._make_result(instance, obj, solver.status_name(status), elapsed, feasible,
{"total_distance": obj}, bound=solver.best_objective_bound / 10.0 if feasible else 0,
iterations=solver.num_branches)
class AlnsRouting(BaseMethod):
method_id = "alns_routing"
method_label = "ALNS Routing"
method_category = "scalable"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
base = NearestDepotRouting(self.time_limit_sec).solve(instance)
best_dist = base.metrics.objective_value
best_routes = base.solution.get("routes", [])
rng = random.Random(42)
iterations = 0
deadline = t0 + self.time_limit_sec
data = instance.data
while time.perf_counter() < deadline and iterations < 300:
iterations += 1
if not best_routes:
break
ri = rng.randint(0, len(best_routes) - 1)
route = list(best_routes[ri])
if len(route) < 2:
continue
i, j = rng.sample(range(len(route)), 2)
route[i], route[j] = route[j], route[i]
new_routes = list(best_routes)
new_routes[ri] = route
new_dist = sum(_route_distance(data["depot"], data["customers"], r) for r in new_routes)
if new_dist < best_dist:
best_dist, best_routes = new_dist, new_routes
elapsed = time.perf_counter() - t0
return self._make_result(instance, best_dist, "alns", elapsed, True,
{"total_distance": best_dist, "routes": best_routes}, iterations=iterations)
class ScenarioRouting(BaseMethod):
method_id = "scenario_routing"
method_label = "Scenario Robust Routing"
method_category = "robust"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
objs = []
for factor in (0.8, 1.0, 1.2):
perturbed = dict(instance.data)
perturbed["demands"] = [max(1, int(d * factor)) for d in instance.data["demands"]]
mini = ProblemInstance(
problem_type="routing", instance_id=instance.instance_id,
label=instance.label, size=instance.size, seed=instance.seed,
data=perturbed, features=instance.features,
)
res = NearestDepotRouting(self.time_limit_sec / 3).solve(mini)
objs.append(res.metrics.objective_value)
robust_obj = max(objs)
elapsed = time.perf_counter() - t0
return self._make_result(instance, robust_obj, "scenario_robust", elapsed, True,
{"worst_case_distance": robust_obj, "scenario_costs": objs})
# ---------------------------------------------------------------------------
# Assignment
# ---------------------------------------------------------------------------
class GreedyAssignment(BaseMethod):
method_id = "greedy_assignment"
method_label = "Greedy Assignment"
method_category = "baseline"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
n = instance.data["n_agents"]
costs = instance.data["cost_matrix"]
assigned_j, total = [], 0.0
used = set()
for i in range(n):
best_j = min((j for j in range(n) if j not in used), key=lambda j: costs[i][j])
assigned_j.append(best_j)
used.add(best_j)
total += costs[i][best_j]
elapsed = time.perf_counter() - t0
return self._make_result(instance, total, "heuristic", elapsed, True,
{"assignment": assigned_j, "total_cost": total})
class HighsAssignment(BaseMethod):
method_id = "highs_assignment"
method_label = "HiGHS MIP Assignment"
method_category = "exact"
solver_id = "highs"
def solve(self, instance: ProblemInstance) -> SolveResult:
import highspy
t0 = time.perf_counter()
n = instance.data["n_agents"]
costs = instance.data["cost_matrix"]
h = highspy.Highs()
h.setOptionValue("time_limit", self.time_limit_sec)
cols = []
for i in range(n):
for j in range(n):
cols.append(highspy.HighsVarType.kInteger)
h.addVars(n * n, cols)
for i in range(n):
row = [0.0] * (n * n)
for j in range(n):
row[i * n + j] = 1.0
h.addRow(1.0, 1.0, len(row), list(range(n * n)), row)
for j in range(n):
row = [0.0] * (n * n)
for i in range(n):
row[i * n + j] = 1.0
h.addRow(1.0, 1.0, len(row), list(range(n * n)), row)
for idx in range(n * n):
h.changeColBounds(idx, 0, 1)
obj = [costs[idx // n][idx % n] for idx in range(n * n)]
h.changeColsCost(n * n, list(range(n * n)), obj)
h.changeObjectiveSense(highspy.ObjSense.kMinimize)
h.run()
elapsed = time.perf_counter() - t0
sol = h.getSolution()
feasible = h.getModelStatus() == highspy.HighsModelStatus.kOptimal
total = sum(sol.col_value[idx] * costs[idx // n][idx % n] for idx in range(n * n)) if feasible else 0
return self._make_result(instance, total, "optimal" if feasible else "infeasible", elapsed, feasible,
{"total_cost": total}, bound=total if feasible else 0)
class LocalSearchAssignment(BaseMethod):
method_id = "local_search_assignment"
method_label = "Local Search"
method_category = "scalable"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
base = GreedyAssignment(self.time_limit_sec).solve(instance)
perm = list(base.solution.get("assignment", []))
costs = instance.data["cost_matrix"]
n = len(perm)
best = sum(costs[i][perm[i]] for i in range(n))
iterations = 0
deadline = t0 + self.time_limit_sec
while time.perf_counter() < deadline and iterations < 500:
iterations += 1
i, j = random.randint(0, n - 1), random.randint(0, n - 1)
new_perm = list(perm)
new_perm[i], new_perm[j] = new_perm[j], new_perm[i]
new_cost = sum(costs[k][new_perm[k]] for k in range(n))
if new_cost < best:
best, perm = new_cost, new_perm
elapsed = time.perf_counter() - t0
return self._make_result(instance, best, "local_search", elapsed, True,
{"assignment": perm, "total_cost": best}, iterations=iterations)
class StochasticAssignment(BaseMethod):
method_id = "stochastic_assignment"
method_label = "Stochastic Assignment"
method_category = "robust"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
costs = instance.data["cost_matrix"]
n = instance.data["n_agents"]
rng = random.Random(42)
worst = 0.0
for _ in range(5):
perturbed = [[c * rng.uniform(0.85, 1.15) for c in row] for row in costs]
mini = ProblemInstance(
problem_type="assignment", instance_id=instance.instance_id,
label=instance.label, size=instance.size, seed=instance.seed,
data={"n_agents": n, "cost_matrix": perturbed},
features=instance.features,
)
res = GreedyAssignment(self.time_limit_sec / 5).solve(mini)
worst = max(worst, res.metrics.objective_value)
elapsed = time.perf_counter() - t0
return self._make_result(instance, worst, "stochastic", elapsed, True, {"worst_case_cost": worst})
# ---------------------------------------------------------------------------
# Inventory, Facility, Packing (condensed implementations)
# ---------------------------------------------------------------------------
class ReorderPointInventory(BaseMethod):
method_id = "reorder_point"
method_label = "Reorder Point Heuristic"
method_category = "baseline"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
total_cost = 0.0
for i in range(data["n_items"]):
stock = data["initial_stock"][i]
for t in range(data["horizon"]):
d = data["demand"][i][t]
if stock < d:
total_cost += data["stockout_cost"][i] * (d - stock)
stock = 0
else:
stock -= d
total_cost += data["holding_cost"][i] * stock
if stock < sum(data["demand"][i]) / data["horizon"]:
total_cost += data["order_cost"][i]
stock += sum(data["demand"][i])
elapsed = time.perf_counter() - t0
return self._make_result(instance, total_cost, "heuristic", elapsed, True, {"total_cost": total_cost})
class CpSatInventory(BaseMethod):
method_id = "cp_sat_inventory"
method_label = "CP-SAT Inventory MIP"
method_category = "exact"
solver_id = "cp_sat"
def solve(self, instance: ProblemInstance) -> SolveResult:
from ortools.sat.python import cp_model
t0 = time.perf_counter()
data = instance.data
ni, h = data["n_items"], data["horizon"]
model = cp_model.CpModel()
order = {}
stock = {}
for i in range(ni):
for t in range(h):
order[i, t] = model.new_int_var(0, data["max_order"][i], f"o_{i}_{t}")
stock[i, t] = model.new_int_var(0, data["max_order"][i] * 2, f"s_{i}_{t}")
obj_terms = []
for i in range(ni):
for t in range(h):
d = data["demand"][i][t]
shortfall = model.new_int_var(0, d, f"sh_{i}_{t}")
model.add(stock[i, t] + order[i, t] >= d - shortfall)
if t == 0:
model.add(stock[i, t] == data["initial_stock"][i] + order[i, t] - d + shortfall)
else:
model.add(stock[i, t] == stock[i, t - 1] + order[i, t] - d + shortfall)
obj_terms.append(int(data["holding_cost"][i] * 100) * stock[i, t])
obj_terms.append(int(data["stockout_cost"][i] * 100) * shortfall)
obj_terms.append(int(data["order_cost"][i] * 100) * order[i, t])
model.minimize(sum(obj_terms))
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = self.time_limit_sec
status = solver.solve(model)
elapsed = time.perf_counter() - t0
feasible = status in (cp_model.OPTIMAL, cp_model.FEASIBLE)
obj = solver.objective_value / 100.0 if feasible else 0.0
return self._make_result(instance, obj, solver.status_name(status), elapsed, feasible,
{"total_cost": obj}, bound=obj if feasible else 0,
iterations=solver.num_branches)
class DecompositionInventory(BaseMethod):
method_id = "decomposition_inventory"
method_label = "Rolling Decomposition"
method_category = "scalable"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
total = 0.0
data = instance.data
window = max(2, data["horizon"] // 3)
for start in range(0, data["horizon"], window):
end = min(start + window, data["horizon"])
mini_data = dict(data)
mini_data["horizon"] = end - start
mini_data["demand"] = [row[start:end] for row in data["demand"]]
mini = ProblemInstance(
problem_type="inventory", instance_id=instance.instance_id,
label=instance.label, size=instance.size, seed=instance.seed,
data=mini_data, features=instance.features,
)
res = ReorderPointInventory(self.time_limit_sec / 3).solve(mini)
total += res.metrics.objective_value
elapsed = time.perf_counter() - t0
return self._make_result(instance, total, "decomposition", elapsed, True, {"total_cost": total})
class SimulationInventory(BaseMethod):
method_id = "simulation_inventory"
method_label = "Simulation-Based Optimization"
method_category = "robust"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
rng = random.Random(42)
costs = []
for _ in range(8):
data = dict(instance.data)
data["demand"] = [
[max(1, int(d * rng.uniform(0.7, 1.3))) for d in row]
for row in instance.data["demand"]
]
mini = ProblemInstance(
problem_type="inventory", instance_id=instance.instance_id,
label=instance.label, size=instance.size, seed=instance.seed,
data=data, features=instance.features,
)
res = ReorderPointInventory(self.time_limit_sec / 8).solve(mini)
costs.append(res.metrics.objective_value)
avg = sum(costs) / len(costs)
elapsed = time.perf_counter() - t0
return self._make_result(instance, avg, "simulation", elapsed, True,
{"expected_cost": avg, "scenario_costs": costs})
class NearestFacility(BaseMethod):
method_id = "nearest_facility"
method_label = "Nearest Facility Greedy"
method_category = "baseline"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
opened, total = set(), 0.0
for c in range(data["n_customers"]):
f = min(range(data["n_facilities"]), key=lambda f: data["transport_costs"][c][f])
if f not in opened:
opened.add(f)
total += data["fixed_costs"][f]
total += data["transport_costs"][c][f]
elapsed = time.perf_counter() - t0
return self._make_result(instance, total, "heuristic", elapsed, True,
{"opened_facilities": list(opened), "total_cost": total})
class CbcFacility(BaseMethod):
method_id = "cbc_facility"
method_label = "CBC Facility MIP"
method_category = "exact"
solver_id = "cbc"
def solve(self, instance: ProblemInstance) -> SolveResult:
import pulp
t0 = time.perf_counter()
data = instance.data
nf, nc = data["n_facilities"], data["n_customers"]
prob = pulp.LpProblem("facility", pulp.LpMinimize)
y = [pulp.LpVariable(f"y{f}", cat="Binary") for f in range(nf)]
x = {}
for c in range(nc):
for f in range(nf):
x[c, f] = pulp.LpVariable(f"x_{c}_{f}", cat="Binary")
prob += sum(data["fixed_costs"][f] * y[f] for f in range(nf))
prob += sum(data["transport_costs"][c][f] * x[c, f] for c in range(nc) for f in range(nf))
for c in range(nc):
prob += sum(x[c, f] for f in range(nf)) == 1
for c in range(nc):
for f in range(nf):
prob += x[c, f] <= y[f]
prob.solve(pulp.PULP_CBC_CMD(timeLimit=self.time_limit_sec, msg=False))
elapsed = time.perf_counter() - t0
feasible = prob.status == 1
obj = pulp.value(prob.objective) if feasible else 0.0
return self._make_result(instance, obj, "optimal" if feasible else "infeasible", elapsed, feasible,
{"total_cost": obj}, bound=obj if feasible else 0)
class GaFacility(BaseMethod):
method_id = "ga_facility"
method_label = "GA Facility Selection"
method_category = "scalable"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
nf, nc = data["n_facilities"], data["n_customers"]
rng = random.Random(42)
def eval_open(mask: list[int]) -> float:
opened = [f for f in range(nf) if mask[f]]
if not opened:
return 1e18
total = sum(data["fixed_costs"][f] for f in opened)
for c in range(nc):
total += min(data["transport_costs"][c][f] for f in opened)
return total
best_mask = [1] * nf
best = eval_open(best_mask)
iterations = 0
deadline = t0 + self.time_limit_sec
while time.perf_counter() < deadline and iterations < 200:
iterations += 1
f = rng.randint(0, nf - 1)
new_mask = list(best_mask)
new_mask[f] = 1 - new_mask[f]
new_obj = eval_open(new_mask)
if new_obj < best:
best, best_mask = new_obj, new_mask
elapsed = time.perf_counter() - t0
return self._make_result(instance, best, "ga", elapsed, True,
{"total_cost": best, "opened": [f for f in range(nf) if best_mask[f]]},
iterations=iterations)
class ScenarioFacility(BaseMethod):
method_id = "scenario_facility"
method_label = "Scenario Robust Location"
method_category = "robust"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
worst = 0.0
for factor in (1.0, 1.15, 1.3):
data = dict(instance.data)
data["fixed_costs"] = [int(c * factor) for c in instance.data["fixed_costs"]]
mini = ProblemInstance(
problem_type="facility_location", instance_id=instance.instance_id,
label=instance.label, size=instance.size, seed=instance.seed,
data=data, features=instance.features,
)
res = NearestFacility(self.time_limit_sec / 3).solve(mini)
worst = max(worst, res.metrics.objective_value)
elapsed = time.perf_counter() - t0
return self._make_result(instance, worst, "scenario_robust", elapsed, True, {"worst_case_cost": worst})
class FirstFitDecreasing(BaseMethod):
method_id = "first_fit_decreasing"
method_label = "First Fit Decreasing"
method_category = "baseline"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
items = sorted(range(data["n_items"]), key=lambda i: -data["item_sizes"][i])
bins: list[list[int]] = []
bin_loads: list[int] = []
for i in items:
placed = False
for b, load in enumerate(bin_loads):
if load + data["item_sizes"][i] <= data["bin_capacity"]:
bins[b].append(i)
bin_loads[b] += data["item_sizes"][i]
placed = True
break
if not placed:
bins.append([i])
bin_loads.append(data["item_sizes"][i])
elapsed = time.perf_counter() - t0
return self._make_result(instance, len(bins), "heuristic", elapsed, True,
{"bins_used": len(bins), "bins": bins})
class CpSatPacking(BaseMethod):
method_id = "cp_sat_packing"
method_label = "CP-SAT Bin Packing"
method_category = "exact"
solver_id = "cp_sat"
def solve(self, instance: ProblemInstance) -> SolveResult:
from ortools.sat.python import cp_model
t0 = time.perf_counter()
data = instance.data
n, cap = data["n_items"], data["bin_capacity"]
max_bins = n
model = cp_model.CpModel()
y = [model.new_bool_var(f"y{b}") for b in range(max_bins)]
x = {}
for i in range(n):
for b in range(max_bins):
x[i, b] = model.new_bool_var(f"x_{i}_{b}")
for i in range(n):
model.add(sum(x[i, b] for b in range(max_bins)) == 1)
for b in range(max_bins):
model.add(sum(data["item_sizes"][i] * x[i, b] for i in range(n)) <= cap * y[b])
model.minimize(sum(y))
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = self.time_limit_sec
status = solver.solve(model)
elapsed = time.perf_counter() - t0
feasible = status in (cp_model.OPTIMAL, cp_model.FEASIBLE)
obj = solver.objective_value if feasible else 0.0
return self._make_result(instance, obj, solver.status_name(status), elapsed, feasible,
{"bins_used": obj}, bound=obj if feasible else 0,
iterations=solver.num_branches)
class AlnsPacking(BaseMethod):
method_id = "alns_packing"
method_label = "ALNS Packing"
method_category = "scalable"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
base = FirstFitDecreasing(self.time_limit_sec).solve(instance)
best_bins = base.solution.get("bins", [])
best = len(best_bins)
iterations = 0
deadline = t0 + self.time_limit_sec
data = instance.data
while time.perf_counter() < deadline and iterations < 200 and len(best_bins) >= 2:
iterations += 1
bi = random.randint(0, len(best_bins) - 1)
if not best_bins[bi]:
continue
item = random.choice(best_bins[bi])
new_bins = [list(b) for b in best_bins]
new_bins[bi].remove(item)
new_bins = [b for b in new_bins if b]
placed = False
for b in new_bins:
load = sum(data["item_sizes"][i] for i in b)
if load + data["item_sizes"][item] <= data["bin_capacity"]:
b.append(item)
placed = True
break
if not placed:
new_bins.append([item])
if len(new_bins) < best:
best, best_bins = len(new_bins), new_bins
elapsed = time.perf_counter() - t0
return self._make_result(instance, best, "alns", elapsed, True,
{"bins_used": best, "bins": best_bins}, iterations=iterations)
class DynamicPacking(BaseMethod):
method_id = "dynamic_packing"
method_label = "Dynamic Item Arrival"
method_category = "robust"
def solve(self, instance: ProblemInstance) -> SolveResult:
t0 = time.perf_counter()
data = instance.data
rng = random.Random(42)
order = list(range(data["n_items"]))
rng.shuffle(order)
bins: list[list[int]] = []
loads: list[int] = []
for i in order:
placed = False
for b, load in enumerate(loads):
if load + data["item_sizes"][i] <= data["bin_capacity"]:
bins[b].append(i)
loads[b] += data["item_sizes"][i]
placed = True
break
if not placed:
bins.append([i])
loads.append(data["item_sizes"][i])
elapsed = time.perf_counter() - t0
return self._make_result(instance, len(bins), "dynamic", elapsed, True,
{"bins_used": len(bins), "arrival_order": order})
METHOD_REGISTRY: dict[str, BaseMethod] = {
cls.method_id: cls # type: ignore[misc]
for cls in [
SptBaseline, CpSatScheduling, GaScheduling, RollingHorizonScheduling,
NearestDepotRouting, CpSatRouting, AlnsRouting, ScenarioRouting,
GreedyAssignment, HighsAssignment, LocalSearchAssignment, StochasticAssignment,
ReorderPointInventory, CpSatInventory, DecompositionInventory, SimulationInventory,
NearestFacility, CbcFacility, GaFacility, ScenarioFacility,
FirstFitDecreasing, CpSatPacking, AlnsPacking, DynamicPacking,
]
}
def get_method(method_id: str, time_limit_sec: float = 10.0) -> BaseMethod:
cls = METHOD_REGISTRY.get(method_id)
if cls is None:
raise ValueError(f"Unknown method: {method_id}")
return cls(time_limit_sec)
|