| """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,
|
| )
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 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)
|
|
|