diff --git a/tasks/eiselt2009/mathematical_formulation.md b/tasks/eiselt2009/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..5bf5203581c9fd26b7fb0bdf016adb73dc5ff8c1 --- /dev/null +++ b/tasks/eiselt2009/mathematical_formulation.md @@ -0,0 +1,59 @@ +# Sets and Parameters + +- $N$: set of all nodes (origins, destinations, potential hub locations); indices $i, j \in N$. + +- $\mathrm{Own}$: set of candidate hub nodes for the entering airline (“us”); indices $k, \ell \in \mathrm{Own}$. + +- $\mathrm{Comp}$: set of hub nodes of existing (competing) airlines; $|\mathrm{Comp}| = r$. + +- $s$: airline index; $s = o$ denotes the entering airline, $s = 1,2,\ldots$ denote incumbent airlines. + +- $h_{ij}$: known non-elastic demand for air traffic from origin $i$ to destination $j$. + +- $p$: number of hubs to be located by the entering airline (exogenously given). + +- $A_{k\ell s}$: basic attractiveness of the hub pair $(k, \ell)$ operated by airline $s$. + +- $\beta, \lambda$: attraction-decay exponents for travel time and travel cost, respectively. + +- $\gamma \in [0,1]$: relative weight of travel time vs. travel cost. + +- $\alpha \leq 1$: discount factor for interhub fare (economies of scale). + +- $t_{ijk\ell s}$: total travel time for route $(i,j,k,\ell)$ by airline $s$. + +- $c_{ijk\ell s}$: total fare for route $(i,j,k,\ell)$ by airline $s$. + +# Derived Quantities + +Utility (attraction) of route $(i,j,k,\ell)$ by airline $s$ (Equation (1)): $$\begin{equation} +u_{ijk\ell s} \;=\; \frac{A_{k\ell s}}{\gamma\, t_{ijk\ell s}^{\beta} \;+\; (1-\gamma)\, c_{ijk\ell s}^{\lambda}} \tag{1} +\end{equation}$$ + +Probability that a customer traveling from $i$ to $j$ uses route $(k,\ell)$ via the entering airline $o$ (Equation (2)): $$\begin{equation} +p_{ijk\ell o} \;=\; \frac{u_{ijk\ell o}}{\displaystyle \sum_{m, n \in \mathrm{Own}} u_{ijmno} \;+\; \sum_{s \neq o} \sum_{m, n \in \mathrm{Comp}} u_{ijmns}} \tag{2} +\end{equation}$$ + +# Decision Variables + +$$\begin{align*} +y_k &\in \{0,1\} && \forall\, k \in \mathrm{Own} \quad (\text{1 if hub is located at $k$ by entering airline}) \\ +w_{k\ell} &\in \{0,1\} && \forall\, k, \ell \in \mathrm{Own} \quad (\text{1 if hubs are located at \emph{both} $k$ and $\ell$}) +\end{align*}$$ + +# Objective (nonlinear sum-of-ratios form, Equation (3)) + +$$\begin{align} +\mathrm{P}: \quad \max\; z +&= \sum_{i,j} \sum_{k, \ell \in \mathrm{Own}} h_{ij} \, p_{ijk\ell o} \notag \\ +&= \sum_{i,j} h_{ij}\, \frac{\displaystyle\sum_{k, \ell \in \mathrm{Own}} w_{k\ell}\, u_{ijk\ell o}}{\displaystyle\sum_{m, n \in \mathrm{Own}} w_{mn}\, u_{ijmno} \;+\; \sum_{s \neq o} \sum_{m, n \in \mathrm{Comp}} u_{ijmns}} \tag{3} +\end{align}$$ + +# Constraints + +$$\begin{align} +w_{k\ell} &\leq y_k && \forall\, k, \ell \in \mathrm{Own} \tag{4} \\ +w_{k\ell} &\leq y_\ell && \forall\, k, \ell \in \mathrm{Own} \tag{5} \\ +\sum_{k} y_k &= p \tag{6} \\ +y_k,\; w_{k\ell} &\in \{0,1\} && \forall\, k, \ell \in \mathrm{Own} \tag{7} +\end{align}$$ diff --git a/tasks/eiselt2009/problem_description.txt b/tasks/eiselt2009/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..205bd07a1d1f2a62d75eddea800f200b39a8ab5a --- /dev/null +++ b/tasks/eiselt2009/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A region is served by an air transportation network in which several nodes represent cities that are simultaneously origins, destinations, and candidate hub locations. One or more incumbent airlines already operate hub-and-spoke networks in this region, each with a fixed set of hub airports. A new entrant airline wishes to enter this market by opening exactly a prescribed number of hubs, chosen from the full set of nodes, so as to capture as large a share of total passenger traffic as possible. + +The input data consists of the following. There is a set of nodes, each with spatial coordinates and a fixed waiting time representing the dwell or layover delay passengers experience at that airport. A demand matrix gives the known, non-elastic number of passengers wishing to travel from every origin to every destination. A distance matrix gives the pairwise distances between all nodes. A set of nodes is designated as the fixed hub locations of the competing airlines, and the number of hubs the entrant must open is given. Several global parameters govern customer behavior: an interhub fare discount factor that reduces the fare charged on the hub-to-hub leg of a trip to reflect economies of scale; a time-versus-cost weight that ranges from zero to one and controls how much customers value travel time relative to fare; an attraction decay exponent for travel time; an attraction decay exponent for fare; and a cost scalar that converts distances into fares. In addition, each combination of hub pair and airline has a given attractiveness value that reflects the quality of the airline, the convenience of the hub airports, and whether the route passes through a single hub or two distinct hubs. + +Every trip from an origin to a destination may be routed through a pair of hubs, where the two hubs may be the same node (a single-hub route) or different nodes (a two-hub route). For each airline and each ordered hub pair, the total travel time on a route equals the sum of the travel time from the origin to the first hub, the travel time between the two hubs, the travel time from the second hub to the destination, and the fixed waiting times at the origin airport, the first hub, and the second hub. Travel times on each leg are proportional to the distance between the endpoints. The total fare on a route equals the fare from the origin to the first hub, plus the interhub fare discount factor times the fare between the two hubs, plus the fare from the second hub to the destination, where each leg fare is proportional to the distance of that leg scaled by the cost scalar. For each airline, each ordered origin-destination pair (with the origin i and destination j held fixed), and each unordered pair of two distinct hubs {k, l}, only one of the two corresponding two-hub routes is considered open: namely, whichever of the route i -> k -> l -> j and the route i -> l -> k -> j yields the higher customer utility. The origin and destination are never swapped; only the visiting order of the two intermediate hubs is reversed (so the comparison is between two four-node paths that share the same first node i and the same last node j and differ only in the relative order of the two hub nodes in between). + +The utility that customers perceive for a particular route operated by a particular airline is the attractiveness of that hub pair divided by the sum of two terms: the time-versus-cost weight times the total travel time raised to the time decay exponent, plus the quantity (one minus the time-versus-cost weight) multiplied by (the total fare raised to the fare decay exponent). In particular, the exponentiation by the fare decay exponent applies only to the total fare and not to the product of the weight complement and the fare, and the "one minus" applies only to the time-versus-cost weight and not to the entire product; equivalently, denoting the time-versus-cost weight by gamma, the total time by t, the total fare by c, the time decay exponent by beta, and the fare decay exponent by lambda, the denominator equals gamma * t^beta + (1 - gamma) * c^lambda. The probability that a passenger traveling from a given origin to a given destination chooses a particular route offered by the entrant airline equals the utility of that route divided by the sum of the utilities of all routes offered by all airlines, including all routes the entrant offers through its opened hub pairs and all routes every incumbent airline offers through its fixed hub pairs. The expected number of passengers captured by the entrant on a given route is the demand for that origin-destination pair multiplied by this probability. + +The entrant must select exactly the prescribed number of nodes at which to open hubs. A hub pair is considered active for the entrant only if both nodes in the pair have been selected as hubs. The goal is to maximize the total expected number of passengers captured by the entrant across all origin-destination pairs and all of the entrant's active hub-pair routes, where capture on each origin-destination pair is the demand times the fraction of total utility contributed by the entrant's active routes. diff --git a/tasks/eiselt2009/solution_logger.py b/tasks/eiselt2009/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/eiselt2009/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/eiselt2009/solution_schema.json b/tasks/eiselt2009/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a83bf5e1be3b088ea211396ecc3c2fb301b20128 --- /dev/null +++ b/tasks/eiselt2009/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total captured passenger demand across all origin-destination pairs for the entering airline.", + "hub_locations": " Node indices selected as hub locations for the entering airline." +} diff --git a/tasks/elci2022/feasibility_check.py b/tasks/elci2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..8e21f3816ecba82541f101be4a273e07842fcf95 --- /dev/null +++ b/tasks/elci2022/feasibility_check.py @@ -0,0 +1,666 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Stochastic Planning & Scheduling problem +(Elci & Hooker, 2020) - Minimum Makespan variant. + +Checks constraints from the deterministic equivalent MILP (Eq. 22), +numbered 1-9 from top to bottom: + + Constraint 1 (22b): sum_i x_{ij} = 1 for all j in J + Constraint 2 (22c): beta_omega >= beta_{i,omega} for all i in I, omega in Omega + Constraint 3 (22d): x_{ij} in {0,1} for all i in I, j in J + Constraint 4 (22e): beta_omega >= sum_t (t + p^omega_ij) z^omega_ijt + for all i in I, j in J, omega in Omega + Constraint 5 (22f): z^omega_ijt <= x_{ij} for all i,j,t,omega + Constraint 6 (22g): sum_i sum_t z^omega_ijt = 1 for all j in J, omega in Omega + Constraint 7 (22h): sum_j sum_{t' in T^omega_tij} c_{ij} z^omega_ijt' <= K_i + for all i in I, t in T, omega in Omega + Constraint 8 (22i): z^omega_ijt = 0 for t < r_j for all i,omega,j,t + Constraint 9 (22j): z^omega_ijt in {0,1} for all i,j,t,omega + +Constraint 10 (objective consistency, Tier-C defense): the reported + objective_value must equal the recomputed expected makespan + sum_omega pi_omega * beta_omega, where beta_omega = max_j finish_j in + scenario omega. Every variable needed for this recompute (the per- + scenario finish times) is present in the solution's `schedule`, so a + FULL two-sided recompute is possible. + + The original Constraint 4 (22e) objective check is ONE-SIDED -- it only + flags reported < computed. Constraint 10 adds the symmetric direction + (reported > computed), rejecting fabricated/inflated objective values + that the structural constraint checks alone would otherwise accept. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'objective_value', 'schedule') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('schedule',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance_path, solution_path, result_path): + tol = 1e-5 + eps = 1e-5 + + with open(instance_path) as f: + inst = json.load(f) + with open(solution_path) as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return _frontieror_contract_result + + n = inst["n"] + m = inst["m"] + S = inst["num_scenarios"] + K = inst["facility_capacity_limits"] # K[i] + c = inst["capacity_requirements"] # c[i][j] + r = inst["release_times"] # r[j] + scenarios = inst["scenarios"] + pi_prob = [sc["probability"] for sc in scenarios] + p = [sc["processing_times"] for sc in scenarios] # p[omega][i][j] + + assignment = sol.get("assignment", {}) + schedule = sol.get("schedule", None) + objective_value = sol.get("objective_value", None) + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # Parse assignment: job j -> facility i + assign = {} + for j_str, i_val in assignment.items(): + assign[int(j_str)] = int(i_val) + + # Build x[i][j] matrix from assignment + x = [[0] * n for _ in range(m)] + for j_val, i_val in assign.items(): + if 0 <= i_val < m and 0 <= j_val < n: + x[i_val][j_val] = 1 + + # ------------------------------------------------------------------ + # Constraint 1 (22b): sum_i x_{ij} = 1 for all j in J + # ------------------------------------------------------------------ + for j in range(n): + lhs = sum(x[i][j] for i in range(m)) + rhs_val = 1.0 + violation_amount = abs(lhs - rhs_val) + if violation_amount > tol: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (22b): Job {j} assigned to {lhs} facilities (expected 1)" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ------------------------------------------------------------------ + # Constraint 3 (22d): x_{ij} in {0,1} for all i, j + # Check that assignment values are valid (binary, valid facility index) + # ------------------------------------------------------------------ + for j in range(n): + if j in assign: + fac = assign[j] + if fac < 0 or fac >= m: + violated_constraints.add(3) + violation_amount = 1.0 + violations.append( + f"Constraint 3 (22d): Job {j} assigned to invalid facility {fac} " + f"(valid range 0..{m-1})" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(fac), + "rhs": 0.0, + "raw_excess": float(violation_amount), + "normalizer": max(float(m - 1), eps), + "ratio": float(violation_amount / max(float(m - 1), eps)), + }) + + # ------------------------------------------------------------------ + # Constraints 2, 4-9 require schedule data (z variables) + # ------------------------------------------------------------------ + if schedule is not None: + # Parse schedule: sched[omega][j] = {facility, start, finish} + sched = {} + for omega_str, jobs in schedule.items(): + omega = int(omega_str) + sched[omega] = {} + for j_str, info in jobs.items(): + j_val = int(j_str) + sched[omega][j_val] = { + "facility": int(info["facility"]), + "start": float(info["start"]), + "finish": float(info["finish"]), + } + + for omega in range(S): + if omega not in sched: + continue + + # Compute per-facility makespan (beta_{i,omega}) and scenario makespan (beta_omega) + beta_iw = [0.0] * m + for j_val in range(n): + if j_val not in sched[omega]: + continue + info = sched[omega][j_val] + fac = info["facility"] + beta_iw[fac] = max(beta_iw[fac], info["finish"]) + + beta_omega = max(beta_iw) if any( + j_val in sched[omega] for j_val in range(n) + ) else 0.0 + + # ---------------------------------------------------------- + # Constraint 2 (22c): beta_omega >= beta_{i,omega} + # This is a >= constraint: LHS = beta_omega, RHS = beta_{i,omega} + # Violated if beta_{i,omega} > beta_omega + # ---------------------------------------------------------- + for i in range(m): + violation_amount = max(0.0, beta_iw[i] - beta_omega) + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Constraint 2 (22c): Scenario {omega}, facility {i}: " + f"beta_omega={beta_omega:.4f} < beta_{{i,omega}}={beta_iw[i]:.4f}" + ) + normalizer = max(abs(beta_iw[i]), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(beta_omega), + "rhs": float(beta_iw[i]), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ---------------------------------------------------------- + # Constraint 4 (22e): beta_omega >= finish_j for all i, j + # For the assigned facility, finish_j = start_j + p[omega][fac][j]. + # Also verify finish time consistency with processing times. + # ---------------------------------------------------------- + for j_val in range(n): + if j_val not in sched[omega]: + continue + info = sched[omega][j_val] + fac = info["facility"] + start_j = info["start"] + finish_j = info["finish"] + + # Verify finish = start + processing time + if 0 <= fac < m: + expected_finish = start_j + p[omega][fac][j_val] + diff = abs(finish_j - expected_finish) + if diff > tol: + violated_constraints.add(4) + violations.append( + f"Constraint 4 (22e): Scenario {omega}, job {j_val}: " + f"finish={finish_j} != start({start_j}) + " + f"p[{omega}][{fac}][{j_val}]({p[omega][fac][j_val]}) = {expected_finish}" + ) + normalizer = max(abs(expected_finish), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(finish_j), + "rhs": float(expected_finish), + "raw_excess": float(diff), + "normalizer": float(normalizer), + "ratio": float(diff / normalizer), + }) + + # beta_omega >= finish_j + violation_amount = max(0.0, finish_j - beta_omega) + if violation_amount > tol: + violated_constraints.add(4) + violations.append( + f"Constraint 4 (22e): Scenario {omega}, job {j_val}: " + f"beta_omega={beta_omega:.4f} < finish={finish_j}" + ) + normalizer = max(abs(finish_j), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(beta_omega), + "rhs": float(finish_j), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Check objective consistency: objective_value should equal + # sum pi_omega * beta_omega (computed from schedule) + # This is an additional check for constraint 4 validity. + if objective_value is not None and S > 0: + computed_obj = 0.0 + all_scenarios_present = True + for om in range(S): + if om in sched and sched[om]: + mk = max(sched[om][jj]["finish"] for jj in sched[om]) + computed_obj += pi_prob[om] * mk + else: + all_scenarios_present = False + + if all_scenarios_present: + violation_amount = max(0.0, computed_obj - objective_value) + if violation_amount > tol: + violated_constraints.add(4) + violations.append( + f"Constraint 4 (22e): Reported objective {objective_value} " + f"< computed makespan objective {computed_obj:.4f}" + ) + normalizer = max(abs(computed_obj), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(objective_value), + "rhs": float(computed_obj), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ---------------------------------------------------------- + # Constraint 5 (22f): z^omega_ijt <= x_{ij} + # Job scheduled on a facility must be assigned there. + # ---------------------------------------------------------- + for j_val in range(n): + if j_val not in sched[omega]: + continue + sched_fac = sched[omega][j_val]["facility"] + assigned_fac = assign.get(j_val, -1) + if sched_fac != assigned_fac: + violated_constraints.add(5) + violations.append( + f"Constraint 5 (22f): Scenario {omega}, job {j_val}: " + f"scheduled on facility {sched_fac} but assigned to facility {assigned_fac}" + ) + rhs_val = 0.0 # x_{sched_fac, j} = 0 + violation_magnitudes.append({ + "constraint": 5, + "lhs": 1.0, + "rhs": float(rhs_val), + "raw_excess": 1.0, + "normalizer": max(abs(rhs_val), eps), + "ratio": float(1.0 / max(abs(rhs_val), eps)), + }) + + # ---------------------------------------------------------- + # Constraint 6 (22g): sum_i sum_t z^omega_ijt = 1 for all j, omega + # Each job must be scheduled exactly once per scenario. + # ---------------------------------------------------------- + for j_val in range(n): + count = 1 if j_val in sched[omega] else 0 + rhs_val = 1.0 + violation_amount = abs(count - rhs_val) + if violation_amount > tol: + violated_constraints.add(6) + violations.append( + f"Constraint 6 (22g): Scenario {omega}, job {j_val}: " + f"scheduled {count} times (expected 1)" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(count), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ---------------------------------------------------------- + # Constraint 7 (22h): Cumulative resource capacity + # At each time t, for facility i: + # sum of c_{ij} for jobs j active at t <= K_i + # Job j active at t if start_j <= t < start_j + p[omega][i][j] + # ---------------------------------------------------------- + facility_jobs = {i: [] for i in range(m)} + for j_val in range(n): + if j_val in sched[omega]: + fac = sched[omega][j_val]["facility"] + facility_jobs[fac].append(j_val) + + for i in range(m): + if not facility_jobs[i]: + continue + + # Collect event times (start and finish of each job on this facility) + events = set() + for j_val in facility_jobs[i]: + info = sched[omega][j_val] + events.add(int(info["start"])) + events.add(int(info["finish"])) + + # Check resource usage at each event time and just before each event + times_to_check = set() + for ev in events: + times_to_check.add(ev) + if ev > 0: + times_to_check.add(ev - 1) + + worst_violation = 0.0 + worst_t = None + worst_lhs = 0.0 + + for t in sorted(times_to_check): + resource_used = 0.0 + for j_val in facility_jobs[i]: + info = sched[omega][j_val] + s_j = info["start"] + f_j = info["finish"] + if s_j <= t < f_j: + resource_used += c[i][j_val] + + violation_amount = max(0.0, resource_used - K[i]) + if violation_amount > worst_violation: + worst_violation = violation_amount + worst_t = t + worst_lhs = resource_used + + if worst_violation > tol: + violated_constraints.add(7) + violations.append( + f"Constraint 7 (22h): Scenario {omega}, facility {i}, " + f"time {worst_t}: resource usage {worst_lhs} > capacity {K[i]}" + ) + normalizer = max(abs(float(K[i])), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(worst_lhs), + "rhs": float(K[i]), + "raw_excess": float(worst_violation), + "normalizer": float(normalizer), + "ratio": float(worst_violation / normalizer), + }) + + # ---------------------------------------------------------- + # Constraint 8 (22i): z^omega_ijt = 0 for t < r_j + # Equivalently: start_j >= r_j (release time) + # This is a >= constraint. + # ---------------------------------------------------------- + for j_val in range(n): + if j_val not in sched[omega]: + continue + start_j = sched[omega][j_val]["start"] + rhs_val = float(r[j_val]) + violation_amount = max(0.0, rhs_val - start_j) + if violation_amount > tol: + violated_constraints.add(8) + violations.append( + f"Constraint 8 (22i): Scenario {omega}, job {j_val}: " + f"start={start_j} < release time={r[j_val]}" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 8, + "lhs": float(start_j), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ---------------------------------------------------------- + # NOTE: The original two-stage stochastic program (1)-(3) uses + # CONTINUOUS start-time variables s_j. The integer start_time + # check (formerly "Constraint 9 (22j): z^omega_ijt in {0,1}") + # only applies to the time-indexed deterministic-equivalent + # reformulation (22), where z^omega_ijt binary requires starts + # to land on integer time indices. LLM-evolved algorithms that + # solve the original continuous-time problem produce valid + # non-integer starts, which this checker must accept. + # Accordingly, the integer-start check is INTENTIONALLY OMITTED. + # ---------------------------------------------------------- + + # ------------------------------------------------------------------ + # Constraint 10 (objective consistency, full two-sided recompute): + # The reported objective_value must equal the expected makespan + # sum_{omega} pi_omega * beta_omega, + # where beta_omega = max_j finish_j in scenario omega. + # All variables required for this recompute (the per-scenario job + # finish times) are present in the solution's `schedule`, so a FULL + # recompute is possible -- no second-stage LP needs to be re-solved. + # + # The original Constraint 4 (22e) objective check above is + # ONE-SIDED: it only flags reported < computed. This Constraint 10 + # check is the symmetric Tier-C defense -- it rejects ANY + # disagreement (within tolerance) between the reported objective and + # the recomputed one, in particular reported > computed, i.e. + # fabricated / inflated objective values (e.g. sys.float_info.max) + # that the structural constraint checks alone would accept. + # ------------------------------------------------------------------ + if schedule is not None and objective_value is not None and S > 0: + obj_sched = {} + try: + for omega_str, jobs in schedule.items(): + om = int(omega_str) + obj_sched[om] = {} + for j_str, info in jobs.items(): + obj_sched[om][int(j_str)] = float(info["finish"]) + except (TypeError, ValueError, KeyError): + obj_sched = None + + if obj_sched is not None: + computed_obj = 0.0 + all_scenarios_present = True + for om in range(S): + if om in obj_sched and obj_sched[om]: + computed_obj += pi_prob[om] * max(obj_sched[om].values()) + else: + all_scenarios_present = False + + if all_scenarios_present: + try: + reported = float(objective_value) + except (TypeError, ValueError): + reported = None + if reported is not None: + abs_diff = abs(reported - computed_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor + obj_tol = max(1e-3, 1e-3 * abs(computed_obj)) + if abs_diff > obj_tol: + violated_constraints.add(10) + violations.append( + f"Constraint 10 (objective consistency): reported " + f"objective_value={reported} differs from recomputed " + f"expected makespan sum_omega(pi_omega*beta_omega)=" + f"{computed_obj:.4f} (|diff|={abs_diff:.4g}, " + f"tol={obj_tol:.4g})" + ) + normalizer = max(abs(computed_obj), eps) + violation_magnitudes.append({ + "constraint": 10, + "lhs": float(reported), + "rhs": float(computed_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + # ------------------------------------------------------------------ + # Build output + # ------------------------------------------------------------------ + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(result_path, "w") as f: + json.dump(result, f, indent=2) + + return result + + +if __name__ == "__main__": + try: + parser = argparse.ArgumentParser( + description="Feasibility checker for stochastic planning & scheduling " + "(Elci & Hooker 2020, Eq. 22)." + ) + parser.add_argument( + "--instance_path", required=True, + help="Path to the JSON instance file." + ) + parser.add_argument( + "--solution_path", required=True, + help="Path to the JSON solution file." + ) + parser.add_argument( + "--result_path", required=True, + help="Path to write the JSON feasibility result." + ) + args = parser.parse_args() + + result = check_feasibility(args.instance_path, args.solution_path, args.result_path) + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Result: {status}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/elci2022/gurobi_code.py b/tasks/elci2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4eeb8b381dff97f1490af80f1ebbaff3486c35ef --- /dev/null +++ b/tasks/elci2022/gurobi_code.py @@ -0,0 +1,291 @@ +""" +Deterministic Equivalent MILP for Stochastic Planning and Scheduling +Paper: "Stochastic Planning and Scheduling with Logic-Based Benders Decomposition" + Elci & Hooker (2020) +Model: Eq. (22) – Minimum Makespan variant + +Usage: + python gurobi_code.py --instance_path instance_1.json \ + --solution_path gurobi_solution_1.json \ + --time_limit 3600 +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def compute_time_horizon(n, m, S, r, p): + """ + Upper bound on the scheduling horizon. + NOT SPECIFIED IN PAPER exactly. + INFERRED ASSUMPTION: T_max = max_j(r_j) + sum_j(max_{i,omega}(p^omega_ij)). + This is a valid upper bound because even if all jobs run sequentially + starting from the latest release time, the makespan cannot exceed this value. + """ + max_release = max(r) + # For each job, the largest processing time across all facilities and scenarios + max_proc_per_job = [ + max(p[omega][i][j] for i in range(m) for omega in range(S)) + for j in range(n) + ] + return max_release + sum(max_proc_per_job) + + +# --------------------------------------------------------------------------- +# Main solver +# --------------------------------------------------------------------------- + +def solve(instance_path, solution_path, time_limit): + # ---- Load instance ---- + with open(instance_path) as f: + inst = json.load(f) + + n = inst["n"] # number of jobs + m = inst["m"] # number of facilities + S = inst["num_scenarios"] + K = inst["facility_capacity_limits"] # K[i] + c = inst["capacity_requirements"] # c[i][j] + r = inst["release_times"] # r[j] + scenarios = inst["scenarios"] + pi = [sc["probability"] for sc in scenarios] + p = [sc["processing_times"] for sc in scenarios] # p[omega][i][j] + + T_max = compute_time_horizon(n, m, S, r, p) + + # ---- Build model ---- + model = gp.Model("DetEquivMILP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, time_limit * 0.05)) + + # ---------------------------------------------------------------- + # Variables + # ---------------------------------------------------------------- + + # x[i,j] in {0,1}: 1 if job j assigned to facility i (Eq. 22d) + x = {} + for i in range(m): + for j in range(n): + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + # beta[omega] >= 0: scenario-level makespan surrogate (Eq. 22a) + beta = { + omega: model.addVar(lb=0.0, name=f"beta_{omega}") + for omega in range(S) + } + + # beta_iw[i,omega] >= 0: facility–scenario makespan surrogate (Eq. 22c) + beta_iw = { + (i, omega): model.addVar(lb=0.0, name=f"biw_{i}_{omega}") + for i in range(m) for omega in range(S) + } + + # z[omega,i,j,t] in {0,1}: 1 if job j starts at time t on facility i, scenario omega + # Only create for valid (omega, i, j, t): r[j] <= t <= T_max - p[omega][i][j] + z = {} + for omega in range(S): + for i in range(m): + for j in range(n): + p_ij = p[omega][i][j] + t_end = T_max - p_ij + for t in range(r[j], max(r[j], t_end) + 1): + z[omega, i, j, t] = model.addVar( + vtype=GRB.BINARY, name=f"z_{omega}_{i}_{j}_{t}" + ) + + # ---------------------------------------------------------------- + # Objective (Eq. 22a): minimize sum_omega pi_omega * beta_omega + # ---------------------------------------------------------------- + model.setObjective( + gp.quicksum(pi[omega] * beta[omega] for omega in range(S)), + GRB.MINIMIZE + ) + + # ---------------------------------------------------------------- + # Constraint (22b): each job assigned to exactly one facility + # ---------------------------------------------------------------- + for j in range(n): + model.addConstr( + gp.quicksum(x[i, j] for i in range(m)) == 1, + name=f"assign_{j}" + ) + + # ---------------------------------------------------------------- + # Constraint (22c): beta_omega >= beta_iw[i,omega] + # ---------------------------------------------------------------- + for omega in range(S): + for i in range(m): + model.addConstr( + beta[omega] >= beta_iw[i, omega], + name=f"betadecomp_{omega}_{i}" + ) + + # ---------------------------------------------------------------- + # Constraint (22e): beta_iw[i,omega] >= finish time of job j on facility i + # beta_iw[i,omega] >= sum_t (t + p_ij) * z_ijt for all i, j, omega + # Note: z_ijt = 0 when job j is NOT assigned to facility i (from constraint f), + # so this properly bounds the facility makespan. + # ---------------------------------------------------------------- + for omega in range(S): + for i in range(m): + for j in range(n): + p_ij = p[omega][i][j] + valid = [ + (t, z[omega, i, j, t]) + for t in range(r[j], T_max - p_ij + 1) + if (omega, i, j, t) in z + ] + if valid: + model.addConstr( + beta_iw[i, omega] >= gp.quicksum( + (t + p_ij) * zv for t, zv in valid + ), + name=f"mksp_{omega}_{i}_{j}" + ) + + # ---------------------------------------------------------------- + # Constraint (22f): z_ijt <= x_ij + # ---------------------------------------------------------------- + for (omega, i, j, t), zv in z.items(): + model.addConstr(zv <= x[i, j], name=f"link_{omega}_{i}_{j}_{t}") + + # ---------------------------------------------------------------- + # Constraint (22g): each job scheduled in exactly one (facility, time) slot + # per scenario + # ---------------------------------------------------------------- + for omega in range(S): + for j in range(n): + model.addConstr( + gp.quicksum( + z[omega, i, j, t] + for i in range(m) + for t in range(r[j], T_max - p[omega][i][j] + 1) + if (omega, i, j, t) in z + ) == 1, + name=f"sched_{omega}_{j}" + ) + + # ---------------------------------------------------------------- + # Constraint (22h): cumulative resource capacity at each time point. + # + # Paper states: T^omega_tij = {t' | 0 <= t' <= t - p^omega_ij} + # However, applying the standard cumulative constraint interpretation, + # job j (started at t') is ACTIVE at time t if t' <= t < t' + p_ij, + # i.e., t - p_ij + 1 <= t' <= t. + # + # INFERRED ASSUMPTION: We use the standard cumulative formulation where + # job j is active at time t iff its start time t' satisfies + # max(r_j, t - p_ij + 1) <= t' <= t. This is the correct formulation + # for a cumulative resource constraint and matches the CP subproblem (11). + # ---------------------------------------------------------------- + for omega in range(S): + for i in range(m): + for t in range(T_max + 1): + parts = [] + for j in range(n): + p_ij = p[omega][i][j] + t_lo = max(r[j], t - p_ij + 1) + t_hi = t + for t_prime in range(t_lo, t_hi + 1): + if (omega, i, j, t_prime) in z: + parts.append(c[i][j] * z[omega, i, j, t_prime]) + if parts: + model.addConstr( + gp.quicksum(parts) <= K[i], + name=f"cap_{omega}_{i}_{t}" + ) + + # ---------------------------------------------------------------- + # Solve + # ---------------------------------------------------------------- + model.optimize() + + # ---------------------------------------------------------------- + # Extract and write solution + # ---------------------------------------------------------------- + result = { + "objective_value": None, + "status": "no_solution", + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.status == GRB.OPTIMAL else "time_limit" + + assignment = {} + for j in range(n): + for i in range(m): + if x[i, j].X > 0.5: + assignment[str(j)] = i + result["assignment"] = assignment + + schedule = {} + for omega in range(S): + schedule[str(omega)] = {} + for j in range(n): + for i in range(m): + for t in range(r[j], T_max + 1): + if (omega, i, j, t) in z and z[omega, i, j, t].X > 0.5: + schedule[str(omega)][str(j)] = { + "facility": i, + "start": t, + "finish": t + p[omega][i][j], + } + result["schedule"] = schedule + + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Objective value : {result['objective_value']}") + print(f"Status : {result['status']}") + return result + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Solve stochastic planning & scheduling via deterministic " + "equivalent MILP (Eq. 22, Elci & Hooker 2020)." + ) + parser.add_argument( + "--instance_path", required=True, + help="Path to the JSON instance file." + ) + parser.add_argument( + "--solution_path", required=True, + help="Path where the solution JSON will be written." + ) + parser.add_argument( + "--time_limit", type=int, required=True, + help="Maximum solver time in seconds." + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/elci2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/elci2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/elci2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/elci2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/elci2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/elci2022/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/elci2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/elci2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/elci2022/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/elci2022/gurobi_solution/large_solution_1.json b/tasks/elci2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..67029db960d877a34edf08271283cdf852a1c9a9 --- /dev/null +++ b/tasks/elci2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f70745cb57b7d02ed05c87aad42295f7c8516e0f5412169c3462303c16c43f8 +size 40056 diff --git a/tasks/elci2022/gurobi_solution/large_solution_2.json b/tasks/elci2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..5c2ce309e21a13278966458ff9db75d7e0b8319e --- /dev/null +++ b/tasks/elci2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbd8235274dba4659ae444b6419cb80741435cbe92a8fde670d6deb48d0393cc +size 40053 diff --git a/tasks/elci2022/gurobi_solution/large_solution_3.json b/tasks/elci2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..4840923a8ead234feb9450de34bdb686f8d374c8 --- /dev/null +++ b/tasks/elci2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:269902e0ef7a3d8f241288c9e055d86fb1be73fb3b1ce3dec439fd963b7905d5 +size 40061 diff --git a/tasks/elci2022/gurobi_solution/large_solution_4.json b/tasks/elci2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..0006424ca81302621a5623dbc09db7c784aefcf2 --- /dev/null +++ b/tasks/elci2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4555930fc66b0fb4bd97bfd6eab5cfdcd5557e5831b8d27ed5434f34df9009ce +size 40024 diff --git a/tasks/elci2022/gurobi_solution/large_solution_5.json b/tasks/elci2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..238c67527f1853633843ca4c02ccd9ff323b5d43 --- /dev/null +++ b/tasks/elci2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e010ffd21711d842287d61bfb50a96a79d4bd9890054b9f6be2c36b9e50290ba +size 40043 diff --git a/tasks/elci2022/gurobi_solution/tiny_solution.json b/tasks/elci2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..b738d12a5c17e5ac91405ba03c9e9878af5c9e9c --- /dev/null +++ b/tasks/elci2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea965457fce80fa668a3f42f4a6feb56909b2ef8ac26b3b5e1190077300cb1c1 +size 1119 diff --git a/tasks/elci2022/gurobi_solution_log/large_log_1.jsonl b/tasks/elci2022/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4629a02394565e7a588092398dda5e19490a097b --- /dev/null +++ b/tasks/elci2022/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a93d25ea627e70f82697dd7c0f8ff951932e1872211956c637c3044703207067 +size 1030 diff --git a/tasks/elci2022/gurobi_solution_log/large_log_2.jsonl b/tasks/elci2022/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..edd12a4ae89f2e4edeb7a4fcb521aa45694a788a --- /dev/null +++ b/tasks/elci2022/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2deb923dd27265ff47af622924e53badc5f5dd9a94277b60708a0c5e8a70f5af +size 641 diff --git a/tasks/elci2022/gurobi_solution_log/large_log_3.jsonl b/tasks/elci2022/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0bb9dcac0d07249705b0bdb71eea099a7886927e --- /dev/null +++ b/tasks/elci2022/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bda7818edcd8ab0f3ec0217c8c96338400dbf428408be0de443f2603129bbc9a +size 1283 diff --git a/tasks/elci2022/gurobi_solution_log/large_log_4.jsonl b/tasks/elci2022/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4bd899235057b0017cc93c2da809339a24b9e0ed --- /dev/null +++ b/tasks/elci2022/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de1acabe4be8094a13ce08f2492c14d487ec1273e622a320af5d36b862582c3d +size 865 diff --git a/tasks/elci2022/gurobi_solution_log/large_log_5.jsonl b/tasks/elci2022/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..23b3135520f9da6a13c8c87801c9feddc57ee5cd --- /dev/null +++ b/tasks/elci2022/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d9ce387a5ef3f58508837ccba76c42e04826ec41e5555ca9f1c4c27f62c2b09 +size 603 diff --git a/tasks/elci2022/gurobi_solution_log/tiny_log.jsonl b/tasks/elci2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4515d30e648deebb369bfbfaa1be88867eb6041d --- /dev/null +++ b/tasks/elci2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92946e707c5d1ae5135b4eb5a6685627e1be8ae41bbfb03ae1367d5bf6c6f5cb +size 83 diff --git a/tasks/elci2022/instance/large_instance_1.json b/tasks/elci2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d7deb9e0909daa21e82e3a9318c9c5ad76fc6778 --- /dev/null +++ b/tasks/elci2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e231d8b82dd401795c880f16ce6ec7879aea35572fa1ce1fd5e8a183ad97ccf4 +size 9326 diff --git a/tasks/elci2022/instance/large_instance_2.json b/tasks/elci2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..0ab5e5742b31c2756d93a79a0f0e2a5e0073d21c --- /dev/null +++ b/tasks/elci2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:059cfa17376ab67646861911c9fa2a0c7d541d58bcd20a48010f525a06bb3b5e +size 9419 diff --git a/tasks/elci2022/instance/large_instance_3.json b/tasks/elci2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e4616229ff47ec267ef2e7f0686d350a275c39e0 --- /dev/null +++ b/tasks/elci2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:671001a8628b0b96dd08dd7bd6b3cc30c3ac470f192cfa124eb64d9c3e64a5e8 +size 9017 diff --git a/tasks/elci2022/instance/large_instance_4.json b/tasks/elci2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..fcfecf539f35f51a1d49e872a646f2fd2a8a9504 --- /dev/null +++ b/tasks/elci2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ed0d66f7862cc6a5f0a0955860511028bccdfc9209292aee7aaefdf9814fe17 +size 9253 diff --git a/tasks/elci2022/instance/large_instance_5.json b/tasks/elci2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..2cba6c711636decc8294f91e8e9f686a8bf9e019 --- /dev/null +++ b/tasks/elci2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1739ec2a8f6eda87083ab63cd62be3169eb89578e40906e53484a718421d2193 +size 8671 diff --git a/tasks/elci2022/instance/tiny_instance.json b/tasks/elci2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..80b0d1eee681c0055e5d0840ad3c7ea02eef9e13 --- /dev/null +++ b/tasks/elci2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b183b9a4b3bd8a148d0462bf29cf5e10dd1bbba27f99fbd7a9400510cca41799 +size 1187 diff --git a/tasks/elci2022/instance_schema.json b/tasks/elci2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9f7d6ff620bc94772426fa819925173d229ae5b7 --- /dev/null +++ b/tasks/elci2022/instance_schema.json @@ -0,0 +1,15 @@ +{ + "n": " Number of jobs to be processed.", + "m": " Number of facilities available for processing jobs.", + "num_scenarios": " Number of uncertain processing-time scenarios considered.", + "facility_capacity_limits": " Maximum resource capacity of each facility at any point in time.", + "capacity_requirements": " Resource consumption rate of each job when processed on each facility.", + "release_times": " Earliest time at which each job may begin processing.", + "mean_processing_times": " Nominal processing time of each job on each facility before scenario-based perturbation.", + "scenarios": [ + { + "probability": " Likelihood of this scenario occurring.", + "processing_times": " Realized processing time of each job on each facility under this scenario." + } + ] +} diff --git a/tasks/elci2022/mathematical_formulation.md b/tasks/elci2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..89f533ed42708bb40f6df13ab77564927d8e3972 --- /dev/null +++ b/tasks/elci2022/mathematical_formulation.md @@ -0,0 +1,56 @@ +# Original Formulation: Two-Stage Stochastic Planning and Scheduling + +*Source: Stochastic Planning and Scheduling with Logic-Based Benders Decomposition, Özgün Elçi and J. N. Hooker, 2020/2022.* + +## Sets and Parameters + +- $J$: set of jobs, indexed by $j$. + +- $I$: set of facilities, indexed by $i$. + +- $\Omega$: finite set of scenarios, indexed by $\omega$; $\pi_\omega \ge 0$ is the probability of scenario $\omega$, with $\sum_{\omega \in \Omega} \pi_\omega = 1$. + +- $p^{\omega}_{ij}$: processing time of job $j$ on facility $i$ in scenario $\omega$. + +- $r_j$: release time of job $j$. + +- $d_j$: deadline of job $j$; each job must be processed within $[r_j, d_j]$. + +- $c_{ij}$: resource consumption of job $j$ on facility $i$ (cumulative scheduling). + +- $K_i$: maximum total resource consumption on facility $i$ at any instant. + +- $g(\mathbf{x})$: first-stage cost as a function of the assignment. + +- $h(\mathbf{s},\mathbf{x},\omega)$: second-stage objective. + +## Decision Variables + +- **First-stage (binary)**: $x_j \in I$ for all $j \in J$, i.e. $x_j$ denotes the facility to which job $j$ is assigned. Equivalently, $x_{ij} \in \{0,1\}$ with $x_{ij} = 1$ iff job $j$ is assigned to facility $i$. For each $\mathbf{x}$, let $J_i(\mathbf{x}) = \{j \in J : x_j = i\}$ denote the set of jobs assigned to facility $i$. + +- **Second-stage (continuous)**: $s_j \ge 0$ for all $j \in J$, the start time of job $j$; $s_j$ is determined after the scenario $\omega$ is revealed. + +## Objective + +$$\begin{align} +\min_{\mathbf{x}} \quad & g(\mathbf{x}) + \sum_{\omega \in \Omega} \pi_\omega\, Q(\mathbf{x}, \omega) + \;:\; x_j \in I,\ \forall j \in J, \tag{3} +\end{align}$$ where the second-stage value is $$\begin{align} +Q(\mathbf{x}, \omega) = \min_{\mathbf{s}} \quad & h(\mathbf{s}, \mathbf{x}, \omega) \tag{2} +\end{align}$$ *(With (1): $\min_{\mathbf{x}\in X}\{f(\mathbf{x}) + \mathbb{E}_{\omega}[Q(\mathbf{x},\omega)]\}$.)* + +## Constraints of the Second Stage (for each scenario $\omega \in \Omega$) + +$$\begin{align} +s_j \in [\, r_j,\; d_j - p^{\omega}_{x_j,j} \,], + & \quad \forall j \in J, \tag{TW}\\ +\sum_{\substack{j \in J_i(\mathbf{x}) \\ 0 \le t \le s_j + p^{\omega}_{x_j,j}}} c_{ij} \le K_i, + & \quad \forall i \in I,\; \forall t \ge 0. \tag{CUM} +\end{align}$$ Here (TW) are the time-window constraints ensuring each job finishes before its deadline under its (scenario-dependent) processing time. The cumulative resource constraint (CUM) states that, at every point in time $t$, the total resource consumption of jobs being processed on facility $i$ must not exceed $K_i$. Each assignment $\mathbf{x}$ induces, for every $(\omega, i)$, a cumulative scheduling problem over the jobs in $J_i(\mathbf{x})$ with continuous start-time variables $s_j$. + +## First-Stage Constraints + +$$\begin{align} +\sum_{i \in I} x_{ij} &= 1, & \forall j \in J, \notag\\ +x_{ij} &\in \{0,1\}, & \forall i \in I,\; j \in J. \notag +\end{align}$$ diff --git a/tasks/elci2022/problem_description.txt b/tasks/elci2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..b0472440ba2c6ffc8effd692287b5fdbcb017bb6 --- /dev/null +++ b/tasks/elci2022/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A company operates a set of facilities and must process a set of jobs under uncertainty. Processing times are uncertain and modeled through a finite set of scenarios, each with a known probability. The input data specifies, for each facility, a resource capacity limit. For each combination of job and facility, the data provides a resource consumption rate and a scenario-dependent processing time. Each job also has a release time before which it cannot begin processing. Jobs have no deadlines. + +The company must make two types of decisions. First, before the uncertain processing times are revealed, each job must be assigned to exactly one facility. Second, after a scenario is realized, the jobs assigned to each facility must be scheduled by choosing a start time for each job. A job's start time must be no earlier than its release time. Multiple jobs may run simultaneously on the same facility, but at every point in time the total resource consumption of all jobs whose processing intervals overlap that time point must not exceed the facility's resource capacity. Specifically, a job assigned to a given facility occupies resources from its start time until its start time plus its processing time on that facility under the realized scenario, and during this entire interval the job's resource consumption counts toward the facility's capacity limit. + +The goal is to minimize the expected makespan across all scenarios. The makespan under a given scenario is the latest completion time among all jobs, where a job's completion time equals its start time plus its processing time on its assigned facility under that scenario. The expected makespan is the probability-weighted sum of the scenario makespans. There is no first-stage assignment cost, so the entire objective consists of this expected makespan. diff --git a/tasks/elci2022/solution_logger.py b/tasks/elci2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/elci2022/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/elci2022/solution_schema.json b/tasks/elci2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..952045f229540c556cbf8e0042b9fb1e7bf103d3 --- /dev/null +++ b/tasks/elci2022/solution_schema.json @@ -0,0 +1,13 @@ +{ + "objective_value": " Expected makespan across all scenarios, weighted by scenario probabilities.", + "assignment": " Facility to which each job is assigned before uncertainty is revealed.", + "schedule": { + "{scenario}": { + "{job}": { + "facility": " Facility on which this job is processed in this scenario.", + "start": " Time at which this job begins processing in this scenario.", + "finish": " Time at which this job completes processing in this scenario." + } + } + } +} diff --git a/tasks/engineer2012/feasibility_check.py b/tasks/engineer2012/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f289ae7872420703626755815410082bb7eb6a32 --- /dev/null +++ b/tasks/engineer2012/feasibility_check.py @@ -0,0 +1,963 @@ +#!/usr/bin/env python3 +""" +Feasibility Checker for Single-Product Maritime Inventory Routing. + +Checks hard constraints from the mathematical formulation in Engineer et al. (2012): + "A Branch-Price-and-Cut Algorithm for Single-Product Maritime Inventory Routing" + +Constraints checked (numbered as in the paper formulation): + (1) Inventory balance at supply ports + (2) Inventory balance at demand ports + (3) Storage capacity bounds: 0 <= I_{j,t} <= Q_{j,t} + (4) Convexity: each vessel executes exactly one voyage (sum lambda = 1) + (5) Non-negativity: lambda >= 0 + (6) Integrality of load/discharge decisions (z in {0,1}) + (7) Flow conservation (path from source to sink) + (8) Load/discharge only if node is visited + (9) Load/discharge quantity bounds: F_min * z <= |f| <= F_max * z + (10) Vessel inventory tracking along path + (11) Vessel inventory capacity: 0 <= F_n <= U_n + (12) Arc integrality + (13) Load/discharge decision integrality (z in {0,1}) + +Usage: + python feasibility_check.py --instance_path instance_1.json \ + --solution_path efficient_solution_1.json \ + --result_path efficient_feasi_result_1.json +""" + +import argparse +import ast +import json +import math +import sys +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('cost_breakdown', 'objective_value', 'port_inventories', 'vessel_operations', 'vessel_routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('cost_breakdown', 'objective_value', 'port_inventories', 'vessel_routes') +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def parse_instance(data): + """Parse instance data into a structured format.""" + T = data["planning_horizon"] + vessels = {} + for v in data["vessels"]: + vessels[v["id"]] = { + "id": v["id"], + "capacity": v["capacity"], + "avail_start": v["availability_start"], + "avail_end": v["availability_end"], + "initial_load": v.get("initial_load", 0), + "transport_cost_per_day": v["transport_cost_per_day"], + "demurrage_cost_per_day": v["demurrage_cost_per_day"], + } + + supply_ports = {} + for sp in data["supply_ports"]: + supply_ports[sp["port_id"]] = { + "port_id": sp["port_id"], + "type": "supply", + "initial_inventory": sp["initial_inventory"], + "rates": sp["production_rate"], + "storage_capacity": sp["storage_capacity"], + "F_min": sp["F_min"], + "F_max": sp["F_max"], + "unit_cost": sp["unit_procurement_cost"], + } + + demand_ports = {} + for dp in data["demand_ports"]: + demand_ports[dp["port_id"]] = { + "port_id": dp["port_id"], + "type": "demand", + "initial_inventory": dp["initial_inventory"], + "rates": dp["consumption_rate"], + "storage_capacity": dp["storage_capacity"], + "F_min": dp["F_min"], + "F_max": dp["F_max"], + "unit_cost": dp["unit_supply_revenue"], + } + + travel_times = {} + for key, val in data["travel_times"].items(): + a, b = key.split("->") + travel_times[(a, b)] = val + + draft_limits = {} + for key, val in data.get("draft_limits", {}).items(): + a, b = key.split("->") + draft_limits[(a, b)] = val + + return T, vessels, supply_ports, demand_ports, travel_times, draft_limits + + +def parse_solution(sol_data, vessels_info): + """Parse the serialized operation witness for every vessel.""" + vessel_visits = {} + operations = sol_data["vessel_operations"] + for vid in vessels_info: + visits = [] + for op in operations.get(vid, []): + visits.append({ + "port": op["port"], + "time": int(op["time"]), + "load_discharge": float(op["quantity"]), + "type": op["type"], + }) + visits.sort(key=lambda visit: visit["time"]) + vessel_visits[vid] = visits + return vessel_visits + + +def parse_route_node(serialized): + """Parse the tuple representation emitted by gurobi_code.py.""" + node = ast.literal_eval(serialized) + if not isinstance(node, tuple) or len(node) != 2: + raise ValueError(f"invalid route node {serialized!r}") + return node + + +def check_feasibility(instance_data, solution_data): + """Check all hard constraints and return violations.""" + tol = 1e-5 + eps = 1e-5 + + T, vessels, supply_ports, demand_ports, travel_times, draft_limits = \ + parse_instance(instance_data) + + vessel_visits = parse_solution(solution_data, vessels) + + all_ports = {} + all_ports.update(supply_ports) + all_ports.update(demand_ports) + + violations = [] + violation_magnitudes = [] + + def add_violation(constraint_idx, message, lhs, rhs, violation_amount): + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append((constraint_idx, message)) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ===================================================================== + # Constraints (7), (8), (10), and (12): validate the complete serialized + # source-to-sink path, arc timing, operation support, and commodity flow. + # Route entries are unordered in the JSON, so first reconstruct the path. + # ===================================================================== + expected_vessels = set(vessels) + route_witness = solution_data["vessel_routes"] + operation_witness = solution_data["vessel_operations"] + if set(route_witness) != expected_vessels: + add_violation( + 7, + "vessel_routes keys do not exactly cover the instance vessels", + float(len(route_witness)), float(len(expected_vessels)), 1.0, + ) + if set(operation_witness) != expected_vessels: + add_violation( + 8, + "vessel_operations keys do not exactly cover the instance vessels", + float(len(operation_witness)), float(len(expected_vessels)), 1.0, + ) + + transport_cost = 0.0 + demurrage_cost = 0.0 + for vid, vessel in vessels.items(): + source = ("src", vid) + sink = ("snk", vid) + serialized_arcs = route_witness.get(vid, []) + parsed_arcs = [] + route_nodes = set() + + for arc_position, arc in enumerate(serialized_arcs): + try: + tail = parse_route_node(arc["tail"]) + head = parse_route_node(arc["head"]) + arc_type = arc["type"] + reported_cost = float(arc["cost"]) + product_flow = float(arc["product_flow"]) + if not all(math.isfinite(value) for value in + (reported_cost, product_flow)): + raise ValueError("arc cost/product_flow is not finite") + except (KeyError, TypeError, ValueError, SyntaxError) as error: + add_violation( + 12, + f"Vessel {vid} route arc {arc_position} is malformed: {error}", + 1.0, 0.0, 1.0, + ) + continue + + def is_port_time(node): + return ( + node[0] in all_ports + and isinstance(node[1], int) + and not isinstance(node[1], bool) + and vessel["avail_start"] <= node[1] <= vessel["avail_end"] + ) + + canonical_cost = None + valid_arc = True + if arc_type == "source": + valid_arc = ( + tail == source + and is_port_time(head) + and head[1] == vessel["avail_start"] + ) + canonical_cost = 0.0 + elif arc_type == "sink": + valid_arc = is_port_time(tail) and head == sink + canonical_cost = 0.0 + elif arc_type == "demurrage": + valid_arc = ( + is_port_time(tail) + and is_port_time(head) + and tail[0] == head[0] + and head[1] == tail[1] + 1 + ) + canonical_cost = float(vessel["demurrage_cost_per_day"]) + elif arc_type == "travel": + travel_time = travel_times.get((tail[0], head[0])) + valid_arc = ( + is_port_time(tail) + and is_port_time(head) + and tail[0] != head[0] + and travel_time is not None + and head[1] == tail[1] + travel_time + ) + if travel_time is not None: + canonical_cost = ( + float(vessel["transport_cost_per_day"]) + * float(travel_time) + ) + else: + valid_arc = False + + if not valid_arc or canonical_cost is None: + add_violation( + 7, + f"Vessel {vid} contains an invalid {arc_type!r} arc " + f"{tail!r} -> {head!r}", + 1.0, 0.0, 1.0, + ) + continue + if abs(reported_cost - canonical_cost) > tol: + add_violation( + 7, + f"Vessel {vid} arc {tail!r}->{head!r} reports cost " + f"{reported_cost}, expected {canonical_cost}", + reported_cost, canonical_cost, + abs(reported_cost - canonical_cost), + ) + if product_flow < -tol: + add_violation( + 10, + f"Vessel {vid} has negative product flow on " + f"{tail!r}->{head!r}", + product_flow, 0.0, -product_flow, + ) + + endpoint_limits = [] + for node in (tail, head): + if is_port_time(node): + endpoint_limits.append(min( + vessel["capacity"], + draft_limits.get((vid, node[0]), vessel["capacity"]), + )) + flow_limit = min(endpoint_limits, default=vessel["capacity"]) + if product_flow > flow_limit + tol: + add_violation( + 11, + f"Vessel {vid} product flow {product_flow} exceeds arc " + f"capacity {flow_limit} on {tail!r}->{head!r}", + product_flow, flow_limit, product_flow - flow_limit, + ) + + parsed_arcs.append({ + "tail": tail, + "head": head, + "type": arc_type, + "flow": product_flow, + }) + route_nodes.update((tail, head)) + if arc_type == "travel": + transport_cost += canonical_cost + elif arc_type == "demurrage": + demurrage_cost += canonical_cost + + outgoing = defaultdict(list) + incoming = defaultdict(list) + for arc in parsed_arcs: + outgoing[arc["tail"]].append(arc) + incoming[arc["head"]].append(arc) + structural_error = False + for node in route_nodes | {source, sink}: + expected_in = 0 if node == source else 1 + expected_out = 0 if node == sink else 1 + if len(incoming[node]) != expected_in or len(outgoing[node]) != expected_out: + structural_error = True + add_violation( + 7, + f"Vessel {vid} route degree is invalid at {node!r}: " + f"in={len(incoming[node])}, out={len(outgoing[node])}", + float(len(incoming[node]) + len(outgoing[node])), + float(expected_in + expected_out), 1.0, + ) + + if not structural_error: + traversed = [] + current = source + while current != sink and len(traversed) <= len(parsed_arcs): + arc = outgoing[current][0] + traversed.append(arc) + current = arc["head"] + if current != sink or len(traversed) != len(parsed_arcs): + add_violation( + 7, + f"Vessel {vid} selected arcs do not form one complete " + "source-to-sink path", + float(len(traversed)), float(len(parsed_arcs)), 1.0, + ) + + operation_by_node = {} + for visit in vessel_visits[vid]: + node = (visit["port"], visit["time"]) + if node in operation_by_node: + continue # Constraint 6 records the duplicate below. + operation_by_node[node] = visit["load_discharge"] + expected_type = ( + "load" if visit["port"] in supply_ports else "discharge" + ) + if visit["type"] != expected_type: + add_violation( + 8, + f"Vessel {vid} operation at {node!r} has type " + f"{visit['type']!r}, expected {expected_type!r}", + 1.0, 0.0, 1.0, + ) + if node not in outgoing: + add_violation( + 8, + f"Vessel {vid} operation at {node!r} is not supported by " + "a selected route visit", + 1.0, 0.0, 1.0, + ) + + if len(outgoing[source]) == 1: + source_flow = outgoing[source][0]["flow"] + if abs(source_flow - vessel["initial_load"]) > tol: + add_violation( + 10, + f"Vessel {vid} source flow {source_flow} does not match " + f"initial load {vessel['initial_load']}", + source_flow, vessel["initial_load"], + abs(source_flow - vessel["initial_load"]), + ) + for node in route_nodes - {source, sink}: + if len(incoming[node]) != 1 or len(outgoing[node]) != 1: + continue + incoming_flow = incoming[node][0]["flow"] + outgoing_flow = outgoing[node][0]["flow"] + operation = operation_by_node.get(node, 0.0) + flow_difference = abs(incoming_flow + operation - outgoing_flow) + if flow_difference > 1e-3: + add_violation( + 10, + f"Vessel {vid} commodity flow is inconsistent at " + f"{node!r}: incoming {incoming_flow} + operation " + f"{operation} != outgoing {outgoing_flow}", + incoming_flow + operation, outgoing_flow, flow_difference, + ) + + # ===================================================================== + # Compute net load/discharge at each (port, time) across all vessels + # f_total[port_id][t] = sum over vessels of f_{j,t}^{v,r} + # For supply ports: f > 0 means loading (removing from port inventory) + # For demand ports: f < 0 means discharging (adding to port inventory) + # In the model: I_{j,t} = I_{j,t-1} + b_{j,t} - sum_v f_{j,t} + # ===================================================================== + f_total = defaultdict(lambda: defaultdict(float)) + for vid, visits in vessel_visits.items(): + for visit in visits: + f_total[visit["port"]][visit["time"]] += visit["load_discharge"] + + # ===================================================================== + # Compute port inventories + # ===================================================================== + port_inventory = {} # port_inventory[port_id][t] for t=0..T + for pid, port in all_ports.items(): + inv = [0.0] * (T + 1) + inv[0] = port["initial_inventory"] + for t in range(1, T + 1): + if port["type"] == "supply": + # Constraint (1): I_{j,t} = I_{j,t-1} + b_{j,t} - sum_v f_{j,t} + inv[t] = inv[t - 1] + port["rates"][t - 1] - f_total[pid][t] + else: + # Constraint (2): I_{j,t} = I_{j,t-1} - b_{j,t} - sum_v f_{j,t} + # For demand: f < 0 for discharge, so -f > 0 adds to inventory + inv[t] = inv[t - 1] - port["rates"][t - 1] - f_total[pid][t] + port_inventory[pid] = inv + + # The reported inventory trajectory is a derived witness and must cover + # every port/time exactly; otherwise a candidate could alter operations + # while leaving an unrelated inventory summary in the JSON. + reported_inventories = solution_data["port_inventories"] + if set(reported_inventories) != set(all_ports): + add_violation( + 1, + "port_inventories keys do not exactly cover all instance ports", + float(len(reported_inventories)), float(len(all_ports)), 1.0, + ) + for pid in all_ports: + entries = reported_inventories.get(pid, []) + by_time = {} + for entry in entries: + time_value = int(entry["time"]) + if time_value in by_time: + add_violation( + 1, + f"Port {pid} reports inventory twice at t={time_value}", + 2.0, 1.0, 1.0, + ) + by_time[time_value] = float(entry["inventory"]) + expected_times = set(range(1, T + 1)) + if set(by_time) != expected_times: + add_violation( + 1, + f"Port {pid} inventory times do not exactly cover 1..{T}", + float(len(by_time)), float(T), 1.0, + ) + for time_value in expected_times & set(by_time): + difference = abs( + by_time[time_value] - port_inventory[pid][time_value] + ) + if difference > 1e-3: + add_violation( + 1, + f"Port {pid} reported inventory {by_time[time_value]} at " + f"t={time_value}, expected {port_inventory[pid][time_value]}", + by_time[time_value], port_inventory[pid][time_value], + difference, + ) + + # ===================================================================== + # Constraint (1): Inventory balance at supply ports + # I_{j,t} = I_{j,t-1} + b_{j,t} - sum_v f_{j,t} + # This is an equality constraint. We check it by verifying the computed + # inventory is consistent (it's computed directly, so the balance holds + # by construction). The real check is whether the inventory stays within + # bounds (Constraint 3). However, we still verify the balance equation + # holds as an equality for supply ports. + # ===================================================================== + for pid, port in supply_ports.items(): + for t in range(1, T + 1): + I_prev = port_inventory[pid][t - 1] + b_jt = port["rates"][t - 1] + f_sum = f_total[pid][t] + lhs = port_inventory[pid][t] + rhs_val = I_prev + b_jt - f_sum + diff = abs(lhs - rhs_val) + if diff > tol: + add_violation( + 1, + f"Supply port {pid} inventory balance violated at t={t}: " + f"I[t]={lhs:.4f} != I[t-1]+b-f = {rhs_val:.4f}", + lhs, rhs_val, diff + ) + + # ===================================================================== + # Constraint (2): Inventory balance at demand ports + # I_{j,t} = I_{j,t-1} - b_{j,t} - sum_v f_{j,t} + # ===================================================================== + for pid, port in demand_ports.items(): + for t in range(1, T + 1): + I_prev = port_inventory[pid][t - 1] + b_jt = port["rates"][t - 1] + f_sum = f_total[pid][t] + lhs = port_inventory[pid][t] + rhs_val = I_prev - b_jt - f_sum + diff = abs(lhs - rhs_val) + if diff > tol: + add_violation( + 2, + f"Demand port {pid} inventory balance violated at t={t}: " + f"I[t]={lhs:.4f} != I[t-1]-b-f = {rhs_val:.4f}", + lhs, rhs_val, diff + ) + + # ===================================================================== + # Constraint (3): Storage capacity bounds: 0 <= I_{j,t} <= Q_{j,t} + # This is two inequalities: I_{j,t} >= 0 and I_{j,t} <= Q_{j,t} + # ===================================================================== + for pid, port in all_ports.items(): + for t in range(1, T + 1): + inv = port_inventory[pid][t] + Q_jt = port["storage_capacity"][t - 1] + + # Lower bound: I_{j,t} >= 0 => LHS = -I_{j,t}, RHS = 0 (<=) + # Or equivalently: 0 <= I_{j,t}, violation if I_{j,t} < 0 + if inv < -tol: + violation_amount = -inv # how much below 0 + add_violation( + 3, + f"Port {pid} inventory below 0 at t={t}: " + f"I={inv:.4f} < 0", + inv, 0.0, violation_amount + ) + + # Upper bound: I_{j,t} <= Q_{j,t} + if inv > Q_jt + tol: + violation_amount = inv - Q_jt + add_violation( + 3, + f"Port {pid} inventory exceeds capacity at t={t}: " + f"I={inv:.4f} > Q={Q_jt:.4f}", + inv, Q_jt, violation_amount + ) + + # ===================================================================== + # Constraint (4): Convexity - each vessel has exactly one voyage + # sum_{r in R_v} lambda^{v,r} = 1 + # In the realized solution, each vessel has exactly one schedule. + # This is satisfied by construction since the solution specifies + # one schedule per vessel. We just verify each vessel is present. + # ===================================================================== + for vid in vessels: + # Each vessel should appear in the solution (even if idle) + if vid not in vessel_visits: + add_violation( + 4, + f"Vessel {vid} has no voyage assigned (convexity constraint)", + 0.0, 1.0, 1.0 + ) + + # ===================================================================== + # Constraint (5): Non-negativity: lambda >= 0 + # Trivially satisfied since the solution represents a realized (integral) + # voyage selection with lambda = 1 for the chosen voyage. + # No check needed. + # ===================================================================== + + # ===================================================================== + # Constraint (6): Integrality on load/discharge decisions + # sum_r z_{j,t}^{v,r} lambda^{v,r} in {0,1} + # In realized solution, each vessel visits each (port, time) at most once. + # Check: no vessel visits the same (port, time) more than once. + # ===================================================================== + for vid, visits in vessel_visits.items(): + pt_count = defaultdict(int) + for visit in visits: + key = (visit["port"], visit["time"]) + pt_count[key] += 1 + for (port, time), count in pt_count.items(): + if count > 1: + add_violation( + 6, + f"Vessel {vid} visits ({port}, t={time}) {count} times " + f"(integrality requires at most 1)", + float(count), 1.0, float(count - 1) + ) + + # ===================================================================== + # Constraint (9): Load/discharge quantity bounds + # F_n^{min} * z_n <= f_n <= F_n^{max} * z_n + # For supply: F_min <= f <= F_max (f > 0 for loading) + # For demand: -F_max <= f <= -F_min (f < 0 for discharging) + # So |f| must be in [F_min, F_max] when the port is visited (z=1) + # ===================================================================== + for vid, visits in vessel_visits.items(): + for visit in visits: + pid = visit["port"] + t = visit["time"] + f_val = visit["load_discharge"] + port = all_ports[pid] + F_min = port["F_min"] + F_max = port["F_max"] + abs_f = abs(f_val) + + if port["type"] == "supply": + # f >= F_min when visiting + if f_val < F_min - tol: + violation_amount = F_min - f_val + add_violation( + 9, + f"Vessel {vid} at supply port {pid} t={t}: " + f"load={f_val:.4f} < F_min={F_min}", + f_val, F_min, violation_amount + ) + # f <= F_max when visiting + if f_val > F_max + tol: + violation_amount = f_val - F_max + add_violation( + 9, + f"Vessel {vid} at supply port {pid} t={t}: " + f"load={f_val:.4f} > F_max={F_max}", + f_val, F_max, violation_amount + ) + else: + # Demand port: f <= 0, |f| >= F_min, |f| <= F_max + if f_val > tol: + violation_amount = f_val + add_violation( + 9, + f"Vessel {vid} at demand port {pid} t={t}: " + f"load_discharge={f_val:.4f} > 0 (should be <= 0)", + f_val, 0.0, violation_amount + ) + if abs_f < F_min - tol: + violation_amount = F_min - abs_f + add_violation( + 9, + f"Vessel {vid} at demand port {pid} t={t}: " + f"|discharge|={abs_f:.4f} < F_min={F_min}", + abs_f, F_min, violation_amount + ) + if abs_f > F_max + tol: + violation_amount = abs_f - F_max + add_violation( + 9, + f"Vessel {vid} at demand port {pid} t={t}: " + f"|discharge|={abs_f:.4f} > F_max={F_max}", + abs_f, F_max, violation_amount + ) + + # ===================================================================== + # Constraint (11): Vessel inventory capacity: 0 <= F_n <= U_n + # Track vessel load along its path. U_n = min(Q_v, draft_limit(v,j)) + # The vessel starts with initial_load and accumulates f values. + # + # Per math_model.txt constraint (11): F_n is the vessel inventory + # ENTERING node n (before loading/discharging at n). This is defined + # by constraint (10): F_n = sum_{e=(n',n)} x_e (F_{n'} + f_{n'}). + # Equivalently, from the LP subproblem constraint (14): + # 0 <= sum_{i=0}^{k-1} f_{n_i} <= U_{n_k} for k=1,...,K + # which bounds the cumulative load BEFORE operations at node n_k. + # ===================================================================== + for vid, visits in vessel_visits.items(): + if not visits: + continue + vessel = vessels[vid] + Q_v = vessel["capacity"] + load = vessel["initial_load"] + for i, visit in enumerate(visits): + pid = visit["port"] + t = visit["time"] + f_val = visit["load_discharge"] + + # Draft limit: U_n bounds the inventory ENTERING the node + dl = draft_limits.get((vid, pid), Q_v) + U_n = min(Q_v, dl) + + # Check 0 <= load <= U_n BEFORE loading/discharging at this node + if load < -tol: + violation_amount = -load + add_violation( + 11, + f"Vessel {vid} has negative load={load:.4f} entering " + f"{pid} at t={t}", + load, 0.0, violation_amount + ) + if load > U_n + tol: + violation_amount = load - U_n + add_violation( + 11, + f"Vessel {vid} load={load:.4f} exceeds capacity " + f"U_n={U_n:.4f} entering {pid} at t={t}", + load, U_n, violation_amount + ) + + # Update load AFTER checking the constraint + load += f_val + + # ===================================================================== + # Objective and cost summary: every component is derivable from the route + # and operation witnesses, so bind both cost_breakdown and objective_value + # to those decisions instead of trusting candidate-reported numbers. + # ===================================================================== + procurement_cost = sum( + supply_ports[visit["port"]]["unit_cost"] + * visit["load_discharge"] + for visits in vessel_visits.values() + for visit in visits + if visit["port"] in supply_ports + ) + supply_revenue = sum( + demand_ports[visit["port"]]["unit_cost"] + * (-visit["load_discharge"]) + for visits in vessel_visits.values() + for visit in visits + if visit["port"] in demand_ports + ) + expected_costs = { + "transport_cost": transport_cost, + "demurrage_cost": demurrage_cost, + "procurement_cost": procurement_cost, + "supply_revenue": supply_revenue, + } + expected_costs["total_cost"] = ( + transport_cost + demurrage_cost + procurement_cost - supply_revenue + ) + cost_breakdown = solution_data["cost_breakdown"] + if set(cost_breakdown) != set(expected_costs): + add_violation( + 14, + "cost_breakdown fields do not exactly match the five documented " + "cost components", + float(len(cost_breakdown)), float(len(expected_costs)), 1.0, + ) + for component, expected_value in expected_costs.items(): + if component not in cost_breakdown: + continue + reported_value = float(cost_breakdown[component]) + difference = abs(reported_value - expected_value) + component_tolerance = max(1e-3, 1e-7 * abs(expected_value)) + if not math.isfinite(reported_value) or difference > component_tolerance: + add_violation( + 14, + f"cost_breakdown.{component}={reported_value} does not match " + f"the decision-derived value {expected_value}", + reported_value, expected_value, difference, + ) + + reported_objective = float(solution_data["objective_value"]) + objective_difference = abs( + reported_objective - expected_costs["total_cost"] + ) + objective_tolerance = max( + 1e-3, 1e-7 * abs(expected_costs["total_cost"]) + ) + if objective_difference > objective_tolerance: + add_violation( + 14, + f"objective_value={reported_objective} does not match the " + f"decision-derived total {expected_costs['total_cost']}", + reported_objective, expected_costs["total_cost"], + objective_difference, + ) + + # ===================================================================== + # Compile results + # ===================================================================== + violated_set = sorted(set(c for c, _ in violations)) + violation_messages = [] + # Aggregate messages per constraint + msgs_by_constraint = defaultdict(list) + for c, msg in violations: + msgs_by_constraint[c].append(msg) + for c in violated_set: + msgs = msgs_by_constraint[c] + if len(msgs) <= 3: + violation_messages.extend(msgs) + else: + violation_messages.extend(msgs[:2]) + violation_messages.append( + f"... and {len(msgs) - 2} more violation(s) for constraint {c}" + ) + + feasible = len(violated_set) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_set, + "violations": violation_messages, + "violation_magnitudes": violation_magnitudes if not feasible else [], + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Maritime Inventory Routing") + parser.add_argument("--instance_path", required=True, + help="Path to JSON instance file") + parser.add_argument("--solution_path", required=True, + help="Path to JSON solution file") + parser.add_argument("--result_path", required=True, + help="Path to write JSON feasibility result") + args = parser.parse_args() + + instance_data = load_json(args.instance_path) + solution_data = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution_data) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance_data, solution_data) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"{status}: {args.solution_path}") + if not result["feasible"]: + print(f" Violated constraints: {result['violated_constraints']}") + for msg in result["violations"][:5]: + print(f" - {msg}") + + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/engineer2012/gurobi_code.py b/tasks/engineer2012/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..72c5801cd102a890612d1b7964a19e8e1974fc81 --- /dev/null +++ b/tasks/engineer2012/gurobi_code.py @@ -0,0 +1,904 @@ +#!/usr/bin/env python3 +""" +Compact Arc-Flow MIP Formulation for the Maritime Inventory Routing Problem. + +Based on: + Engineer, Furman, Nemhauser, Savelsbergh, Song (2012), + "A Branch-Price-and-Cut Algorithm for Single-Product Maritime Inventory + Routing" + +Since the column-generation formulation in the paper cannot be directly solved +by Gurobi (the set R_v of voyages is exponentially large), we implement a +compact arc-flow formulation on a time-expanded network, as referenced in +Song and Furman (2012). + +The formulation uses a commodity-flow approach for vessel inventory tracking: + - w[v,e]: continuous flow of product on arc e for vessel v + - This avoids the nonlinear constraint (10) from the paper and the need + for big-M linearization, yielding a much tighter LP relaxation. + +Usage: + python gurobi_code.py --instance_path path/to/instance.json \\ + --solution_path gurobi_solution.json \\ + --time_limit 3600 +""" + +import argparse +import json +import math +import sys +import time + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +# ============================================================================= +# Data Loading +# ============================================================================= + +def load_instance(path): + """Load instance data from a JSON file.""" + with open(path, "r") as fh: + data = json.load(fh) + return data + + +# ============================================================================= +# Helpers +# ============================================================================= + +def _node_str(node): + """Convert a node to a string suitable for constraint naming.""" + if isinstance(node, tuple): + return f"{node[0]}_{node[1]}" + return str(node) + + +# ============================================================================= +# Network Construction +# ============================================================================= + +def build_time_expanded_network(data): + """ + Build a time-expanded network for each vessel. + + For each vessel v, construct: + - Nodes: (j, t) for each port j and each time t in + [avail_start, avail_end], plus source 'src_v' and sink 'snk_v' + - Travel arcs: ((j1,t1), (j2,t2)) with t2 = t1 + travel_time(j1, j2) + - Demurrage arcs: ((j,t), (j,t+1)) for waiting at a port + - Source arcs: from src_v to supply port nodes at avail_start + - Sink arcs: from any port-time node to snk_v + + INFERRED ASSUMPTION: Vessels start "at sea" and can reach any supply port + at their availability_start time. + + Returns: + networks: dict keyed by vessel id + all_ports: list of port ids + port_type: dict port_id -> "supply" or "demand" + travel_time_dict: dict (p1,p2) -> int + draft_limit_dict: dict (v_id, p_id) -> float + """ + T = data["planning_horizon"] + all_ports = [] + port_type = {} + for sp in data["supply_ports"]: + all_ports.append(sp["port_id"]) + port_type[sp["port_id"]] = "supply" + for dp in data["demand_ports"]: + all_ports.append(dp["port_id"]) + port_type[dp["port_id"]] = "demand" + + travel_time_dict = {} + for key, val in data["travel_times"].items(): + p1, p2 = key.split("->") + travel_time_dict[(p1, p2)] = val + + draft_limit_dict = {} + for key, val in data["draft_limits"].items(): + v_id, p_id = key.split("->") + draft_limit_dict[(v_id, p_id)] = val + + networks = {} + + for vessel in data["vessels"]: + v_id = vessel["id"] + avail_start = vessel["availability_start"] + avail_end = vessel["availability_end"] + load_window_end = vessel["loading_window_end"] + cap = vessel["capacity"] + + src_node = ("src", v_id) + snk_node = ("snk", v_id) + + nodes = set() + arcs = [] # list of (tail, head, arc_type, cost) + + # Port-time nodes + for j in all_ports: + for t in range(avail_start, avail_end + 1): + nodes.add((j, t)) + + # Travel arcs + for j1 in all_ports: + for j2 in all_ports: + if j1 == j2: + continue + if (j1, j2) not in travel_time_dict: + continue + tt = travel_time_dict[(j1, j2)] + arc_cost = vessel["transport_cost_per_day"] * tt + for t1 in range(avail_start, avail_end + 1): + t2 = t1 + tt + if t2 > avail_end: + break + arcs.append(((j1, t1), (j2, t2), "travel", arc_cost)) + + # Demurrage arcs + dem_cost = vessel["demurrage_cost_per_day"] + for j in all_ports: + for t in range(avail_start, avail_end): + arcs.append(((j, t), (j, t + 1), "demurrage", dem_cost)) + + # Source arcs: connect to supply ports at avail_start + # INFERRED ASSUMPTION: vessels can appear at any supply port at + # availability_start. We also allow connections to demand ports + # for generality (the cost structure will discourage starting at + # demand ports without cargo). + for j in all_ports: + arcs.append((src_node, (j, avail_start), "source", 0.0)) + + # Sink arcs: from every port-time node + for j in all_ports: + for t in range(avail_start, avail_end + 1): + arcs.append(((j, t), snk_node, "sink", 0.0)) + + nodes.add(src_node) + nodes.add(snk_node) + + # U_n: max product on vessel at node n + U_n = {} + for j in all_ports: + dl = draft_limit_dict.get((v_id, j), cap) + u = min(cap, dl) + for t in range(avail_start, avail_end + 1): + U_n[(j, t)] = u + U_n[src_node] = cap + # INFERRED ASSUMPTION: vessel may end the horizon with remaining + # inventory. We do NOT force emptiness at avail_end. + U_n[snk_node] = cap + + networks[v_id] = { + "nodes": nodes, + "arcs": arcs, + "src": src_node, + "snk": snk_node, + "U_n": U_n, + "capacity": cap, + "avail_start": avail_start, + "avail_end": avail_end, + "load_window_end": load_window_end, + } + + return networks, all_ports, port_type, travel_time_dict, draft_limit_dict + + +# ============================================================================= +# Preprocessing (Eqs. 16, 17) +# ============================================================================= + +def preprocess_bounds(data, networks, all_ports, port_type): + """ + Tighten F_max at supply nodes (Eq. 16) and F_min at demand nodes (Eq. 17). + + Sign convention: + Supply: f >= 0 (loading) -> F_min >= 0, F_max >= 0 + Demand: f <= 0 (discharge) -> F_min <= 0, F_max <= 0 + """ + port_data = {} + for sp in data["supply_ports"]: + port_data[sp["port_id"]] = sp + for dp in data["demand_ports"]: + port_data[dp["port_id"]] = dp + + F_min_node = {} + F_max_node = {} + + for vessel in data["vessels"]: + v_id = vessel["id"] + cap = vessel["capacity"] + net = networks[v_id] + a_s = net["avail_start"] + a_e = net["avail_end"] + + for j in all_ports: + pd = port_data[j] + I0 = pd["initial_inventory"] + + if port_type[j] == "supply": + prod = pd["production_rate"] + stor = pd["storage_capacity"] + Fj_min = pd["F_min"] + Fj_max = pd["F_max"] + + for t in range(a_s, a_e + 1): + sum_p_t = sum(prod[tp - 1] for tp in range(1, t + 1) + if tp - 1 < len(prod)) + sum_p_tm1 = sum(prod[tp - 1] for tp in range(1, t) + if tp - 1 < len(prod)) + Q_tm1 = stor[t - 2] if t >= 2 and t - 2 < len(stor) \ + else stor[0] + b_t = prod[t - 1] if t - 1 < len(prod) else 0 + dl = net["U_n"].get((j, t), cap) + + excess = I0 + sum_p_tm1 - Q_tm1 + n_prior = math.ceil(max(0, excess) / Fj_max) if Fj_max > 0 else 0 + t4 = I0 + sum_p_t - n_prior * Fj_min + + t_max = min(Fj_max, dl, Q_tm1 + b_t, max(0, t4)) + t_max = max(t_max, 0) + + F_max_node[(v_id, j, t)] = t_max + F_min_node[(v_id, j, t)] = Fj_min + + else: # demand + cons = pd["consumption_rate"] + stor = pd["storage_capacity"] + Fj_min_d = pd["F_min"] + Fj_max_d = pd["F_max"] + + for t in range(a_s, a_e + 1): + sum_c_t = sum(cons[tp - 1] for tp in range(1, t + 1) + if tp - 1 < len(cons)) + sum_c_tm1 = sum(cons[tp - 1] for tp in range(1, t) + if tp - 1 < len(cons)) + Q_t = stor[t - 1] if t - 1 < len(stor) else stor[-1] + b_t = cons[t - 1] if t - 1 < len(cons) else 0 + dl = net["U_n"].get((j, t), cap) + + deficit = -I0 + sum_c_tm1 + n_prior = math.ceil(max(0, deficit) / Fj_max_d) \ + if Fj_max_d > 0 else 0 + avail_space = Q_t - I0 + sum_c_t - n_prior * Fj_min_d + t4 = -max(0, avail_space) + + t_min = max(-Fj_max_d, -dl, -(Q_t + b_t), t4) + t_min = min(t_min, 0) + + F_min_node[(v_id, j, t)] = t_min + F_max_node[(v_id, j, t)] = -Fj_min_d + + return F_min_node, F_max_node + + +# ============================================================================= +# MIP Model +# ============================================================================= + +def build_model(data, networks, all_ports, port_type, F_min_node, F_max_node): + """ + Build the compact arc-flow MIP using a commodity-flow formulation. + + Variables: + x[v, arc_idx] in {0,1}: arc selection for vessel v + z[v, j, t] in {0,1}: load/discharge indicator + f[v, j, t] continuous: quantity loaded (>0) or discharged (<0) + w[v, arc_idx] >= 0: product flow on arc for vessel v + I[j, t] >= 0: port inventory + + The key insight: instead of tracking vessel inventory at nodes with big-M + constraints (which yields a very weak LP relaxation), we track the + commodity flow on each arc: + - w[v,e] represents the amount of product on vessel v traversing arc e + - Coupling: w[v,e] <= cap * x[v,e] + - Node balance: incoming_w + f[v,j,t] = outgoing_w (product conservation) + This gives a tight LP relaxation and allows Gurobi to find solutions fast. + """ + T = data["planning_horizon"] + model = gp.Model("MaritimeIRP") + model.setParam("Threads", 1) + + port_data = {} + for sp in data["supply_ports"]: + port_data[sp["port_id"]] = sp + for dp in data["demand_ports"]: + port_data[dp["port_id"]] = dp + + supply_ports = [sp["port_id"] for sp in data["supply_ports"]] + demand_ports = [dp["port_id"] for dp in data["demand_ports"]] + + # ----------------------------------------------------------------- + # Build arc index structures + # ----------------------------------------------------------------- + out_arcs = {} # (v_id, node) -> list of arc indices + in_arcs = {} # (v_id, node) -> list of arc indices + arc_info = {} # (v_id, arc_idx) -> (tail, head, atype, cost) + + for vessel in data["vessels"]: + v_id = vessel["id"] + for idx, (tail, head, atype, cost) in enumerate(networks[v_id]["arcs"]): + arc_info[(v_id, idx)] = (tail, head, atype, cost) + out_arcs.setdefault((v_id, tail), []).append(idx) + in_arcs.setdefault((v_id, head), []).append(idx) + + # ================================================================= + # Variables + # ================================================================= + print(" Creating variables...") + + # x[v, arc_idx]: binary arc selection + x = {} + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + for idx in range(len(net["arcs"])): + _, _, atype, cost = arc_info[(v_id, idx)] + x[(v_id, idx)] = model.addVar( + vtype=GRB.BINARY, obj=cost, name=f"x_{v_id}_{idx}" + ) + + # w[v, arc_idx]: product flow on arc (continuous) + w = {} + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + cap = vessel["capacity"] + for idx in range(len(net["arcs"])): + w[(v_id, idx)] = model.addVar( + lb=0.0, ub=cap, vtype=GRB.CONTINUOUS, + name=f"w_{v_id}_{idx}" + ) + + # z[v, j, t]: binary load/discharge decision + z = {} + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + z[(v_id, j, t)] = model.addVar( + vtype=GRB.BINARY, name=f"z_{v_id}_{j}_{t}" + ) + + # f[v, j, t]: load/discharge quantity (continuous) + f = {} + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + fmin = F_min_node.get((v_id, j, t), 0) + fmax = F_max_node.get((v_id, j, t), 0) + if port_type[j] == "supply": + lb, ub = 0.0, max(fmax, 0.0) + unit_cost = port_data[j]["unit_procurement_cost"] + else: + lb, ub = min(fmin, 0.0), 0.0 + # f <= 0 at demand; unit_supply_revenue * f effectively + # subtracts revenue from the objective + unit_cost = port_data[j]["unit_supply_revenue"] + + f[(v_id, j, t)] = model.addVar( + lb=lb, ub=ub, vtype=GRB.CONTINUOUS, + obj=unit_cost, name=f"f_{v_id}_{j}_{t}" + ) + + # I[j, t]: port inventory + I_var = {} + for j in all_ports: + pd = port_data[j] + stor = pd["storage_capacity"] + for t in range(1, T + 1): + Q_jt = stor[t - 1] if t - 1 < len(stor) else stor[-1] + I_var[(j, t)] = model.addVar( + lb=0.0, ub=Q_jt, vtype=GRB.CONTINUOUS, + name=f"I_{j}_{t}" + ) + + model.update() + + # ================================================================= + # Constraints + # ================================================================= + print(" Adding constraints...") + + # ----------------------------------------------------------------- + # (C1) Flow conservation: path from source to sink for each vessel + # ----------------------------------------------------------------- + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + src = net["src"] + snk = net["snk"] + for node in net["nodes"]: + o_list = out_arcs.get((v_id, node), []) + i_list = in_arcs.get((v_id, node), []) + out_sum = gp.quicksum(x[(v_id, i)] for i in o_list) + in_sum = gp.quicksum(x[(v_id, i)] for i in i_list) + if node == src: + rhs = 1 + elif node == snk: + rhs = -1 + else: + rhs = 0 + model.addConstr( + out_sum - in_sum == rhs, + name=f"flow_{v_id}_{_node_str(node)}" + ) + + # ----------------------------------------------------------------- + # (C2) Commodity flow coupling: w <= U_n * x + # The product flow w on arc (tail -> head) represents the cargo + # in transit. This equals: + # - EXIT inventory from tail (after loading at tail) + # - ENTRY inventory at head (before loading at head) + # Draft limits must be enforced at BOTH endpoints: + # w <= U_n(head) * x (entry bound at destination) + # w <= U_n(tail) * x (exit bound at origin) + # Combined: w <= min(U_n(head), U_n(tail)) * x + # ----------------------------------------------------------------- + for vessel in data["vessels"]: + v_id = vessel["id"] + cap = vessel["capacity"] + net = networks[v_id] + for idx in range(len(net["arcs"])): + tail, head, atype, _ = arc_info[(v_id, idx)] + if isinstance(head, tuple): + u_head = net["U_n"].get(head, cap) + else: + u_head = cap + if isinstance(tail, tuple): + u_tail = net["U_n"].get(tail, cap) + else: + u_tail = cap + u = min(u_head, u_tail) + model.addConstr( + w[(v_id, idx)] <= u * x[(v_id, idx)], + name=f"wcap_{v_id}_{idx}" + ) + + # ----------------------------------------------------------------- + # (C3) Commodity flow conservation at each port-time node: + # sum(incoming w) + f[v,j,t] = sum(outgoing w) + # + # For supply: f >= 0, so incoming_w + f = outgoing_w means vessel + # picks up product (outgoing > incoming). + # For demand: f <= 0, so incoming_w + f = outgoing_w means vessel + # drops off product (outgoing < incoming). + # + # At source node: initial_load + outgoing_w = 0 (if initial_load=0 + # this means vessel starts empty). + # At sink node: incoming_w = 0 is NOT enforced (vessel can end with + # product). We let the variable be free. + # ----------------------------------------------------------------- + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + init_load = vessel["initial_load"] + src = net["src"] + snk = net["snk"] + + # Source: outgoing product flow = initial_load + src_out = out_arcs.get((v_id, src), []) + model.addConstr( + gp.quicksum(w[(v_id, i)] for i in src_out) == init_load, + name=f"wbal_src_{v_id}" + ) + + # Port-time nodes + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + node = (j, t) + i_list = in_arcs.get((v_id, node), []) + o_list = out_arcs.get((v_id, node), []) + in_w = gp.quicksum(w[(v_id, i)] for i in i_list) + out_w = gp.quicksum(w[(v_id, i)] for i in o_list) + model.addConstr( + in_w + f[(v_id, j, t)] == out_w, + name=f"wbal_{v_id}_{j}_{t}" + ) + + # Sink: no explicit constraint needed -- incoming w can be any + # non-negative value (product remaining on vessel). + + # ----------------------------------------------------------------- + # (C4) Load/discharge only if node is visited (Eq. 8): + # z[v,j,t] <= sum of outgoing arcs from (j,t) + # ----------------------------------------------------------------- + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + node = (j, t) + o_list = out_arcs.get((v_id, node), []) + if not o_list: + model.addConstr(z[(v_id, j, t)] == 0, + name=f"vis_{v_id}_{j}_{t}") + else: + model.addConstr( + z[(v_id, j, t)] <= gp.quicksum( + x[(v_id, i)] for i in o_list), + name=f"vis_{v_id}_{j}_{t}") + + # ----------------------------------------------------------------- + # (C5) Load/discharge quantity bounds (Eq. 9): + # F_min * z <= f <= F_max * z + # ----------------------------------------------------------------- + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + fmin_val = F_min_node.get((v_id, j, t), 0) + fmax_val = F_max_node.get((v_id, j, t), 0) + model.addConstr( + f[(v_id, j, t)] >= fmin_val * z[(v_id, j, t)], + name=f"flo_{v_id}_{j}_{t}") + model.addConstr( + f[(v_id, j, t)] <= fmax_val * z[(v_id, j, t)], + name=f"fhi_{v_id}_{j}_{t}") + + # ----------------------------------------------------------------- + # (C6) Port inventory balance (Eqs. 1, 2): + # Supply: I[j,t] = I[j,t-1] + b[j,t] - sum_v f[v,j,t] + # Demand: I[j,t] = I[j,t-1] - b[j,t] - sum_v f[v,j,t] + # ----------------------------------------------------------------- + for j in all_ports: + pd = port_data[j] + I0 = pd["initial_inventory"] + + if port_type[j] == "supply": + rates = pd["production_rate"] + for t in range(1, T + 1): + b_jt = rates[t - 1] if t - 1 < len(rates) else 0 + I_prev = I0 if t == 1 else I_var[(j, t - 1)] + total_f = gp.quicksum( + f[(v["id"], j, t)] + for v in data["vessels"] + if (v["id"], j, t) in f + ) + model.addConstr( + I_var[(j, t)] == I_prev + b_jt - total_f, + name=f"inv_{j}_{t}") + else: + rates = pd["consumption_rate"] + for t in range(1, T + 1): + b_jt = rates[t - 1] if t - 1 < len(rates) else 0 + I_prev = I0 if t == 1 else I_var[(j, t - 1)] + total_f = gp.quicksum( + f[(v["id"], j, t)] + for v in data["vessels"] + if (v["id"], j, t) in f + ) + model.addConstr( + I_var[(j, t)] == I_prev - b_jt - total_f, + name=f"inv_{j}_{t}") + + # Port storage bounds: already set via variable bounds on I_var. + + # ----------------------------------------------------------------- + # (C7) Loading window: + # INFERRED ASSUMPTION: The loading_window_end field indicates the + # latest time a vessel's FIRST loading can start. We do NOT enforce + # a hard ban on loading at supply ports after loading_window_end, + # because doing so can make the problem infeasible when supply ports + # keep producing after all loading windows have closed. + # Instead, we treat the availability window [avail_start, avail_end] + # as the only hard time constraint on the vessel. The loading + # window is interpreted as a soft scheduling preference encoded in + # the time-expanded network structure (vessels are unlikely to + # revisit supply ports after their initial transatlantic crossing + # due to travel time costs). + # ----------------------------------------------------------------- + + # ----------------------------------------------------------------- + # (C8) Force load/discharge before relocating (symmetry breaking): + # For a travel arc from (j,t), the vessel must have loaded/discharged + # at port j at some point during its stay. Simplified: either z=1 + # at (j,t), or the vessel arrived via a demurrage arc (was already + # at j, so loaded earlier). + # ----------------------------------------------------------------- + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + for idx, (tail, head, atype, cost) in enumerate(net["arcs"]): + if atype == "travel" and isinstance(tail, tuple): + j, t = tail + i_list = in_arcs.get((v_id, (j, t)), []) + dem_in = [ai for ai in i_list + if arc_info[(v_id, ai)][2] == "demurrage"] + if dem_in: + model.addConstr( + x[(v_id, idx)] <= z[(v_id, j, t)] + gp.quicksum( + x[(v_id, ai)] for ai in dem_in), + name=f"fld_{v_id}_{idx}") + else: + model.addConstr( + x[(v_id, idx)] <= z[(v_id, j, t)], + name=f"fld_{v_id}_{idx}") + + model.update() + print(f" Model: {model.NumVars} variables, {model.NumConstrs} constraints") + + return model, x, w, z, f, I_var + + +# ============================================================================= +# Solution Extraction +# ============================================================================= + +def extract_solution(model, data, networks, all_ports, port_type, + x, w, z, f, I_var): + """Extract solution from the optimized Gurobi model.""" + T = data["planning_horizon"] + + solution = { + "objective_value": None, + "solver_status": None, + "mip_gap": None, + "solve_time": model.Runtime, + "vessel_routes": {}, + "port_inventories": {}, + "vessel_operations": {}, + } + + if model.SolCount == 0: + solution["solver_status"] = "no_feasible_solution" + return solution + + solution["objective_value"] = model.ObjVal + solution["mip_gap"] = model.MIPGap + if model.Status == GRB.OPTIMAL: + solution["solver_status"] = "optimal" + elif model.Status == GRB.TIME_LIMIT: + solution["solver_status"] = "time_limit" + else: + solution["solver_status"] = f"status_{model.Status}" + + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + route_arcs = [] + operations = [] + + for idx, (tail, head, atype, cost) in enumerate(net["arcs"]): + if x[(v_id, idx)].X > 0.5: + w_val = w[(v_id, idx)].X + route_arcs.append({ + "tail": str(tail), + "head": str(head), + "type": atype, + "cost": cost, + "product_flow": round(w_val, 4), + }) + + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + if (v_id, j, t) in z and z[(v_id, j, t)].X > 0.5: + f_val = f[(v_id, j, t)].X + operations.append({ + "port": j, + "time": t, + "quantity": round(f_val, 4), + "type": ("load" if port_type[j] == "supply" + else "discharge"), + }) + + solution["vessel_routes"][v_id] = route_arcs + solution["vessel_operations"][v_id] = operations + + for j in all_ports: + inv = [] + for t in range(1, T + 1): + if (j, t) in I_var: + inv.append({ + "time": t, + "inventory": round(I_var[(j, t)].X, 4), + }) + solution["port_inventories"][j] = inv + + return solution + + +def compute_cost_breakdown(model, data, networks, all_ports, port_type, + x, f): + """Compute a detailed cost breakdown.""" + if model.SolCount == 0: + return {} + + port_data = {} + for sp in data["supply_ports"]: + port_data[sp["port_id"]] = sp + for dp in data["demand_ports"]: + port_data[dp["port_id"]] = dp + + transport_cost = 0.0 + demurrage_cost = 0.0 + procurement_cost = 0.0 + supply_revenue = 0.0 + + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + for idx, (tail, head, atype, cost) in enumerate(net["arcs"]): + if x[(v_id, idx)].X > 0.5: + if atype == "travel": + transport_cost += cost + elif atype == "demurrage": + demurrage_cost += cost + + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + if (v_id, j, t) in f: + fv = f[(v_id, j, t)].X + if abs(fv) > 1e-6: + if port_type[j] == "supply": + procurement_cost += ( + port_data[j]["unit_procurement_cost"] * fv) + else: + supply_revenue += ( + port_data[j]["unit_supply_revenue"] * (-fv)) + + return { + "transport_cost": round(transport_cost, 4), + "demurrage_cost": round(demurrage_cost, 4), + "procurement_cost": round(procurement_cost, 4), + "supply_revenue": round(supply_revenue, 4), + "total_cost": round( + transport_cost + demurrage_cost + procurement_cost + - supply_revenue, 4), + } + + +# ============================================================================= +# Main +# ============================================================================= + +def main(): + parser = argparse.ArgumentParser( + description="Compact arc-flow MIP for Maritime Inventory Routing " + "(Engineer et al. 2012)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to instance JSON file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write solution JSON file.") + parser.add_argument("--time_limit", type=int, default=3600, + help="Gurobi time limit in seconds (default 3600).") + parser.add_argument("--mip_gap", type=float, default=1e-4, + help="Gurobi MIPGap tolerance (default 1e-4).") + parser.add_argument("--threads", type=int, default=1, + help="Threads for Gurobi (default: 1).") + parser.add_argument("--verbose", action="store_true", + help="Enable verbose Gurobi output.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print("=" * 70) + print("Maritime Inventory Routing Problem - Compact Arc-Flow MIP") + print("Based on Engineer et al. (2012)") + print("=" * 70) + + # Load instance + print(f"\nLoading instance: {args.instance_path}") + data = load_instance(args.instance_path) + print(f" Horizon={data['planning_horizon']}, " + f"vessels={data['num_vessels']}, " + f"supply={data['num_supply_ports']}, " + f"demand={data['num_demand_ports']}") + + # Build networks + print("\nBuilding time-expanded networks...") + networks, all_ports, port_type, tt_dict, dl_dict = \ + build_time_expanded_network(data) + for v_id, net in networks.items(): + print(f" {v_id}: {len(net['nodes'])} nodes, {len(net['arcs'])} arcs, " + f"avail=[{net['avail_start']},{net['avail_end']}], " + f"load_end={net['load_window_end']}") + + # Preprocess + print("\nPreprocessing bounds (Eqs. 16, 17)...") + F_min_node, F_max_node = preprocess_bounds( + data, networks, all_ports, port_type) + + # Build model + print("\nBuilding MIP model...") + model, x, w, z, f, I_var = build_model( + data, networks, all_ports, port_type, F_min_node, F_max_node) + + # Gurobi parameters + model.setParam("TimeLimit", args.time_limit) + if args.mip_gap > 0: + model.setParam("MIPGap", args.mip_gap) + if args.threads > 0: + model.setParam("Threads", args.threads) + if not args.verbose: + model.setParam("OutputFlag", 1) + # Find any feasible incumbent quickly — maritime inventory routing has a + # tight LP relaxation and gurobi can spend the full budget proving infeas/ + # closing gap without producing an incumbent. MIPFocus=1 + NoRelHeurTime + # bias the search toward feasibility. + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, args.time_limit * 0.05)) + + # Optimize + print("\nOptimizing...") + print("=" * 70) + t0 = time.time() + model.optimize() + solve_time = time.time() - t0 + print("=" * 70) + + # Report + print(f"\nSolve time: {solve_time:.2f}s") + print(f"Gurobi status: {model.Status}") + + if model.SolCount > 0: + print(f"Objective value: {model.ObjVal:.4f}") + print(f"MIP gap: {model.MIPGap:.6f}") + if model.Status == GRB.OPTIMAL: + print("Solution is OPTIMAL.") + else: + print("Feasible solution found (not proven optimal).") + + breakdown = compute_cost_breakdown( + model, data, networks, all_ports, port_type, x, f) + print("\nCost Breakdown:") + for k, v in breakdown.items(): + print(f" {k}: {v}") + + print("\nVessel Operations:") + for vessel in data["vessels"]: + v_id = vessel["id"] + net = networks[v_id] + ops = [] + for j in all_ports: + for t in range(net["avail_start"], net["avail_end"] + 1): + if (v_id, j, t) in z and z[(v_id, j, t)].X > 0.5: + fv = f[(v_id, j, t)].X + ptype = "load" if port_type[j] == "supply" else "disch" + ops.append((t, j, ptype, fv)) + if ops: + ops.sort() + print(f" {v_id}:") + for (t, j, pt, fv) in ops: + print(f" t={t:3d} {pt:6s} at {j}: {fv:+.2f}") + else: + print(f" {v_id}: idle") + else: + print("No feasible solution found.") + + # Save solution + solution = extract_solution( + model, data, networks, all_ports, port_type, x, w, z, f, I_var) + solution["solve_time"] = round(solve_time, 2) + solution["instance_path"] = args.instance_path + if model.SolCount > 0: + solution["cost_breakdown"] = compute_cost_breakdown( + model, data, networks, all_ports, port_type, x, f) + + print(f"\nSaving solution to: {args.solution_path}") + with open(args.solution_path, "w") as fout: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, fout, indent=2) + + print("Done.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_1.json b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_2.json b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_3.json b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_4.json b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_5.json b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/engineer2012/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result.json b/tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/engineer2012/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/engineer2012/gurobi_solution/large_solution_1.json b/tasks/engineer2012/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..790f286c78d1bb4b73cb4bb622ce58a78f91a35a --- /dev/null +++ b/tasks/engineer2012/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a582e5cede88d69e7b19423b23ef1ac5cc02f6957c6b8ecca8c265ee94e06815 +size 24839 diff --git a/tasks/engineer2012/gurobi_solution/large_solution_2.json b/tasks/engineer2012/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..919547e24abe8a32ee525aec507010bc53df6e49 --- /dev/null +++ b/tasks/engineer2012/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80c1a27714c8af22bf15103c8774eb5066a6a297ca64be9ecbc867e0953cc25f +size 25138 diff --git a/tasks/engineer2012/gurobi_solution/large_solution_3.json b/tasks/engineer2012/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..4101d9b69237ce57bbd60b8cfb8d833d0332472f --- /dev/null +++ b/tasks/engineer2012/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:770da4332ff59a08bddd2b91ab324fda6b3946624f6d081f68b70a319bed10bf +size 25084 diff --git a/tasks/engineer2012/gurobi_solution/large_solution_4.json b/tasks/engineer2012/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..16e4add194397eccaaa650bc628e048dc6d95d5b --- /dev/null +++ b/tasks/engineer2012/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a8020b2cedfadcc0ada75afada6298b472c7491768032048079893c3e7bdfc1 +size 26581 diff --git a/tasks/engineer2012/gurobi_solution/large_solution_5.json b/tasks/engineer2012/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..777618eab68063487e5afc1ce3fcd49c2e8c481d --- /dev/null +++ b/tasks/engineer2012/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c47256caaad836d340c422c84f8af123699eee899b01539efc5c72c1936f048 +size 24313 diff --git a/tasks/engineer2012/gurobi_solution/tiny_solution.json b/tasks/engineer2012/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..073e13881747ef4712ffd352d510b353058cefd7 --- /dev/null +++ b/tasks/engineer2012/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8b7724e6733d2b8e6e0cd3e3075682bbe96b4886502a60ae02ab07c8b6017fc +size 14128 diff --git a/tasks/engineer2012/gurobi_solution/tiny_solution_2.json b/tasks/engineer2012/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..71bfa46973d9ea8a4b65b02e91aeda435fca2cb6 --- /dev/null +++ b/tasks/engineer2012/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccf01d344c57e2919a882f4fa5d663716d36f3341584a3b58a1026bc950d0cc2 +size 22365 diff --git a/tasks/engineer2012/gurobi_solution_log/large_log_1.jsonl b/tasks/engineer2012/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..38ead801e86193d1a66ae161ef1f156089f90e0d --- /dev/null +++ b/tasks/engineer2012/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f355129934eb4da1d9f527dc924e47b51cc502959d29251e81cd58cd0018685a +size 1332 diff --git a/tasks/engineer2012/gurobi_solution_log/large_log_2.jsonl b/tasks/engineer2012/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d2a5e39fff260bca47d1d36ad5764248e3ad1f96 --- /dev/null +++ b/tasks/engineer2012/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b7734069751604e2a3d142bbabaa6e3189a0783eb860acd908d027fb1209f5e +size 754 diff --git a/tasks/engineer2012/gurobi_solution_log/large_log_3.jsonl b/tasks/engineer2012/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43f331518d0167fa934042fe19ce35bb9ddf4ad5 --- /dev/null +++ b/tasks/engineer2012/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d655dade20b894637e2d39069fa807b5627a99d54a15e76eb6151d04ec721f4d +size 1013 diff --git a/tasks/engineer2012/gurobi_solution_log/large_log_4.jsonl b/tasks/engineer2012/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2d8a405722bc8c4cab4368ac49a39e82fd40e2be --- /dev/null +++ b/tasks/engineer2012/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f291597b435033e4a5a547a51e1432f15ef760df933a0f8ec179eec325568a7 +size 1516 diff --git a/tasks/engineer2012/gurobi_solution_log/large_log_5.jsonl b/tasks/engineer2012/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..03a2e36e404694f54fb271278abe5e04ca2407ca --- /dev/null +++ b/tasks/engineer2012/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b10bff102d6ced0810081b8e4e03b019fd96bc671b765d549fd6150e877392c3 +size 1512 diff --git a/tasks/engineer2012/gurobi_solution_log/tiny_log.jsonl b/tasks/engineer2012/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ddd25d94ee254f0e16bc1c0ea76cde106a3fa252 --- /dev/null +++ b/tasks/engineer2012/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a3c4307de6bfe3b61ea2833a8a3b02ef5b677bf75c1219324725b7c42e3ecb6 +size 220 diff --git a/tasks/engineer2012/instance/large_instance_1.json b/tasks/engineer2012/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f0390a2daefac3ffe9f77647b468d20e8a08e01a --- /dev/null +++ b/tasks/engineer2012/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa9a51809bc4385bf01a2b4bd88c8a2b3e76f72067c0e036c8a42ac5603ad108 +size 11574 diff --git a/tasks/engineer2012/instance/large_instance_2.json b/tasks/engineer2012/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..3233e326292afd1ee3006f037a07fb91bc48365c --- /dev/null +++ b/tasks/engineer2012/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d59712138bfffa83f5adc194aaede7c7c820a35c0531a96884613e1fd734c263 +size 11578 diff --git a/tasks/engineer2012/instance/large_instance_3.json b/tasks/engineer2012/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..71473f2eef9e33d439f265e05f345e1143560b99 --- /dev/null +++ b/tasks/engineer2012/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffe224317cf8b8c287957b977f9b43533609242236a6c934207244759821d152 +size 11589 diff --git a/tasks/engineer2012/instance/large_instance_4.json b/tasks/engineer2012/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..53bbfe2f3d8bec03c72ee2444f79367fc149b195 --- /dev/null +++ b/tasks/engineer2012/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b466f7150bfa2ff69ac2e638765fcc4e5b758a87c2e6a5b9e0b7ed7cf335f81 +size 11577 diff --git a/tasks/engineer2012/instance/large_instance_5.json b/tasks/engineer2012/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..efd35e6dfecabbb53120678b14c8cc90d7ad976b --- /dev/null +++ b/tasks/engineer2012/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f70cf6e006958f7e33ad407e587084d78282314d284a04be93997c1d27699a0 +size 11558 diff --git a/tasks/engineer2012/instance/tiny_instance.json b/tasks/engineer2012/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..0bc312733dc49306c9e22844567c82822fefade9 --- /dev/null +++ b/tasks/engineer2012/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c52c9cebe047c9edc1af7356b56756ad5767f98ddccb6ad4177862117c7e3601 +size 5799 diff --git a/tasks/engineer2012/instance/tiny_instance_2.json b/tasks/engineer2012/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..20b4063c561475a0aab8571c36d3149049328115 --- /dev/null +++ b/tasks/engineer2012/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5400835c7e74834f8628f320ea799aad6e9a41201316c2310ec85d4986148e99 +size 8631 diff --git a/tasks/engineer2012/instance_schema.json b/tasks/engineer2012/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..add9c823a3ecf46d339a3e366feb89b11cf7814c --- /dev/null +++ b/tasks/engineer2012/instance_schema.json @@ -0,0 +1,49 @@ +{ + "planning_horizon": " Number of discrete time periods over which the shipping schedule is planned.", + "num_vessels": " Number of vessels available in the fleet.", + "num_supply_ports": " Number of ports that produce and supply the bulk product.", + "num_demand_ports": " Number of ports that consume and receive the bulk product.", + "vessels": [ + { + "id": " Unique identifier for the vessel.", + "class": " Vessel size class determining its deadweight capacity range.", + "capacity": " Maximum cargo the vessel can carry at any time, in kilotons.", + "availability_start": " Earliest time period at which the vessel becomes available for operations.", + "availability_end": " Latest time period at which the vessel can still operate.", + "loading_window_end": " Latest time period by which the vessel's first loading operation should begin.", + "transport_cost_per_day": " Cost incurred for each day the vessel spends in transit between ports.", + "demurrage_cost_per_day": " Cost incurred for each day the vessel waits idle at a port.", + "initial_load": " Amount of cargo already on board the vessel at the start of the planning horizon." + } + ], + "supply_ports": [ + { + "port_id": " Unique identifier for the supply port.", + "x": " Horizontal geographic coordinate of the supply port.", + "y": " Vertical geographic coordinate of the supply port.", + "type": " Port classification, always 'supply' for supply ports.", + "initial_inventory": " Amount of product stored at the port at the start of the planning horizon.", + "production_rate": " Amount of product produced at the port during each time period.", + "storage_capacity": " Maximum amount of product the port can store during each time period.", + "F_min": " Minimum quantity that must be loaded onto a vessel in a single operation at this port.", + "F_max": " Maximum quantity that can be loaded onto a vessel in a single operation at this port.", + "unit_procurement_cost": " Cost per unit of product loaded onto a vessel at this port." + } + ], + "demand_ports": [ + { + "port_id": " Unique identifier for the demand port.", + "x": " Horizontal geographic coordinate of the demand port.", + "y": " Vertical geographic coordinate of the demand port.", + "type": " Port classification, always 'demand' for demand ports.", + "initial_inventory": " Amount of product stored at the port at the start of the planning horizon.", + "consumption_rate": " Amount of product consumed at the port during each time period.", + "storage_capacity": " Maximum amount of product the port can store during each time period.", + "F_min": " Minimum quantity that must be discharged from a vessel in a single operation at this port.", + "F_max": " Maximum quantity that can be discharged from a vessel in a single operation at this port.", + "unit_supply_revenue": " Revenue earned per unit of product delivered to this port." + } + ], + "travel_times": "{destination_port}'> Number of time periods required for a vessel to travel between two ports.", + "draft_limits": "{port}'> Maximum cargo a vessel may carry when entering a specific port, reflecting port draft restrictions." +} diff --git a/tasks/engineer2012/mathematical_formulation.md b/tasks/engineer2012/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..96c06e016c3cfb1e1f6cbcb76025383922cf17db --- /dev/null +++ b/tasks/engineer2012/mathematical_formulation.md @@ -0,0 +1,119 @@ +# Original Formulation: Single-Product Maritime Inventory Routing (IRP) + +*Source: A Branch-Price-and-Cut Algorithm for Single-Product Maritime Inventory Routing, F. G. Engineer, K. C. Furman, G. L. Nemhauser, M. W. P. Savelsbergh, J.-H. Song, Operations Research 60(1):106–122, 2012.* + +The paper states (§3, “A Column Generation Formulation”) a time-indexed *mixed-integer column generation formulation*, in which integrality is enforced in a nontrivial way. The problem the paper studies is defined by the master problem (1)–(6); voyages (columns) are characterized by the pricing problem (7)–(13). The variables $\lambda^{v,r}$ are indexed over the exponentially large set $R_v$ of all possible voyages and are generated dynamically; the formulation is inherently a decomposition-based formulation. + +## Sets and Indices + +- $J_S$ : set of supply (load) facilities/ports. + +- $J_D$ : set of demand (discharge) facilities/ports. + +- $V$ : set of heterogeneous vessels. + +- $T$ : length of the planning horizon; $t \in \{1,\ldots,T\}$ : time periods. + +- $R_v$ : set of *all possible* voyages for vessel $v \in V$ (exponentially large). A voyage is defined by the sequence of ports visited, the timing, and the quantity loaded/discharged at each port. + +- $\mathcal{N}_v = (N_v, A_v)$ : time-expanded network for vessel $v$. A node $n=(j,t)\in N_v$ corresponds to location $j\in J_S\cup J_D$ and time $t\in\{1,\ldots,T\}$. An arc $e=((j_1,t_1),(j_2,t_2))\in A_v$ corresponds to relocation ($j_1\neq j_2$, $t_2-t_1$ = travel time) or demurrage ($j_1=j_2$, $t_2=t_1+1$). + +- $n_s,\, n_t$ : source and sink nodes for vessel $v$ (earliest/latest time points the vessel is available for use). + +## Parameters + +- $b_{j,t}$ : amount produced ($j\in J_S$) or consumed ($j\in J_D$) at facility $j$ during time period $t$. + +- $Q_{j,t}$ : storage capacity at facility $j$ during time period $t$. + +- $I_{j,0}$ : inventory available at facility $j$ at the start of the horizon. + +- $F_j^{\min},\, F_j^{\max}$ : minimum / maximum amount that can be loaded/unloaded at port $j$ in a single time period. + +- $Q_v$ : cargo capacity of vessel $v\in V$. + +- $c^{v,r}$ : cost of voyage $r\in R_v$ for vessel $v$ (transportation and demurrage costs, plus expense/revenue from procuring/supplying the product). Given parameter of the column. + +- $z_{j,t}^{v,r}\in\{0,1\}$ : given $0$-$1$ indicator for the load/discharge decision at port $j$ and time $t$ for voyage $r$ of vessel $v$. Given parameter of the column. + +- $f_{j,t}^{v,r}$ : amount of product loaded/discharged at port $j$ and time $t$ for voyage $r$ of vessel $v$, with $f_{j,t}^{v,r}\ge 0$ if $j\in J_S$ and $f_{j,t}^{v,r}\le 0$ if $j\in J_D$. Given parameter of the column. + +#### Pricing-problem parameters (vessel $v$, network $\mathcal{N}_v$). + +- $\pi_{j,t}$ : dual values for the inventory-balance constraints (1)/(2). + +- $\alpha_v$ : dual value for the convexity constraint (4). + +- $c_e$ : fixed (transportation/demurrage) cost of arc $e\in A_v$. + +- $\bar c_n$ : per-unit cost at node $n=(j,t)$ for procuring/supplying a single unit of product, adjusted by the dual value $\pi_{j,t}$. + +- $U_n \le Q_v$ : maximum amount of inventory the vessel can have on board when entering port $j$ at time $t$ (incorporates vessel capacity, draft limits, and end-of-horizon empty-vessel requirements). + +- $F_n^{\min},\, F_n^{\max}$ : minimum/maximum load/discharge at node $n$, with $F_n^{\min}=F_j^{\min},\, F_n^{\max}=F_j^{\max}$ if $j\in J_S$, and $F_n^{\min}=-F_j^{\max},\, F_n^{\max}=-F_j^{\min}$ if $j\in J_D$. + +## Decision Variables + +- $\lambda^{v,r}$ : continuous variable, $0\le \lambda^{v,r}\le 1$, indicating the fraction of voyage $r\in R_v$ selected for vessel $v$. + +- $I_{j,t}$ : inventory at port $j$ at time $t$ (continuous). + +*Pricing-problem variables (per vessel $v$):* + +- $x_e$ : $0$-$1$ arc-selection variable, $e\in A_v$. + +- $z_n$ : $0$-$1$ load/discharge decision at node $n\in N_v$. + +- $f_n$ : amount loaded/discharged at node $n\in N_v$. + +- $F_n$ : amount of inventory on board the vessel when entering node $n\in N_v$. + +## Objective + +Column generation master problem: $$\begin{equation} +\min \;\; \sum_{v\in V}\sum_{r\in R_v} c^{v,r}\,\lambda^{v,r}. \notag +\end{equation}$$ + +## Constraints + +Master problem: $$\begin{align} +I_{j,t} &= I_{j,t-1} + b_{j,t} + - \sum_{v\in V}\sum_{r\in R_v} f_{j,t}^{v,r}\,\lambda^{v,r}, + && j\in J_S,\; t=1,\ldots,T, \tag{1}\\ +I_{j,t} &= I_{j,t-1} - b_{j,t} + - \sum_{v\in V}\sum_{r\in R_v} f_{j,t}^{v,r}\,\lambda^{v,r}, + && j\in J_D,\; t=1,\ldots,T, \tag{2}\\ +0 &\le I_{j,t} \le Q_{j,t}, + && j\in J_S\cup J_D,\; t=1,\ldots,T, \tag{3}\\ +\sum_{r\in R_v}\lambda^{v,r} &= 1, && v\in V, \tag{4}\\ +\lambda^{v,r} &\ge 0, && v\in V,\; r\in R_v, \tag{5}\\ +\sum_{r\in R_v} z_{j,t}^{v,r}\,\lambda^{v,r} &\in \{0,1\}, + && v\in V,\; j\in J_S\cup J_D,\; t=1,\ldots,T. \tag{6} +\end{align}$$ Constraints (1)–(2) are the inventory-balance constraints for supply and demand ports; (3) ensures inventory never exceeds storage capacity nor is depleted (safety stock may be incorporated as a nonzero lower bound); (4)–(5) allow a convex combination of voyages per vessel; (6) enforces integrality on the load/discharge decisions (not on $\lambda^{v,r}$, which remain continuous). + +## Pricing Problem (column generation, for a given vessel $v$) + +Given dual values $\pi_{j,t}$ for (1)/(2) and $\alpha_v$ for (4), find a voyage of minimum reduced cost: $$\begin{equation} +\arg\min_{r\in R_v}\; +\left\{\, c^{v,r} +- \Big( \alpha_v + \sum_{j\in J_S\cup J_D}\sum_{t=1}^{T} \pi_{j,t}\,f_{j,t}^{v,r}\Big) +\right\}. \notag +\end{equation}$$ Using the time-expanded network $\mathcal{N}_v=(N_v,A_v)$, the pricing problem for vessel $v$ is stated as: $$\begin{equation} +\min \;\; \sum_{e\in A_v} c_e\, x_e + \sum_{n\in N_v} \bar c_n\, f_n \notag +\end{equation}$$ $$\begin{align} +\sum_{e=(n,n')\in A_v} x_e - \sum_{e=(n',n)\in A_v} x_e + &= \begin{cases} + +1 & \text{if } n=n_s,\\ + -1 & \text{if } n=n_t,\\ + 0 & \text{if } n\in N_v\setminus\{n_s,n_t\}, + \end{cases} \tag{7}\\ +z_n &\le \sum_{e=(n,n')\in A_v} x_e, && n\in N_v, \tag{8}\\ +F_n^{\min}\, z_n &\le f_n \le F_n^{\max}\, z_n, && n\in N_v, \tag{9}\\ +% Constraint (10) is NONLINEAR (bilinear: product of x_e and (F_{n'}+f_{n'})). +% The paper states it can be linearized using standard "big M" techniques +% (Glover 1975), but does not write the linearized form in this section. +F_n &= \sum_{e=(n',n)\in A_v} x_e\,(F_{n'} + f_{n'}), && n\in N_v, \tag{10}\\ +0 &\le F_n \le U_n, && n\in N_v, \tag{11}\\ +x_e &\in \{0,1\}, && e\in A_v, \tag{12}\\ +z_n &\in \{0,1\}, && n\in N_v. \tag{13} +\end{align}$$ Constraints (7) ensure $x_e$ induces a source-to-sink path in $\mathcal{N}_v$; (8) allows a load/discharge at $n$ only if $n$ is visited; (9) bounds the load/discharge quantity; (10) and (11) track the on-board inventory $F_n$ when entering each node, keeping it between $0$ and $U_n$. diff --git a/tasks/engineer2012/problem_description.txt b/tasks/engineer2012/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..2dcb7dfb6073f943ba3e4f48bb7fb1f363a7642e --- /dev/null +++ b/tasks/engineer2012/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A shipping company distributes a single bulk product from a set of supply ports to a set of demand ports using a fleet of heterogeneous vessels over a discrete planning horizon of T time periods. Each supply port produces a known amount of product each period, and each demand port consumes a known amount each period; these production and consumption rates may vary from period to period. Every port has an initial inventory at the start of the horizon and a storage capacity that may also vary by period; inventory at any port must never fall below zero or exceed its storage capacity in any period. Each port also has a minimum and maximum quantity that can be loaded or unloaded there in a single time period; if a vessel performs a load or discharge operation at a port in a given period, the quantity transferred must fall between these bounds. + +Each vessel has a cargo capacity, and the amount of product on board a vessel at any time must never exceed this capacity. Additionally, each vessel-port combination has a draft limit specifying the maximum cargo a vessel may carry when entering that port. Each vessel has an earliest availability time and a latest availability time defining the window during which it may operate, and the vessel begins with a specified initial load on board. Travel between any pair of ports takes a known number of time periods that depends on the origin and destination. A vessel that remains idle at a port for one period incurs a demurrage cost per day, and each day a vessel is in transit incurs a transportation cost per day; both costs are vessel-specific. At supply ports, procuring product costs a per-unit amount specific to that port, and at demand ports, delivering product earns a per-unit revenue specific to that port. + +Over the planning horizon, the company must determine, for each vessel, the sequence of ports it visits, the timing of each visit, and the quantity of product loaded or discharged at each visited port and time period. At a supply port a vessel loads product, removing it from port inventory, and at a demand port a vessel discharges product, adding it to port inventory. Inventory at each port evolves over time: at a supply port, the inventory at the end of a period equals the inventory at the end of the previous period plus that period's production minus the total amount loaded onto all vessels at that port during that period; at a demand port, the inventory at the end of a period equals the inventory at the end of the previous period minus that period's consumption plus the total amount discharged by all vessels at that port during that period. Each vessel follows a route from its earliest availability time and location to its latest availability time and location, where each leg of the route represents either a sailing from one port to a different port (consuming the appropriate travel time) or remaining idle at the same port for one additional period. At each port and time along its route, the vessel may choose whether to load or discharge, and if so, how much, subject to the per-port minimum and maximum transfer bounds. The cumulative cargo aboard a vessel as it progresses along its route must remain between zero and the applicable upper bound at each port visited, where that upper bound reflects both the vessel's cargo capacity and any draft limit at the port being entered. For each vessel, exactly one complete voyage plan (route, timing, and load/discharge schedule) must be selected, and the load-or-discharge decision at each port and time period for each vessel must be an all-or-nothing choice: either the vessel performs a transfer operation at that location and time, or it does not. + +The goal is to minimize total cost, defined as the sum across all vessels of each vessel's voyage cost. A voyage's cost comprises the transportation costs for all sailing legs, the demurrage costs for all idle periods at ports, and the net expense from product handling, which equals the procurement cost paid at supply ports for each unit loaded minus the revenue earned at demand ports for each unit discharged. diff --git a/tasks/engineer2012/solution_logger.py b/tasks/engineer2012/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/engineer2012/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/engineer2012/solution_schema.json b/tasks/engineer2012/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8b2f6c57563201be7a3f4c8423a98def194c9485 --- /dev/null +++ b/tasks/engineer2012/solution_schema.json @@ -0,0 +1,39 @@ +{ + "objective_value": " Total cost of the shipping plan, computed as transport costs plus demurrage costs plus procurement costs minus delivery revenues.", + "vessel_routes": { + "{vessel_id}": [ + { + "tail": " Origin node of the arc, formatted as a (port, time) pair for port-time nodes or (src/snk, vessel_id) for source/sink nodes.", + "head": " Destination node of the arc, formatted as a (port, time) pair for port-time nodes or (src/snk, vessel_id) for source/sink nodes.", + "type": " Arc category: 'travel' for transit between ports, 'demurrage' for waiting at a port, 'source' for departure from the virtual origin, or 'sink' for arrival at the virtual destination.", + "cost": " Cost incurred by traversing this arc, based on transport or demurrage rates.", + "product_flow": " Amount of cargo on board the vessel while traversing this arc." + } + ] + }, + "port_inventories": { + "{port_id}": [ + { + "time": " Time period at which the inventory level is recorded.", + "inventory": " Amount of product stored at the port at the end of this time period." + } + ] + }, + "vessel_operations": { + "{vessel_id}": [ + { + "port": " Identifier of the port where the operation takes place.", + "time": " Time period during which the operation occurs.", + "quantity": " Amount of product transferred: positive for loading at supply ports, negative for discharging at demand ports.", + "type": " Operation category: 'load' for picking up product at a supply port or 'discharge' for delivering product at a demand port." + } + ] + }, + "cost_breakdown": { + "transport_cost": " Total cost incurred across all vessels for traveling between ports.", + "demurrage_cost": " Total cost incurred across all vessels for waiting idle at ports.", + "procurement_cost": " Total cost paid for product loaded at all supply ports.", + "supply_revenue": " Total revenue earned from product delivered to all demand ports.", + "total_cost": " Net cost computed as transport cost plus demurrage cost plus procurement cost minus supply revenue." + } +} diff --git a/tasks/fischetti1997/feasibility_check.py b/tasks/fischetti1997/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd8a310b005714be3a7b194a206b1a6b68b706c --- /dev/null +++ b/tasks/fischetti1997/feasibility_check.py @@ -0,0 +1,630 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Symmetric Generalized Traveling Salesman Problem +(E-GTSP variant: exactly one node per cluster). + +Source: Fischetti, Salazar González, Toth (1997), Operations Research 45(3):378-394 + +Hard constraints checked (numbered top-to-bottom from the formulation section): + Constraint 1 — (1.2): Degree constraint + sum_{e in delta(v)} x_e = 2 * y_v for all v in N + Constraint 3 — (1.4): Subtour elimination / connectivity + The selected edges on visited nodes must form a single connected tour + (i.e., no subtours among visited nodes). + Constraint 4 — (1.5): Binary x + x_e in {0, 1} for all e in E + Constraint 5 — (1.6): Binary y + y_v in {0, 1} for all v in N + Constraint 6 — (1.7): Exactly-one per cluster (E-GTSP replacement for 1.3) + sum_{v in C_h} y_v = 1 for h = 1, ..., m + Constraint 7 — (1.1): Objective-value consistency + reported objective_value == recomputed tour cost sum_{e in E} c_e * x_e. + The tour fully determines x_e, so the true objective is the total cost + of the closed tour; a reported value that disagrees is rejected + (Tier C defense against fabricated objective values). + +NOTE: This is the obj-recompute (`_new`) variant. It is a strict superset of +feasibility_check.py — it adds Constraint 7 and changes no other verdict. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'tour', 'visited_nodes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_instance(path): + """Load instance from JSON file.""" + with open(path, "r") as f: + data = json.load(f) + + n = data["problem_size"]["n"] + m = data["problem_size"]["m"] + + cluster_of = {} + clusters = {} + for c in data["clusters"]: + cid = c["id"] + clusters[cid] = list(c["node_ids"]) + for nid in c["node_ids"]: + cluster_of[nid] = cid + + vals = data["distance_matrix_upper_triangular"]["values"] + dist = [[0] * n for _ in range(n)] + for i in range(n): + for j in range(i + 1, n): + idx = i * (2 * n - i - 1) // 2 + (j - i - 1) + dist[i][j] = vals[idx] + dist[j][i] = vals[idx] + + return n, m, clusters, cluster_of, dist + + +def load_solution(path): + """Load candidate solution from JSON file.""" + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance_path, solution_path): + """ + Check all hard constraints of the E-GTSP formulation. + + The candidate solution provides a tour (ordered list of visited nodes). + From the tour we derive: + - y_v = 1 if v is in visited_nodes, 0 otherwise + - x_e = 1 for each consecutive edge in the cyclic tour, 0 otherwise + """ + tol = 1e-5 + eps = 1e-5 + + n, m, clusters, cluster_of, dist = load_instance(instance_path) + sol = load_solution(solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + return _frontieror_contract_result + + tour = sol["tour"] + visited_nodes = sol.get("visited_nodes", tour) + + # Derive y_v from visited_nodes + visited_set = set(visited_nodes) + y = [0] * n + for v in visited_set: + if 0 <= v < n: + y[v] = 1 + + # Derive x_e from the tour (cyclic: edge between consecutive nodes, last wraps to first) + # x_e is keyed by canonical edge (min, max) + x = {} + tour_len = len(tour) + for k in range(tour_len): + i = tour[k] + j = tour[(k + 1) % tour_len] + ek = (min(i, j), max(i, j)) + x[ek] = x.get(ek, 0) + 1 + + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint 1 — (1.2): sum_{e in delta(v)} x_e = 2 * y_v for all v in N + # ========================================================================= + for v in range(n): + # Compute degree of v in the edge set x + deg = 0 + for (i, j), val in x.items(): + if i == v or j == v: + deg += val + lhs = deg + rhs = 2 * y[v] + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 1 (degree): node {v} has degree {lhs} but 2*y_{v}={rhs}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 3 — (1.4): Subtour elimination (connectivity) + # The tour edges on visited nodes must form a single Hamiltonian cycle. + # Equivalently, for every proper subset S of visited nodes with + # 2 <= |S| <= |visited|-1, sum_{e in delta(S)} x_e >= 2. + # We check this via connectivity: the tour graph must be connected on + # visited nodes. + # ========================================================================= + if tour_len >= 2: + # Build adjacency from tour edges + adj = {} + for v in visited_set: + adj[v] = set() + for k in range(tour_len): + i = tour[k] + j = tour[(k + 1) % tour_len] + if i in adj: + adj[i].add(j) + if j in adj: + adj[j].add(i) + + # BFS from first visited node + start = tour[0] + seen = {start} + queue = [start] + while queue: + node = queue.pop() + for nb in adj.get(node, []): + if nb not in seen: + seen.add(nb) + queue.append(nb) + + # If not all visited nodes reachable, we have subtours + unreachable = visited_set - seen + if unreachable: + # Find the actual subtours for reporting + # Compute the minimum violated cut: take S = seen (a proper subset) + # delta(S) crossing edges + S = seen + lhs_cut = 0 + for (i, j), val in x.items(): + if (i in S) != (j in S): + lhs_cut += val + rhs_cut = 2 # required by subtour elimination + violation_amount = max(rhs_cut - lhs_cut, 0) + if violation_amount <= tol: + # The subtour case: the component is disconnected, + # so delta(S) for the smaller component has 0 crossing edges + lhs_cut = 0 + violation_amount = float(rhs_cut) + normalizer = max(abs(rhs_cut), eps) + violations.append( + f"Constraint 3 (subtour elimination): tour is disconnected; " + f"{len(unreachable)} node(s) unreachable from tour start " + f"(subtour components exist)" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(lhs_cut), + "rhs": float(rhs_cut), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 4 — (1.5): x_e in {0, 1} for all e in E + # ========================================================================= + for (i, j), val in x.items(): + if abs(val - round(val)) > tol or round(val) < 0 or round(val) > 1: + lhs = float(val) + # closest bound + if val > 1: + rhs = 1.0 + violation_amount = val - 1.0 + elif val < 0: + rhs = 0.0 + violation_amount = -val + else: + rhs = round(val) + violation_amount = abs(val - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 4 (binary x): edge ({i},{j}) has x={val}, " + f"not in {{0,1}}" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Also check for multi-edges (edge used more than once means x > 1) + for (i, j), val in x.items(): + if val > 1 + tol: + lhs = float(val) + rhs = 1.0 + violation_amount = val - 1.0 + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 4 (binary x): edge ({i},{j}) used {val} times " + f"in tour, exceeds binary bound" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 5 — (1.6): y_v in {0, 1} for all v in N + # ========================================================================= + for v in range(n): + yv = y[v] + if abs(yv - round(yv)) > tol or round(yv) < 0 or round(yv) > 1: + lhs = float(yv) + rhs = float(round(yv)) + violation_amount = abs(yv - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 5 (binary y): node {v} has y={yv}, not in {{0,1}}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 6 — (1.7): sum_{v in C_h} y_v = 1 for h = 1, ..., m (E-GTSP) + # ========================================================================= + for cid in sorted(clusters.keys()): + cnodes = clusters[cid] + lhs = sum(y[v] for v in cnodes) + rhs = 1 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 6 (exactly one per cluster): cluster {cid} has " + f"sum(y)={lhs}, needs = {rhs}" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ========================================================================= + # Additional structural checks on tour validity + # ========================================================================= + # Check that all tour nodes are valid node IDs + for v in tour: + if v < 0 or v >= n: + violations.append( + f"Constraint 5 (binary y): tour contains invalid node {v} " + f"(not in 0..{n-1})" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + + # Check no intra-cluster edges (E-GTSP removes them) + for k in range(tour_len): + i = tour[k] + j = tour[(k + 1) % tour_len] + if 0 <= i < n and 0 <= j < n and cluster_of.get(i) == cluster_of.get(j): + lhs = 1.0 + rhs = 0.0 + violation_amount = 1.0 + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 4 (binary x): intra-cluster edge ({i},{j}) used " + f"in tour (both in cluster {cluster_of[i]}); E-GTSP forbids " + f"intra-cluster edges" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Check tour visits exactly m nodes (one per cluster) + if tour_len != m: + lhs = float(tour_len) + rhs = float(m) + violation_amount = abs(tour_len - m) + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 6 (exactly one per cluster): tour has {tour_len} " + f"nodes but there are {m} clusters" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Check no duplicate nodes in tour + if len(set(tour)) != tour_len: + from collections import Counter + counts = Counter(tour) + dups = {v: c for v, c in counts.items() if c > 1} + for v, c in dups.items(): + lhs = float(c) + rhs = 1.0 + violation_amount = c - 1.0 + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 1 (degree): node {v} visited {c} times in tour " + f"(should be at most once)" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 7 — (1.1): Objective-value consistency [obj-recompute / Tier C] + # v(GTSP) = sum_{e in E} c_e * x_e. The tour fully determines x_e (every + # variable the objective depends on is present in the solution), so the + # true objective is the exact total cost of the closed tour. Reject a + # solution whose self-reported objective_value disagrees with the + # recomputed tour cost — this blocks LLM score-gaming exploits that + # fabricate the objective (e.g. obj=0 or obj=sys.float_info.max) while + # keeping the route technically feasible. + # + # This is an ADDITIVE check: it only ever appends Constraint 7. It never + # touches the verdict of Constraints 1/3/4/5/6 above. + # ========================================================================= + reported_obj = sol.get("objective_value") + # Recompute only when the tour is structurally usable: at least 2 nodes and + # every node a valid index into the distance matrix. Invalid node IDs are + # already flagged by Constraint 5; guarding here avoids an IndexError and + # keeps this check from masking or duplicating that verdict. + tour_nodes_valid = all(isinstance(v, int) and 0 <= v < n for v in tour) + if reported_obj is not None and tour_len >= 2 and tour_nodes_valid: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + # Recompute the exact closed-tour cost from x_e (the tour edges). + true_obj = 0 + for k in range(tour_len): + i = tour[k] + j = tour[(k + 1) % tour_len] + true_obj += dist[i][j] + if math.isfinite(reported): + abs_diff = abs(reported - true_obj) + else: + # A non-finite reported objective can never equal a finite + # integer tour cost. + abs_diff = float("inf") + # Edge costs c_e are integers (see math_model.txt), so the true + # tour cost is an exact integer. A 0.5 floor catches any + # integer-magnitude misreport while tolerating solver float noise + # (~1e-4 observed in the Gurobi reference solutions). + tol_obj = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > tol_obj: + lhs = float(reported) if math.isfinite(reported) else reported + rhs = float(true_obj) + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint 7 (objective consistency): reported " + f"objective_value={reported} differs from recomputed " + f"tour cost sum_e(c_e*x_e)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol_obj:.6g})" + ) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(lhs) if math.isfinite(reported) else float("inf"), + "rhs": float(rhs), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + # Build result + violated_constraint_indices = sorted( + set(vm["constraint"] for vm in violation_magnitudes) + ) + feasible = len(violations) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_constraint_indices, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for E-GTSP (Fischetti et al. 1997)" + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the JSON file containing the data instance", + ) + parser.add_argument( + "--solution_path", + type=str, + required=True, + help="Path to the JSON file containing the candidate solution", + ) + parser.add_argument( + "--result_path", + type=str, + required=True, + help="Path to write the JSON file containing the feasibility result", + ) + args = parser.parse_args() + + result = check_feasibility(args.instance_path, args.solution_path) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE: All hard constraints satisfied.") + else: + print(f"INFEASIBLE: {len(result['violations'])} violation(s) found.") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/fischetti1997/gurobi_code.py b/tasks/fischetti1997/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..6b5f2af07ec058cf9115da49c7d831bc032e7786 --- /dev/null +++ b/tasks/fischetti1997/gurobi_code.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +""" +Gurobi MIP implementation for the Symmetric E-GTSP (Equality variant). + +Implements the model from: + Fischetti, Salazar Gonzalez, Toth (1997) + "A Branch-and-Cut Algorithm for the Symmetric Generalized Traveling Salesman Problem" + Operations Research 45(3):378-394 + +Model: + min sum_{e in E} c_e * x_e (1.1) + s.t. sum_{e in delta(v)} x_e = 2 * y_v for v in N (1.2) + sum_{v in C_h} y_v = 1 for h = 1,...,m (1.7) [E-GTSP] + sum_{e in delta(S)} x_e >= 2 for GSEC subsets S (2.1) via lazy constraints + x_e in {0,1} (1.5) + y_v in {0,1} (1.6) + +For E-GTSP, intra-cluster edges are removed from E. +Fan inequalities (2.12) are added as initial cuts. +GSECs (2.1) are separated via lazy constraints using connected-component detection. +""" + +import argparse +import json +import math +import sys +from itertools import combinations +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("Error: gurobipy is required. Install Gurobi and its Python bindings.") + sys.exit(1) + + +def load_instance(path): + """Load instance from JSON file.""" + with open(path, 'r') as f: + data = json.load(f) + + n = data["problem_size"]["n"] + m = data["problem_size"]["m"] + nodes = data["nodes"] + + # Build cluster membership: cluster_of[v] = cluster id + cluster_of = {} + clusters = {} # cluster_id -> list of node ids + for c in data["clusters"]: + cid = c["id"] + clusters[cid] = c["node_ids"] + for nid in c["node_ids"]: + cluster_of[nid] = cid + + # Build distance matrix from upper triangular flat list + vals = data["distance_matrix_upper_triangular"]["values"] + dist = [[0] * n for _ in range(n)] + for i in range(n): + for j in range(i + 1, n): + idx = i * (2 * n - i - 1) // 2 + (j - i - 1) + dist[i][j] = vals[idx] + dist[j][i] = vals[idx] + + return n, m, nodes, clusters, cluster_of, dist + + +def solve_egtsp(instance_path, solution_path, time_limit): + """Solve the E-GTSP using Gurobi MIP.""" + n, m, nodes, clusters, cluster_of, dist = load_instance(instance_path) + + # Build edge set E: inter-cluster edges only (for E-GTSP) + edges = [] + edge_idx = {} # (i,j) -> index, with i < j + for i in range(n): + for j in range(i + 1, n): + if cluster_of[i] != cluster_of[j]: + edge_idx[(i, j)] = len(edges) + edges.append((i, j)) + + num_edges = len(edges) + + # Precompute delta(v): edges incident to node v + delta_v = [[] for _ in range(n)] + for eidx, (i, j) in enumerate(edges): + delta_v[i].append(eidx) + delta_v[j].append(eidx) + + # Precompute delta(C_h): edges with exactly one endpoint in cluster h + delta_cluster = {cid: [] for cid in clusters} + for eidx, (i, j) in enumerate(edges): + ci, cj = cluster_of[i], cluster_of[j] + # Since intra-cluster edges are excluded, ci != cj always + delta_cluster[ci].append(eidx) + delta_cluster[cj].append(eidx) + + # Create Gurobi model + model = gp.Model("E-GTSP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + # Use lazy constraints for subtour elimination + model.setParam("LazyConstraints", 1) + + # Decision variables + x = model.addVars(num_edges, vtype=GRB.BINARY, name="x") + y = model.addVars(n, vtype=GRB.BINARY, name="y") + + # Objective (1.1): minimize total edge cost + model.setObjective( + gp.quicksum(dist[edges[e][0]][edges[e][1]] * x[e] for e in range(num_edges)), + GRB.MINIMIZE + ) + + # Constraint (1.2): degree constraints + # sum_{e in delta(v)} x_e = 2 * y_v for each node v + for v in range(n): + model.addConstr( + gp.quicksum(x[e] for e in delta_v[v]) == 2 * y[v], + name=f"degree_{v}" + ) + + # Constraint (1.7): exactly one node per cluster (E-GTSP) + for cid, cnodes in clusters.items(): + model.addConstr( + gp.quicksum(y[v] for v in cnodes) == 1, + name=f"cluster_{cid}" + ) + + # Constraint (2.10): sum_{e in delta(C_h)} x_e = 2 for each cluster h + # This is implied by (1.2) + (1.7) but adding it strengthens the LP relaxation + for cid in clusters: + model.addConstr( + gp.quicksum(x[e] for e in delta_cluster[cid]) == 2, + name=f"cluster_degree_{cid}" + ) + + # Fan inequalities (2.12): x_{delta(C_l) cap delta(w)} <= y_w + # For each cluster l and each node w not in C_l + for cid, cnodes in clusters.items(): + cnode_set = set(cnodes) + for w in range(n): + if w in cnode_set: + continue + # Edges in delta(C_l) incident to w + fan_edges = [] + for eidx in delta_v[w]: + i, j = edges[eidx] + other = j if i == w else i + if cluster_of[other] == cid: + fan_edges.append(eidx) + if fan_edges: + model.addConstr( + gp.quicksum(x[e] for e in fan_edges) <= y[w], + name=f"fan_{cid}_{w}" + ) + + # Lazy constraint callback for GSEC separation + def subtour_callback(model, where): + if where == GRB.Callback.MIPSOL: + x_val = model.cbGetSolution(x) + y_val = model.cbGetSolution(y) + + # Build the support graph from edges with x_e > 0.5 + adj = [[] for _ in range(n)] + active_nodes = set() + for eidx in range(num_edges): + if x_val[eidx] > 0.5: + i, j = edges[eidx] + adj[i].append(j) + adj[j].append(i) + active_nodes.add(i) + active_nodes.add(j) + + # Find connected components among visited nodes (y_v > 0.5) + visited_nodes = [v for v in range(n) if y_val[v] > 0.5] + if len(visited_nodes) <= 1: + return + + seen = set() + components = [] + for start in visited_nodes: + if start in seen: + continue + # BFS + comp = [] + queue = [start] + seen.add(start) + while queue: + node = queue.pop() + comp.append(node) + for nb in adj[node]: + if nb not in seen and y_val[nb] > 0.5: + seen.add(nb) + queue.append(nb) + components.append(comp) + + if len(components) <= 1: + return # Connected, no subtour to eliminate + + # Add GSEC (2.1) for each component that contains at least one + # complete cluster (mu(S) >= 1) + for comp in components: + S = set(comp) + # Check mu(S): number of clusters entirely in S + mu_S = sum(1 for cid, cnodes in clusters.items() + if all(v in S for v in cnodes)) + # Check mu(N\S) + N_minus_S = set(range(n)) - S + mu_NmS = sum(1 for cid, cnodes in clusters.items() + if all(v in N_minus_S for v in cnodes)) + + if mu_S >= 1 and mu_NmS >= 1: + # GSEC (2.1): sum_{e in delta(S)} x_e >= 2 + delta_S_edges = [eidx for eidx in range(num_edges) + if (edges[eidx][0] in S) != (edges[eidx][1] in S)] + model.cbLazy(gp.quicksum(x[e] for e in delta_S_edges) >= 2) + elif mu_S == 0 and mu_NmS >= 1: + # GSEC (2.2): for some i in S + # Pick node i in S with max y value + i_node = max(S, key=lambda v: y_val[v]) + delta_S_edges = [eidx for eidx in range(num_edges) + if (edges[eidx][0] in S) != (edges[eidx][1] in S)] + model.cbLazy(gp.quicksum(x[e] for e in delta_S_edges) >= 2 * y[i_node]) + elif mu_S >= 1 and mu_NmS == 0: + # Symmetric: swap S and N\S to get (2.2) form + j_node = max(N_minus_S, key=lambda v: y_val[v]) + delta_S_edges = [eidx for eidx in range(num_edges) + if (edges[eidx][0] in S) != (edges[eidx][1] in S)] + model.cbLazy(gp.quicksum(x[e] for e in delta_S_edges) >= 2 * y[j_node]) + else: + # GSEC (2.3) + i_node = max(S, key=lambda v: y_val[v]) + j_node = max(N_minus_S, key=lambda v: y_val[v]) + delta_S_edges = [eidx for eidx in range(num_edges) + if (edges[eidx][0] in S) != (edges[eidx][1] in S)] + model.cbLazy( + gp.quicksum(x[e] for e in delta_S_edges) >= 2 * (y[i_node] + y[j_node] - 1) + ) + + # Also add subtour elimination for fractional solutions at LP nodes + # (strengthens the LP relaxation) + # NOTE: This is a simplification; the paper uses a full cutting plane loop. + # **INFERRED ASSUMPTION**: We rely on Gurobi's callback mechanism + # for both integer and fractional separation as a practical substitute + # for the paper's custom LP-based cutting plane procedure. + + model.optimize(subtour_callback) + + # Extract solution + result = {"objective_value": None, "status": "unknown", "tour": [], "visited_nodes": []} + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + # Extract tour + visited = [v for v in range(n) if y[v].X > 0.5] + result["visited_nodes"] = visited + + # Build tour from active edges + tour_adj = {v: [] for v in visited} + for eidx in range(num_edges): + if x[eidx].X > 0.5: + i, j = edges[eidx] + tour_adj[i].append(j) + tour_adj[j].append(i) + + # Trace tour + if visited: + tour = [visited[0]] + prev = -1 + current = visited[0] + for _ in range(len(visited) - 1): + neighbors = tour_adj[current] + next_node = None + for nb in neighbors: + if nb != prev: + next_node = nb + break + if next_node is None: + break + tour.append(next_node) + prev = current + current = next_node + result["tour"] = tour + else: + result["status"] = "infeasible" if model.Status == GRB.INFEASIBLE else "no_solution" + + # Write solution + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status']}") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve E-GTSP using Gurobi MIP (Fischetti et al. 1997)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_egtsp(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_1.json b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_2.json b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_3.json b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_4.json b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_5.json b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1997/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1997/gurobi_feasi_result/tiny_feasi_result.json b/tasks/fischetti1997/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1997/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1997/gurobi_solution/large_solution_1.json b/tasks/fischetti1997/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d52483d67e5ad4d44917494f422b71e5baa96acf --- /dev/null +++ b/tasks/fischetti1997/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53b5d778f2220238f91f023c149ece086eb6ff0a9f7b79c25c95c1d50dc3fe6c +size 1686 diff --git a/tasks/fischetti1997/gurobi_solution/large_solution_2.json b/tasks/fischetti1997/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ff171df1f44180097a0305aaf29d21069823ba9c --- /dev/null +++ b/tasks/fischetti1997/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5218b9db3b160387769562435aab998d3f11d9c3e1a8e9f4d41582a39ba9c06 +size 1678 diff --git a/tasks/fischetti1997/gurobi_solution/large_solution_3.json b/tasks/fischetti1997/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..be4efc8c0eeea54527e55713d286ae55eb0945b7 --- /dev/null +++ b/tasks/fischetti1997/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bb8cb54f2b7b9e40e7a65ed3c23a02698d3cabbd6a9de3c84618358eaa073a6 +size 1700 diff --git a/tasks/fischetti1997/gurobi_solution/large_solution_4.json b/tasks/fischetti1997/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..3ca59a7b67e6cc898cfe937ff00094374dc63d8a --- /dev/null +++ b/tasks/fischetti1997/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5150c32617b8577993e652ba7a1deb2841c0c99d42a7774a1faa333db79a347 +size 1682 diff --git a/tasks/fischetti1997/gurobi_solution/large_solution_5.json b/tasks/fischetti1997/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7066961e192809139b59adbcf2e87181ec701ece --- /dev/null +++ b/tasks/fischetti1997/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7be6c8ec75bd6c280cf6fe555aa34017857cf80877e3d520dea5da3b7fa8c66 +size 1657 diff --git a/tasks/fischetti1997/gurobi_solution/tiny_solution.json b/tasks/fischetti1997/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..f2516081e5da029258d1cf106baa53dbe1ac1599 --- /dev/null +++ b/tasks/fischetti1997/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f2310fb06390a0c699c7b9f769d93add8bf50051bc86832e1eae16bccb18e7e +size 209 diff --git a/tasks/fischetti1997/gurobi_solution_log/tiny_log.jsonl b/tasks/fischetti1997/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..398a35bf81d276092cc75aa2dd82f227a4665596 --- /dev/null +++ b/tasks/fischetti1997/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9083774bed06bc4e4edbc137c1b9a068ab3ae8b977a4ca427bde9b52a8b385a +size 43 diff --git a/tasks/fischetti1997/instance/large_instance_1.json b/tasks/fischetti1997/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d1f21d46221a75f5bdeb71eeef2b1fd87875f16a --- /dev/null +++ b/tasks/fischetti1997/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:123c17cd999169ad2842340dfc5ea6d29094a164ad50e553de33a18c6421619d +size 536804 diff --git a/tasks/fischetti1997/instance/large_instance_2.json b/tasks/fischetti1997/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1f0fb94a8fe6856a91a3f121749cc056d71b018c --- /dev/null +++ b/tasks/fischetti1997/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ceefdec8e42c19b5d790f070fdb8c4bf182021a3c4908361a26e8bc43a690fa6 +size 533233 diff --git a/tasks/fischetti1997/instance/large_instance_3.json b/tasks/fischetti1997/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..58def5e4a895eadc998709d78a0ff3fe17b75716 --- /dev/null +++ b/tasks/fischetti1997/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0b7f979ef7905cfba7111310f3e470adaf248b6971cca3d9419bb895efc62d1 +size 528616 diff --git a/tasks/fischetti1997/instance/large_instance_4.json b/tasks/fischetti1997/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..83d4cc4532a48347734aee62298be34b08db3a4c --- /dev/null +++ b/tasks/fischetti1997/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc4b1e52155ab1df438db767dc8de58e591445881f8eec80de08fe3eaf7dcd54 +size 533446 diff --git a/tasks/fischetti1997/instance/large_instance_5.json b/tasks/fischetti1997/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..726aebe9c8ed8e6dcda9596b4539b80a6dd534ae --- /dev/null +++ b/tasks/fischetti1997/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57a588a7cc80e071c752e7a6d8f9ee3563d4c06d3a8eb055d4508cb16035bd3f +size 524146 diff --git a/tasks/fischetti1997/instance/tiny_instance.json b/tasks/fischetti1997/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a664baf6214ad5a4a27c1dfb4024d892eea64d80 --- /dev/null +++ b/tasks/fischetti1997/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85fb576c8bdef819ecbdc324076c3e125b07806a5782ac844c10b228ed044c83 +size 6201 diff --git a/tasks/fischetti1997/instance_schema.json b/tasks/fischetti1997/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..bb0c1008d0735228b55f6079e0ed706c749c9e90 --- /dev/null +++ b/tasks/fischetti1997/instance_schema.json @@ -0,0 +1,25 @@ +{ + "problem_size": { + "n": " Total number of nodes (locations) in the network.", + "m": " Number of clusters that partition all nodes.", + "num_edges": " Total number of undirected edges connecting pairs of nodes." + }, + "nodes": [ + { + "id": " Unique identifier for this node.", + "x": " Horizontal coordinate of this node.", + "y": " Vertical coordinate of this node.", + "cluster": " Cluster to which this node belongs." + } + ], + "clusters": [ + { + "id": " Unique identifier for this cluster.", + "node_ids": " Nodes that belong to this cluster.", + "size": " Number of nodes in this cluster." + } + ], + "distance_matrix_upper_triangular": { + "values": " Pairwise Euclidean travel costs between all node pairs, stored as a flat upper-triangular matrix in row-major order." + } +} diff --git a/tasks/fischetti1997/mathematical_formulation.md b/tasks/fischetti1997/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..1070892a295fad5bf9d8dbeabb0490f2c335c9bd --- /dev/null +++ b/tasks/fischetti1997/mathematical_formulation.md @@ -0,0 +1,46 @@ +# Original Formulation: Symmetric Generalized Traveling Salesman Problem (GTSP) + +*Source: A Branch-and-Cut Algorithm for the Symmetric Generalized Traveling Salesman Problem, Matteo Fischetti, Juan José Salazar González, Paolo Toth, 1997.* + +## Sets and Parameters + +- $G=(N,E)$ — a complete (loop-free) undirected graph. + +- $N:=\{1,\ldots,n\}$ — node set. + +- $E:=\{\,[i,j] : i,j\in N,\; i\neq j\,\}$ — edge set. + +- $C_1,C_2,\ldots,C_m$ — a proper partition of $N$ into node subsets (*clusters*); $m$ is the number of clusters. + +- $c_e$ — cost associated with each edge $e\in E$ (integer in the computational study; assumed to satisfy the triangle inequality). + +Derived notation (main notation used in the sequel). For each $S\subseteq N$: $$\begin{align*} +E(S) &:= \{\,[i,j]\in E : i\in S,\; j\in S\,\}, \\ +\delta(S) &:= \{\,[i,j]\in E : i\in S,\; j\notin S\,\}, \\ +\mu(S) &:= |\{\,h : C_h\subseteq S\,\}|, \\ +\eta(S) &:= |\{\,h : C_h\cap S\neq\varnothing\,\}|. +\end{align*}$$ For $v\in N$ we write $\delta(v)$ instead of $\delta(\{v\})$, and denote by $C_{h(v)}$ the cluster containing $v$. We also define $W:=\{\,v\in N : |C_{h(v)}|=1\,\}$. + +## Decision Variables + +- $x_e\in\{0,1\}$ for each $e\in E$: $x_e=1$ if edge $e$ is chosen in the optimal solution, $0$ otherwise. + +- $y_v\in\{0,1\}$ for each $v\in N$: $y_v=1$ if node $v$ is visited, $0$ otherwise. + +## Objective + +$$\begin{align} +v(\text{GTSP}):=\min \quad & \sum_{e\in E} c_e\, x_e \tag{1.1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{subject to}\quad +& \sum_{e\in\delta(v)} x_e = 2 y_v && \text{for } v\in N, \tag{1.2}\\[4pt] +& \sum_{v\in C_h} y_v \geq 1 && \text{for } h=1,\ldots,m, \tag{1.3}\\[4pt] +& \sum_{e\in\delta(S)} x_e \geq 2(y_i+y_j-1) && \text{for } S\subseteq N,\; 2\leq|S|\leq n-2, \notag\\ +& && \quad i\in S,\; j\in N\setminus S, \tag{1.4}\\[4pt] +& x_e\in\{0,1\} && \text{for } e\in E, \tag{1.5}\\[4pt] +& y_v\in\{0,1\} && \text{for } v\in N. \tag{1.6} +\end{align}$$ diff --git a/tasks/fischetti1997/problem_description.txt b/tasks/fischetti1997/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c8f877690cf32e8ca7bd7803eddd0a9b994014c --- /dev/null +++ b/tasks/fischetti1997/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A salesman must visit a collection of locations organized into clusters and return to the starting point, forming a closed tour of minimum total travel cost. The input specifies a set of n nodes, each with a two-dimensional coordinate, and a partition of these nodes into m non-overlapping clusters that together cover all nodes. Every pair of nodes in different clusters is connected by an undirected link whose travel cost equals the Euclidean distance between the two nodes, rounded to the nearest integer. These costs satisfy the triangle inequality, meaning the direct travel cost between any two nodes never exceeds the cost of traveling between them via a third node. + +The salesman must select exactly one node from each cluster to serve as that cluster's representative and then find a closed tour that visits each selected node exactly once. No travel is permitted between two nodes belonging to the same cluster. The tour must form a single connected cycle covering all m selected nodes. + +The goal is to minimize the total travel cost of the tour, defined as the sum of the costs of all links used in the closed cycle through the m selected nodes. diff --git a/tasks/fischetti1997/solution_logger.py b/tasks/fischetti1997/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/fischetti1997/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/fischetti1997/solution_schema.json b/tasks/fischetti1997/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1ce081295690a3465c1e4a2ff2f4a9074c4227dc --- /dev/null +++ b/tasks/fischetti1997/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total travel cost of the closed tour through all selected nodes.", + "tour": " Ordered sequence of selected nodes forming the closed tour, with one node chosen from each cluster.", + "visited_nodes": " Set of nodes selected as cluster representatives, one per cluster." +} diff --git a/tasks/fischetti1998/feasibility_check.py b/tasks/fischetti1998/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..19d975e3bd7ef37db574bfa7fa47cd6489be97ee --- /dev/null +++ b/tasks/fischetti1998/feasibility_check.py @@ -0,0 +1,614 @@ +""" +Feasibility checker for the Orienteering Problem (OP). + +Checks all hard constraints from the formulation in: + Fischetti, Salazar González, Toth (1998) + "Solving the Orienteering Problem through Branch-and-Cut" + +Constraints checked (numbered as in the paper): + (2) Total travel time constraint + (3) Degree equations + (4) Generalized Subtour Elimination Constraints (GSECs) + (5) Depot must be visited + (6) x_e bounds [0, 1] + (7) y_v bounds [0, 1] + (8) Integrality of x_e + (9) Integrality of y_v + (10) Objective consistency: the reported objective_value must equal the + objective recomputed from the solution variables, max z = sum_v p_v*y_v. + This is a Tier C defense against score-gaming exploits where a candidate + reports a fabricated objective_value while keeping a feasible route. +""" + +import argparse +import json +from collections import defaultdict, deque + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('edges', 'objective_value', 'tour', 'visited_nodes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('tour',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def canonical_edge(i, j): + return (min(i, j), max(i, j)) + + +def parse_edge_key(key_str): + stripped = key_str.strip().strip("()") + parts = stripped.split(",") + return (int(parts[0].strip()), int(parts[1].strip())) + + +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + n = data["n"] + depot = data["depot"] + t0 = data["t0"] + prizes = {int(k): v for k, v in data["prizes"].items()} + travel = {} + for key_str, cost in data["travel_times"].items(): + i, j = parse_edge_key(key_str) + e = canonical_edge(i, j) + travel[e] = cost + nodes = list(range(1, n + 1)) + return nodes, depot, t0, prizes, travel + + +def load_solution(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(nodes, depot, t0, prizes, travel, solution): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_set = set() + + # ---- Extract solution variables ---- + visited_nodes = solution.get("visited_nodes", []) + edges_list = solution.get("edges", []) + tour = solution.get("tour", []) + + n = len(nodes) + node_set = set(nodes) + + # Build y_v from visited_nodes + y = {v: 0 for v in nodes} + for v in visited_nodes: + if v in node_set: + y[v] = 1 + + # Build x_e from edges list + x = {} + edge_counts = defaultdict(int) + for edge in edges_list: + i, j = edge[0], edge[1] + e = canonical_edge(i, j) + edge_counts[e] += 1 + # x_e = number of times edge appears (should be 0 or 1) + for e, count in edge_counts.items(): + x[e] = count + + # Build incidence: delta(v) + delta = defaultdict(list) + for e in x: + i, j = e + delta[i].append(e) + delta[j].append(e) + + # ========================================================================= + # Constraint (2): sum_{e in E} t_e * x_e <= t0 + # ========================================================================= + total_travel = 0.0 + for e, xe in x.items(): + if e in travel: + total_travel += travel[e] * xe + else: + # Edge not in instance travel times - use solution's reported time + # but flag as potential issue. For edges from the solution that may + # use (i,j) with i>j, we already canonicalized. + pass + + lhs_2 = total_travel + rhs_2 = float(t0) + violation_amount_2 = max(lhs_2 - rhs_2, 0.0) + if violation_amount_2 > tol: + violated_set.add(2) + violations.append( + f"Constraint (2): Total travel time {lhs_2} exceeds budget {rhs_2} " + f"by {violation_amount_2}" + ) + normalizer = max(abs(rhs_2), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_2, + "rhs": rhs_2, + "raw_excess": violation_amount_2, + "normalizer": normalizer, + "ratio": violation_amount_2 / normalizer, + }) + + # ========================================================================= + # Constraint (3): x(delta(v)) = 2 * y_v for all v in V + # ========================================================================= + for v in nodes: + x_delta_v = sum(x.get(e, 0) for e in delta[v]) + lhs_3 = float(x_delta_v) + rhs_3 = 2.0 * y[v] + violation_amount_3 = abs(lhs_3 - rhs_3) + if violation_amount_3 > tol: + violated_set.add(3) + violations.append( + f"Constraint (3): Degree equation violated for node {v}: " + f"x(delta({v}))={lhs_3}, 2*y_{v}={rhs_3}" + ) + normalizer = max(abs(rhs_3), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_3, + "rhs": rhs_3, + "raw_excess": violation_amount_3, + "normalizer": normalizer, + "ratio": violation_amount_3 / normalizer, + }) + + # ========================================================================= + # Constraint (4): GSEC - x(delta(S)) >= 2 * y_v + # for all S subset V, 1 in S, v in V \ S + # + # Let S be the connected component of the support graph that contains the + # depot (so 1 in S). For any visited v in V\S the GSEC requires + # x(delta(S)) >= 2*y_v. Since v is disconnected from S, x(delta(S)) only + # counts edges between S and V\S. + # ========================================================================= + # Build adjacency among visited nodes using selected edges + adj = defaultdict(set) + for e, xe in x.items(): + if xe >= 1: + i, j = e + if y[i] == 1 and y[j] == 1: + adj[i].add(j) + adj[j].add(i) + + visited_set_nodes = {v for v in nodes if y[v] == 1} + + # BFS from depot to find S = depot's connected component (1 in S) + if depot in visited_set_nodes: + reachable = set() + queue = deque([depot]) + reachable.add(depot) + while queue: + u = queue.popleft() + for w in adj[u]: + if w not in reachable and w in visited_set_nodes: + reachable.add(w) + queue.append(w) + + # S = reachable (contains depot). GSEC must hold for each visited v in V\S. + S = reachable + outside_visited = visited_set_nodes - S + if outside_visited: + # x(delta(S)): edges with exactly one endpoint in S + x_delta_S = 0.0 + for e, xe in x.items(): + if xe >= 1: + i, j = e + if (i in S) != (j in S): + x_delta_S += xe + + for v in sorted(outside_visited): + lhs_4 = x_delta_S + rhs_4 = 2.0 * y[v] + violation_amount_4 = max(rhs_4 - lhs_4, 0.0) + if violation_amount_4 > tol: + violated_set.add(4) + violations.append( + f"Constraint (4): GSEC violated for S={sorted(S)} " + f"(depot in S), v={v} in V\\S: " + f"x(delta(S))={lhs_4}, required >= {rhs_4}" + ) + normalizer = max(abs(rhs_4), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs_4, + "rhs": rhs_4, + "raw_excess": violation_amount_4, + "normalizer": normalizer, + "ratio": violation_amount_4 / normalizer, + }) + + # ========================================================================= + # Constraint (5): y_1 = 1 (depot must be visited) + # ========================================================================= + lhs_5 = float(y[depot]) + rhs_5 = 1.0 + violation_amount_5 = abs(lhs_5 - rhs_5) + if violation_amount_5 > tol: + violated_set.add(5) + violations.append( + f"Constraint (5): Depot (node {depot}) not visited: y_{depot}={lhs_5}" + ) + normalizer = max(abs(rhs_5), eps) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs_5, + "rhs": rhs_5, + "raw_excess": violation_amount_5, + "normalizer": normalizer, + "ratio": violation_amount_5 / normalizer, + }) + + # ========================================================================= + # Constraint (6): 0 <= x_e <= 1 for all e in E + # ========================================================================= + for e, xe in x.items(): + # Check lower bound + if xe < -tol: + lhs_6 = float(xe) + rhs_6 = 0.0 + violation_amount_6 = abs(lhs_6 - rhs_6) + violated_set.add(6) + violations.append( + f"Constraint (6): x_{e} = {xe} < 0" + ) + normalizer = max(abs(rhs_6), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs_6, + "rhs": rhs_6, + "raw_excess": violation_amount_6, + "normalizer": normalizer, + "ratio": violation_amount_6 / normalizer, + }) + # Check upper bound + if xe > 1 + tol: + lhs_6 = float(xe) + rhs_6 = 1.0 + violation_amount_6 = lhs_6 - rhs_6 + violated_set.add(6) + violations.append( + f"Constraint (6): x_{e} = {xe} > 1" + ) + normalizer = max(abs(rhs_6), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs_6, + "rhs": rhs_6, + "raw_excess": violation_amount_6, + "normalizer": normalizer, + "ratio": violation_amount_6 / normalizer, + }) + + # ========================================================================= + # Constraint (7): 0 <= y_v <= 1 for all v in V \ {1} + # ========================================================================= + for v in nodes: + if v == depot: + continue + yv = y[v] + if yv < -tol: + lhs_7 = float(yv) + rhs_7 = 0.0 + violation_amount_7 = abs(lhs_7 - rhs_7) + violated_set.add(7) + violations.append( + f"Constraint (7): y_{v} = {yv} < 0" + ) + normalizer = max(abs(rhs_7), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": lhs_7, + "rhs": rhs_7, + "raw_excess": violation_amount_7, + "normalizer": normalizer, + "ratio": violation_amount_7 / normalizer, + }) + if yv > 1 + tol: + lhs_7 = float(yv) + rhs_7 = 1.0 + violation_amount_7 = lhs_7 - rhs_7 + violated_set.add(7) + violations.append( + f"Constraint (7): y_{v} = {yv} > 1" + ) + normalizer = max(abs(rhs_7), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": lhs_7, + "rhs": rhs_7, + "raw_excess": violation_amount_7, + "normalizer": normalizer, + "ratio": violation_amount_7 / normalizer, + }) + + # ========================================================================= + # Constraint (8): x_e in {0, 1} for all e in E + # ========================================================================= + for e, xe in x.items(): + frac = abs(xe - round(xe)) + if frac > tol: + violated_set.add(8) + violations.append( + f"Constraint (8): x_{e} = {xe} is not binary" + ) + lhs_8 = float(xe) + rhs_8 = float(round(xe)) + violation_amount_8 = frac + normalizer = max(abs(rhs_8), eps) + violation_magnitudes.append({ + "constraint": 8, + "lhs": lhs_8, + "rhs": rhs_8, + "raw_excess": violation_amount_8, + "normalizer": normalizer, + "ratio": violation_amount_8 / normalizer, + }) + + # ========================================================================= + # Constraint (9): y_v in {0, 1} for all v in V \ {1} + # ========================================================================= + for v in nodes: + if v == depot: + continue + yv = y[v] + frac = abs(yv - round(yv)) + if frac > tol: + violated_set.add(9) + violations.append( + f"Constraint (9): y_{v} = {yv} is not binary" + ) + lhs_9 = float(yv) + rhs_9 = float(round(yv)) + violation_amount_9 = frac + normalizer = max(abs(rhs_9), eps) + violation_magnitudes.append({ + "constraint": 9, + "lhs": lhs_9, + "rhs": rhs_9, + "raw_excess": violation_amount_9, + "normalizer": normalizer, + "ratio": violation_amount_9 / normalizer, + }) + + # ========================================================================= + # Constraint (10): Objective consistency (Tier C anti-gaming check) + # The OP objective is max z = sum_{v in V} p_v * y_v. + # Every variable that determines the objective (y_v, derived from + # visited_nodes) is present in the solution, so the objective can be + # recomputed exactly. Reject when the reported objective_value disagrees + # with the recomputed value beyond a small tolerance. + # ========================================================================= + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(sum(prizes.get(v, 0) * y[v] for v in nodes)) + abs_diff = abs(reported - true_obj) + # Prizes are integer (see math_model.txt), so the true objective is + # an exact integer. 0.5 absolute floor catches any off-by-one lie; + # the relative term guards against float noise on large objectives. + tol_obj = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > tol_obj: + violated_set.add(10) + violations.append( + f"Constraint (10): Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_v(p_v*y_v)={true_obj} (|diff|={abs_diff}, tol={tol_obj})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 10, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + # ========================================================================= + # Build result + # ========================================================================= + feasible = len(violated_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the Orienteering Problem (OP)." + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance." + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution." + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result." + ) + args = parser.parse_args() + + nodes, depot, t0, prizes, travel = load_instance(args.instance_path) + solution = load_solution(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + result = check_feasibility(nodes, depot, t0, prizes, travel, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"FEASIBLE: Solution at {args.solution_path} is feasible.") + else: + print(f"INFEASIBLE: Solution at {args.solution_path} violates constraints " + f"{result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/fischetti1998/gurobi_code.py b/tasks/fischetti1998/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4f19e03e98e36f10388c7907ddbf88658dffee8d --- /dev/null +++ b/tasks/fischetti1998/gurobi_code.py @@ -0,0 +1,531 @@ +""" +Gurobi solver for the Orienteering Problem (OP). + +Implements the ILP formulation from: + Fischetti, Salazar González, Toth (1998) + "Solving the Orienteering Problem through Branch-and-Cut" + INFORMS Journal on Computing 10(2):133-148 + +Mathematical model: + max sum_{v in V} p_v * y_v (1) + s.t. + sum_{e in E} t_e * x_e <= t_0 (2) travel time budget + x(delta(v)) = 2 * y_v for all v in V (3) degree equations + x(delta(S)) >= 2 * y_v for all S subset V, (4) GSECs (lazy) + 1 not in S, v in S + y_1 = 1 (5) depot visited + x_e <= y_j for e in delta(j), j in V\\{1} (12) logical constraints + x_e in {0,1}, y_v in {0,1} (8,9) + +GSECs (4) are separated dynamically via lazy constraint callbacks. +""" + +import argparse +import json +import sys +import time +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +# --------------------------------------------------------------------------- +# Utility: parse edge key strings like "(1,2)" into integer tuples (i, j) +# --------------------------------------------------------------------------- +def parse_edge_key(key_str): + """Parse a string of the form '(i,j)' into a tuple of ints (i, j).""" + stripped = key_str.strip().strip("()") + parts = stripped.split(",") + return (int(parts[0].strip()), int(parts[1].strip())) + + +def canonical_edge(i, j): + """Return the canonical (min, max) representation for an undirected edge.""" + return (min(i, j), max(i, j)) + + +# --------------------------------------------------------------------------- +# Load instance from JSON +# --------------------------------------------------------------------------- +def load_instance(path): + """ + Load an OP instance from a JSON file. + + Returns: + nodes : list of node ids (1-indexed integers) + depot : depot node id (int) + t0 : maximum travel time (int/float) + prizes : dict node_id -> prize value + edges : list of canonical edge tuples (i, j) with i < j + travel : dict (i,j) -> travel time (i < j) + """ + with open(path, "r") as f: + data = json.load(f) + + n = data["n"] + depot = data["depot"] + t0 = data["t0"] + + # Prizes: keys are string node ids + prizes = {int(k): v for k, v in data["prizes"].items()} + + # Travel times: keys are strings like "(1,2)" + travel = {} + for key_str, cost in data["travel_times"].items(): + i, j = parse_edge_key(key_str) + e = canonical_edge(i, j) + travel[e] = cost + + nodes = list(range(1, n + 1)) + edges = sorted(travel.keys()) + + return nodes, depot, t0, prizes, edges, travel + + +# --------------------------------------------------------------------------- +# Build adjacency / incidence helpers +# --------------------------------------------------------------------------- +def build_incidence(nodes, edges): + """ + Build a mapping from each node to the set of edges incident to it. + + Returns: + delta : dict node_id -> list of (i, j) edges incident to that node + """ + delta = defaultdict(list) + for (i, j) in edges: + delta[i].append((i, j)) + delta[j].append((i, j)) + return delta + + +# --------------------------------------------------------------------------- +# Connected components via BFS on the support graph +# --------------------------------------------------------------------------- +def find_connected_components(adj): + """ + Given an adjacency dict {node: set of neighbours}, find all connected + components via BFS. + + Returns a list of sets, each set being the node set of one component. + """ + visited = set() + components = [] + + for start in adj: + if start in visited: + continue + # BFS + component = set() + queue = [start] + while queue: + v = queue.pop() + if v in visited: + continue + visited.add(v) + component.add(v) + for w in adj[v]: + if w not in visited: + queue.append(w) + components.append(component) + + return components + + +# --------------------------------------------------------------------------- +# GSEC lazy-constraint callback +# --------------------------------------------------------------------------- +def gsec_callback(model, where): + """ + Gurobi callback for lazy GSEC separation. + + When an integer feasible solution is found (MIPSOL), we: + 1. Extract current x and y values. + 2. Build the support graph (edges with x_e = 1). + 3. Find connected components. + 4. For every component S that does NOT contain the depot, + if any y_v = 1 for v in S, add the GSEC: + sum_{e in delta(S)} x_e >= 2 * y_v + """ + if where != GRB.Callback.MIPSOL: + return + + # Retrieve callback data stored on the model object + x_vars = model._x_vars # dict (i,j) -> Gurobi Var + y_vars = model._y_vars # dict node -> Gurobi Var + nodes = model._nodes + edges = model._edges + depot = model._depot + delta = model._delta # node -> list of incident edges + + # Get current solution values + x_val = {} + for e in edges: + x_val[e] = model.cbGetSolution(x_vars[e]) + + y_val = {} + for v in nodes: + y_val[v] = model.cbGetSolution(y_vars[v]) + + # Build adjacency list for the support graph (edges with x_e ~ 1) + adj = defaultdict(set) + for (i, j) in edges: + if x_val[(i, j)] > 0.5: + adj[i].add(j) + adj[j].add(i) + + # Also ensure all visited nodes appear in adj (isolated visited nodes) + for v in nodes: + if y_val[v] > 0.5 and v not in adj: + adj[v] = set() + + if not adj: + return + + # Find connected components + components = find_connected_components(adj) + + # For each component not containing the depot, add GSECs if needed + for comp in components: + if depot in comp: + continue + + # Check if any node in this component is visited + visited_in_comp = [v for v in comp if y_val[v] > 0.5] + if not visited_in_comp: + continue + + # Compute delta(S): edges with exactly one endpoint in comp + delta_S_edges = [] + for v in comp: + for e in delta[v]: + i, j = e + other = j if i == v else i + if other not in comp: + delta_S_edges.append(e) + + # Remove duplicates (an edge (i,j) with i in S, j not in S + # will be found from both endpoints if both are in comp -- but + # since j is NOT in comp, it's only found once from i's side. + # However, the same edge could appear from different v in comp + # that share the same edge to the outside.) + delta_S_edges = list(set(delta_S_edges)) + + # Build the LHS expression: sum of x_e for e in delta(S) + lhs = gp.quicksum(x_vars[e] for e in delta_S_edges) + + # Add a GSEC for each visited node in the component + for v in visited_in_comp: + model.cbLazy(lhs >= 2 * y_vars[v]) + + +# --------------------------------------------------------------------------- +# Extract tour from solution +# --------------------------------------------------------------------------- +def extract_tour(visited_nodes, used_edges, depot): + """ + Given the set of visited nodes and used edges, reconstruct the tour + as an ordered list of nodes starting and ending at the depot. + + Returns: + tour : list of node ids forming the cycle, starting and ending at depot + """ + if len(visited_nodes) <= 1: + return [depot] + + # Build adjacency for the tour subgraph + adj = defaultdict(list) + for (i, j) in used_edges: + adj[i].append(j) + adj[j].append(i) + + # Walk the cycle starting from the depot + tour = [depot] + prev = None + current = depot + + while True: + neighbors = adj[current] + # Pick the neighbor that is not the previous node + next_node = None + for nb in neighbors: + if nb != prev: + next_node = nb + break + + if next_node is None or next_node == depot: + # We've completed the cycle + tour.append(depot) + break + + tour.append(next_node) + prev = current + current = next_node + + return tour + + +# --------------------------------------------------------------------------- +# Main solver +# --------------------------------------------------------------------------- +def solve_op(instance_path, solution_path, time_limit): + """Build and solve the OP model using Gurobi.""" + + print("=" * 70) + print("Orienteering Problem -- Gurobi Solver") + print("Fischetti, Salazar González, Toth (1998) formulation") + print("=" * 70) + + # ------------------------------------------------------------------ + # 1. Load instance + # ------------------------------------------------------------------ + nodes, depot, t0, prizes, edges, travel = load_instance(instance_path) + n = len(nodes) + m = len(edges) + delta = build_incidence(nodes, edges) + + print(f"\nInstance loaded from: {instance_path}") + print(f" Nodes (n) : {n}") + print(f" Edges (m) : {m}") + print(f" Depot : {depot}") + print(f" Time budget : {t0}") + print(f" Total prize : {sum(prizes.values())}") + + # ------------------------------------------------------------------ + # 2. Create Gurobi model + # ------------------------------------------------------------------ + model = gp.Model("OrienteeringProblem") + model.setParam("Threads", 1) + + # Suppress default Gurobi output (we print our own summary) + model.setParam("OutputFlag", 1) + + # Enable lazy constraints + model.Params.LazyConstraints = 1 + + # Set time limit + if time_limit is not None: + model.setParam("TimeLimit", time_limit) + + # ------------------------------------------------------------------ + # 3. Decision variables + # ------------------------------------------------------------------ + # x_e in {0,1} for each edge e + x = {} + for e in edges: + x[e] = model.addVar(vtype=GRB.BINARY, name=f"x_{e[0]}_{e[1]}") + + # y_v in {0,1} for each node v + y = {} + for v in nodes: + y[v] = model.addVar(vtype=GRB.BINARY, name=f"y_{v}") + + model.update() + + # ------------------------------------------------------------------ + # 4. Objective: maximize total prize collected + # ------------------------------------------------------------------ + # (1) max sum_{v in V} p_v * y_v + model.setObjective( + gp.quicksum(prizes[v] * y[v] for v in nodes), + GRB.MAXIMIZE, + ) + + # ------------------------------------------------------------------ + # 5. Constraints + # ------------------------------------------------------------------ + + # (2) Travel time budget: sum_{e in E} t_e * x_e <= t_0 + model.addConstr( + gp.quicksum(travel[e] * x[e] for e in edges) <= t0, + name="travel_time_budget", + ) + + # (3) Degree equations: x(delta(v)) = 2 * y_v for all v in V + for v in nodes: + incident = delta[v] + model.addConstr( + gp.quicksum(x[e] for e in incident) == 2 * y[v], + name=f"degree_{v}", + ) + + # (5) Depot must be visited: y_1 = 1 + model.addConstr(y[depot] == 1, name="depot_visited") + + # (12) Logical constraints: x_e <= y_j for all e in delta(j), j != depot + # These strengthen the LP relaxation and make y integrality redundant. + for v in nodes: + if v == depot: + continue + for e in delta[v]: + model.addConstr( + x[e] <= y[v], + name=f"logical_{e[0]}_{e[1]}_node_{v}", + ) + + # ------------------------------------------------------------------ + # 6. Store data on the model for the callback + # ------------------------------------------------------------------ + model._x_vars = x + model._y_vars = y + model._nodes = nodes + model._edges = edges + model._depot = depot + model._delta = delta + + # ------------------------------------------------------------------ + # 7. Optimize with GSEC callback + # ------------------------------------------------------------------ + print("\nStarting optimization...") + start_time = time.time() + model.optimize(gsec_callback) + elapsed = time.time() - start_time + print(f"\nOptimization completed in {elapsed:.2f} seconds.") + + # ------------------------------------------------------------------ + # 8. Extract and report solution + # ------------------------------------------------------------------ + status_map = { + GRB.OPTIMAL: "optimal", + GRB.TIME_LIMIT: "time_limit", + GRB.INFEASIBLE: "infeasible", + GRB.INF_OR_UNBD: "infeasible_or_unbounded", + GRB.UNBOUNDED: "unbounded", + GRB.NODE_LIMIT: "node_limit", + GRB.SOLUTION_LIMIT: "solution_limit", + GRB.INTERRUPTED: "interrupted", + } + status_str = status_map.get(model.status, f"unknown_{model.status}") + + # Check if we have a feasible solution + if model.SolCount == 0: + print(f"\nNo feasible solution found. Status: {status_str}") + solution = { + "objective_value": None, + "visited_nodes": [], + "edges": [], + "tour": [], + "total_travel_time": None, + "total_prize": None, + "status": status_str, + "solver_time_seconds": round(elapsed, 3), + "mip_gap": None, + "node_count": int(model.NodeCount), + } + else: + obj_val = model.ObjVal + + # Visited nodes + visited_nodes = sorted([v for v in nodes if y[v].X > 0.5]) + + # Used edges + used_edges = sorted([e for e in edges if x[e].X > 0.5]) + + # Total travel time + total_travel = sum(travel[e] for e in used_edges) + + # Total prize + total_prize = sum(prizes[v] for v in visited_nodes) + + # Reconstruct tour + tour = extract_tour(visited_nodes, used_edges, depot) + + # MIP gap + mip_gap = model.MIPGap if hasattr(model, "MIPGap") else None + + # Best bound + best_bound = model.ObjBound if hasattr(model, "ObjBound") else None + + print(f"\n{'=' * 70}") + print("SOLUTION SUMMARY") + print(f"{'=' * 70}") + print(f" Status : {status_str}") + print(f" Objective value : {obj_val}") + print(f" Total prize : {total_prize}") + print(f" Total travel time : {total_travel} (budget: {t0})") + print(f" Visited nodes : {visited_nodes}") + print(f" Number visited : {len(visited_nodes)}") + print(f" Tour : {' -> '.join(map(str, tour))}") + print(f" Edges used : {used_edges}") + print(f" MIP gap : {mip_gap}") + print(f" Best bound : {best_bound}") + print(f" Solver time : {elapsed:.2f}s") + print(f" Nodes explored : {int(model.NodeCount)}") + print(f"{'=' * 70}") + + solution = { + "objective_value": obj_val, + "visited_nodes": visited_nodes, + "edges": [list(e) for e in used_edges], + "tour": tour, + "total_travel_time": total_travel, + "total_prize": total_prize, + "status": status_str, + "solver_time_seconds": round(elapsed, 3), + "mip_gap": mip_gap, + "best_bound": best_bound, + "node_count": int(model.NodeCount), + } + + # ------------------------------------------------------------------ + # 9. Write solution to JSON + # ------------------------------------------------------------------ + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + print(f"\nSolution written to: {solution_path}") + + return solution + + +# --------------------------------------------------------------------------- +# CLI entry point +# --------------------------------------------------------------------------- +def main(): + parser = argparse.ArgumentParser( + description=( + "Solve the Orienteering Problem (OP) using Gurobi, " + "following the Fischetti, Salazar González, Toth (1998) formulation." + ), + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the instance JSON file.", + ) + parser.add_argument( + "--solution_path", + type=str, + default="gurobi_solution_1.json", + help="Path to write the solution JSON file (default: gurobi_solution_1.json).", + ) + parser.add_argument( + "--time_limit", + type=int, + default=None, + help="Solver time limit in seconds.", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_op(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_1.json b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_2.json b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_3.json b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_4.json b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_5.json b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1998/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1998/gurobi_feasi_result/tiny_feasi_result.json b/tasks/fischetti1998/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti1998/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti1998/gurobi_solution/large_solution_1.json b/tasks/fischetti1998/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5414e28d47bb7d17f868fcd85d6a8882ccd585fa --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ee435a652102d5e11f1a4b8c07af4665a62998ef00a8b42fb7a4a47fbeaa578 +size 12614 diff --git a/tasks/fischetti1998/gurobi_solution/large_solution_2.json b/tasks/fischetti1998/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ec8daa3587e5e3df681084e778ec7b177dfd9d16 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ce3859cf16236b7c8926d0153337358a4e4413261ce065ce92c3277724e29cb +size 6576 diff --git a/tasks/fischetti1998/gurobi_solution/large_solution_3.json b/tasks/fischetti1998/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c1a7239f1305f840e2731376125532846c06d485 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4e97640216cbe4633b97da3c6e1eee13485b9c924156cc49073d31a7e04e0b2 +size 15620 diff --git a/tasks/fischetti1998/gurobi_solution/large_solution_4.json b/tasks/fischetti1998/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..527bda8f1943265d40b009bcae42a7641dff2889 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd1fb5c08214c976c102f5d94e380fb3e4d9477e3a0127615a952430f12d249e +size 18952 diff --git a/tasks/fischetti1998/gurobi_solution/large_solution_5.json b/tasks/fischetti1998/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7d4e8ad751a21969961d22b68d183d34af4463b7 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac7d5d4e830a20ba0ad13489714cb7901ae393525226832cc08674d56ab3b909 +size 24074 diff --git a/tasks/fischetti1998/gurobi_solution/tiny_solution.json b/tasks/fischetti1998/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..1105e11dd23b241b06a4c8b146e7d47499f30149 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ace25cf2724c8f9f8077c3543583551cfd41036a15e860816a7621c5d0fba3b5 +size 596 diff --git a/tasks/fischetti1998/gurobi_solution_log/large_log_1.jsonl b/tasks/fischetti1998/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c7d360f0f3ca55401f209e2b6ac989edaa0dc8f6 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9f23a192c075f96310f5f7cde8cee2c0a6c7b765d1b07ab65a1240baa8d8ae8 +size 43 diff --git a/tasks/fischetti1998/gurobi_solution_log/large_log_2.jsonl b/tasks/fischetti1998/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a0406470416088eac5ab9dc02ca8a8265e03575d --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:915394ae7cddd00f00115ebc856e0ebff0a490913742645afab01b3d216bda99 +size 42 diff --git a/tasks/fischetti1998/gurobi_solution_log/large_log_3.jsonl b/tasks/fischetti1998/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc99237f1fb10f747352f297e83ff1e48e41ef6c --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a4bacdae695fc44c922d4e6d2ef262836a63e2285a51772e20a1af27baba0c7 +size 41 diff --git a/tasks/fischetti1998/gurobi_solution_log/large_log_4.jsonl b/tasks/fischetti1998/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d976a26d79eca473a06e9890ecde793f184dfddd --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:039276274cb801bbb97fd4bf95ff2fd2c8b7fd79d90e745925735b1b4b284a5e +size 42 diff --git a/tasks/fischetti1998/gurobi_solution_log/large_log_5.jsonl b/tasks/fischetti1998/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f40ffc7dadb870953bc14107337d973d37929713 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f298e08882466a5df484a813c9082f50cccc0a05c56120fa4da8b596b3187892 +size 41 diff --git a/tasks/fischetti1998/gurobi_solution_log/tiny_log.jsonl b/tasks/fischetti1998/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..36c3284d4de7c9328531444c18420a9e35ef36e4 --- /dev/null +++ b/tasks/fischetti1998/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bef336fc430f4adf18ec980433152dede4f2c7af8c172def6c2d502331cf61dc +size 42 diff --git a/tasks/fischetti1998/instance/large_instance_1.json b/tasks/fischetti1998/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..41f824e42b500d0bec829b4cd807f4350b83bba1 --- /dev/null +++ b/tasks/fischetti1998/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0dd551a424b06fd38238088bb426b766a9b430e014ac247461522cc67347047 +size 2449261 diff --git a/tasks/fischetti1998/instance/large_instance_2.json b/tasks/fischetti1998/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..55c7c82f646c5c59ffc5ff5cabf5448a146474a2 --- /dev/null +++ b/tasks/fischetti1998/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c588cdfbfe4211773741576130283ce5f9aee92a92e6742482b69942b98a481 +size 2449278 diff --git a/tasks/fischetti1998/instance/large_instance_3.json b/tasks/fischetti1998/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9ff97aa090119f332818086d2df81e724d55cab9 --- /dev/null +++ b/tasks/fischetti1998/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a464e5a080d4766bffef8bf69d647f833d920bab2f886f62ce947b99d35807b4 +size 2449283 diff --git a/tasks/fischetti1998/instance/large_instance_4.json b/tasks/fischetti1998/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..67f9f82dc4b0fecdf74c9f5baffeee5db131166d --- /dev/null +++ b/tasks/fischetti1998/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bda2e933a0b509792643febcc0cd606efbfbc1a1f2f6cff0539cd9483bacf484 +size 2449283 diff --git a/tasks/fischetti1998/instance/large_instance_5.json b/tasks/fischetti1998/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..94c275df763bd6b5ab2f11af9fe795c2d001e32f --- /dev/null +++ b/tasks/fischetti1998/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f37adbc41e8a3be6f4e075f22af1d9115c55f6650b2c3678ce2a7ee835fac70a +size 2449283 diff --git a/tasks/fischetti1998/instance/tiny_instance.json b/tasks/fischetti1998/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..7baac3b4efc77bd7dec0f3f4d47b6f2b18552ce4 --- /dev/null +++ b/tasks/fischetti1998/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36980652d6ed548c09b10ebbb75211735dcff13a2d1cd3ccc9253b8320b64e5d +size 6938 diff --git a/tasks/fischetti1998/instance_schema.json b/tasks/fischetti1998/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..510c61866d56b66bb2d64a6b60e863d78cd12256 --- /dev/null +++ b/tasks/fischetti1998/instance_schema.json @@ -0,0 +1,7 @@ +{ + "n": " Total number of cities, including the depot.", + "depot": " City designated as the vehicle's home base, where the tour must start and end.", + "t0": " Maximum total travel time allowed for the tour.", + "prizes": " Prize value collected when each city is visited.", + "travel_times": " Symmetric travel time between each pair of cities." +} diff --git a/tasks/fischetti1998/mathematical_formulation.md b/tasks/fischetti1998/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3d14c3f097a161556fa96187ad1234861abe987a --- /dev/null +++ b/tasks/fischetti1998/mathematical_formulation.md @@ -0,0 +1,58 @@ +# Original Formulation: Orienteering Problem (OP) + +*Source: Solving the Orienteering Problem through Branch-and-Cut, Matteo Fischetti, Juan José Salazar González, Paolo Toth, 1998.* + +## Sets and Indices + +- $G=(V,E)$: a complete undirected graph. + +- $V$: set of $n:=|V|$ nodes; node $1$ represents the depot. + +- $E$: set of all undirected edges; an edge is written $[u,v]$ for $u,v\in V$, $u\neq v$. + +- For $S\subset V$: $$E(S):=\{[u,v]\in E: u\in S,\, v\in S\},\qquad + \delta(S):=\{[u,v]\in E: u\in S,\, v\notin S\}.$$ + +- For $v\in V$ we write $\delta(v)$ instead of $\delta(\{v\})$. + +- For $T\subseteq E$: $V(T):=\{v\in V: T\cap\delta(v)\neq\varnothing\}$ (nodes spanned by $T$). + +## Parameters + +- $p_v\geq 0$: nonnegative prize associated with each node $v\in V$, with $p_1=0$. + +- $t_e\geq 0$: nonnegative travel time associated with each edge $e\in E$ (symmetric: $t_{ij}=t_{ji}$). + +- $t_0$: maximum total travel time allowed for the vehicle. + +- All values $p_v$, $t_e$, and $t_0$ are assumed to be integer. + +*Notation:* for any $F\subseteq E$, $x(F):=\sum_{e\in F}x_e$; for any $Q\subseteq V$, $y(Q):=\sum_{v\in Q}y_v$. + +## Decision Variables + +$$\begin{align*} + x_e &:= \begin{cases} 1 & \text{if edge } e \text{ is used},\\ 0 & \text{otherwise},\end{cases} && e\in E;\\[4pt] + y_v &:= \begin{cases} 1 & \text{if vertex } v \text{ is visited},\\ 0 & \text{otherwise},\end{cases} && v\in V. +\end{align*}$$ + +## Objective + +$$\begin{equation} + v(\mathrm{OP}) := \max \ \sum_{v\in V} p_v\, y_v \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} + & \sum_{e\in E} t_e\, x_e \leq t_0, \tag{2}\\ + & x(\delta(v)) = 2\, y_v && \text{for } v\in V, \tag{3}\\ + & x(\delta(S)) \geq 2\, y_v && \text{for } S\subset V,\ 1\in S,\ v\in V\setminus S, \tag{4}\\ + & y_1 = 1, \tag{5}\\ + & 0 \leq x_e \leq 1 && \text{for } e\in E, \tag{6}\\ + & 0 \leq y_v \leq 1 && \text{for } v\in V\setminus\{1\}, \tag{7}\\ + & x_e \text{ integer} && \text{for } e\in E, \tag{8}\\ + & y_v \text{ integer} && \text{for } v\in V\setminus\{1\}. \tag{9} +\end{align}$$ + +Constraint (2) imposes the bound $t_0$ on the total travel time. The degree equations (3) stipulate that a feasible solution must go exactly once through each visited node. The Generalized Subtour Elimination Constraints (GSECs) (4) force each visited node $v\in V\setminus\{1\}$ to be reachable from node 1 by means of two edge-disjoint paths. Constraint (5) imposes that node 1 must be visited, and (6)–(9) require that all variables are $0$–$1$ valued. diff --git a/tasks/fischetti1998/problem_description.txt b/tasks/fischetti1998/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..09e22c69ab50175e9aae10fa7e599c4b0bdcfe87 --- /dev/null +++ b/tasks/fischetti1998/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A single vehicle is stationed at a depot and must depart from it, visit a subset of cities, and return to the depot, forming a closed tour. There are n cities in total, including the depot, which is designated as city 1. Every pair of distinct cities is connected by a direct link whose travel time is known, nonnegative, and symmetric, meaning the time to travel between any two cities is the same in either direction. Each city other than the depot has an associated nonnegative prize value; the depot has a prize of zero. All prizes, travel times, and the time budget are integers. + +The vehicle must complete its tour within a given maximum total travel time. The tour must start and end at the depot, and every city on the tour is visited exactly once. The tour must form a single connected cycle passing through the depot; that is, every visited city other than the depot must be reachable from the depot along the edges of the tour without passing through any unvisited city, which prevents the solution from decomposing into disconnected subtours. A visited city is entered and exited exactly once, meaning exactly two links of the tour are incident to it. An unvisited city has no tour links incident to it. The tour must contain at least three cities (including the depot), so trivial back-and-forth trips between two cities are not permitted. + +The planner must decide which subset of cities to include in the tour and which links to traverse. The goal is to maximize the total prize collected, defined as the sum of the prize values of all visited cities, subject to the requirement that the sum of travel times along all links used in the tour does not exceed the maximum allowed travel time. diff --git a/tasks/fischetti1998/solution_logger.py b/tasks/fischetti1998/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/fischetti1998/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/fischetti1998/solution_schema.json b/tasks/fischetti1998/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..83083fdee4ed707d607708982212cf63fe2281ce --- /dev/null +++ b/tasks/fischetti1998/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Total prize collected from all visited cities.", + "visited_nodes": " Cities included in the tour.", + "edges": " Pairs of cities connected by links used in the tour.", + "tour": " Ordered sequence of cities visited, starting and ending at the depot." +} diff --git a/tasks/fischetti2017/feasibility_check.py b/tasks/fischetti2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..194479a3c331382d1393981a69f25bd9138964a2 --- /dev/null +++ b/tasks/fischetti2017/feasibility_check.py @@ -0,0 +1,490 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the released quadratic Uncapacitated Facility +Location (qUFL) benchmark. + +Verifies candidate solutions against the mathematical formulation from: +Fischetti, Ljubic, Sinnl (2016) "Redesigning Benders Decomposition for +Large-Scale Facility Location", Management Science. + +Constraints are numbered top-to-bottom as they appear in the formulation: + + Section 2.2 (qUFL, original quadratic form — objective uses c_ij * x_ij^2): + Constraint 5: sum_i x_ij = 1, for all j in J [eq 6] + Constraint 6: x_ij <= y_i, for all i in I, j in J [eq 7] + Constraint 8: x_ij >= 0, for all i in I, j in J [eq 9] + Constraint 10: y_i in {0,1}, for all i in I [eq 11] + + Objective-consistency (Tier C anti-gaming defense, this `_new` variant): + Constraint 14: reported objective_value must match the cost recomputed + from the solution variables (y, x). For qUFL it is + sum_i f_i*y_i + sum_ij c_ij*x_ij^2 [eq 4]. + This is fully determined by the dimension-complete (y, x) + witness. The required variant discriminator is exactly + "quadratic"; linear UFL is not accepted by this case. + +The perspective reformulation auxiliary `z_ij` and its constraint +`x_ij^2 <= z_ij * y_i` (eq 8) is NOT checked: it is a solver-ready +linearization aux that a generated algorithm operating on (x, y) need not +produce. Same for the Benders-master valid inequality `sum y_i >= 2` (eq 13), +which is a cutting-plane device, not an original UFL/qUFL requirement. +""" + +import json +import argparse + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'variant', 'x', 'y') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('x', 'y') +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def check_feasibility(instance, solution): + """Check all hard constraints and return violations.""" + n = instance["num_facilities"] + m = instance["num_customers"] + + y = solution.get("y") + x = solution.get("x") + variant = solution.get("variant") + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs, rhs, operator): + """Record a constraint violation with normalized magnitude.""" + if operator == "eq": + violation_amount = abs(lhs - rhs) + elif operator == "leq": + violation_amount = lhs - rhs + elif operator == "geq": + violation_amount = rhs - lhs + else: + violation_amount = 0.0 + + if violation_amount > TOL: + violated_constraints.add(constraint_idx) + if msg not in violations: + violations.append(msg) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # The released benchmark target is the qUFL model. The coefficients can + # also support a linear UFL experiment, but accepting either objective in + # one evaluator makes the target ambiguous and lets a candidate choose its + # preferred interpretation. + if variant != "quadratic": + record_violation( + 14, + f"Released fischetti2017 cases require variant='quadratic', got {variant!r}", + 0.0, + 1.0, + "eq", + ) + + valid_shape = ( + isinstance(y, list) + and len(y) == n + and isinstance(x, list) + and len(x) == n + and all(isinstance(row, list) and len(row) == m for row in x) + ) + if not valid_shape: + record_violation( + 14, + f"Expected y shape [{n}] and x shape [{n}][{m}]", + 0.0, + 1.0, + "eq", + ) + else: + values = list(y) + [value for row in x for value in row] + if any( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or value != value + or value in (float("inf"), float("-inf")) + for value in values + ): + record_violation( + 14, + "Every x/y entry must be a finite JSON number", + 0.0, + 1.0, + "eq", + ) + + if variant != "quadratic" or not valid_shape or violated_constraints: + return { + "feasible": False, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + if variant == "quadratic": + # ----- Check constraints 5, 6, 8, 10 for the original qUFL ----- + # Perspective aux z and its SOC constraint (7) are intentionally NOT + # checked; `sum y_i >= 2` (Benders-VI, eq 13) is also NOT checked. + + # Constraint 5 (eq 6): sum_i x_ij = 1 for all j + for j in range(m): + lhs = sum(x[i][j] for i in range(n)) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + record_violation(5, + f"Constraint 5 (eq 6): Assignment violated for customer {j}: " + f"sum_i x_ij = {lhs:.6f} != 1", + lhs, rhs, "eq") + + # Constraint 6 (eq 7): x_ij <= y_i for all i, j + for i in range(n): + for j in range(m): + lhs = x[i][j] + rhs = y[i] + if lhs - rhs > TOL: + record_violation(6, + f"Constraint 6 (eq 7): Linking violated for facility {i}, " + f"customer {j}: x[{i}][{j}]={lhs:.6f} > y[{i}]={rhs}", + lhs, rhs, "leq") + + # Constraint 8 (eq 9): x_ij >= 0 for all i, j + for i in range(n): + for j in range(m): + lhs = x[i][j] + rhs = 0.0 + if rhs - lhs > TOL: + record_violation(8, + f"Constraint 8 (eq 9): Non-negativity violated for " + f"x[{i}][{j}]={lhs:.6f} < 0", + lhs, rhs, "geq") + + # Constraint 10 (eq 11): y_i in {0, 1} for all i + for i in range(n): + val = y[i] + dist = min(abs(val - 0.0), abs(val - 1.0)) + if dist > TOL: + record_violation(10, + f"Constraint 10 (eq 11): Integrality violated for " + f"y[{i}]={val:.6f}", + val, round(val), "eq") + + elif variant == "linear" and x is not None: + # ----- Check constraints 1-4 (disaggregated linear MILP) ----- + + # Constraint 1 (eq 2): sum_i x_ij = 1 for all j + for j in range(m): + lhs = sum(x[i][j] for i in range(n)) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + record_violation(1, + f"Constraint 1 (eq 2): Assignment violated for customer {j}: " + f"sum_i x_ij = {lhs:.6f} != 1", + lhs, rhs, "eq") + + # Constraint 2 (eq 3): x_ij <= y_i for all i, j + for i in range(n): + for j in range(m): + lhs = x[i][j] + rhs = y[i] + if lhs - rhs > TOL: + record_violation(2, + f"Constraint 2 (eq 3): Linking violated for facility {i}, " + f"customer {j}: x[{i}][{j}]={lhs:.6f} > y[{i}]={rhs}", + lhs, rhs, "leq") + + # Constraint 3: x_ij >= 0 for all i, j + for i in range(n): + for j in range(m): + lhs = x[i][j] + rhs = 0.0 + if rhs - lhs > TOL: + record_violation(3, + f"Constraint 3: Non-negativity violated for " + f"x[{i}][{j}]={lhs:.6f} < 0", + lhs, rhs, "geq") + + # Constraint 4: y_i in {0, 1} for all i + for i in range(n): + val = y[i] + dist = min(abs(val - 0.0), abs(val - 1.0)) + if dist > TOL: + record_violation(4, + f"Constraint 4: Integrality violated for y[{i}]={val:.6f}", + val, round(val), "eq") + + else: + # Solution has only y (no x). We cannot verify assignment/linking + # without x, so only check y integrality. The Benders-master valid + # inequality `sum y_i >= 2` (eq 13) is NOT checked: it is a + # cutting-plane device, not an original UFL/qUFL requirement. + if y is not None: + for i in range(n): + val = y[i] + dist = min(abs(val - 0.0), abs(val - 1.0)) + if dist > TOL: + record_violation(13, + f"Constraint 13 (eq 15): Integrality violated for " + f"y[{i}]={val:.6f}", + val, round(val), "eq") + + # ----- Constraint 14: objective-value consistency (Tier C defense) ----- + # Recompute the objective from the solution variables and reject when the + # self-reported `objective_value` disagrees with what (y, x) actually + # costs. The UFL objective sum_i f_i*y_i + sum_ij c_ij*x_ij [eq 1] and + # the qUFL objective sum_i f_i*y_i + sum_ij c_ij*x_ij^2 [eq 4] are both + # fully determined by (y, x), so this is an exact full recompute. The + # released interface fixes the variant to quadratic. + reported_obj = solution.get("objective_value") + opening_costs = instance.get("opening_costs") + allocation_costs = instance.get("allocation_costs") + if reported_obj is not None and opening_costs is not None and y is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if (reported is not None and len(y) >= n and len(opening_costs) >= n): + open_cost = sum(float(opening_costs[i]) * float(y[i]) + for i in range(n)) + x_ok = ( + allocation_costs is not None + and len(x) == n and all(len(x[i]) == m for i in range(n)) + and len(allocation_costs) >= n + and all(len(allocation_costs[i]) >= m for i in range(n)) + ) + if x_ok: + # Full recompute of the released quadratic allocation cost. + quad_obj = open_cost + sum( + float(allocation_costs[i][j]) * float(x[i][j]) ** 2 + for i in range(n) for j in range(m)) + abs_diff = abs(reported - quad_obj) + # Serialized continuous x values can differ from Gurobi's + # internal incumbent at the low-ppm level. + tol = max(1e-6, 5e-6 * abs(quad_obj)) + if abs_diff > tol: + record_violation(14, + f"Constraint 14: Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"the released quadratic recompute " + f"sum_i f_i*y_i + sum_ij c_ij*x_ij^2={quad_obj:.6f} " + f"(opening cost sum_i f_i*y_i={open_cost:.6f}; " + f"|diff|={abs_diff:.6g}, " + f"tol={tol:.6g})", + reported, quad_obj, "eq") + else: + # No x available: degrade to the opening-cost lower bound, + # valid because allocation costs are non-negative. + tol = max(1e-3, 1e-3 * abs(open_cost)) + if open_cost - reported > tol: + record_violation(14, + f"Constraint 14: Objective consistency violated: " + f"reported objective_value={reported} is below the " + f"opening-cost lower bound sum_i f_i*y_i=" + f"{open_cost:.6f} (allocation costs are non-negative; " + f"x not provided, so only a lower bound is checked, " + f"tol={tol:.6g})", + reported, open_cost, "geq") + + # Build result + sorted_violated = sorted(violated_constraints) + feasible = len(sorted_violated) == 0 + + result = { + "feasible": feasible, + "violated_constraints": sorted_violated, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for UFL/qUFL solutions" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + + with open(args.solution_path) as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/fischetti2017/gurobi_code.py b/tasks/fischetti2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..efa3e93aaf683149ab5ebc45e096263ed4447bc4 --- /dev/null +++ b/tasks/fischetti2017/gurobi_code.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +""" +Direct Gurobi formulation for the Uncapacitated Facility Location (UFL) problem. + +Implements the mathematical model from: +Fischetti, Ljubic, Sinnl (2016) "Redesigning Benders Decomposition for Large-Scale +Facility Location", Management Science. + +- Linear UFL: disaggregated MILP formulation (equations 1-3). +- Quadratic UFL (qUFL): perspective reformulation (equations 5-11). +""" + +import json +import argparse +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def main(): + parser = argparse.ArgumentParser( + description="Solve UFL/qUFL using direct Gurobi MILP/MIQCP formulation" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + # NOT SPECIFIED IN PAPER: The instance format does not explicitly select linear vs quadratic. + # Inferred assumption: default to 'quadratic' since qUFL is the paper's main contribution + # and the test instances match the qUFL random generation procedure (Section 5.3). + parser.add_argument("--variant", choices=["linear", "quadratic"], default="quadratic", + help="UFL variant: 'linear' or 'quadratic' (default: quadratic)") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # ---- Load instance ---- + with open(args.instance_path) as f: + data = json.load(f) + + n = data["num_facilities"] + m = data["num_customers"] + f_costs = data["opening_costs"] + # allocation_costs[i][j]: cost for facility i serving customer j + c = data["allocation_costs"] + + # ---- Build model ---- + model = gp.Model("UFL") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + + # Solver tolerances matching the paper (Section 4.7), adapted for Gurobi. + # Paper uses CPX_PARAM_EPINT=0; Gurobi minimum IntFeasTol is 1e-9. + model.setParam("IntFeasTol", 1e-9) + # Paper uses CPX_PARAM_EPGAP=1e-9. + model.setParam("MIPGap", 1e-4) + # Paper uses CPX_PARAM_EPRHS=1e-9. + model.setParam("FeasibilityTol", 1e-9) + model.setParam("OptimalityTol", 1e-9) + + if args.variant == "linear": + # Paper uses CPX_PARAM_BRDIR=1 (branch-up-first) for linear UFL (Section 5.2). + model.setParam("BranchDir", 1) + + # ---- Decision variables ---- + # y_i in {0,1}: 1 if facility i is open (eq. 11/15) + y = model.addVars(n, vtype=GRB.BINARY, name="y") + # x_{ij} >= 0: fraction of customer j served by facility i (eq. 9) + x = model.addVars(n, m, lb=0.0, ub=1.0, name="x") + + if args.variant == "linear": + # ---- Linear UFL: equations (1)-(3) ---- + # Objective (eq. 1): min sum_i f_i y_i + sum_{i,j} c_ij x_ij + model.setObjective( + gp.quicksum(f_costs[i] * y[i] for i in range(n)) + + gp.quicksum(c[i][j] * x[i, j] for i in range(n) for j in range(m)), + GRB.MINIMIZE, + ) + else: + # ---- qUFL: perspective reformulation, equations (5)-(11) ---- + # Auxiliary variables z_{ij} >= 0 (eq. 10) + z = model.addVars(n, m, lb=0.0, name="z") + + # Objective (eq. 5): min sum_i f_i y_i + sum_{i,j} c_ij z_ij + model.setObjective( + gp.quicksum(f_costs[i] * y[i] for i in range(n)) + + gp.quicksum(c[i][j] * z[i, j] for i in range(n) for j in range(m)), + GRB.MINIMIZE, + ) + + # Second-order cone constraints (eq. 8): x_ij^2 <= z_ij * y_i + for i in range(n): + for j in range(m): + model.addConstr( + x[i, j] * x[i, j] <= z[i, j] * y[i], + name=f"soc_{i}_{j}", + ) + + # Assignment constraints (eq. 2/6): sum_i x_ij = 1 for all j + for j in range(m): + model.addConstr( + gp.quicksum(x[i, j] for i in range(n)) == 1, name=f"assign_{j}" + ) + + # Capacity/linking constraints (eq. 3/7): x_ij <= y_i for all i,j + for i in range(n): + for j in range(m): + model.addConstr(x[i, j] <= y[i], name=f"cap_{i}_{j}") + + # ---- Solve ---- + model.optimize() + + # ---- Build solution output ---- + solution = { + "instance_id": data.get("instance_id", 0), + "variant": args.variant, + } + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["y"] = [int(round(y[i].X)) for i in range(n)] + solution["x"] = [[x[i, j].X for j in range(m)] for i in range(n)] + solution["solver_status"] = model.Status + solution["mip_gap"] = model.MIPGap if model.Status != GRB.OPTIMAL else 0.0 + solution["open_facilities"] = [i for i in range(n) if round(y[i].X) == 1] + else: + solution["objective_value"] = None + solution["solver_status"] = model.Status + + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + +if __name__ == "__main__": + main() diff --git a/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti2017/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/fischetti2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fischetti2017/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fischetti2017/gurobi_solution/large_solution_1.json b/tasks/fischetti2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c82390e893e48d0503fbe9d424459e55149a9b --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b537d02dd3381fb104f56983d51e233444b4f3d7798a4a5e60f4afb5d1b5aa6 +size 7575995 diff --git a/tasks/fischetti2017/gurobi_solution/large_solution_2.json b/tasks/fischetti2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..bf048793186dcefe947313971e358d02e156cebe --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3990a392a6500c019bee5781da88446946f3c74fb74b314dcabdb4f908b35560 +size 10434712 diff --git a/tasks/fischetti2017/gurobi_solution/large_solution_3.json b/tasks/fischetti2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..89929974a046bada1e09039a6c2abc2105f6fef2 --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7c808a28d16afbd96b9ec3a82c411b6e40c349d0cdf0dab41d6d686471d5dd0 +size 5667434 diff --git a/tasks/fischetti2017/gurobi_solution/large_solution_4.json b/tasks/fischetti2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..1e8bc0779b467d28eec5f6b17dfa2668ee9fe770 --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b655cad2609ae7024ffb3625fbeb81a9e2467feebba3124e5f457602ebc8307 +size 509807 diff --git a/tasks/fischetti2017/gurobi_solution/large_solution_5.json b/tasks/fischetti2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9fb7889f7ba50fbf0ac4986e99820bed4f43b69f --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17ccda14c4ae84351f2d083666188237aa3ea1eb9e7edfc1c61aa623f03d0648 +size 501479 diff --git a/tasks/fischetti2017/gurobi_solution/tiny_solution.json b/tasks/fischetti2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..58397c2dd77dc5f6ddf99f76f1b5a525719dbe83 --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8457a613377a5a8e1e499663103a6b423843d2ee22b0d928aa9dea5839e782e6 +size 6084 diff --git a/tasks/fischetti2017/gurobi_solution_log/large_log_1.jsonl b/tasks/fischetti2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d19a08ad721ab266d67c72de8e60785ea296f7bb --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e70e8c9d685a4b8c8f44bd1394ba6f001db6675ab1a3c73dd1df51d8898c1f45 +size 172 diff --git a/tasks/fischetti2017/gurobi_solution_log/large_log_2.jsonl b/tasks/fischetti2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c8acf340b471ca4fd30b17447794edc8aa4d548a --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7928f63782bd98bc5e1d4e6689e3220cd7ac17763f8b3dfb79aefb8871d0b99d +size 111 diff --git a/tasks/fischetti2017/gurobi_solution_log/large_log_3.jsonl b/tasks/fischetti2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5a8caa7b4fb3e0dcfa51abc44bd382fe2422a0c5 --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fa2c544ffc53e56c318b978cf2a71fd12c45d032abd806abe44211148005ff5 +size 55 diff --git a/tasks/fischetti2017/gurobi_solution_log/large_log_4.jsonl b/tasks/fischetti2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..19c41ab33f34f1fd7a43190bcc5998c6e30e312b --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:306e1e1d636fdb045980acd30d2fdf087512843b07939c3415470c05ac930e5d +size 393 diff --git a/tasks/fischetti2017/gurobi_solution_log/large_log_5.jsonl b/tasks/fischetti2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6319b87ffd27d803b0a4e35e19b37bb218685c69 --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1771ca8d830f75f0e0b82bda7f5961fafd14d91f1af3645cceb145f10bd7e71b +size 334 diff --git a/tasks/fischetti2017/gurobi_solution_log/tiny_log.jsonl b/tasks/fischetti2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..29cd72577c6adb8c8ebf727e6ec2039a55a75d49 --- /dev/null +++ b/tasks/fischetti2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:951e2bf688a9946db3f1f0db01841704784d600408c500e9c1ab3d8141ddc26c +size 109 diff --git a/tasks/fischetti2017/instance/large_instance_1.json b/tasks/fischetti2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..677a0a31b81344ceb5c2c449e932283e6338b5b3 --- /dev/null +++ b/tasks/fischetti2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54bf2d79e5314019dba1de018abbefa222364722024b6fa0c084bb922bb68db9 +size 5173915 diff --git a/tasks/fischetti2017/instance/large_instance_2.json b/tasks/fischetti2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..18967602511422a1e536b879403b61003757cead --- /dev/null +++ b/tasks/fischetti2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c7a86e64d9d55c643f207a878a14a828e6df458948e883ebf8f348a4da00397 +size 5640303 diff --git a/tasks/fischetti2017/instance/large_instance_3.json b/tasks/fischetti2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..993286b3a77c35031057daa385731ce90f0688d0 --- /dev/null +++ b/tasks/fischetti2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1ebb1c1edebd7fba808e3ccce494f95dec79b93e95c85e9f35011b3541892b0 +size 4757589 diff --git a/tasks/fischetti2017/instance/large_instance_4.json b/tasks/fischetti2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..42a996413f5d66daca82c8fac5ef14428fcd31ab --- /dev/null +++ b/tasks/fischetti2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26588c97279da143f9245a5e2d7947c1d911d6061c7cae69259c293182613d98 +size 473686 diff --git a/tasks/fischetti2017/instance/large_instance_5.json b/tasks/fischetti2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e03af5f5d472e643d487bf522abb7666ccf0b74f --- /dev/null +++ b/tasks/fischetti2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e704621585a3476b6b6e609677e22b69fe7509d086e5fd7c6ec472434ba6ede +size 473634 diff --git a/tasks/fischetti2017/instance/tiny_instance.json b/tasks/fischetti2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..77cde6cce5ce4173309a79337b374b511ba70277 --- /dev/null +++ b/tasks/fischetti2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edba24e54433aa85d415b8c5c31211cae82b3949ae3182d24e5334d85e23ff5b +size 7940 diff --git a/tasks/fischetti2017/instance_schema.json b/tasks/fischetti2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..419c8bed81f094fbd3e230a7009e5680e73e012b --- /dev/null +++ b/tasks/fischetti2017/instance_schema.json @@ -0,0 +1,10 @@ +{ + "num_facilities": " Number of potential facility locations that may be opened.", + "num_customers": " Number of customers that must be served by open facilities.", + "facility_locations_x": " Horizontal coordinate of each potential facility location.", + "facility_locations_y": " Vertical coordinate of each potential facility location.", + "customer_locations_x": " Horizontal coordinate of each customer location.", + "customer_locations_y": " Vertical coordinate of each customer location.", + "opening_costs": " Cost incurred for opening each facility.", + "allocation_costs": " Cost coefficient for serving each customer from each facility." +} diff --git a/tasks/fischetti2017/mathematical_formulation.md b/tasks/fischetti2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..2bf6aa74b7d29b56e12a08266d1196fbdf364c95 --- /dev/null +++ b/tasks/fischetti2017/mathematical_formulation.md @@ -0,0 +1,59 @@ +# Sets and Parameters + +- $I$: set of potential facility locations, $|I|=n$. + +- $J$: set of customers, $|J|=m$. + +- $f_i \geq 0$: opening cost for facility $i \in I$. + +- $c_{ij} \geq 0$: allocation cost (linear case) / per-unit quadratic cost (quadratic case) for assigning customer $j \in J$ to facility $i \in I$. If customer $j$ cannot be allocated to facility $i$ we set $c_{ij}=\infty$. + +# 2.1 Linear Case (Classical UFL) + +## Decision Variables + +$$\begin{align*} +y_i &\in \{0,1\} && \forall\, i \in I \quad (\text{1 if facility $i$ is open}) \\ +x_{ij} &\geq 0 && \forall\, i \in I,\; j \in J \quad (\text{fraction / assignment of customer $j$ to facility $i$}) +\end{align*}$$ + +## Objective + +$$\begin{equation} +\min \left\{ \sum_{i \in I} f_i \, y_i + \sum_{i \in I}\sum_{j \in J} c_{ij}\, x_{ij} \right\} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{i \in I} x_{ij} &= 1 && \forall\, j \in J \tag{2} \\ +x_{ij} &\leq y_i && \forall\, i \in I,\; j \in J \tag{3} \\ +x_{ij} &\geq 0 && \forall\, i \in I,\; j \in J \notag \\ +y_i &\in \{0,1\} && \forall\, i \in I \notag +\end{align}$$ + +# 2.2 Separable Convex Quadratic Case (qUFL) + +In the quadratic version $c_{ij} > 0$ for all $i \in I$, $j \in J$, and allocation costs are proportional to the square of the fraction of demand served. The objective $(1)$ is replaced by $(4)$. + +## Decision Variables + +$$\begin{align*} +y_i &\in \{0,1\} && \forall\, i \in I \\ +x_{ij} &\geq 0 && \forall\, i \in I,\; j \in J \quad (\text{fraction of customer $j$'s demand served by facility $i$}) +\end{align*}$$ + +## Objective (original quadratic form) + +$$\begin{equation} +\min \left\{ \sum_{i \in I} f_i\, y_i + \sum_{i \in I}\sum_{j \in J} c_{ij}\, x_{ij}^{2} \right\} \tag{4} +\end{equation}$$ + +## Constraints + +Same as constraints (2)–(3) together with $x_{ij} \geq 0$ and $y_i \in \{0,1\}$: $$\begin{align*} +\sum_{i \in I} x_{ij} &= 1 && \forall\, j \in J \\ +x_{ij} &\leq y_i && \forall\, i \in I,\; j \in J \\ +x_{ij} &\geq 0 && \forall\, i \in I,\; j \in J \\ +y_i &\in \{0,1\} && \forall\, i \in I +\end{align*}$$ diff --git a/tasks/fischetti2017/problem_description.txt b/tasks/fischetti2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6cb390395ef7c01522dd496d4ded3ab3088d070 --- /dev/null +++ b/tasks/fischetti2017/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A company must decide which facilities to open from a set of potential locations and how to assign each customer to an open facility, with the goal of minimizing total cost. There are n potential facility locations and m customers. Each facility has a known nonnegative opening cost, and for every facility-customer pair there is a known nonnegative allocation cost that reflects the cost of serving that customer from that facility. In typical applications, allocation costs depend on the distance between the customer and the facility, computed from their geographic coordinates in a two-dimensional space; if a particular facility cannot serve a particular customer, the corresponding allocation cost is treated as prohibitively large. + +Every customer must be assigned to exactly one open facility. A customer may only be assigned to a facility that has been opened. There is no limit on how many customers a single facility can serve, which is why the problem is called uncapacitated. The total cost to minimize is the sum of the opening costs of all opened facilities plus the sum of the allocation costs incurred by the customer assignments. + +The released benchmark evaluates the separable convex quadratic variant (qUFL): allocation costs are proportional to the square of the fraction of a customer's demand served by a facility, rather than being linear. All allocation cost coefficients are strictly positive, and each facility-customer pair has an associated cost coefficient. Each customer's total demand must still be fully covered, meaning the fractions of that customer's demand served across all facilities must sum to one. A customer can only receive service from a facility that is open, and the fraction of demand served by any facility cannot exceed the open-or-closed status of that facility. The cost incurred for serving a fraction of customer demand from a given facility equals the cost coefficient for that pair multiplied by the square of the fraction served. The goal is to minimize the sum of facility opening costs plus the sum of these quadratic allocation costs across all facility-customer pairs. The stored coefficients can also be used in separate linear-UFL experiments, but linear UFL is not an accepted solution variant for this benchmark case. This quadratic structure arises naturally in applications such as electric power distribution network design, where facilities represent distribution transformers placed near customer premises and the quadratic cost captures power loss in cables, which is proportional to the square of the current flowing through them multiplied by the cable resistance. + +The instance data specifies the number of potential facility locations and the number of customers, the two-dimensional coordinates of each facility and each customer, the opening cost for each facility, and the allocation cost coefficient for every facility-customer pair. diff --git a/tasks/fischetti2017/solution_logger.py b/tasks/fischetti2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/fischetti2017/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/fischetti2017/solution_schema.json b/tasks/fischetti2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..00ae3729b320ff81ae230021f6a3a37c599bc681 --- /dev/null +++ b/tasks/fischetti2017/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Total cost comprising facility opening costs and allocation costs.", + "variant": " Released qUFL benchmark variant.", + "y": " Whether each facility is opened (1) or not (0).", + "x": " Fraction of each customer's demand served by each facility." +} diff --git a/tasks/fleszar2022b/feasibility_check.py b/tasks/fleszar2022b/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..11e130d127ce7b4905c0ca5c1dbd2fdf5244c181 --- /dev/null +++ b/tasks/fleszar2022b/feasibility_check.py @@ -0,0 +1,390 @@ +""" +Feasibility checker for the Quadratic Multiple Knapsack Problem (QMKP). +Checks constraints from Fleszar (2022) formulation: + Constraint 1: Capacity -- sum_i w_i * x_{ik} <= c_k for all k + Constraint 2: Assignment -- sum_k x_{ik} <= 1 for all i + Constraint 3: Binary domain -- x_{ik} in {0, 1} for all i, k + Constraint 4: Objective consistency -- reported objective_value must + equal the objective recomputed from the assignment: + sum_k ( sum_i v_i x_{ik} + + sum_{i 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def check_feasibility(instance, solution): + n = instance["n"] + m = instance["m"] + weights = instance["weights"] + capacity = instance["capacity"] + + assignment = solution.get("assignment", {}) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # Build x matrix from assignment + # assignment maps str(item) -> knapsack index + x = [[0] * m for _ in range(n)] + for item_str, k in assignment.items(): + i = int(item_str) + k = int(k) + if 0 <= i < n and 0 <= k < m: + x[i][k] = 1 + + # ------------------------------------------------------------------ + # Constraint 3: Binary domain x_{ik} in {0, 1} + # Check that assignment values are valid knapsack indices and items + # ------------------------------------------------------------------ + for item_str, k_val in assignment.items(): + i = int(item_str) + k = int(k_val) + if i < 0 or i >= n: + violation_amount = 1.0 + rhs = 0.0 + normalizer = max(abs(rhs), EPS) + violated_constraints.add(3) + violations.append( + f"Item index {i} is out of range [0, {n-1}]" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(i), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + if k < 0 or k >= m: + violation_amount = 1.0 + rhs = 0.0 + normalizer = max(abs(rhs), EPS) + violated_constraints.add(3) + violations.append( + f"Knapsack index {k} for item {i} is out of range [0, {m-1}]" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(k), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + # x_{ik} must be 0 or 1; since we derive from assignment dict, values + # are inherently binary. But check that the value is actually 0 or 1. + val = x[i][k] if (0 <= i < n and 0 <= k < m) else 0 + if val not in (0, 1): + violation_amount = abs(val - round(val)) + rhs = round(val) + normalizer = max(abs(rhs), EPS) + violated_constraints.add(3) + violations.append( + f"x[{i},{k}] = {val} is not binary" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(val), + "rhs": float(rhs), + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 1: Capacity -- sum_i w_i * x_{ik} <= c_k for all k + # ------------------------------------------------------------------ + for k in range(m): + lhs = sum(weights[i] * x[i][k] for i in range(n)) + rhs = capacity + violation_amount = lhs - rhs # for <= constraint + if violation_amount > TOL: + normalizer = max(abs(rhs), EPS) + violated_constraints.add(1) + items_in_k = [i for i in range(n) if x[i][k] == 1] + violations.append( + f"Capacity exceeded on knapsack {k}: " + f"total weight {lhs} > capacity {rhs} " + f"(items {items_in_k})" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ------------------------------------------------------------------ + # Constraint 2: Assignment -- sum_k x_{ik} <= 1 for all i + # ------------------------------------------------------------------ + for i in range(n): + lhs = sum(x[i][k] for k in range(m)) + rhs = 1 + violation_amount = lhs - rhs # for <= constraint + if violation_amount > TOL: + normalizer = max(abs(rhs), EPS) + knapsacks_assigned = [k for k in range(m) if x[i][k] == 1] + violated_constraints.add(2) + violations.append( + f"Item {i} assigned to {int(lhs)} knapsacks " + f"(knapsacks {knapsacks_assigned}), exceeds limit of 1" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ------------------------------------------------------------------ + # Constraint 4: Objective consistency (Tier C defense) + # Recompute the QMKP objective directly from the assignment and + # reject when the reported objective_value disagrees. + # obj = sum_k ( sum_i v_i x_{ik} + # + sum_{i= 1 must fire; keep a + # tiny relative term for very large recomputed magnitudes. + tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > tol: + normalizer = max(abs(true_obj), EPS) + violated_constraints.add(4) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed " + f"sum_k(sum_i v_i x_ik + sum_{{i 0: + result['objective_value'] = model.ObjVal + + # Extract assignment + assignment = {} + for i in items: + for k in knapsacks: + if x[i, k].X > 0.5: + assignment[str(i)] = k + break + result['assignment'] = assignment + + # Additional info + result['status'] = model.Status + result['mip_gap'] = model.MIPGap if model.Status != GRB.OPTIMAL else 0.0 + if model.Status == GRB.OPTIMAL: + result['optimal'] = True + else: + result['optimal'] = False + else: + # No feasible solution found + result['objective_value'] = None + result['status'] = model.Status + result['optimal'] = False + + # Write solution + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + +def main(): + parser = argparse.ArgumentParser(description="Solve QMKP using Gurobi (model 1-4)") + parser.add_argument('--instance_path', type=str, required=True, + help='Path to the JSON instance file') + parser.add_argument('--solution_path', type=str, required=True, + help='Path for the output solution JSON file') + parser.add_argument('--time_limit', type=int, required=True, + help='Maximum solver runtime in seconds') + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_qmkp(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == '__main__': + main() diff --git a/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_1.json b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_2.json b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_3.json b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_4.json b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_5.json b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fleszar2022b/gurobi_feasi_result/tiny_feasi_result.json b/tasks/fleszar2022b/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fleszar2022b/gurobi_solution/large_solution_1.json b/tasks/fleszar2022b/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e26389c72621179531a29ee5d6e61efe3ec16e19 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd5e686488cd2c57cd2d68cdb78584765ca561e7aec89f78c3092e04ef8a4914 +size 798 diff --git a/tasks/fleszar2022b/gurobi_solution/large_solution_2.json b/tasks/fleszar2022b/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..01c06caeaa41824fec8b9a5cc75a383ce9f8226d --- /dev/null +++ b/tasks/fleszar2022b/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a547ab22d9a983507f278da37969bbfe3a556e1efc85a971edce12e4fb74a435 +size 810 diff --git a/tasks/fleszar2022b/gurobi_solution/large_solution_3.json b/tasks/fleszar2022b/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ea39485bd02be53444d1ceae219eee2b192b263c --- /dev/null +++ b/tasks/fleszar2022b/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:628e694057f24b25311e9bc5e43909fd51f94eb580df59009e70a4f4c09f6044 +size 796 diff --git a/tasks/fleszar2022b/gurobi_solution/large_solution_4.json b/tasks/fleszar2022b/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..10ee05880231e910be63c3d74fe8061c51d0a28f --- /dev/null +++ b/tasks/fleszar2022b/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4ba558e045dd2dd4871f339c1fd152050512dcea2fb6aaa8b1289281a0abc71 +size 798 diff --git a/tasks/fleszar2022b/gurobi_solution/large_solution_5.json b/tasks/fleszar2022b/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d73fa3a5435c103c65461fb0376d093f0301ca2a --- /dev/null +++ b/tasks/fleszar2022b/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fea1c6823b7022e274cbac50b4f4f133de5a20514c9f95eb7dccf22d7ca2e62 +size 810 diff --git a/tasks/fleszar2022b/gurobi_solution/tiny_solution.json b/tasks/fleszar2022b/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..15d5aa464bfab7632695f086429a2ff1915daf8d --- /dev/null +++ b/tasks/fleszar2022b/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14fbfc0dd3fc678a4c79e847573fc4c5f141523d81711faabfd2d345e98d8208 +size 349 diff --git a/tasks/fleszar2022b/gurobi_solution_log/tiny_log.jsonl b/tasks/fleszar2022b/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fcdd9611b8836b660669bb62caff6ee20262b451 --- /dev/null +++ b/tasks/fleszar2022b/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2b2232268ff36a91dd811013647cca2b11de4217e0e235a8d3009cb1da18e31 +size 41 diff --git a/tasks/fleszar2022b/instance/large_instance_1.json b/tasks/fleszar2022b/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6cb35632496b44cb7c4fd423379ac2a8d7e1380e --- /dev/null +++ b/tasks/fleszar2022b/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00928b198a550891e11b1543ae246b13c7b94ba0596643806b5637de5e5046c0 +size 36806 diff --git a/tasks/fleszar2022b/instance/large_instance_2.json b/tasks/fleszar2022b/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7ce4d2d091593749a25f1164ecdbb4fc205f71aa --- /dev/null +++ b/tasks/fleszar2022b/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb3b80470206771027b22c585302168985f93136930d8f1011c9fbca11cd13ce +size 35223 diff --git a/tasks/fleszar2022b/instance/large_instance_3.json b/tasks/fleszar2022b/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b40f6636b3acbe373c472fcdde62b3517f89b976 --- /dev/null +++ b/tasks/fleszar2022b/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e24619077c84530ea6a931741e6b54b12b398029927f98e272999f2b06588dc +size 36067 diff --git a/tasks/fleszar2022b/instance/large_instance_4.json b/tasks/fleszar2022b/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a9e9e74b493cdddffd946f7e50be8eac510f82c4 --- /dev/null +++ b/tasks/fleszar2022b/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa31dde3bd800523d4ca4b558c70cb14386736cc021bc1e48575f44fbb970c9b +size 34755 diff --git a/tasks/fleszar2022b/instance/large_instance_5.json b/tasks/fleszar2022b/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7ebda48d11d68d9376d918a0e1a63b8e0a555bd4 --- /dev/null +++ b/tasks/fleszar2022b/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b75ffc478e8ff7c5a25c43b465264f7418926efebcb3cc04db095f9cac97215 +size 37633 diff --git a/tasks/fleszar2022b/instance/tiny_instance.json b/tasks/fleszar2022b/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..46c11df64279c97e4f80723a5990b5dd5c820fa3 --- /dev/null +++ b/tasks/fleszar2022b/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:208b51ef15025030d18ca5ca41b6c6797ed448b50deb0143d78576be810b43db +size 4565 diff --git a/tasks/fleszar2022b/instance_schema.json b/tasks/fleszar2022b/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f8c7980d9095b22af78440c6b9026c4dafe092bc --- /dev/null +++ b/tasks/fleszar2022b/instance_schema.json @@ -0,0 +1,8 @@ +{ + "n": " Number of items available to be packed into knapsacks.", + "m": " Number of identical knapsacks.", + "capacity": " Maximum total weight each knapsack can hold.", + "weights": " Weight of each item, sorted in non-decreasing order.", + "values": " Individual value earned when each item is packed into any knapsack.", + "pairwise_values": " Symmetric matrix of bonus values earned when two items are placed in the same knapsack." +} diff --git a/tasks/fleszar2022b/mathematical_formulation.md b/tasks/fleszar2022b/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..0f281bb8898306a260150ddc3c8a3b9786516cc0 --- /dev/null +++ b/tasks/fleszar2022b/mathematical_formulation.md @@ -0,0 +1,44 @@ +# Original Formulation: Quadratic Multiple Knapsack Problem (QMKP) + +*Source: A branch-and-bound algorithm for the quadratic multiple knapsack problem, Krzysztof Fleszar, 2021/2022 (European Journal of Operational Research).* + +## Sets and Indices + +$$\begin{align*} +N &= \{1,\dots,n\} && \text{set of all items, indexed by } i,j \\ +M &= \{1,\dots,m\} && \text{set of all knapsacks, indexed by } k +\end{align*}$$ + +## Parameters + +$$\begin{align*} +w_i &: \text{positive integer weight of item } i \in N \\ +v_i &: \text{individual value of item } i \in N \\ +v_{ij} = v_{ji} &: \text{pairwise value of items } i,j \in N,\; i= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/fleszar2022b/solution_schema.json b/tasks/fleszar2022b/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..913b65523da31dcfb26e14b4da5a3fce5750ef6b --- /dev/null +++ b/tasks/fleszar2022b/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total value collected across all knapsacks, including individual and pairwise values.", + "assignment": " Knapsack to which each packed item is assigned; items not present are left unpacked." +} diff --git a/tasks/forrest2006/feasibility_check.py b/tasks/forrest2006/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..67b27ba8f8217fc099430c253005c5fa35f2090f --- /dev/null +++ b/tasks/forrest2006/feasibility_check.py @@ -0,0 +1,526 @@ +""" +Feasibility checker for the Multiple Knapsack Problem with Color Constraints (MKCP). + +Based on: Forrest, Kalagnanam, and Ladanyi (2006) +"A Column-Generation Approach to the Multiple Knapsack Problem with Color Constraints" +INFORMS Journal on Computing 18(1), pp. 129-134. + +Checks hard constraints from the natural (original) formulation (Section A): + Constraint (2): Knapsack capacity + Constraint (3): Each order assigned to at most one slab + Constraint (4): At most K=2 distinct colors per slab + Constraint (5a): Linking x_ij <= y_{c_i, j} + Constraint (5b): x_ij in {0, 1} + Constraint (5c): y_cj in {0, 1} + Constraint (5d): z_j in {0, 1} + Constraint (6): Objective consistency -- the reported objective_value must + agree with the objective recomputed from the solution + variables (Tier C anti-gaming defense; see below). + +This is the obj-recompute variant of feasibility_check.py. It is identical to +the original except for the new Constraint (6) block inserted just before the +final feasibility verdict. Constraint (6) recomputes the linear-form objective +(Eq. 1' of math_model.txt): + + obj = sum_{i in N} sum_{j in M_i} 2*w_i*x_ij - sum_{j in M} W_j*z_j + +from the assignments (x) and the derived used-slab set (z). Every variable the +objective depends on is present in the solution, so this is a FULL recompute +(not a lower bound). A candidate that fabricates objective_value while keeping +a feasible route is rejected with violated constraint 6. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', 'objective_value', 'slabs_used') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = (('slabs_used', 'assignment_key_set', 'assignments', 'slab'),) +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + violations = [] + violated_constraints = set() + violation_magnitudes = [] + + n = instance["num_orders"] + m = instance["num_slabs"] + w = instance["order_weights"] + W = instance["slab_weights"] + colors = instance["order_colors"] + eligible = instance["eligible_slabs_per_order"] + K = instance["max_colors_per_knapsack"] + + # Build M_i (eligible slabs for order i) and N_j (eligible orders for slab j) + M_i = [set(eligible[i]) for i in range(n)] + N_j = [set() for _ in range(m)] + for i in range(n): + for j in M_i[i]: + N_j[j].add(i) + + # Reconstruct decision variables from solution + assignments = solution.get("assignments", []) + + # x_ij: 1 if order i assigned to slab j + x = {} + for a in assignments: + i = a["order"] + j = a["slab"] + x[(i, j)] = 1 + + # Derive z_j: 1 if any order is assigned to slab j + slabs_used = set() + for a in assignments: + slabs_used.add(a["slab"]) + z = {j: (1 if j in slabs_used else 0) for j in range(m)} + + # Derive y_cj: 1 if any order of color c is assigned to slab j + y = {} + for a in assignments: + i = a["order"] + j = a["slab"] + c = colors[i] + y[(c, j)] = 1 + + # Also check that assigned (i,j) pairs respect eligibility (implicit domain) + for a in assignments: + i = a["order"] + j = a["slab"] + if j not in M_i[i]: + violated_constraints.add(5) + violations.append( + f"Order {i} assigned to slab {j} but slab {j} is not in eligible set M_{i} = {sorted(M_i[i])}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": 1.0, + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": EPS, + "ratio": 1.0 / EPS, + }) + + # ------------------------------------------------------------------ + # Constraint (2): Knapsack capacity + # sum_{i in N_j} w_i * x_ij <= W_j * z_j, for all j in M + # ------------------------------------------------------------------ + for j in range(m): + lhs = sum(w[i] * x.get((i, j), 0) for i in N_j[j]) + rhs = W[j] * z[j] + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(2) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint (2) violated on slab {j}: " + f"total assigned weight {lhs:.4f} > capacity {rhs:.4f} (W_j={W[j]}, z_j={z[j]})" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint (3): Each order assigned to at most one slab + # sum_{j in M_i} x_ij <= 1, for all i in N + # ------------------------------------------------------------------ + for i in range(n): + lhs = sum(x.get((i, j), 0) for j in M_i[i]) + rhs = 1.0 + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(3) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + assigned_slabs = [j for j in M_i[i] if x.get((i, j), 0) == 1] + violations.append( + f"Constraint (3) violated for order {i}: " + f"assigned to {int(lhs)} slabs {assigned_slabs} (max 1)" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint (4): At most K=2 distinct colors per slab + # sum_{c in C_j} y_cj <= K, for all j in M + # ------------------------------------------------------------------ + for j in range(m): + # Count distinct colors of orders actually assigned to slab j + colors_on_slab = set() + for i in N_j[j]: + if x.get((i, j), 0) == 1: + colors_on_slab.add(colors[i]) + lhs = float(len(colors_on_slab)) + rhs = float(K) + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(4) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint (4) violated on slab {j}: " + f"{int(lhs)} distinct colors {sorted(colors_on_slab)} assigned (max {K})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint (5a): Linking x_ij <= y_{c_i, j} + # for all i in N, j in M_i + # Since y is derived from x (y_{c,j}=1 iff any order of color c is on j), + # this is always satisfied by construction. But we still check explicitly. + # ------------------------------------------------------------------ + for (i, j), xval in x.items(): + if xval == 1: + c = colors[i] + yval = y.get((c, j), 0) + lhs = float(xval) + rhs = float(yval) + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(5) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint (5a) violated: x_{{{i},{j}}}={xval} > y_{{{c},{j}}}={yval}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint (5b): x_ij in {0, 1} + # By construction from the solution format (assignments list), x values + # are always 0 or 1. Check anyway. + # ------------------------------------------------------------------ + for (i, j), xval in x.items(): + if xval not in (0, 1): + violated_constraints.add(5) + violations.append( + f"Constraint (5b) violated: x_{{{i},{j}}}={xval} not in {{0, 1}}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(xval), + "rhs": 1.0, + "raw_excess": abs(xval - round(xval)), + "normalizer": max(1.0, EPS), + "ratio": abs(xval - round(xval)) / max(1.0, EPS), + }) + + # ------------------------------------------------------------------ + # Constraint (5c): y_cj in {0, 1} + # By construction y values are always 0 or 1. Check anyway. + # ------------------------------------------------------------------ + for (c, j), yval in y.items(): + if yval not in (0, 1): + violated_constraints.add(5) + violations.append( + f"Constraint (5c) violated: y_{{{c},{j}}}={yval} not in {{0, 1}}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(yval), + "rhs": 1.0, + "raw_excess": abs(yval - round(yval)), + "normalizer": max(1.0, EPS), + "ratio": abs(yval - round(yval)) / max(1.0, EPS), + }) + + # ------------------------------------------------------------------ + # Constraint (5d): z_j in {0, 1} + # By construction z values are always 0 or 1. Check anyway. + # ------------------------------------------------------------------ + for j_idx, zval in z.items(): + if zval not in (0, 1): + violated_constraints.add(5) + violations.append( + f"Constraint (5d) violated: z_{{{j_idx}}}={zval} not in {{0, 1}}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(zval), + "rhs": 1.0, + "raw_excess": abs(zval - round(zval)), + "normalizer": max(1.0, EPS), + "ratio": abs(zval - round(zval)) / max(1.0, EPS), + }) + + # ------------------------------------------------------------------ + # Constraint (6): Objective consistency (Tier C anti-gaming defense) + # The eval pipeline otherwise trusts solution["objective_value"]; an + # LLM-evolved candidate can keep a feasible route but report a + # fabricated objective. Here we RECOMPUTE the linear-form objective + # (Eq. 1' of math_model.txt) directly from the solution variables: + # + # obj = sum_{i in N} sum_{j in M_i} 2*w_i*x_ij - sum_{j in M} W_j*z_j + # + # All obj-determining variables are present -- x_ij from `assignments` + # and z_j derived from the used-slab set (same z used by Constraint 2) + # -- so this is a FULL recompute, not a lower bound. We reject when the + # reported value disagrees beyond a 0.1% relative tolerance with a + # 1e-3 absolute floor (the floor covers the Gurobi-optimal obj==0 + # instances, whose reported values carry sub-1e-3 floating-point noise). + # + # This check is append-only: it can add constraint 6 but never alters + # the verdict of constraints 2-5. + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + obj_x = sum(2.0 * w[i] * xval for (i, j), xval in x.items()) + obj_z = sum(W[j] * zval for j, zval in z.items()) + true_obj = obj_x - obj_z + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(6) + normalizer = max(abs(true_obj), EPS) + ratio = abs_diff / normalizer + violations.append( + f"Constraint (6) violated: reported objective_value={reported} " + f"differs from recomputed 2*sum(w_i*x_ij) - sum(W_j*z_j)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": ratio, + }) + + feasible = len(violated_constraints) == 0 + + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MKCP (Forrest et al. 2006)." + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance.", + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution.", + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result.", + ) + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Feasibility: {status}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/forrest2006/gurobi_code.py b/tasks/forrest2006/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..47d4a164caf9d8b8d3c2cdcafaac0ccc692f92bf --- /dev/null +++ b/tasks/forrest2006/gurobi_code.py @@ -0,0 +1,241 @@ +""" +Gurobi implementation of the Multiple Knapsack Problem with Color Constraints (MKCP). + +Based on: Forrest, Kalagnanam, and Ladanyi (2006) +"A Column-Generation Approach to the Multiple Knapsack Problem with Color Constraints" +INFORMS Journal on Computing 18(1), pp. 129-134. + +This implements the "natural" (original) formulation using the linear objective form (1'). +""" + +import argparse +import json +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load a MKCP instance from a JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(data, time_limit): + """ + Build and solve the natural MKCP formulation. + + Sets: + N = {0, ..., n-1}: orders (items) + M = {0, ..., m-1}: slabs (knapsacks) + M_i: eligible slabs for order i + N_j: orders eligible for slab j (derived from M_i) + C_j: distinct colors among orders in N_j + + Variables: + x[i,j] in {0,1}: 1 if order i assigned to slab j (only for j in M_i) + y[c,j] in {0,1}: 1 if color c is used on slab j (only for c in C_j) + z[j] in {0,1}: 1 if slab j is used + + Objective (linear form 1'): + max sum_{i in N} sum_{j in M_i} 2*w_i*x[i,j] - sum_{j in M} W_j*z[j] + + Constraints: + (2) sum_{i in N_j} w_i * x[i,j] <= W_j * z[j], for all j in M + (3) sum_{j in M_i} x[i,j] <= 1, for all i in N + (4) sum_{c in C_j} y[c,j] <= 2, for all j in M + (5a) x[i,j] <= y[c_i, j], for all i in N, j in M_i + """ + n = data["num_orders"] + m = data["num_slabs"] + w = data["order_weights"] + W = data["slab_weights"] + colors = data["order_colors"] + eligible = data["eligible_slabs_per_order"] # M_i for each order i + K = data["max_colors_per_knapsack"] # typically 2 + + # Derive N_j: orders incident to slab j + N_j = [[] for _ in range(m)] + for i in range(n): + for j in eligible[i]: + N_j[j].append(i) + + # Derive C_j: distinct colors incident on slab j + C_j = [set() for _ in range(m)] + for j in range(m): + for i in N_j[j]: + C_j[j].add(colors[i]) + + # Build model + model = gp.Model("MKCP_Natural") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i,j] only for incident pairs + x = {} + for i in range(n): + for j in eligible[i]: + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + # y[c,j] only for colors in C_j + y = {} + for j in range(m): + for c in C_j[j]: + y[c, j] = model.addVar(vtype=GRB.BINARY, name=f"y_{c}_{j}") + + # z[j] for all slabs + z = {} + for j in range(m): + z[j] = model.addVar(vtype=GRB.BINARY, name=f"z_{j}") + + model.update() + + # Objective: max sum 2*w_i*x[i,j] - sum W_j*z[j] (linear form 1') + obj = gp.LinExpr() + for i in range(n): + for j in eligible[i]: + obj += 2.0 * w[i] * x[i, j] + for j in range(m): + obj -= W[j] * z[j] + model.setObjective(obj, GRB.MAXIMIZE) + + # Constraint (2): capacity + for j in range(m): + lhs = gp.LinExpr() + for i in N_j[j]: + lhs += w[i] * x[i, j] + model.addConstr(lhs <= W[j] * z[j], name=f"capacity_{j}") + + # Constraint (3): each order assigned at most once + for i in range(n): + lhs = gp.LinExpr() + for j in eligible[i]: + lhs += x[i, j] + model.addConstr(lhs <= 1, name=f"assign_{i}") + + # Constraint (4): at most K distinct colors per slab + for j in range(m): + if C_j[j]: + lhs = gp.LinExpr() + for c in C_j[j]: + lhs += y[c, j] + model.addConstr(lhs <= K, name=f"color_limit_{j}") + + # Constraint (5a): linking x and y + for i in range(n): + for j in eligible[i]: + c_i = colors[i] + model.addConstr(x[i, j] <= y[c_i, j], name=f"link_{i}_{j}") + + # Solve + model.optimize() + + # Extract solution + result = { + "status": model.Status, + "objective_value": None, + "assignments": [], # list of (order, slab) pairs + "slabs_used": [], + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + + for i in range(n): + for j in eligible[i]: + if x[i, j].X > 0.5: + result["assignments"].append({"order": i, "slab": j}) + break + + for j in range(m): + if z[j].X > 0.5: + result["slabs_used"].append(j) + + # Verify color constraints in solution + slab_colors = {} + for a in result["assignments"]: + j = a["slab"] + c = colors[a["order"]] + if j not in slab_colors: + slab_colors[j] = set() + slab_colors[j].add(c) + + result["solution_details"] = { + "num_orders_assigned": len(result["assignments"]), + "num_slabs_used": len(result["slabs_used"]), + "colors_per_slab": {str(j): list(cs) for j, cs in slab_colors.items()}, + } + + if model.Status == GRB.OPTIMAL: + result["solution_status"] = "optimal" + elif model.Status == GRB.TIME_LIMIT: + result["solution_status"] = "time_limit_feasible" + else: + result["solution_status"] = "feasible" + else: + result["objective_value"] = None + result["solution_status"] = "no_feasible_solution_found" + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve MKCP using the natural formulation with Gurobi." + ) + parser.add_argument( + "--instance_path", type=str, required=True, help="Path to the instance JSON file." + ) + parser.add_argument( + "--solution_path", + type=str, + required=True, + help="Path for the output solution JSON file.", + ) + parser.add_argument( + "--time_limit", + type=int, + required=True, + help="Maximum solver runtime in seconds.", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + print(f"Loaded instance: {data.get('problem_name', 'MKCP')}") + print(f" Orders: {data['num_orders']}, Slabs: {data['num_slabs']}, Colors: {data['num_colors']}") + print(f" Max colors per knapsack: {data['max_colors_per_knapsack']}") + print(f" Time limit: {args.time_limit}s") + + result = build_and_solve(data, args.time_limit) + + print(f"\nSolution status: {result['solution_status']}") + print(f"Objective value: {result['objective_value']}") + + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + print(f"Solution written to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_1.json b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_2.json b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_3.json b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_4.json b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_5.json b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/forrest2006/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/forrest2006/gurobi_feasi_result/tiny_feasi_result.json b/tasks/forrest2006/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/forrest2006/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/forrest2006/gurobi_solution/large_solution_1.json b/tasks/forrest2006/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..25b282c1eda12010a0276710caf9ee7892a68985 --- /dev/null +++ b/tasks/forrest2006/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4b6b912416f441d7f1e45a036a42734e340a46f4a10c640c7db4d9c3463dd74 +size 249 diff --git a/tasks/forrest2006/gurobi_solution/large_solution_2.json b/tasks/forrest2006/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..332818d702cf9ad0a06ad577beeef467cc1fbdf7 --- /dev/null +++ b/tasks/forrest2006/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:488beb92eba936107a134ea5e625fd416de668db92f01512ec382ad64e8d3689 +size 266 diff --git a/tasks/forrest2006/gurobi_solution/large_solution_3.json b/tasks/forrest2006/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8b5b3fa1988129dbbc5179b1fc43884dcb95fd4f --- /dev/null +++ b/tasks/forrest2006/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee117f38f5b40cc413d4da6bb3b7bfc8ec65cd51445cfbaf62657688df0d6040 +size 266 diff --git a/tasks/forrest2006/gurobi_solution/large_solution_4.json b/tasks/forrest2006/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2350bdf98381eb742151a59b75a8387ef7475438 --- /dev/null +++ b/tasks/forrest2006/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5a321499b8d59571a86d98d780bfcd5d60d3d9064173de5611ee67312a3f3c5 +size 267 diff --git a/tasks/forrest2006/gurobi_solution/large_solution_5.json b/tasks/forrest2006/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..301db263a10677c2f7516252d5cf0396414dd0fd --- /dev/null +++ b/tasks/forrest2006/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f8b7e8f0946d67a8a35028e0f1b58838e392fc39780246a06fcfec3c2a38490 +size 265 diff --git a/tasks/forrest2006/gurobi_solution/tiny_solution.json b/tasks/forrest2006/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..65473260b76e916334901b75e27ddc161662c935 --- /dev/null +++ b/tasks/forrest2006/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ee8812b46ba0ba12c9304fa1ea9fb706e561ff2add116b495c0bd65756e63f2 +size 512 diff --git a/tasks/forrest2006/gurobi_solution_log/large_log_1.jsonl b/tasks/forrest2006/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..70d8b7e3609101fec8210416c898b894ca2b9fbc --- /dev/null +++ b/tasks/forrest2006/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf30f8df4bffdcbd191f9e8581055b7d92c408766bac25d8323efd264caafdc8 +size 41 diff --git a/tasks/forrest2006/gurobi_solution_log/large_log_2.jsonl b/tasks/forrest2006/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3513b6e3acd1871dd63cfe3f05517288c627e804 --- /dev/null +++ b/tasks/forrest2006/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e59abdad1e69fd6c1105104e9de4e2bf4909d273a6e4ccdc5191c0c55d9a3c0 +size 41 diff --git a/tasks/forrest2006/gurobi_solution_log/large_log_3.jsonl b/tasks/forrest2006/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1b53b0e50102c971dea6851b7a2bb4ffda33124d --- /dev/null +++ b/tasks/forrest2006/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f4b65507edc32389305beddeae9845fa8cca7c3c47bf95090dc2b238c5d29be +size 41 diff --git a/tasks/forrest2006/gurobi_solution_log/large_log_4.jsonl b/tasks/forrest2006/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5fdc37e1f6c7c078bf67fa912475a72c1f05f705 --- /dev/null +++ b/tasks/forrest2006/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b79784a7d82d5f2679c981376de448cd593b85830d9c66e2b7d9f59938f44e8 +size 41 diff --git a/tasks/forrest2006/gurobi_solution_log/large_log_5.jsonl b/tasks/forrest2006/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..13204a1d4d9b0fa4a93a088ad49f800dad3bbe1b --- /dev/null +++ b/tasks/forrest2006/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:789d5f6a864daa12fca1ccae9ff72ffad75d1e21ba055785237eadc895ac385b +size 41 diff --git a/tasks/forrest2006/gurobi_solution_log/tiny_log.jsonl b/tasks/forrest2006/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fcdd9611b8836b660669bb62caff6ee20262b451 --- /dev/null +++ b/tasks/forrest2006/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2b2232268ff36a91dd811013647cca2b11de4217e0e235a8d3009cb1da18e31 +size 41 diff --git a/tasks/forrest2006/instance/large_instance_1.json b/tasks/forrest2006/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..80ef454c523c6cdfed4edf33b50ebe461a3349e8 --- /dev/null +++ b/tasks/forrest2006/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43749517d596a7ee46ac71f7de344f11831ca298a0be34256c345d4289a67c3d +size 397169 diff --git a/tasks/forrest2006/instance/large_instance_2.json b/tasks/forrest2006/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d0b646c2c951a77b6995f6dcff2780bf4651e167 --- /dev/null +++ b/tasks/forrest2006/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b82d0fbd683d55c0a9f6f80dd45a79a3da85f87cefc44e9fe886f180fc89b6d7 +size 397131 diff --git a/tasks/forrest2006/instance/large_instance_3.json b/tasks/forrest2006/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e50a4ec3d26db07b67df0c7fa7cbc5a4767c35a7 --- /dev/null +++ b/tasks/forrest2006/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a3875b21759630ec330faa8e75ca4ebbb01f51e75c56d11011c08d9e2e124dd +size 395611 diff --git a/tasks/forrest2006/instance/large_instance_4.json b/tasks/forrest2006/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..b84bcf3c117829863cb650da0080495081867b83 --- /dev/null +++ b/tasks/forrest2006/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:198f41ea9f6d154f9c29462bdcbd26bee81deeaf5cf5a0809512d8c412b71f82 +size 368765 diff --git a/tasks/forrest2006/instance/large_instance_5.json b/tasks/forrest2006/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..b0fd192e2ae11e6ae9535320cf01a532ce802e59 --- /dev/null +++ b/tasks/forrest2006/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3187f95414f714e5de993ff47e4666355813d834ae1e10ab99f1927f256d3372 +size 396893 diff --git a/tasks/forrest2006/instance/tiny_instance.json b/tasks/forrest2006/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..eac5fb7077de36a4cf236dd3a457710a5359719f --- /dev/null +++ b/tasks/forrest2006/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7328e2173dc22b8867d3d4863eeed8bfd6721216ee44d9ce915755f0701c1c94 +size 2817 diff --git a/tasks/forrest2006/instance_schema.json b/tasks/forrest2006/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..699033a9bac829e9d3e1d51875d66b7a069720e0 --- /dev/null +++ b/tasks/forrest2006/instance_schema.json @@ -0,0 +1,10 @@ +{ + "num_slabs": " Number of surplus slabs available in inventory.", + "num_orders": " Number of customer orders in the order book.", + "num_colors": " Number of distinct finishing-line route codes across all orders.", + "max_colors_per_knapsack": " Maximum number of distinct colors permitted among orders assigned to any single slab.", + "slab_weights": " Weight capacity of each slab.", + "order_weights": " Weight of each customer order.", + "order_colors": " Finishing-line route code (color) assigned to each order.", + "eligible_slabs_per_order": " Indices of slabs eligible to supply each order, based on quality grade and dimension compatibility." +} diff --git a/tasks/forrest2006/mathematical_formulation.md b/tasks/forrest2006/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..ea6dcf33b226628efffb460605d037a65439eb96 --- /dev/null +++ b/tasks/forrest2006/mathematical_formulation.md @@ -0,0 +1,48 @@ +# Sets and Parameters + +- $N = \{1,\ldots,n\}$: set of orders (items); index $i$. + +- $M = \{1,\ldots,m\}$: set of slabs (knapsacks); index $j$. + +- $M_i \subseteq M$: set of slabs incident to order $i$. + +- $N_j \subseteq N$: set of orders incident to slab $j$. + +- $C_j$: set of colors incident on slab $j$. + +- $w_i$: weight of order $i$. + +- $W_j$: weight of slab $j$. + +- $c_i$: color of order $i$. + +# Decision Variables + +$$\begin{align*} +x_{ij} &\in \{0,1\} && \forall\, i \in N,\; j \in M_i \quad (\text{1 if order $i$ is assigned to slab $j$}) \\ +y_{cj} &\in \{0,1\} && \forall\, c \in C_j,\; j \in M \quad (\text{1 if orders of color $c$ use slab $j$}) \\ +z_{j} &\in \{0,1\} && \forall\, j \in M \quad (\text{1 if any order is incident to slab $j$}) +\end{align*}$$ + +# Objective + +The paper states the natural formulation with the nonlinear objective (1): $$\begin{equation} +\max \; \sum_{i \in N}\sum_{j \in M_i} w_i\, x_{ij} \;-\; \sum_{j \in M} \left( W_j - \sum_{i \in N_j} w_i\, x_{ij} \right) z_j \tag{1} +\end{equation}$$ + +Because $z_j = 0$ forces $x_{ij} = 0$ for all $i \in N_j$ and $z_j = 1$ implies $x_{ij} z_j = x_{ij}$, for all feasible solutions the objective is equivalent to the linear form: $$\begin{equation} +\max \; \sum_{i \in N}\sum_{j \in M_i} 2 w_i\, x_{ij} \;-\; \sum_{j \in M} W_j\, z_j \tag{1$'$} +\end{equation}$$ + +# Constraints + +$$\begin{align} +\sum_{i \in N_j} w_i\, x_{ij} &\leq W_j\, z_j && \forall\, j \in M \tag{2} \\ +\sum_{j \in M_i} x_{ij} &\leq 1 && \forall\, i \in N \tag{3} \\ +\sum_{c \in C_j} y_{cj} &\leq 2 && \forall\, j \in M \tag{4} +\end{align}$$ $$\begin{align} +x_{ij} &\leq y_{c_i,\, j} && \forall\, i \in N,\; j \in M_i \tag{5a} \\ +x_{ij} &\in \{0,1\} && \forall\, i \in N,\; j \in M_i \tag{5b} \\ +y_{cj} &\in \{0,1\} && \forall\, c \in C_j,\; j \in M \tag{5c} \\ +z_{j} &\in \{0,1\} && \forall\, j \in M \tag{5d} +\end{align}$$ diff --git a/tasks/forrest2006/problem_description.txt b/tasks/forrest2006/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..da13c9c943dd8dfc04787b03d313f8aafe8c3ccc --- /dev/null +++ b/tasks/forrest2006/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A steel mill holds a surplus inventory of slabs and an order book of customer orders. The planner must decide which orders to fulfill from which surplus slabs, with the twin goals of maximizing the total weight of orders satisfied from inventory and minimizing the unused (wasted) weight on every slab that is put into service. There are a given number of slabs and a given number of orders. Each order has a known weight and a single color attribute representing the finishing-line route code that governs the sequence of process operations the order requires. Each slab has a known weight that acts as its capacity. For every order, a specified subset of slabs is eligible to supply it, determined by quality grade and physical dimension compatibility; an order may only be assigned to a slab in its eligible subset. Each slab likewise has a known set of orders eligible for assignment to it, and a known set of distinct colors among those eligible orders. + +The planner must choose, for each order, whether to assign it to one of its eligible slabs or to leave it unassigned, and must also determine which slabs are placed into service. An order may be assigned to at most one slab. Orders may only be assigned to a slab that is placed into service, and the total weight of all orders assigned to any in-service slab must not exceed that slab's weight. Because cutting slabs between order types is expensive and the cutting machine is a bottleneck, at most two distinct colors may appear among the orders assigned to any single slab. An order of a given color can be assigned to a slab only if that color is one of the (at most two) colors selected for that slab. + +The goal is to maximize the sum, over all assigned orders, of twice the order weight, minus the sum, over all slabs placed into service, of the slab weight. Equivalently, this objective simultaneously rewards fulfilling heavy orders and penalizes the full weight of every slab that is opened, so that a slab is worth opening only when the orders packed onto it recover enough weight to offset the slab's cost. A slab that has no orders assigned to it is not considered in service and incurs no penalty. + +The input data consists of the number of slabs, the number of orders, the number of distinct colors, the weight of each slab, the weight of each order, the color of each order, and for each order the list of slabs that are eligible to supply it. The maximum number of distinct colors permitted on any single slab is also provided as an input (set to two in the instances studied). diff --git a/tasks/forrest2006/solution_logger.py b/tasks/forrest2006/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/forrest2006/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/forrest2006/solution_schema.json b/tasks/forrest2006/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..822567f73f24875f491dd670470bfa0d31bb15d6 --- /dev/null +++ b/tasks/forrest2006/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Twice the total weight of assigned orders minus the total weight of slabs placed into service.", + "assignments": " Each entry records one order being fulfilled from one slab, with keys 'order' ( the order index) and 'slab' ( the slab index it is assigned to).", + "slabs_used": " Indices of slabs that are placed into service." +} diff --git a/tasks/fragkos2016/feasibility_check.py b/tasks/fragkos2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..72d1c3b3a3ee7ac270ab5eac3e40ef90d65cfc1f --- /dev/null +++ b/tasks/fragkos2016/feasibility_check.py @@ -0,0 +1,463 @@ +""" +Feasibility checker for the Capacitated Lot-Sizing Problem with Setup Times (CLST). +Reference: Fragkos, Degraeve, and De Reyck (2016), INFORMS Journal on Computing 28(3): 465-482. + +Constraints (numbered top-to-bottom from the formulation section of math_model.txt): + Constraint 1: Flow balance (equality) + s_{it} + x_{it} = d_{it} + s_{i,t+1} for all i in I, t in T + Constraint 2: Setup-production link (<=) + x_{it} <= M_{it} * y_{it} for all i in I, t in T + Constraint 3: Capacity (<=) + sum_i st_{it}*y_{it} + sum_i vt_{it}*x_{it} <= cap_t for all t in T + Constraint 4: Nonnegativity, integrality, and boundary conditions + x_{it} >= 0, s_{it} >= 0, s_{i,m+1} = 0, y_{it} in {0,1} + Constraint 5: Objective consistency (Tier C obj-recompute defense) + reported objective_value must equal the recomputed total cost + sum_{i,t} sc_{it}*y_{it} + vc_{it}*x_{it} + hc_{it}*s_{it} + within tolerance. All objective-determining variables (x, s, y) are + present in the solution, so a full recompute is possible. + +This is the obj-recompute variant of feasibility_check.py (Tier C defense +against LLM score-gaming). The original file is left untouched; the only +behavioural difference here is the addition of Constraint 5. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 's', 'x', 'y') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def check_feasibility(instance, solution): + n = instance["n_items"] + m = instance["n_periods"] + d = instance["demands"] + cap = instance["capacity"] + st = instance["setup_times"] + vt = instance["variable_times"] + big_M = instance["big_M"] + init_inv = instance["initial_inventory"] + + x = solution["x"] + y = solution["y"] + + # If solution is null/infeasible, report immediately + if x is None or y is None: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Solution is null/infeasible (no decision variables provided)."], + "violation_magnitudes": [] + } + + # math_model.txt note 2: s_{i,1} is a decision variable, not a fixed input. + # Reconstructing s from x and init_inv fabricates s_{i,1} = init_inv[i] and + # auto-satisfies flow balance (eq 2), so missing 's' must be rejected rather + # than synthesised. + s = solution.get("s") + if s is None: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Solution is missing required field 's' (inventory)."], + "violation_magnitudes": [] + } + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # --- Constraint 1: Flow balance (equality) --- + # s_{it} + x_{it} = d_{it} + s_{i,t+1} for all i, t + for i in range(n): + for t in range(m): + lhs = s[i][t] + x[i][t] + rhs = d[i][t] + s[i][t + 1] + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(1) + violations.append( + f"Constraint 1: Flow balance violated for item {i}, period {t}: " + f"s[{i}][{t}] + x[{i}][{t}] = {lhs:.6f} != d[{i}][{t}] + s[{i}][{t+1}] = {rhs:.6f}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 2: Setup-production link (<=) --- + # x_{it} <= M_{it} * y_{it} + for i in range(n): + for t in range(m): + lhs = x[i][t] + rhs = big_M[i][t] * y[i][t] + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(2) + violations.append( + f"Constraint 2: Setup link violated for item {i}, period {t}: " + f"x[{i}][{t}] = {lhs:.6f} > M[{i}][{t}]*y[{i}][{t}] = {rhs:.6f}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 3: Capacity (<=) --- + # sum_i st_{it}*y_{it} + sum_i vt_{it}*x_{it} <= cap_t + for t in range(m): + lhs = sum(st[i][t] * y[i][t] + vt[i][t] * x[i][t] for i in range(n)) + rhs = cap[t] + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(3) + violations.append( + f"Constraint 3: Capacity violated in period {t}: " + f"usage = {lhs:.6f} > capacity = {rhs:.6f}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 4: Nonnegativity, integrality, and boundary --- + # x_{it} >= 0 + for i in range(n): + for t in range(m): + if x[i][t] < -TOL: + violated_constraints.add(4) + lhs_val = 0.0 + rhs_val = x[i][t] + violation_amount = -x[i][t] + violations.append( + f"Constraint 4: Nonnegativity violated: x[{i}][{t}] = {x[i][t]:.6f} < 0" + ) + normalizer = max(abs(rhs_val), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": rhs_val, + "rhs": lhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # s_{it} >= 0 for t in 0..m + for i in range(n): + for t in range(m + 1): + if s[i][t] < -TOL: + violated_constraints.add(4) + lhs_val = 0.0 + rhs_val = s[i][t] + violation_amount = -s[i][t] + violations.append( + f"Constraint 4: Nonnegativity violated: s[{i}][{t}] = {s[i][t]:.6f} < 0" + ) + normalizer = max(abs(rhs_val), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": rhs_val, + "rhs": lhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # s_{i,m+1} = 0 (ending inventory) + for i in range(n): + violation_amount = abs(s[i][m]) + if violation_amount > TOL: + violated_constraints.add(4) + lhs_val = s[i][m] + rhs_val = 0.0 + violations.append( + f"Constraint 4: Ending inventory violated: s[{i}][{m}] = {s[i][m]:.6f} != 0" + ) + normalizer = max(abs(rhs_val), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # y_{it} in {0, 1} + for i in range(n): + for t in range(m): + val = y[i][t] + dist_to_binary = min(abs(val - 0), abs(val - 1)) + if dist_to_binary > TOL: + violated_constraints.add(4) + # Treat as equality to nearest binary: violation = distance + nearest = round(val) + lhs_val = val + rhs_val = float(nearest) + violation_amount = dist_to_binary + violations.append( + f"Constraint 4: Integrality violated: y[{i}][{t}] = {val:.6f} not in {{0, 1}}" + ) + normalizer = max(abs(rhs_val), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 5: Objective consistency (Tier C obj-recompute) --- + # The reported objective_value must agree with the objective recomputed + # directly from the solution variables: + # obj = sum_{i,t} sc_{it}*y_{it} + vc_{it}*x_{it} + hc_{it}*s_{it} + # All objective-determining variables (x, s, y) are present in the + # solution, so this is an exact full recompute (no lower bound needed). + # Holding cost sums s_{it} over t in T (periods 0..m-1); the boundary + # entry s_{i,m} is excluded, consistent with the paper's Eq. (1) and + # the Gurobi reference implementation (gurobi_code.py). + sc = instance.get("setup_costs") + vc = instance.get("variable_costs") + hc = instance.get("holding_costs") + reported_obj = solution.get("objective_value") + if sc is not None and vc is not None and hc is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + try: + true_obj = float(sum( + sc[i][t] * y[i][t] + vc[i][t] * x[i][t] + hc[i][t] * s[i][t] + for i in range(n) for t in range(m) + )) + except (IndexError, TypeError): + true_obj = None + if true_obj is not None: + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(5) + violations.append( + f"Constraint 5: Objective consistency violated: reported " + f"objective_value = {reported} differs from recomputed " + f"sum_(i,t)[sc*y + vc*x + hc*s] = {true_obj} " + f"(|diff| = {abs_diff:.6g}, tol = {tol:.6g})" + ) + normalizer = max(abs(true_obj), EPS) + violation_magnitudes.append({ + "constraint": 5, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer + }) + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for CLST (Fragkos et al. 2016)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility result written to {args.result_path}") + print(f" Feasible: {result['feasible']}") + if not result["feasible"]: + print(f" Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/fragkos2016/gurobi_code.py b/tasks/fragkos2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..279a488c9e85df30bee29d00992530450c642779 --- /dev/null +++ b/tasks/fragkos2016/gurobi_code.py @@ -0,0 +1,186 @@ +""" +Gurobi implementation of the Capacitated Lot-Sizing Problem with Setup Times (CLST). +Reference: Fragkos, Degraeve, and De Reyck (2016), + "A Horizon Decomposition Approach for the Capacitated Lot-Sizing Problem with Setup Times", + INFORMS Journal on Computing 28(3): 465-482. + +Mathematical model: Section 3.1, pp. 467 (equations 1-5). +""" + +import argparse +import json +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(path): + with open(path) as f: + data = json.load(f) + return data + + +def solve_clst(data, time_limit): + n = data["n_items"] # number of items + m = data["n_periods"] # number of periods + + # Parameters (0-indexed internally) + cap = data["capacity"] # cap[t], t in 0..m-1 + d = data["demands"] # d[i][t] + sc = data["setup_costs"] # sc[i][t] + vc = data["variable_costs"] # vc[i][t] + hc = data["holding_costs"] # hc[i][t] + st = data["setup_times"] # st[i][t] + vt = data["variable_times"] # vt[i][t] + big_M = data["big_M"] # big_M[i][t] + init_inv = data["initial_inventory"] # s_{i,1} for each item i + + # Compute sd_{itk} = sum_{j=t}^{k} d[i][j] (0-indexed) + # sd[i][t] = sum from period t to m-1 + sd_to_end = [[0.0] * m for _ in range(n)] + for i in range(n): + cumsum = 0.0 + for t in range(m - 1, -1, -1): + cumsum += d[i][t] + sd_to_end[i][t] = cumsum + + model = gp.Model("CLST") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i][t]: production quantity, i in 0..n-1, t in 0..m-1 + x = [[model.addVar(lb=0.0, name=f"x_{i}_{t}") for t in range(m)] for i in range(n)] + # s[i][t]: inventory at beginning of period t, t in 0..m (index m = s_{i,m+1}) + s = [[model.addVar(lb=0.0, name=f"s_{i}_{t}") for t in range(m + 1)] for i in range(n)] + # y[i][t]: binary setup variable + y = [[model.addVar(vtype=GRB.BINARY, name=f"y_{i}_{t}") for t in range(m)] for i in range(n)] + + # Objective (1): minimize setup + production + holding costs + # NOTE: hc_{it} in the paper is the cost of holding inventory from period t-1 to t, + # indexed over periods t in T. The inventory variable s_{it} is the inventory at the + # beginning of period t. The paper sums hc_{it} * s_{it} for t in T (1..m). + # In 0-indexed terms, s[i][t] for t in 0..m-1, multiplied by hc[i][t]. + obj = gp.quicksum( + sc[i][t] * y[i][t] + vc[i][t] * x[i][t] + hc[i][t] * s[i][t] + for i in range(n) for t in range(m) + ) + model.setObjective(obj, GRB.MINIMIZE) + + # Constraint (2): flow balance + # s_{it} + x_{it} = d_{it} + s_{i,t+1} for all i, t in T + for i in range(n): + for t in range(m): + model.addConstr( + s[i][t] + x[i][t] == d[i][t] + s[i][t + 1], + name=f"flow_{i}_{t}" + ) + + # Constraint (3): production-setup link + # x_{it} <= M_{it} * y_{it} + for i in range(n): + for t in range(m): + model.addConstr( + x[i][t] <= big_M[i][t] * y[i][t], + name=f"setup_link_{i}_{t}" + ) + + # Constraint (4): capacity per period + # sum_i st_{it}*y_{it} + sum_i vt_{it}*x_{it} <= cap_t + for t in range(m): + model.addConstr( + gp.quicksum(st[i][t] * y[i][t] + vt[i][t] * x[i][t] for i in range(n)) <= cap[t], + name=f"capacity_{t}" + ) + + # Constraint (5): boundary conditions + # s_{i,m+1} = 0 (ending inventory is zero) + for i in range(n): + model.addConstr(s[i][m] == 0.0, name=f"end_inv_{i}") + + # Initial inventory: s[i][0] represents s_{i,1} (inventory at the start). + # The math model (constraints 1-5) only requires s_{it} >= 0 (nonnegativity) + # and s_{i,m+1} = 0 (ending inventory). There is no equality constraint + # fixing initial inventory to zero. Section 3.1 (p. 467) notes that + # initial inventory is allowed at a high cost (Vanderbeck 1998). + # We set a lower bound so that s[i][0] >= init_inv[i] (the provided + # starting stock), letting the solver acquire additional initial inventory + # if needed. The holding-cost term hc[i][0]*s[i][0] already in the + # objective penalises any excess. + for i in range(n): + s[i][0].lb = init_inv[i] + + model.optimize() + + # Extract solution + status = model.Status + result = {} + + if model.SolCount > 0: + obj_val = model.ObjVal + x_sol = [[x[i][t].X for t in range(m)] for i in range(n)] + s_sol = [[s[i][t].X for t in range(m + 1)] for i in range(n)] + y_sol = [[round(y[i][t].X) for t in range(m)] for i in range(n)] + + result = { + "objective_value": obj_val, + "status": model.Status, + "x": x_sol, + "s": s_sol, + "y": y_sol, + } + else: + # No feasible solution found within time limit + result = { + "objective_value": None, + "status": model.Status, + "x": None, + "s": None, + "y": None, + } + + return result + + +def main(): + parser = argparse.ArgumentParser(description="Gurobi solver for CLST (Fragkos et al. 2016)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the solution JSON file.") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + result = solve_clst(data, args.time_limit) + + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + else: + print("No feasible solution found within time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2016/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/fragkos2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2016/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2016/gurobi_solution/large_solution_1.json b/tasks/fragkos2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4e79564f1eeda9f0144505cc2d7e87e355e6bf5b --- /dev/null +++ b/tasks/fragkos2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9869454e45754b647da1f7ef5e24dc245120fe5250dabc886f36d7a588ce7cca +size 40196 diff --git a/tasks/fragkos2016/gurobi_solution/large_solution_2.json b/tasks/fragkos2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..9697b114193ad3f6ad9c84b14c53419991914df8 --- /dev/null +++ b/tasks/fragkos2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a3fbd880234251283b5dcdf1f08a81465420fc176df8f2edb97dc5d065dbf4c +size 39836 diff --git a/tasks/fragkos2016/gurobi_solution/large_solution_3.json b/tasks/fragkos2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..400e27f4265da549d8c9a76e8bd0c2f25902b41e --- /dev/null +++ b/tasks/fragkos2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85deb6bd42cc0915fb3a9471b00ee44d890bf84c7a1df5a8ba6951188b1f84ad +size 41018 diff --git a/tasks/fragkos2016/gurobi_solution/large_solution_4.json b/tasks/fragkos2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f444d066d7b2ac441fd40012aff7a54eb1134ff9 --- /dev/null +++ b/tasks/fragkos2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f15bffdb192a48a0f730b9282977f1fb2def22dacd80df9e65afa7363ff69cc +size 40878 diff --git a/tasks/fragkos2016/gurobi_solution/large_solution_5.json b/tasks/fragkos2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d32d01c0cafdcd910341c6cf00badf45f3282ba1 --- /dev/null +++ b/tasks/fragkos2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:502e4bb668f5ca2e07bac50c3b128b34955ef4b8046e8d5a8ffa6ae09f7aad19 +size 40755 diff --git a/tasks/fragkos2016/gurobi_solution/tiny_solution.json b/tasks/fragkos2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..60984a4ed3797cfe46f64db47272a792828f4e0d --- /dev/null +++ b/tasks/fragkos2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2bb67b14bb97c5bd9cfb1127bd6cce91d35c56e8c197b1355824f29b5ed2b796 +size 1539 diff --git a/tasks/fragkos2016/gurobi_solution_log/tiny_log.jsonl b/tasks/fragkos2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7339a533cfb3fc881c67bdbdcf76ee4944c397f0 --- /dev/null +++ b/tasks/fragkos2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a34ebae05fffde937ff4f059e2f2cc34c1f84338639a6f582bdfb0818d9e006a +size 55 diff --git a/tasks/fragkos2016/instance/large_instance_1.json b/tasks/fragkos2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a8f6e235bc570590bfa25453b3d920c76b081507 --- /dev/null +++ b/tasks/fragkos2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f683266f4c604cf3c78c8de37dc687f1f832dfbf31e000986c017bf469660d2 +size 94183 diff --git a/tasks/fragkos2016/instance/large_instance_2.json b/tasks/fragkos2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..be71aa5ecc23f954af022372f22350c6b9878cf5 --- /dev/null +++ b/tasks/fragkos2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9b036fb43807c58e3f8146357c37579417a20d716990b3689b2c589ae8a8d8d +size 94546 diff --git a/tasks/fragkos2016/instance/large_instance_3.json b/tasks/fragkos2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e4f2caeba3b3e495707b8799b3a641b0dfcd5173 --- /dev/null +++ b/tasks/fragkos2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ea2397cc21094b9c768be902ae1fd63ef8feb0e3b78b4d54090f88698dcc316 +size 94519 diff --git a/tasks/fragkos2016/instance/large_instance_4.json b/tasks/fragkos2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..af4f0591094d6f55977256d14c38744127691ef2 --- /dev/null +++ b/tasks/fragkos2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6add59f702593796794cd4b9f68ae277023b0c86eb6c11660b1fc6ad633ed41 +size 94036 diff --git a/tasks/fragkos2016/instance/large_instance_5.json b/tasks/fragkos2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5bfa8eeae99a095eada844b53529671791a770c7 --- /dev/null +++ b/tasks/fragkos2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e281ab0ed99420c674dddb90d8a6450dbf9bd6f07c5ee304d5aeccb42582309 +size 94468 diff --git a/tasks/fragkos2016/instance/tiny_instance.json b/tasks/fragkos2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..02fe39176560aa37e4f99d747f03c53150f8f179 --- /dev/null +++ b/tasks/fragkos2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14c5c56564db4da200c1e9d9542e1838b122d1ff6505ef66fffa145783ef1d6f +size 3555 diff --git a/tasks/fragkos2016/instance_schema.json b/tasks/fragkos2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c19ff3953afb29754f5582a667eb53a2e6834318 --- /dev/null +++ b/tasks/fragkos2016/instance_schema.json @@ -0,0 +1,13 @@ +{ + "n_items": " Number of distinct items to be produced.", + "n_periods": " Number of discrete time periods in the planning horizon.", + "capacity": " Total available production and setup time in each period.", + "initial_inventory": " Stock on hand for each item at the start of the first period.", + "demands": " Quantity of each item that must be fulfilled in each period.", + "setup_costs": " Fixed cost incurred when the production line is set up for each item in each period.", + "holding_costs": " Per-unit cost of carrying inventory of each item from one period to the next.", + "variable_costs": " Per-unit production cost for each item in each period.", + "setup_times": " Time consumed to set up the production line for each item in each period.", + "variable_times": " Time required to produce one unit of each item in each period.", + "big_M": " Maximum production quantity for each item in each period, given capacity and remaining demand." +} diff --git a/tasks/fragkos2016/mathematical_formulation.md b/tasks/fragkos2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..b09f7d899a263fad9d550e8dbe450c1fecadf7c1 --- /dev/null +++ b/tasks/fragkos2016/mathematical_formulation.md @@ -0,0 +1,47 @@ +# Original Formulation: Capacitated Lot-Sizing Problem with Setup Times (CLST) + +*Source: A Horizon Decomposition Approach for the Capacitated Lot-Sizing Problem with Setup Times, Ioannis Fragkos, Zeger Degraeve, Bert De Reyck, 2016 (INFORMS Journal on Computing 28(3): 465–482). Section 3.1, p. 467.* + +## Sets and Indices + +$$\begin{align*} +&I = \{1, \dots, n\}: && \text{set of items, indexed by } i.\\ +&T = \{1, \dots, m\}: && \text{set of periods, indexed by } t. +\end{align*}$$ + +## Parameters + +$$\begin{align*} +&d_{it}: && \text{demand of item } i \text{ in period } t, \quad i \in I,\ t \in T.\\ +&sd_{itk}: && \text{sum of demand of item } i \text{ from period } t \text{ to period } k, \quad i \in I,\ t \in T,\ k \in T:\ t \le k.\\ +&hc_{it}: && \text{cost of holding inventory for item } i \text{ from period } t-1 \text{ to period } t, \quad i \in I,\ t \in T.\\ +&sc_{it}: && \text{setup cost of item } i \text{ in period } t, \quad i \in I,\ t \in T.\\ +&vc_{it}: && \text{production cost of item } i \text{ in period } t, \quad i \in I,\ t \in T.\\ +&st_{it}: && \text{setup time of item } i \text{ in period } t, \quad i \in I,\ t \in T.\\ +&vt_{it}: && \text{variable production time of item } i \text{ in period } t, \quad i \in I,\ t \in T.\\ +&cap_{t}: && \text{time capacity in period } t, \quad t \in T.\\ +&M_{it}: && \text{big-M quantity, defined as } M_{it} = \min\{\, sd_{itm},\ (cap_t - st_{it})/(vt_{it}) \,\}, \quad i \in I,\ t \in T. +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +&x_{it}: && \text{production quantity of item } i \text{ in period } t, \quad i \in I,\ t \in T.\\ +&s_{it}: && \text{inventory quantity of item } i \text{ at the beginning of period } t, \quad i \in I,\ t \in T \cup \{m+1\}.\\ +&y_{it}: && \text{equals } 1 \text{ if a setup occurs for item } i \text{ in period } t,\ 0 \text{ otherwise}, \quad i \in I,\ t \in T. +\end{align*}$$ + +## Objective + +$$\begin{equation} +\min \quad \left\{ \sum_{i \in I} \sum_{t \in T} sc_{it}\, y_{it} \;+\; \sum_{i \in I} \sum_{t \in T} vc_{it}\, x_{it} \;+\; \sum_{i \in I} \sum_{t \in T} hc_{it}\, s_{it} \right\} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +& s_{it} + x_{it} = d_{it} + s_{i,t+1} && \forall i \in I,\ \forall t \in T \tag{2}\\[4pt] +& x_{it} \le M_{it}\, y_{it} && \forall i \in I,\ \forall t \in T \tag{3}\\[4pt] +& \sum_{i \in I} st_{it}\, y_{it} + \sum_{i \in I} vt_{it}\, x_{it} \le cap_t && \forall t \in T \tag{4}\\[4pt] +& x_{it},\, s_{it} \ge 0,\quad s_{i,m+1} = 0,\quad y_{it} \in \{0,1\} && \forall i \in I,\ \forall t \in T \tag{5} +\end{align}$$ diff --git a/tasks/fragkos2016/problem_description.txt b/tasks/fragkos2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..67d80168687252164f8c04c3aeb185e430735ac2 --- /dev/null +++ b/tasks/fragkos2016/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A manufacturing facility produces multiple items over a finite planning horizon divided into discrete time periods. The input data specifies the number of items and the number of periods. For each item in each period, the data provides the demand that must be satisfied, the cost incurred for setting up production of that item, the per-unit production cost, the per-unit cost of holding inventory from one period to the next, the time required to set up the production line for that item, and the per-unit production time. Each period has a given total time capacity that limits the combined production and setup activity across all items. An initial inventory level is given for each item at the start of the first period. + +The planner must determine, for each item in each period, the quantity to produce and whether to set up the production line for that item. These decisions implicitly determine the inventory carried from each period to the next. The inventory of each item at the beginning of a period, plus the quantity produced in that period, must equal the demand for that item in that period plus the inventory carried into the next period. Production of an item in a period can only occur if the production line is set up for that item in that period. In each period, the total time consumed by all setups and all production across every item must not exceed the period's time capacity. All production quantities and inventory levels must be non-negative. All inventory must be fully depleted by the end of the planning horizon, meaning no inventory remains after the final period. + +The goal is to minimize the total cost, which is the sum of three components: the total setup costs summed over all items and periods where a setup occurs, the total production costs computed as the per-unit production cost times the quantity produced for each item in each period, and the total inventory holding costs computed as the per-unit holding cost times the inventory level for each item in each period. diff --git a/tasks/fragkos2016/solution_logger.py b/tasks/fragkos2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/fragkos2016/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/fragkos2016/solution_schema.json b/tasks/fragkos2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..bd2ee4eb96c04d1224fc263e924c0ab8db5f1cb3 --- /dev/null +++ b/tasks/fragkos2016/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Total cost comprising setup, production, and inventory holding costs across all items and periods.", + "x": " Quantity produced of each item in each period.", + "s": " Inventory of each item at the beginning of each period, plus a final entry representing inventory after the last period.", + "y": " Whether the production line is set up for each item in each period (1 = yes, 0 = no)." +} diff --git a/tasks/fragkos2021/feasibility_check.py b/tasks/fragkos2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d78be372c4a4d3e95e9e7979961f63f10dfae045 --- /dev/null +++ b/tasks/fragkos2021/feasibility_check.py @@ -0,0 +1,498 @@ +""" +Feasibility checker for the Stochastic Reliable Uncapacitated Facility Location +Problem (RUFLP) from Li, Li, Shu, Song, Zhang (2021). + +Checks hard constraints from the mathematical formulation (math_model.txt), +numbered strictly top to bottom: + + Constraint 1: Ambiguity set probability interval (Eq 1) + sum_{matching xi} p_xi in [q_k^-, q_k^+] for all k + Constraint 2: Ambiguity set normalization (Eq 1) + sum_{xi} p_xi = 1 + Constraint 3: Binary domain (Decision Variables section) + x_j in {0,1} for all j in J + Constraint 4: Epigraph constraint (Eq 4) + eta >= E_p[Q(x, xi)] for all p in P + Constraint 5: RP cut constraint + (implied by C4; algorithmic — not separately checked) + Constraint 6: Valid cut (Eq 5) + (implied by C4; algorithmic — not separately checked) + Constraint 7: Separation normalization (Eq 6, sum p_xi = 1) + Internal to separation sub-problem — not checkable from solution + Constraint 8: Separation upper bound (Eq 6, <= q_k^+) + Internal to separation sub-problem — not checkable from solution + Constraint 9: Separation lower bound (Eq 6, >= q_k^-) + Internal to separation sub-problem — not checkable from solution + Constraint 10: Dual feasibility (Eq 7, alpha + sum >= Q) + Internal to dual sub-problem — not checkable from solution + Constraint 11: Dual non-negativity overline_beta (Eq 7) + Internal to dual sub-problem — not checkable from solution + Constraint 12: Dual non-negativity underline_beta (Eq 7) + Internal to dual sub-problem — not checkable from solution + Constraint 13: Pricing pi bound (Eq 9) + Internal to pricing sub-problem — not checkable from solution + Constraint 14: Pricing lambda <= xi_j (Eq 9) + Internal to pricing sub-problem — not checkable from solution + Constraint 15: Pricing lambda <= 1 - xi_j (Eq 9) + Internal to pricing sub-problem — not checkable from solution + Constraint 16: Pricing lambda >= sum expression (Eq 9) + Internal to pricing sub-problem — not checkable from solution + Constraint 17: Pricing lambda >= 0 (Eq 9) + Internal to pricing sub-problem — not checkable from solution + Constraint 18: Pricing xi binary (Eq 9) + Internal to pricing sub-problem — not checkable from solution + Constraint 19: Objective-value consistency (Tier C objective recompute) + objective_value == sum_j f_j x_j + E_{p^dagger}[Q(x, xi)] + The reported objective_value must equal the true objective of + the reported facility-location vector x. For the stochastic + case P is a singleton and x is the only obj-determining + variable, so this is an EXACT full recompute. Constraint 4 + only rejects an objective reported too LOW (eta < E[Q]); + constraint 19 additionally rejects an objective reported too + HIGH and tightens the check to a two-sided equality, defeating + fabricated objective_value exploits. + +Constraints 1-2 define the ambiguity set P (a property of the problem, not the +solution). For the stochastic case, P is a singleton — automatically satisfied. + +Constraints 5-18 involve variables internal to the cutting plane, separation, +dual, or pricing sub-problems (p, alpha, beta, pi, lambda, xi). These variables +are not part of the candidate solution and cannot be checked. + +Checkable hard constraints on the candidate solution (x, objective_value): + - Constraint 3: x_j in {0,1} for all j + - Constraint 4: eta >= E[Q(x, xi)] (where eta = objective_value - setup_cost) + - Constraint 19: objective_value == setup_cost + E[Q(x, xi)] (full recompute) +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('facility_locations', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +# ----------------------------------------------------------------------- +# Algorithm 1 (from paper): Evaluate E_{p^dagger}[Q(x, xi)] +# for independent facility disruptions. O(|I||J| log |J|) +# ----------------------------------------------------------------------- +def compute_expected_cost(x_vals, q, c, penalty, demands, n_fac, n_cus): + """ + Compute E_{p^dagger}[Q(x, xi)] using Algorithm 1 from the paper. + + For independent disruptions, the expected transportation cost for customer i + is computed by sorting open facilities by cost and accumulating: + cost_i = sum_t gamma * q_{j_t} * d_i * c_{i,j_t} + where gamma = Prob(all cheaper facilities disrupted). + + Dummy facility 0 (always available at penalty cost) is appended last. + """ + DUMMY = n_fac + open_facs = [j for j in range(n_fac) if x_vals[j] > 0.5] + + total = 0.0 + for i in range(n_cus): + # Sort open facilities by transportation cost ascending; dummy last + L_i = sorted(open_facs, key=lambda j: c[i][j]) + [DUMMY] + + gamma = 1.0 # Prob(all previous facilities disrupted) + for j_t in L_i: + if j_t == DUMMY: + q_t = 1.0 # dummy always online + c_t = penalty[i] + else: + q_t = q[j_t] # survival probability + c_t = c[i][j_t] + + total += gamma * q_t * demands[i] * c_t + gamma *= (1.0 - q_t) + + return total + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Stochastic RUFLP (Li et al. 2021)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON problem instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON candidate solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path for the output JSON feasibility result") + args = parser.parse_args() + + # ------------------------------------------------------------------ + # Load instance + # ------------------------------------------------------------------ + with open(args.instance_path, "r") as f: + instance = json.load(f) + + n_fac = instance["num_facilities"] + n_cus = instance["num_customers"] + nodes = instance["nodes"] + + demands = [nodes[i]["demand"] for i in range(n_cus)] + f_costs = [nodes[j]["fixed_setup_cost"] for j in range(n_fac)] + q = [nodes[j]["survival_probability"] for j in range(n_fac)] + c = instance["transportation_cost_matrix"] + penalty = instance["penalty_cost"] + + # ------------------------------------------------------------------ + # Load candidate solution + # ------------------------------------------------------------------ + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + x_vals = solution["facility_locations"] + obj_reported = solution["objective_value"] + + # ------------------------------------------------------------------ + # Tolerance parameters + # ------------------------------------------------------------------ + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ================================================================== + # Constraint 3: x_j in {0,1} for all j in J + # (Binary domain from Decision Variables section) + # ================================================================== + + # 3a: Check dimensionality — |x| must equal |J| + if len(x_vals) != n_fac: + violated_constraints.add(3) + lhs = float(len(x_vals)) + rhs = float(n_fac) + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Dimension mismatch: facility_locations has length {len(x_vals)}, " + f"expected {n_fac}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # 3b: Check each x_j is binary (0 or 1) + for j in range(min(len(x_vals), n_fac)): + val = x_vals[j] + # x_j should be 0 or 1; measure distance to nearest binary value + dist_to_binary = min(abs(val - 0.0), abs(val - 1.0)) + if dist_to_binary > tol: + violated_constraints.add(3) + lhs = float(val) + rhs = round(val) # nearest binary + violation_amount = dist_to_binary + normalizer = max(abs(rhs), eps) + violations.append( + f"Facility {j}: x_{j} = {val} is not binary " + f"(distance to nearest binary value = {dist_to_binary:.6e})" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": float(rhs), + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ================================================================== + # Constraint 4: eta >= E_p[Q(x, xi)] for all p in P + # (Epigraph constraint from Eq 4) + # + # For the stochastic case, P is a singleton, so this reduces to: + # eta >= E_{p^dagger}[Q(x, xi)] + # + # Since objective_value = sum_j f_j x_j + eta, we derive: + # eta = objective_value - setup_cost + # and check eta >= E[Q(x, xi)]. + # ================================================================== + if len(x_vals) == n_fac: + # Compute setup cost + setup_cost = sum( + f_costs[j] * (1.0 if x_vals[j] > 0.5 else 0.0) + for j in range(n_fac) + ) + + # Compute E[Q(x, xi)] via Algorithm 1 + expected_transport = compute_expected_cost( + x_vals, q, c, penalty, demands, n_fac, n_cus + ) + + # Derive eta from reported objective + eta = obj_reported - setup_cost + + # Check: eta >= E[Q(x, xi)] + # Equivalently: objective_value >= setup_cost + E[Q(x, xi)] + # LHS = eta, RHS = E[Q(x, xi)] + # For >= constraint: violation_amount = max(0, RHS - LHS) + lhs_val = eta + rhs_val = expected_transport + violation_amount = max(0.0, rhs_val - lhs_val) + + if violation_amount > tol: + violated_constraints.add(4) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Epigraph violated: eta = {eta:.6f} < E[Q(x, xi)] = " + f"{expected_transport:.6f} " + f"(objective_value = {obj_reported:.6f}, " + f"setup_cost = {setup_cost:.6f}, " + f"true_objective = {setup_cost + expected_transport:.6f})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ============================================================== + # Constraint 19: Objective-value consistency (Tier C obj recompute) + # + # objective_value must equal the true objective of the reported + # facility-location vector x: + # true_obj = sum_j f_j x_j + E_{p^dagger}[Q(x, xi)] + # = setup_cost + expected_transport + # + # For the stochastic RUFLP, P is a singleton and x (facility_locations) + # is the ONLY objective-determining variable in the solution, so this + # is an EXACT full recompute (all five Gurobi reference solutions + # recompute to abs_diff == 0). + # + # Constraint 4 above only rejects an objective reported too LOW + # (eta < E[Q]); constraint 19 additionally rejects an objective + # reported too HIGH and tightens the check to a two-sided equality, + # defeating fabricated objective_value exploits (obj = 0, + # obj = sys.float_info.max, obj = huge constant, ...). + # ============================================================== + true_obj = setup_cost + expected_transport + obj_diff = abs(float(obj_reported) - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + + if obj_diff > obj_tol: + violated_constraints.add(19) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Objective consistency violated: reported objective_value = " + f"{obj_reported} differs from recomputed " + f"setup_cost + E[Q(x, xi)] = {true_obj:.6f} " + f"(setup_cost = {setup_cost:.6f}, " + f"E[Q(x, xi)] = {expected_transport:.6f}, " + f"|diff| = {obj_diff:.6e}, tol = {obj_tol:.6e})" + ) + violation_magnitudes.append({ + "constraint": 19, + "lhs": float(obj_reported), + "rhs": float(true_obj), + "raw_excess": obj_diff, + "normalizer": normalizer, + "ratio": obj_diff / normalizer, + }) + + # ================================================================== + # Constraints 1-2: Ambiguity set constraints on probability + # distribution p. For stochastic RUFLP, P is a known singleton — + # these are part of the problem definition, not the solution. + # Not checkable from candidate solution. + # + # Constraints 5-6: RP cut and Valid Cut — algorithmic constraints + # implied by Constraint 4. Not separately checked. + # + # Constraints 7-18: Internal to separation, dual, and pricing + # sub-problems. Variables (p, alpha, beta, pi, lambda, xi) are + # not part of the candidate solution. Not checkable. + # ================================================================== + + # ------------------------------------------------------------------ + # Compile results + # ------------------------------------------------------------------ + feasible = len(violated_constraints) == 0 + sorted_violated = sorted(violated_constraints) + + result = { + "feasible": feasible, + "violated_constraints": sorted_violated, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + # Print summary + if feasible: + print("FEASIBLE: All checkable hard constraints satisfied.") + else: + print(f"INFEASIBLE: Violated constraints: {sorted_violated}") + for v in violations: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/fragkos2021/gurobi_code.py b/tasks/fragkos2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..713b5507071d9007ececc863532f184b4be0a6a3 --- /dev/null +++ b/tasks/fragkos2021/gurobi_code.py @@ -0,0 +1,387 @@ +""" +Gurobi implementation of the Stochastic Reliable Uncapacitated Facility Location +Problem (RUFLP) via the Cutting Plane Algorithm. + +Reference: + Li, Li, Shu, Song, Zhang (2021) "A General Model and Efficient Algorithms for + Reliable Facility Location Problem under Uncertain Disruptions." + INFORMS Journal on Computing 34(1):407-426. + +Model: + min_{x in {0,1}^|J|} sum_{j in J} f_j x_j + E_{p^dagger}[Q(x, tilde_xi)] + + where Q(x, xi) = sum_{i in I} d_i * min_{j in J union {0} | x_j * xi_j = 1} c_{ij} + + For the stochastic RUFLP (instance model_type = "stochastic_RUFLP"), P = {p^dagger} + is a singleton, so the max over P collapses to a single expectation. + +Algorithm: + Cutting Plane (CP) algorithm (Algorithm CP in paper, Section 4). + The relaxed master problem (RP) is a MILP solved by Gurobi using LazyConstraints + callbacks. For each integer solution found, the separation problem is evaluated via + Algorithm 1 (O(|I||J|log|J|)), and a valid Benders-type cut is added via Algorithm 2 + (O(|I||J|^2)) if needed. + + Termination: relative optimality gap <= 0.5% or time limit reached. +""" + +import argparse +import json +import os +import tempfile +import time +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +# --------------------------------------------------------------------------- +# Algorithm 1: Evaluate E_{p^dagger}[Q(x*, tilde_xi)] +# --------------------------------------------------------------------------- + +def algorithm1_eval(x_vals, q, c, penalty, demands, n_fac, n_cus): + """ + Algorithm 1 (Paper Section 4.1): Evaluate E_{p^dagger}[Q(x*, tilde_xi)] + for independent facility disruptions. + + For independent disruptions: + Prob(xi_{j_t}=0 | xi_{j_1}=0, ..., xi_{j_{t-1}}=0) = 1 - q_{j_t} (O(1)) + + Variable gamma = Prob(j_1, ..., j_{t-1} all disrupted). + + Lines 7-10 from Algorithm 1 (PDF p.16): + cost += gamma * (1 - Prob(xi_{j_t}=0 | all prev disrupted)) * d_i * c_{i,j_t} + = gamma * q_{j_t} * d_i * c_{i,j_t} [since q_{j_t} = survival prob] + gamma *= Prob(xi_{j_t}=0 | all prev disrupted) = (1 - q_{j_t}) + + Dummy facility (index = n_fac): always online (xi_0 = 1, so q_0 = 1, Prob(disrupt)=0). + Its cost is penalty[i] = c_{i0}. + + Complexity: O(|I||J| log |J|) + + Args: + x_vals : list[float], facility open/close decisions (> 0.5 treated as open) + q : list[float], q[j] = survival probability of facility j + c : list[list[float]], c[i][j] = unit shipment cost from j to i + penalty : list[float], penalty[i] = c_{i0} (penalty cost for customer i) + demands : list[float], demands[i] = d_i + n_fac : int, number of facilities |J| + n_cus : int, number of customers |I| + + Returns: + float: E_{p^dagger}[Q(x*, tilde_xi)] + """ + DUMMY = n_fac # dummy facility index (represents the penalty option) + open_facs = [j for j in range(n_fac) if x_vals[j] > 0.5] + + total = 0.0 + for i in range(n_cus): + # Step A (Lines 1-3): sort open facilities by c[i][j] ascending; dummy last + # (dummy always last because penalty[i] >= c[i][j] for all j by assumption) + L_i = sorted(open_facs, key=lambda j: c[i][j]) + [DUMMY] + + # Step B (Lines 4-11): accumulate expected cost for customer i + gamma = 1.0 # P(j_1,...,j_{t-1} all disrupted) + for j_t in L_i: + if j_t == DUMMY: + q_t = 1.0 # dummy never disrupted + c_t = penalty[i] + else: + q_t = q[j_t] # survival probability P(xi_{j_t}=1) + c_t = c[i][j_t] + + # Prob(j_t online | all prev disrupted) = q_t (by independence) + # Prob(j_t disrupted | all prev disrupted) = 1 - q_t + total += gamma * q_t * demands[i] * c_t + gamma *= (1.0 - q_t) # update joint disruption probability + + return total + + +# --------------------------------------------------------------------------- +# Algorithm 2: Formulate valid cut (Equation 5) for the stochastic case +# --------------------------------------------------------------------------- + +def algorithm2_cut(x_vals, q, c, penalty, demands, n_fac, n_cus): + """ + Algorithm 2 (Paper Section 4.1, PDF p.17): Formulate the valid cut (Eq. 5) + for given x* and p^dagger (stochastic independent disruptions). + + Cut: eta >= cost + sum_{j in J | x_j^*=0} (cost_j[j] - cost) * x_j + + where: + cost = E_{p^dagger}[Q(x^*, tilde_xi)] + cost_j[j] = E_{p^dagger}[Q(x^* v z_j, tilde_xi)] for closed facility j + + Note: cost_j[j] <= cost for all j (adding a facility cannot increase expected cost), + so (cost_j[j] - cost) <= 0. These are valid supporting hyperplane coefficients. + + Complexity: O(|I||J|^2) + """ + DUMMY = n_fac + open_facs = [j for j in range(n_fac) if x_vals[j] > 0.5] + closed_facs = [j for j in range(n_fac) if x_vals[j] <= 0.5] + + # Line 1: Step A — pre-compute sorted L_i for all customers + L_base = [] + for i in range(n_cus): + L_base.append(sorted(open_facs, key=lambda jj: c[i][jj]) + [DUMMY]) + + # Lines 3-6 (Step B of Alg 1): compute cost = E[Q(x*)] + cost = 0.0 + for i in range(n_cus): + gamma = 1.0 + for j_t in L_base[i]: + q_t = 1.0 if j_t == DUMMY else q[j_t] + c_t = penalty[i] if j_t == DUMMY else c[i][j_t] + cost += gamma * q_t * demands[i] * c_t + gamma *= (1.0 - q_t) + + # Lines 7-17 (Step C): for each closed facility j, compute cost_j = E[Q(x^* v z_j)] + cost_j = {} + for j in closed_facs: + val = 0.0 + for i in range(n_cus): + # Lines 10-15: insert j into L_base[i] at its sorted position (before dummy) + L_i = L_base[i] + pos = 0 + # Advance past facilities with c[i][*] <= c[i][j] (do not go past dummy) + while pos < len(L_i) - 1 and c[i][L_i[pos]] <= c[i][j]: + pos += 1 + L_new = L_i[:pos] + [j] + L_i[pos:] + + # Step C (Lines 11-14): same accumulation as Algorithm 1 Step B + gamma = 1.0 + for j_t in L_new: + q_t = 1.0 if j_t == DUMMY else q[j_t] + c_t = penalty[i] if j_t == DUMMY else c[i][j_t] + val += gamma * q_t * demands[i] * c_t + gamma *= (1.0 - q_t) + # Line 15: remove j from L_i (L_new is local; L_base[i] is unchanged) + + cost_j[j] = val + + return cost, cost_j + + +# --------------------------------------------------------------------------- +# Main solver +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi-based Cutting Plane solver for Stochastic RUFLP" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON problem instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds (default: 3600)") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # ------------------------------------------------------------------ + # Load problem instance + # ------------------------------------------------------------------ + with open(args.instance_path, "r") as f: + instance = json.load(f) + + n_fac = instance["num_facilities"] + n_cus = instance["num_customers"] + nodes = instance["nodes"] + + demands = [nodes[i]["demand"] for i in range(n_cus)] + f_costs = [nodes[j]["fixed_setup_cost"] for j in range(n_fac)] + # q[j] = survival probability = P(facility j is online) + q = [nodes[j]["survival_probability"] for j in range(n_fac)] + # c[i][j] = unit shipment cost from facility j to customer i + c = instance["transportation_cost_matrix"] + # penalty[i] = c_{i0}: unit penalty cost when customer i has no open facility + penalty = instance["penalty_cost"] + + start_time = time.time() + + # ------------------------------------------------------------------ + # Atomic JSON writer. Used both for the up-front stub and for the + # incremental flush on every new incumbent inside the callback, so that + # if the wrapper SIGTERMs the process, the on-disk file always reflects + # the latest captured incumbent (or the trivial stub if Gurobi found + # nothing yet) — never a half-written or stale-dimension file. + # ------------------------------------------------------------------ + def _atomic_write_solution(path, x_vec, ub, elapsed_s, cuts): + payload = { + "objective_value": ub, + "facility_locations": x_vec, + "instance_id": instance.get("instance_id", ""), + "total_time_seconds": round(elapsed_s, 4), + "cuts_added": cuts, + } + dirn = _os.path.dirname(_os.path.abspath(path)) or "." + fd, tmp = tempfile.mkstemp(prefix=_os.path.basename(path) + ".", + suffix=".tmp", dir=dirn) + try: + with _os.fdopen(fd, "w") as f: + payload["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(payload, f, indent=2) + _os.replace(tmp, path) + except Exception: + try: + _os.unlink(tmp) + except OSError: + pass + raise + + # ------------------------------------------------------------------ + # Preemptive trivial-fallback solution (open no facilities, pay all penalties). + # Writes a correctly-sized stub up front so that if the solver is killed by + # SIGTERM at the wall-time limit, a valid-dimension solution is still on disk. + # The callback overwrites this with real incumbents as they are found. + # ------------------------------------------------------------------ + trivial_x = [0] * n_fac + trivial_obj = sum(demands[i] * penalty[i] for i in range(n_cus)) + _atomic_write_solution(args.solution_path, trivial_x, trivial_obj, 0.0, 0) + + # ------------------------------------------------------------------ + # State shared between callback and main thread + # ------------------------------------------------------------------ + best = { + "ub": float("inf"), + "x": None, + "cuts": 0, + } + + # ------------------------------------------------------------------ + # Build Gurobi relaxed master problem (RP) + # ------------------------------------------------------------------ + model = gp.Model("RUFLP_Stochastic_Gurobi") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + model.setParam("LazyConstraints", 1) + model.setParam("OutputFlag", 0) + + # Binary facility-open decisions x_j + x = model.addVars(n_fac, vtype=GRB.BINARY, name="x") + + # eta >= 0: epigraph variable bounding worst-case expected cost. + # INFERRED ASSUMPTION: lb=0 is valid because E[Q(x,xi)] >= 0 for all x + # (all transportation costs are non-negative). The paper starts with an empty + # Lambda set (no cuts), which would leave eta unbounded; setting lb=0 provides + # the minimal valid tightening without adding explicit initial cuts. + eta = model.addVar(lb=0.0, name="eta") + + # Objective: min sum_j f_j x_j + eta (Equation 4) + model.setObjective( + gp.quicksum(f_costs[j] * x[j] for j in range(n_fac)) + eta, + GRB.MINIMIZE, + ) + + # ------------------------------------------------------------------ + # LazyConstraints callback — implements Steps 2 and 3 of Algorithm CP + # ------------------------------------------------------------------ + def separation_callback(model, where): + if where != GRB.Callback.MIPSOL: + return + + # Check elapsed time; terminate if over budget + if time.time() - start_time >= args.time_limit: + model.terminate() + return + + # Retrieve current integer-feasible RP solution + x_vals = [model.cbGetSolution(x[j]) for j in range(n_fac)] + eta_val = model.cbGetSolution(eta) + + # Step 2: Algorithm 1 — evaluate E_{p^dagger}[Q(x*, tilde_xi)] + e_cost = algorithm1_eval(x_vals, q, c, penalty, demands, n_fac, n_cus) + + # Track best upper bound: UB = setup cost + expected transportation cost + setup = sum(f_costs[j] * round(x_vals[j]) for j in range(n_fac)) + ub = setup + e_cost + if ub < best["ub"]: + best["ub"] = ub + best["x"] = [round(x_vals[j]) for j in range(n_fac)] + # Flush the new incumbent to disk atomically. If the wrapper + # SIGTERMs us before model.optimize() returns, this file is what + # the feasibility checker will read. + _atomic_write_solution( + args.solution_path, + best["x"], + best["ub"], + time.time() - start_time, + best["cuts"], + ) + + # Step 3: If eta underestimates E[Q], separation violated — add valid cut + if eta_val < e_cost - 1e-6: + # Algorithm 2: compute cut coefficients + cost, cost_j = algorithm2_cut(x_vals, q, c, penalty, demands, n_fac, n_cus) + + # Valid cut (Equation 5): + # eta >= cost + sum_{j: x_j^*=0} (cost_j[j] - cost) * x_j + # Coefficients (cost_j[j] - cost) <= 0: opening more facilities reduces cost. + rhs = cost + gp.quicksum( + (cost_j[j] - cost) * x[j] for j in cost_j + ) + model.cbLazy(eta >= rhs) + best["cuts"] += 1 + + # ------------------------------------------------------------------ + # Solve + # ------------------------------------------------------------------ + model.optimize(separation_callback) + + # ------------------------------------------------------------------ + # Extract best solution found + # ------------------------------------------------------------------ + # If no solution was captured in the callback, try reading final model solution + if best["x"] is None and model.SolCount > 0: + x_vals = [x[j].X for j in range(n_fac)] + e_cost = algorithm1_eval(x_vals, q, c, penalty, demands, n_fac, n_cus) + setup = sum(f_costs[j] * round(x_vals[j]) for j in range(n_fac)) + best["ub"] = setup + e_cost + best["x"] = [round(x_vals[j]) for j in range(n_fac)] + + # Fallback: trivial solution opens no facilities (all customers pay penalty). + # INFERRED ASSUMPTION: if Gurobi found no feasible solution, use x=0. + if best["x"] is None: + best["x"] = [0] * n_fac + best["ub"] = sum(demands[i] * penalty[i] for i in range(n_cus)) + + total_time = time.time() - start_time + + # ------------------------------------------------------------------ + # Final write: covers the case where Gurobi exited cleanly within the + # time limit, or pulled an incumbent from SolCount that the callback + # never saw. The callback already kept the on-disk file fresh during + # the solve, so this is a tail-end refresh, not the primary save. + # ------------------------------------------------------------------ + _atomic_write_solution( + args.solution_path, + best["x"], + best["ub"], + total_time, + best["cuts"], + ) + + print(f"Objective value : {best['ub']:.4f}") + print(f"Cuts added : {best['cuts']}") + print(f"Total time : {total_time:.2f}s") + print(f"Solution saved : {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2021/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/fragkos2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/fragkos2021/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/fragkos2021/gurobi_solution/large_solution_1.json b/tasks/fragkos2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5ea868c8f737c2fd34ce21df376ec87b7bdc4f75 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54bd91b44cfaac7f7c877447514f5a67b236344b8461bbfd60cba70dd61a9306 +size 70185 diff --git a/tasks/fragkos2021/gurobi_solution/large_solution_2.json b/tasks/fragkos2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e4115ff2a5ec558f2f297d9114971735b115ddab --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af1d2ace547abbec1e40948f8a676b22ba78eb1fc78f11f9a6a2ee433e98068e +size 70186 diff --git a/tasks/fragkos2021/gurobi_solution/large_solution_3.json b/tasks/fragkos2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..f8ec754de88f321395e9cb55bb9a600c1d2e98ff --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58833c261dbb95e4e19e3d798688fd5ffed6daa6edad8454a3c6657f45045a86 +size 70184 diff --git a/tasks/fragkos2021/gurobi_solution/large_solution_4.json b/tasks/fragkos2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..86b1789ec0765832da6026d801373d1422aa0477 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6b2b5db722b42c638387dceefaf37dc24531f42ca216379d9c1979fbfbf3b13 +size 70186 diff --git a/tasks/fragkos2021/gurobi_solution/large_solution_5.json b/tasks/fragkos2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7b5553d74073acf3e5b0aee9513202a51b7ba855 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac238ff5eaeaac0f6bb430c0f9238faa6564130a483770632204104256ca8ad8 +size 70186 diff --git a/tasks/fragkos2021/gurobi_solution/tiny_solution.json b/tasks/fragkos2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..8c58e624b7292a8df03f840fd259a077643d5e59 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c91e0cb5852a8722f5b1908288c1850d8de596991186ebcfe66f005359954f5d +size 315 diff --git a/tasks/fragkos2021/gurobi_solution_log/large_log_1.jsonl b/tasks/fragkos2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..766a84d7032391e7ab05218ebe0a22b02566e641 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb095f19517599ad8f5e11d8395007d5efecdc641c53fd7f4dc8ff61fbd96f29 +size 41 diff --git a/tasks/fragkos2021/gurobi_solution_log/large_log_2.jsonl b/tasks/fragkos2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c2c53de6190c04d8c984c0cd413de1a73d92a476 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cb9432e5061c3e33c4ebe0d2ad1f2edcab3fa18fe834386672e7791c65dd48c +size 41 diff --git a/tasks/fragkos2021/gurobi_solution_log/large_log_3.jsonl b/tasks/fragkos2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7b77863850938c304f277b1290cf360358a6acd4 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c99c2e1bff55e1ad8ef999352c42e254fa3fc99c0dcc504a87af4f82d8c3baa +size 41 diff --git a/tasks/fragkos2021/gurobi_solution_log/large_log_4.jsonl b/tasks/fragkos2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..686c725a15d9592de3f732ea02c01d6321259900 --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c18ff87ed479998f4e8f46860e93936e4601ef29d617dd12cc33b5df91c9d8a0 +size 41 diff --git a/tasks/fragkos2021/gurobi_solution_log/large_log_5.jsonl b/tasks/fragkos2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..95c5bd63cd7200573697531a121936ea8780a53e --- /dev/null +++ b/tasks/fragkos2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c89cdc391efc94b43369ff9952c45cefc2ced0ef07211a001994c1df9f416903 +size 41 diff --git a/tasks/fragkos2021/gurobi_solution_log/tiny_log.jsonl b/tasks/fragkos2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/fragkos2021/instance/large_instance_1.json b/tasks/fragkos2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8227733b813a022d16d1d88abab37deecc985b --- /dev/null +++ b/tasks/fragkos2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8c14eeef2055d4a708a7025f2a5f53b7614a59eab72f9e8b4cb1aa2595a9153 +size 1806654333 diff --git a/tasks/fragkos2021/instance/large_instance_2.json b/tasks/fragkos2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e59359ec747c1da4eadde6b6f771b3f12726e968 --- /dev/null +++ b/tasks/fragkos2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2e7b11573830786b0bde1699616cb7802130c1cb1ec5e0aa718688c60443ca1 +size 1806274977 diff --git a/tasks/fragkos2021/instance/large_instance_3.json b/tasks/fragkos2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e4595c4d1792d3e2601fc3d2802820539c836334 --- /dev/null +++ b/tasks/fragkos2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77a3a1b89a2b60f2b7f2ea718129f04134a9028631efba1469e29194decb046a +size 1806795186 diff --git a/tasks/fragkos2021/instance/large_instance_4.json b/tasks/fragkos2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9fe050607e736183a2864e17cd024b8c32808f88 --- /dev/null +++ b/tasks/fragkos2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d243ff2cf7290e4a764dd5244954eb2459fa9cf9f11eb38f9ebe0d85c16df4d +size 1806672720 diff --git a/tasks/fragkos2021/instance/large_instance_5.json b/tasks/fragkos2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..916652636adfadea3bd343a30b91615dfc5c5402 --- /dev/null +++ b/tasks/fragkos2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0462b2681f869ae09b9783714c926d4b2a14c41dae8bfe837c4b6def773d121d +size 1806349479 diff --git a/tasks/fragkos2021/instance/tiny_instance.json b/tasks/fragkos2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..35d150bae0a6c85cdc20be611711f3ff9965a242 --- /dev/null +++ b/tasks/fragkos2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abf06f6876f2a48f21da69f3aefb120565090912d1da528eac304c31b9b5bb80 +size 13630 diff --git a/tasks/fragkos2021/instance_schema.json b/tasks/fragkos2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ac45a1d939f7b73b5057b5f116aeff3c51685364 --- /dev/null +++ b/tasks/fragkos2021/instance_schema.json @@ -0,0 +1,16 @@ +{ + "num_nodes": " Total number of nodes, each serving as both a potential facility location and a customer.", + "num_facilities": " Number of potential facility locations that may be opened.", + "num_customers": " Number of customers whose demand must be served.", + "nodes": [ + { + "id": " Zero-based index identifying this node.", + "demand": " Quantity of goods this customer requires to be shipped.", + "fixed_setup_cost": " One-time cost incurred to open a facility at this location.", + "disruption_probability": " Probability that a facility at this location becomes unavailable due to a disruptive event.", + "survival_probability": " Probability that a facility at this location remains operational and available to serve customers." + } + ], + "transportation_cost_matrix": " Per-unit shipping cost from each facility to each customer.", + "penalty_cost": " Per-unit cost incurred when a customer cannot be served by any open and operational facility." +} diff --git a/tasks/fragkos2021/mathematical_formulation.md b/tasks/fragkos2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..b3bf52fef2f8e9c7c062448aaec894c1cacf5108 --- /dev/null +++ b/tasks/fragkos2021/mathematical_formulation.md @@ -0,0 +1,57 @@ +# Sets and Parameters + +- $J = \{1,\ldots,|J|\}$: set of potential facility locations; index $j$. + +- $I = \{1,\ldots,|I|\}$: set of customers; index $i$. + +- $d_i$: demand rate of customer $i \in I$. + +- $f_j$: fixed setup cost to open facility $j \in J$. + +- $c_{ij}$: unit shipment cost from facility $j \in J$ to customer $i \in I$. + +- $c_{i0}$: unit penalty cost if customer $i$ is not served ($c_{i0} \geq c_{ij}$ for all $i,j$). + +- $\tilde{\boldsymbol{\xi}} = (\tilde{\xi}_1,\ldots,\tilde{\xi}_{|J|})^\top$: random binary disruption vector with $\tilde{\xi}_j = 1$ if facility $j$ is online, $0$ if disrupted. + +- $\Xi := \{ (\xi_1,\ldots,\xi_{|J|})^\top \mid \xi_j \in \{0,1\},\; \forall j \in J \} = \{0,1\}^{|J|}$. + +- Dummy facility $0$: $x_0 \equiv 1$, $\xi_0 \equiv 1$. + +- For $k \in \{1,\ldots,n\}$: $A_k, B_k \subseteq J$ are the sets of online and offline facilities described by the $k$-th piece of information, associated with probability interval $[\underline{q}_k, \overline{q}_k]$. + +# Ambiguity Set (Equation (1)) + +For any realization $\boldsymbol{\xi} \in \Xi$, let $p_{\boldsymbol{\xi}} := \Pr(\tilde{\boldsymbol{\xi}} = \boldsymbol{\xi})$. The ambiguity set of admissible distributions $\boldsymbol{p} = (p_{\boldsymbol{\xi}})_{\boldsymbol{\xi} \in \Xi}$ is $$\begin{equation} +P := \left\{\, \boldsymbol{p} \in [0,1]^{2^{|J|}} \;\left|\; +\begin{aligned} +& \sum_{\substack{\boldsymbol{\xi} \in \Xi \,:\, \xi_j = 1 \;\forall j \in A_k, \\ \xi_j = 0 \;\forall j \in B_k}} p_{\boldsymbol{\xi}} \in [\underline{q}_k, \overline{q}_k] \quad \forall k \in \{1,\ldots,n\}, \\[2pt] +& \sum_{\boldsymbol{\xi} \in \Xi} p_{\boldsymbol{\xi}} = 1 +\end{aligned} +\right.\right\}. \tag{1} +\end{equation}$$ + +# Second-Stage Transportation and Penalty Cost + +Given a facility location decision $\boldsymbol{x}$ and a disruption realization $\boldsymbol{\xi}$, $$\begin{equation} +Q(\boldsymbol{x}, \boldsymbol{\xi}) := \sum_{i \in I} d_i \cdot \min_{j \in J \cup \{0\} \,:\, x_j \xi_j = 1} c_{ij}, +\end{equation}$$ with the convention $x_0 \equiv 1$ and $\xi_0 \equiv 1$ (the penalty cost $c_{i0}$ is incurred only when all open facilities are disrupted). + +# Decision Variables + +$$\begin{align*} +x_j &\in \{0,1\} && \forall\, j \in J \quad (\text{1 if facility $j$ is opened, 0 otherwise}) \\ +\boldsymbol{x} &= (x_1, x_2, \ldots, x_{|J|})^\top +\end{align*}$$ + +# Objective and Problem $\mathcal{P}$ (Equation (3)) + +The two-stage distributionally robust formulation minimizes the fixed setup cost plus the worst-case expected transportation and penalty cost over all distributions in the ambiguity set $P$: $$\begin{equation} +\mathcal{P}: \quad \min_{\boldsymbol{x} \in \{0,1\}^{|J|}} \left\{\, \sum_{j \in J} f_j\, x_j \;+\; \max_{\boldsymbol{p} \in P} \; \mathbb{E}_{\boldsymbol{p}}\!\left[\, Q(\boldsymbol{x}, \tilde{\boldsymbol{\xi}}) \,\right] \right\}. \tag{3} +\end{equation}$$ + +# Constraints + +$$\begin{align*} +x_j &\in \{0,1\} && \forall\, j \in J. +\end{align*}$$ (All additional structure is captured implicitly by the definition of $Q$ and by the ambiguity set $P$.) diff --git a/tasks/fragkos2021/problem_description.txt b/tasks/fragkos2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..343438d3657d7507347f8ee6c0f4bdd5557c6285 --- /dev/null +++ b/tasks/fragkos2021/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A company must decide which facilities to open from a set of potential locations in order to serve a set of customers, where each facility is subject to random disruption that may render it temporarily unavailable. The number of potential facility locations and the number of customers are both given. Each customer has a known demand rate. Each potential facility has a known fixed setup cost to open. There is no limit on the amount of demand any single facility can serve. For every facility-customer pair, a unit shipment cost is given, representing the cost per unit of demand to transport goods from that facility to that customer. For each customer, a unit penalty cost is also given, representing the per-unit cost incurred when that customer cannot be served by any open, non-disrupted facility; the penalty cost for each customer is at least as large as the shipment cost from any facility to that customer. + +Each facility, once opened, may fail due to disruptive events. The disruption status of all facilities is described by a joint probability distribution over all possible combinations of facility availability. In the stochastic setting, the full joint distribution over all disruption scenarios is exactly known, and the set of allowable distributions contains only that single distribution. In the more general distributionally robust setting, the exact joint distribution is not known but is constrained to lie within an ambiguity set defined by a collection of pieces of disruption information. Each piece of information specifies a subset of facilities required to be online and a subset required to be offline, together with a lower and upper bound on the probability that those conditions hold simultaneously. The true distribution must assign probabilities summing to one across all possible disruption scenarios and must satisfy every such probability interval constraint. + +Given a set of opened facilities and a realized disruption outcome, each customer is served by the available facility (one that is both opened and not disrupted) offering the lowest unit shipment cost for that customer. A dummy always-available penalty option exists so that if all of a customer's opened facilities are disrupted, the customer incurs the penalty cost instead. The total transportation and penalty cost under a specific disruption realization is therefore the sum over all customers of that customer's demand multiplied by the minimum unit cost among all opened and non-disrupted facilities serving that customer, including the penalty option. + +The company must choose which facilities to open before disruptions are realized. The goal is to minimize the sum of two cost components: the total fixed setup cost of all opened facilities, plus the worst-case expected transportation and penalty cost, where the worst case is taken over all disruption probability distributions consistent with the ambiguity set. In the stochastic special case where the distribution is exactly known, this worst-case expectation reduces to the ordinary expected transportation and penalty cost under the given distribution. diff --git a/tasks/fragkos2021/solution_logger.py b/tasks/fragkos2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/fragkos2021/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/fragkos2021/solution_schema.json b/tasks/fragkos2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5a5683570d96dc7fbfa8b8316f944fddf071499e --- /dev/null +++ b/tasks/fragkos2021/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total cost comprising fixed facility setup costs plus expected transportation and penalty costs across all disruption scenarios.", + "facility_locations": " Whether each potential facility is opened (1) or not (0)." +} diff --git a/tasks/freeman2018/feasibility_check.py b/tasks/freeman2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf08e4aee6bd980216870cdd13f3114cad63c46 --- /dev/null +++ b/tasks/freeman2018/feasibility_check.py @@ -0,0 +1,793 @@ +""" +Feasibility checker for the Attractive Orienteering Problem (AtOP). + +Paper: Freeman, Keskin, Çapar (2018) - "Attractive Orienteering Problem with + Proximity and Timing Interactions" + +Checks all hard constraints from the MINLP formulation (Part A) one by one. +Constraints are numbered 1-17 following the paper's formulation order: + 1 -> (2) Tour starts from dummy site 0 in period 1 + 2 -> (3) Exactly one site visit per period (t=2..T) + 3 -> (4) Flow conservation period 1->2 + 4 -> (5) Flow conservation periods 2..T-1 + 5 -> (6) Max travel distance per period <= L + 6 -> (7) Events only at destination in period 1 + 7 -> (8) Events only at destination in periods 2..T + 8 -> (9) Max events per site + 9 -> (10) Max consecutive events (delta) + 10 -> (11) Gravity model definition of P_ikt + 11 -> (12) Attendance <= sum of P_ikt * gamma_i + 12 -> (13) Attendance <= venue capacity + 13 -> (14) X binary + 14 -> (15) Y binary + 15 -> (16) P_ikt <= 1 + 16 -> (17) A_kt >= 0 + 17 -> (1) Objective consistency: reported objective_value must match the + total profit recomputed from the solution's own variables + (sum_k,t r_k A_kt - sum_k,t f_k Y_kt - c sum_j,k,t d^s_jk X_jkt). +""" + +import json +import argparse +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('attendance', 'event_sites', 'events', 'objective_value', 'tour') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('event_sites', 'objective_value') +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def precompute(data): + """Compute derived parameters from instance data.""" + params = data['parameters'] + T = data['num_periods'] + K = data['num_sites'] + I = data['num_customers'] + q = params['q'] + weekly_cycle = params['weekly_attraction_cycle'] + avg_bus_cust = params['avg_businesses_customers'] + avg_bus_sites = params['avg_businesses_sites'] + delta = params['delta'] + epsilon = params['epsilon'] + L_max = params['L'] + c = params['c'] + + sites = {s['id']: s for s in data['sites']} + customers = {cu['id']: cu for cu in data['customers']} + site_ids = list(range(1, K + 1)) + customer_ids = list(range(1, I + 1)) + + # Day-of-week attraction + t_tilde = {} + for t in range(1, T + 1): + t_tilde[t] = weekly_cycle[(t - 1) % 7] + + # Self-attraction s_{it} + s_it = {} + for i in customer_ids: + N_i = customers[i]['num_businesses'] + for t in range(1, T + 1): + s_it[i, t] = t_tilde[t] * N_i / avg_bus_cust + + # Site attraction a_{kt} + a_kt = {} + for k in site_ids: + N_k = sites[k]['num_businesses'] + for t in range(1, T + 1): + a_kt[k, t] = t_tilde[t] * N_k / avg_bus_sites + + # Customer-to-site distances + d_p = {} + for key, val in data['customer_to_site_distances'].items(): + parts = key.split('_') + ci, sk = int(parts[0]), int(parts[1]) + d_p[ci, sk] = val + + # Customer-to-site attraction alpha_{ikt} + alpha = {} + for i in customer_ids: + for k in site_ids: + dist = d_p[i, k] + dist_scaled = dist / 1000.0 + if dist_scaled < 1e-10: + dist_scaled = 1e-10 + denom = dist_scaled ** q + for t in range(1, T + 1): + alpha[i, k, t] = a_kt[k, t] / denom + + # Site-to-site distances (including dummy site 0) + d_s = {} + for key, val in data['site_to_site_distances'].items(): + parts = key.split('_') + j_id, k_id = int(parts[0]), int(parts[1]) + d_s[j_id, k_id] = val + + theta = {s['id']: s['capacity'] for s in data['sites']} + r = {s['id']: s['revenue_per_customer'] for s in data['sites']} + f_cost = {s['id']: s['fixed_cost'] for s in data['sites']} + m_max = {s['id']: s['max_events'] for s in data['sites']} + gamma = {cu['id']: cu['population'] for cu in data['customers']} + + return { + 'T': T, 'K': K, 'I': I, + 'delta': delta, 'epsilon': epsilon, 'L_max': L_max, 'c': c, 'q': q, + 'site_ids': site_ids, 'customer_ids': customer_ids, + 'sites': sites, 'customers': customers, + 't_tilde': t_tilde, 's_it': s_it, 'a_kt': a_kt, 'alpha': alpha, + 'd_s': d_s, 'd_p': d_p, + 'theta': theta, 'r': r, 'f_cost': f_cost, 'm_max': m_max, + 'gamma': gamma, + } + + +def parse_solution(sol, ctx): + """ + Parse solution into uniform internal representation. + + Returns: + tour: dict {t: site_id} for t=1..T + events: dict {t: 0 or 1} for t=1..T + attendance: dict {(k,t): value} or None if not provided + """ + T = ctx['T'] + + # Parse tour: {period_str: site_id} + tour = {} + for t_str, site in sol['tour'].items(): + tour[int(t_str)] = int(site) + + # Parse events: {period_str: 0/1} + events = {} + for t_str, val in sol['events'].items(): + events[int(t_str)] = int(val) + + # Parse attendance if available + attendance = None + if 'attendance' in sol: + attendance = {} + for key, val in sol['attendance'].items(): + parts = key.split('_') + k, t = int(parts[0]), int(parts[1]) + attendance[k, t] = float(val) + + return tour, events, attendance + + +def add_violation(violations_list, magnitudes_list, violated_set, + constraint_idx, message, lhs, rhs, violation_amount, tol, eps, + relative_tol=5e-2): + """Record a constraint violation if it exceeds tolerance. + + Effective tolerance combines: + - absolute tol (1e-5) — fundamental solver noise floor; + - 1% relative slack vs max(|lhs|, |rhs|, 1.0) — catches numerical + dust from barrier solver / presolve where a near-zero RHS is + coupled with a residual LHS like 0.01 (eq.12 attendance on + sites with no event). Real constraint violations of order 1%+ + of the natural scale still get flagged. + """ + # Most model constraints retain the historical 5% scale-aware allowance + # for nonlinear residuals. Callers that already computed a semantically + # meaningful tolerance (notably the exactly recomputed objective below) + # can set ``relative_tol=0`` so this helper does not silently widen it. + eff_tol = max(tol, relative_tol * max(abs(lhs), abs(rhs), 1.0)) + if violation_amount > eff_tol: + violated_set.add(constraint_idx) + violations_list.append(message) + normalizer = max(abs(rhs), eps) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + +def check_feasibility(data, sol): + tol = 1e-5 + eps = 1e-5 + + ctx = precompute(data) + T = ctx['T'] + K = ctx['K'] + I = ctx['I'] + delta = ctx['delta'] + epsilon = ctx['epsilon'] + L_max = ctx['L_max'] + site_ids = ctx['site_ids'] + customer_ids = ctx['customer_ids'] + d_s = ctx['d_s'] + s_it = ctx['s_it'] + alpha = ctx['alpha'] + theta = ctx['theta'] + gamma = ctx['gamma'] + m_max = ctx['m_max'] + + tour, events, attendance_sol = parse_solution(sol, ctx) + + violations = [] + magnitudes = [] + violated_set = set() + + # ========================================================================= + # Reconstruct X_{jkt} from the tour + # ========================================================================= + # X[j,k,t] = 1 for the actual transitions in the tour + # Period 1: from dummy site 0 to tour[1] + # Period t (t>=2): from tour[t-1] to tour[t] + X = {} + if 1 in tour: + X[0, tour[1], 1] = 1 + for t in range(2, T + 1): + if t in tour and (t - 1) in tour: + X[tour[t - 1], tour[t], t] = 1 + + # Reconstruct Y_{kt} from events + Y = {} + for t in range(1, T + 1): + if events.get(t, 0) == 1: + k = tour.get(t) + if k is not None: + Y[k, t] = 1 + + # ========================================================================= + # Constraint 1 (paper eq. 2): sum_k X_{0,k,1} = 1 + # Tour starts from dummy site 0 in period 1 + # ========================================================================= + lhs = sum(X.get((0, k, 1), 0) for k in site_ids) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 1, f"Constraint 1 (eq.2): Tour start from dummy site 0: " + f"sum_k X_{{0,k,1}} = {lhs}, expected 1", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 2 (paper eq. 3): sum_j sum_k X_{j,k,t} = 1 for t=2..T + # Exactly one move per period + # ========================================================================= + for t in range(2, T + 1): + lhs = sum(X.get((j, k, t), 0) for j in site_ids for k in site_ids) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 2, f"Constraint 2 (eq.3): Period {t}: " + f"sum X_{{j,k,{t}}} = {lhs}, expected 1", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 3 (paper eq. 4): X_{0,k,1} = sum_j X_{k,j,2} for all k + # Flow conservation period 1->2 + # ========================================================================= + if T >= 2: + for k in site_ids: + lhs_val = X.get((0, k, 1), 0) + rhs_val = sum(X.get((k, j, 2), 0) for j in site_ids) + violation_amount = abs(lhs_val - rhs_val) + add_violation(violations, magnitudes, violated_set, + 3, f"Constraint 3 (eq.4): Flow conservation site {k} " + f"period 1->2: X_{{0,{k},1}}={lhs_val} != " + f"sum_j X_{{{k},j,2}}={rhs_val}", + lhs_val, rhs_val, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 4 (paper eq. 5): sum_j X_{j,k,t} = sum_j X_{k,j,t+1} + # Flow conservation for t=2..T-1 + # ========================================================================= + for t in range(2, T): + for k in site_ids: + lhs_val = sum(X.get((j, k, t), 0) for j in site_ids) + rhs_val = sum(X.get((k, j, t + 1), 0) for j in site_ids) + violation_amount = abs(lhs_val - rhs_val) + add_violation(violations, magnitudes, violated_set, + 4, f"Constraint 4 (eq.5): Flow conservation site {k} " + f"period {t}->{t+1}: in={lhs_val} != out={rhs_val}", + lhs_val, rhs_val, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 5 (paper eq. 6): sum_j sum_k X_{j,k,t} * d^s_{j,k} <= L + # Maximum travel distance per period + # ========================================================================= + for t in range(1, T + 1): + if t == 1: + lhs = sum(X.get((0, k, 1), 0) * d_s.get((0, k), 0.0) + for k in site_ids) + else: + lhs = sum(X.get((j, k, t), 0) * d_s.get((j, k), 0.0) + for j in site_ids for k in site_ids) + rhs = L_max + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 5, f"Constraint 5 (eq.6): Travel distance period {t}: " + f"{lhs:.2f} > L={rhs}", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 6 (paper eq. 7): Y_{k,1} <= X_{0,k,1} for all k + # Events only at destination in period 1 + # ========================================================================= + for k in site_ids: + y_val = Y.get((k, 1), 0) + x_val = X.get((0, k, 1), 0) + lhs = y_val + rhs = x_val + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 6, f"Constraint 6 (eq.7): Event at site {k} period 1 " + f"but not visited: Y={y_val}, X={x_val}", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 7 (paper eq. 8): Y_{k,t} <= sum_j X_{j,k,t} for t=2..T + # Events only at destination in periods 2..T + # ========================================================================= + for k in site_ids: + for t in range(2, T + 1): + y_val = Y.get((k, t), 0) + x_sum = sum(X.get((j, k, t), 0) for j in site_ids) + lhs = y_val + rhs = x_sum + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 7, f"Constraint 7 (eq.8): Event at site {k} period {t} " + f"but not visited: Y={y_val}, sum_X={x_sum}", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 8 (paper eq. 9): sum_t Y_{k,t} <= m_k for all k + # Maximum number of events at each site + # ========================================================================= + for k in site_ids: + lhs = sum(Y.get((k, t), 0) for t in range(1, T + 1)) + rhs = m_max[k] + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 8, f"Constraint 8 (eq.9): Site {k} has {lhs} events, " + f"max allowed {rhs}", + float(lhs), float(rhs), violation_amount, tol, eps) + + # ========================================================================= + # Constraint 9 (paper eq. 10): + # sum_k sum_{t'=t}^{t+delta+1} Y_{k,t'} <= delta for t=1..T-delta-1 + # Maximum consecutive events + # ========================================================================= + for t in range(1, T - delta): + upper = min(t + delta + 1, T) + lhs = sum(Y.get((k, tp), 0) for k in site_ids + for tp in range(t, upper + 1)) + rhs = delta + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 9, f"Constraint 9 (eq.10): Window [{t},{upper}] has " + f"{lhs} events, max {rhs}", + float(lhs), float(rhs), violation_amount, tol, eps) + + # ========================================================================= + # Compute P_{ikt} and A_{kt} from the gravity model for constraint checks + # ========================================================================= + # P_{ikt} = alpha_{ikt} * Y_{kt} / (s_{it} + sum_{j,tau in window} alpha_{ij,tau} * Y_{j,tau}) + P = {} + for i in customer_ids: + for k in site_ids: + for t in range(1, T + 1): + if Y.get((k, t), 0) == 0: + P[i, k, t] = 0.0 + continue + # Compute denominator + denom = s_it[i, t] + tau_lo = max(t - epsilon, 1) + tau_hi = min(t + epsilon, T) + for tau in range(tau_lo, tau_hi + 1): + for j in site_ids: + if Y.get((j, tau), 0) == 1: + denom += alpha.get((i, j, tau), 0.0) + numer = alpha.get((i, k, t), 0.0) + if denom > 1e-15: + P[i, k, t] = numer / denom + else: + P[i, k, t] = 0.0 + + # Compute model-implied attendance + A_model = {} + for k in site_ids: + for t in range(1, T + 1): + raw_attend = sum(P.get((i, k, t), 0.0) * gamma[i] + for i in customer_ids) + A_model[k, t] = min(raw_attend, theta[k]) + + # Determine which attendance values to check: + # If solution provides attendance, use it; otherwise use model-computed values + A_check = {} + if attendance_sol is not None: + for k in site_ids: + for t in range(1, T + 1): + A_check[k, t] = attendance_sol.get((k, t), 0.0) + else: + A_check = A_model + + # ========================================================================= + # Constraint 10 (paper eq. 11): Gravity model P_{ikt} definition + # (s_{it} + sum alpha Y) * P_{ikt} = alpha_{ikt} * Y_{kt} + # ========================================================================= + for i in customer_ids: + for k in site_ids: + for t in range(1, T + 1): + # LHS: (s_{it} + sum_j sum_tau alpha_{ij,tau} Y_{j,tau}) * P_{ikt} + denom_val = s_it[i, t] + tau_lo = max(t - epsilon, 1) + tau_hi = min(t + epsilon, T) + for tau in range(tau_lo, tau_hi + 1): + for j in site_ids: + if Y.get((j, tau), 0) == 1: + denom_val += alpha.get((i, j, tau), 0.0) + lhs = denom_val * P.get((i, k, t), 0.0) + # RHS: alpha_{ikt} * Y_{kt} + rhs = alpha.get((i, k, t), 0.0) * Y.get((k, t), 0) + violation_amount = abs(lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 10, f"Constraint 10 (eq.11): Gravity model " + f"i={i},k={k},t={t}: LHS={lhs:.6f}, " + f"RHS={rhs:.6f}", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 11 (paper eq. 12): A_{kt} <= sum_i P_{ikt} * gamma_i + # ========================================================================= + for k in site_ids: + for t in range(1, T + 1): + lhs = A_check.get((k, t), 0.0) + rhs = sum(P.get((i, k, t), 0.0) * gamma[i] for i in customer_ids) + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 11, f"Constraint 11 (eq.12): Attendance site {k} " + f"period {t}: A={lhs:.2f} > sum P*gamma={rhs:.2f}", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 12 (paper eq. 13): A_{kt} <= theta_k + # Venue capacity + # ========================================================================= + for k in site_ids: + for t in range(1, T + 1): + lhs = A_check.get((k, t), 0.0) + rhs = float(theta[k]) + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 12, f"Constraint 12 (eq.13): Attendance site {k} " + f"period {t}: A={lhs:.2f} > capacity={rhs}", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 13 (paper eq. 14): X_{jkt} in {0,1} + # Binary domain for routing variables + # ========================================================================= + for key, val in X.items(): + if val not in (0, 1): + j, k, t = key + violation_amount = min(abs(val - 0), abs(val - 1)) + add_violation(violations, magnitudes, violated_set, + 13, f"Constraint 13 (eq.14): X_{{{j},{k},{t}}} = {val} " + f"not binary", + float(val), round(val), violation_amount, tol, eps) + + # ========================================================================= + # Constraint 14 (paper eq. 15): Y_{kt} in {0,1} + # Binary domain for event variables + # ========================================================================= + for key, val in Y.items(): + if val not in (0, 1): + k, t = key + violation_amount = min(abs(val - 0), abs(val - 1)) + add_violation(violations, magnitudes, violated_set, + 14, f"Constraint 14 (eq.15): Y_{{{k},{t}}} = {val} " + f"not binary", + float(val), round(val), violation_amount, tol, eps) + + # ========================================================================= + # Constraint 15 (paper eq. 16): P_{ikt} <= 1 + # ========================================================================= + for i in customer_ids: + for k in site_ids: + for t in range(1, T + 1): + lhs = P.get((i, k, t), 0.0) + rhs = 1.0 + violation_amount = max(0.0, lhs - rhs) + add_violation(violations, magnitudes, violated_set, + 15, f"Constraint 15 (eq.16): P_{{{i},{k},{t}}} = " + f"{lhs:.6f} > 1", + lhs, rhs, violation_amount, tol, eps) + + # ========================================================================= + # Constraint 16 (paper eq. 17): A_{kt} >= 0 + # ========================================================================= + for k in site_ids: + for t in range(1, T + 1): + val = A_check.get((k, t), 0.0) + lhs = 0.0 + rhs = val + violation_amount = max(0.0, lhs - rhs) # 0 - val if val < 0 + if violation_amount > tol: + add_violation(violations, magnitudes, violated_set, + 16, f"Constraint 16 (eq.17): A_{{{k},{t}}} = " + f"{val:.6f} < 0", + val, 0.0, abs(val), tol, eps) + + # ========================================================================= + # Constraint 17 (paper eq. 1, objective): Objective consistency + # The reported objective_value must equal the total profit recomputed from + # the solution's own decision variables: + # sum_{k,t} r_k * A_kt - sum_{k,t} f_k * Y_kt - c * sum_{j,k,t} d^s_jk X_jkt + # All obj-determining variables are present in the solution (tour -> X, + # events -> Y, attendance -> A; when attendance is omitted the model-implied + # A_model is used, exactly as for the constraint checks above via A_check), + # so this is a FULL recompute, not a lower bound. + # ========================================================================= + reported_obj = sol.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + r = ctx['r'] + f_cost = ctx['f_cost'] + c = ctx['c'] + # Revenue: sum_{k,t} r_k * A_kt (A_check = solution attendance, or + # model-implied attendance when the solution omits it). + revenue = sum(r[k] * A_check.get((k, t), 0.0) + for k in site_ids for t in range(1, T + 1)) + # Fixed event cost: sum_{k,t} f_k * Y_kt (Y holds only the 1s). + fixed_cost = sum(f_cost[k] * yv for (k, t), yv in Y.items()) + # Travel cost: c * sum_{j,k,t} d^s_jk * X_jkt (X holds only the 1s; + # period-1 transitions originate at dummy site 0 with d^s_0k = 0). + travel_cost = c * sum(xv * d_s.get((j, k), 0.0) + for (j, k, t), xv in X.items()) + true_obj = revenue - fixed_cost - travel_cost + # 0.1% relative tolerance with a 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if math.isfinite(reported): + abs_diff = abs(reported - true_obj) + lhs_record = reported + else: + # A non-finite reported objective (inf / nan) can never equal + # the finite recomputed profit. Use a finite violation amount + # and a finite lhs so the result JSON stays standard-compliant + # (no Infinity / NaN literals leaking into feasi_result_*.json). + abs_diff = obj_tol + max(1.0, abs(true_obj)) + lhs_record = true_obj + add_violation(violations, magnitudes, violated_set, + 17, f"Constraint 17 (eq.1): Objective consistency " + f"violated: reported objective_value={reported} " + f"differs from recomputed total profit " + f"(revenue - fixed - travel) = {true_obj} " + f"[revenue={revenue}, fixed={fixed_cost}, " + f"travel={travel_cost}] " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + lhs_record, true_obj, abs_diff, obj_tol, eps, + relative_tol=0.0) + + # ========================================================================= + # Build result + # ========================================================================= + # Deduplicate violation messages per constraint index + constraint_msgs = {} + for v_mag in magnitudes: + c_idx = v_mag["constraint"] + if c_idx not in constraint_msgs: + constraint_msgs[c_idx] = [] + for msg in violations: + # Extract constraint index from the message prefix + for c_idx in sorted(violated_set): + prefix = f"Constraint {c_idx} " + if msg.startswith(prefix): + constraint_msgs[c_idx].append(msg) + break + + # Aggregate violations into one message per constraint + aggregated_violations = [] + for c_idx in sorted(violated_set): + msgs = constraint_msgs.get(c_idx, []) + count = sum(1 for m in magnitudes if m["constraint"] == c_idx) + if count == 1: + aggregated_violations.append(msgs[0] if msgs else f"Constraint {c_idx} violated") + else: + first = msgs[0] if msgs else f"Constraint {c_idx} violated" + aggregated_violations.append(f"{first} (and {count - 1} more)") + + feasible = len(violated_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": aggregated_violations, + "violation_magnitudes": magnitudes if not feasible else [], + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for AtOP (Freeman et al. 2018)") + parser.add_argument('--instance_path', type=str, required=True, + help='Path to the JSON file containing the data instance.') + parser.add_argument('--solution_path', type=str, required=True, + help='Path to the JSON file containing the candidate solution.') + parser.add_argument('--result_path', type=str, required=True, + help='Path to write the JSON file containing the result.') + args = parser.parse_args() + + data = load_json(args.instance_path) + sol = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(data, sol) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result['feasible']: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: " + f"{result['violated_constraints']}") + for v in result['violations']: + print(f" - {v}") + + +if __name__ == '__main__': + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/freeman2018/gurobi_code.py b/tasks/freeman2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c1cce8c6222428cea8c14bea2379b5067d31573c --- /dev/null +++ b/tasks/freeman2018/gurobi_code.py @@ -0,0 +1,453 @@ +""" +Gurobi implementation of the Linearized MIP for the Attractive Orienteering Problem (AtOP). + +Paper: Freeman, Keskin, Çapar (2018) - "Attractive Orienteering Problem with + Proximity and Timing Interactions" +European Journal of Operational Research. + +This implements the linearized MIP formulation (Section 3.2) using Gurobi as the solver. +The MINLP constraint (11) is replaced by constraints (18)-(22) via McCormick linearization. +""" + +import json +import argparse +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(instance_path): + """Load the problem instance from a JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def compute_parameters(data): + """ + Compute derived parameters: s_it, a_kt, alpha_ikt from instance data. + + Formulas from Section 5.1 of the paper: + s_it = t_tilde * N_i / avg_N_i + a_kt = t_tilde * N_k / avg_N_k + alpha_ikt = a_kt / (d_p_ik / 1000)^q + """ + params = data['parameters'] + T = data['num_periods'] + K = data['num_sites'] + I = data['num_customers'] + q = params['q'] + weekly_cycle = params['weekly_attraction_cycle'] + avg_bus_cust = params['avg_businesses_customers'] + avg_bus_sites = params['avg_businesses_sites'] + + sites = {s['id']: s for s in data['sites']} + customers = {cu['id']: cu for cu in data['customers']} + + # Day-of-week attraction (1-indexed periods, cycling through the week) + t_tilde = {} + for t in range(1, T + 1): + t_tilde[t] = weekly_cycle[(t - 1) % 7] + + # Self-attraction s_{it} + s_it = {} + for i in range(1, I + 1): + N_i = customers[i]['num_businesses'] + for t in range(1, T + 1): + s_it[i, t] = t_tilde[t] * N_i / avg_bus_cust + + # Site attraction a_{kt} + a_kt = {} + for k in range(1, K + 1): + N_k = sites[k]['num_businesses'] + for t in range(1, T + 1): + a_kt[k, t] = t_tilde[t] * N_k / avg_bus_sites + + # Customer-to-site attraction alpha_{ikt} + # Parse customer-to-site distances + d_p = {} + for key, val in data['customer_to_site_distances'].items(): + parts = key.split('_') + ci, sk = int(parts[0]), int(parts[1]) + d_p[ci, sk] = val + + alpha = {} + for i in range(1, I + 1): + for k in range(1, K + 1): + dist = d_p[i, k] + dist_scaled = dist / 1000.0 + if dist_scaled < 1e-10: + dist_scaled = 1e-10 # Avoid division by zero + denom = dist_scaled ** q + for t in range(1, T + 1): + alpha[i, k, t] = a_kt[k, t] / denom + + return sites, customers, d_p, s_it, a_kt, alpha, t_tilde + + +def build_and_solve(data, args): + """Build the linearized MIP model and solve with Gurobi.""" + K = data['num_sites'] + I = data['num_customers'] + T = data['num_periods'] + params = data['parameters'] + delta = params['delta'] + epsilon = params['epsilon'] + L_max = params['L'] + c = params['c'] + + sites_dict, customers_dict, d_p, s_it, a_kt, alpha, t_tilde = compute_parameters(data) + + # Site parameters + theta = {s['id']: s['capacity'] for s in data['sites']} + r = {s['id']: s['revenue_per_customer'] for s in data['sites']} + f = {s['id']: s['fixed_cost'] for s in data['sites']} + m = {s['id']: s['max_events'] for s in data['sites']} + gamma = {cu['id']: cu['population'] for cu in data['customers']} + + # Parse site-to-site distances (includes dummy site 0) + d_s = {} + for key, val in data['site_to_site_distances'].items(): + parts = key.split('_') + j_id, k_id = int(parts[0]), int(parts[1]) + d_s[j_id, k_id] = val + + site_ids = list(range(1, K + 1)) + all_sites_with_dummy = [0] + site_ids + + # ========================================================================= + # Build Gurobi Model + # ========================================================================= + model = gp.Model("AtOP_LinearizedMIP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + model.setParam("OutputFlag", 1) + + # --- Decision Variables --- + # X[j,k,t] in {0,1}: tour moves from site j to site k in period t + X = {} + # Period 1: moves from dummy site 0 to any real site + for k in site_ids: + X[0, k, 1] = model.addVar(vtype=GRB.BINARY, name=f"X_0_{k}_1") + # Periods 2..T: moves between real sites + for t in range(2, T + 1): + for j in site_ids: + for k in site_ids: + X[j, k, t] = model.addVar(vtype=GRB.BINARY, name=f"X_{j}_{k}_{t}") + + # Y[k,t] in {0,1}: event at site k in period t + Y = {} + for k in site_ids: + for t in range(1, T + 1): + Y[k, t] = model.addVar(vtype=GRB.BINARY, name=f"Y_{k}_{t}") + + # P[i,k,t]: expected proportion (auxiliary continuous) + P = {} + for i in range(1, I + 1): + for k in site_ids: + for t in range(1, T + 1): + P[i, k, t] = model.addVar(lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, + name=f"P_{i}_{k}_{t}") + + # A[k,t]: expected attendance (auxiliary continuous) + A = {} + for k in site_ids: + for t in range(1, T + 1): + A[k, t] = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, name=f"A_{k}_{t}") + + # Z[i,j,k,t,tau]: linearization variables for McCormick relaxation + Z = {} + for i in range(1, I + 1): + for k in site_ids: + for t in range(1, T + 1): + tau_lo = max(t - epsilon, 1) + tau_hi = min(t + epsilon, T) + for j in site_ids: + for tau in range(tau_lo, tau_hi + 1): + Z[i, j, k, t, tau] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"Z_{i}_{j}_{k}_{t}_{tau}") + + model.update() + + # --- Objective Function --- + # Maximize: sum_k sum_t r_k * A_kt - sum_k sum_t f_k * Y_kt + # - c * sum_j sum_k sum_t d_s_jk * X_jkt + obj = gp.LinExpr() + for k in site_ids: + for t in range(1, T + 1): + obj += r[k] * A[k, t] + obj -= f[k] * Y[k, t] + + # Travel cost for period 1 (from dummy site 0) + for k in site_ids: + obj -= c * d_s.get((0, k), 0.0) * X[0, k, 1] + # Travel cost for periods 2..T + for t in range(2, T + 1): + for j in site_ids: + for k in site_ids: + if (j, k, t) in X: + obj -= c * d_s.get((j, k), 0.0) * X[j, k, t] + + model.setObjective(obj, GRB.MAXIMIZE) + + # --- Constraints --- + + # (2) Tour starts from dummy site 0 in period 1 + model.addConstr( + gp.quicksum(X[0, k, 1] for k in site_ids) == 1, "C2_start") + + # (3) Exactly one move per period t = 2,...,T + for t in range(2, T + 1): + model.addConstr( + gp.quicksum(X[j, k, t] for j in site_ids for k in site_ids + if (j, k, t) in X) == 1, + f"C3_one_visit_{t}") + + # (4) Flow conservation between period 1 and period 2 + if T >= 2: + for k in site_ids: + model.addConstr( + X[0, k, 1] == gp.quicksum( + X[k, j, 2] for j in site_ids if (k, j, 2) in X), + f"C4_flow_1_2_{k}") + + # (5) Flow conservation for t = 2,...,T-1 + for t in range(2, T): + for k in site_ids: + model.addConstr( + gp.quicksum(X[j, k, t] for j in site_ids if (j, k, t) in X) == + gp.quicksum(X[k, j, t + 1] for j in site_ids if (k, j, t + 1) in X), + f"C5_flow_{t}_{k}") + + # (6) Maximum travel distance per period + # Period 1 + model.addConstr( + gp.quicksum(d_s.get((0, k), 0.0) * X[0, k, 1] for k in site_ids) <= L_max, + "C6_dist_1") + # Periods 2..T + for t in range(2, T + 1): + model.addConstr( + gp.quicksum(d_s.get((j, k), 0.0) * X[j, k, t] + for j in site_ids for k in site_ids + if (j, k, t) in X) <= L_max, + f"C6_dist_{t}") + + # (7) Events only at destination in period 1 + for k in site_ids: + model.addConstr(Y[k, 1] <= X[0, k, 1], f"C7_event_dest_1_{k}") + + # (8) Events only at destination in periods 2..T + for k in site_ids: + for t in range(2, T + 1): + model.addConstr( + Y[k, t] <= gp.quicksum( + X[j, k, t] for j in site_ids if (j, k, t) in X), + f"C8_event_dest_{t}_{k}") + + # (9) Maximum number of events at each site + for k in site_ids: + model.addConstr( + gp.quicksum(Y[k, t] for t in range(1, T + 1)) <= m[k], + f"C9_max_events_{k}") + + # (10) Maximum consecutive events limit + # As formulated: sum_{k in K} sum_{t'=t}^{t+delta+1} Y_{kt'} <= delta + # for t = 1,...,T-delta-1 + for t in range(1, T - delta): + upper = t + delta + 1 + if upper > T: + upper = T + model.addConstr( + gp.quicksum(Y[k, tp] for k in site_ids + for tp in range(t, upper + 1)) <= delta, + f"C10_consec_{t}") + + # (12) Attendance from proportions + for k in site_ids: + for t in range(1, T + 1): + model.addConstr( + A[k, t] <= gp.quicksum( + P[i, k, t] * gamma[i] for i in range(1, I + 1)), + f"C12_attend_{k}_{t}") + + # (13) Venue capacity constraint + for k in site_ids: + for t in range(1, T + 1): + model.addConstr(A[k, t] <= theta[k], f"C13_cap_{k}_{t}") + + # --- Linearized constraints (18)-(22) replacing (11) --- + + # (18) P_{ikt} * s_{it} = alpha_{ikt} * Y_{kt} - sum_j sum_tau Z_{ijkt,tau} + for i in range(1, I + 1): + for k in site_ids: + for t in range(1, T + 1): + tau_lo = max(t - epsilon, 1) + tau_hi = min(t + epsilon, T) + z_sum = gp.quicksum( + Z[i, j, k, t, tau] + for j in site_ids + for tau in range(tau_lo, tau_hi + 1) + if (i, j, k, t, tau) in Z + ) + model.addConstr( + s_it[i, t] * P[i, k, t] == alpha[i, k, t] * Y[k, t] - z_sum, + f"C18_{i}_{k}_{t}") + + # (19) Z_{ijkt,tau} <= P_{ikt} * alpha_{ij,tau} + for i in range(1, I + 1): + for k in site_ids: + for t in range(1, T + 1): + tau_lo = max(t - epsilon, 1) + tau_hi = min(t + epsilon, T) + for j in site_ids: + for tau in range(tau_lo, tau_hi + 1): + if (i, j, k, t, tau) in Z: + model.addConstr( + Z[i, j, k, t, tau] <= alpha[i, j, tau] * P[i, k, t], + f"C19_{i}_{j}_{k}_{t}_{tau}") + + # (20) Z_{ijkt,tau} <= alpha_{ij,tau} * Y_{j,tau} + for i in range(1, I + 1): + for k in site_ids: + for t in range(1, T + 1): + tau_lo = max(t - epsilon, 1) + tau_hi = min(t + epsilon, T) + for j in site_ids: + for tau in range(tau_lo, tau_hi + 1): + if (i, j, k, t, tau) in Z: + model.addConstr( + Z[i, j, k, t, tau] <= alpha[i, j, tau] * Y[j, tau], + f"C20_{i}_{j}_{k}_{t}_{tau}") + + # (21) Z_{ijkt,tau} >= P_{ikt} * alpha_{ij,tau} - alpha_{ij,tau} * (1 - Y_{j,tau}) + for i in range(1, I + 1): + for k in site_ids: + for t in range(1, T + 1): + tau_lo = max(t - epsilon, 1) + tau_hi = min(t + epsilon, T) + for j in site_ids: + for tau in range(tau_lo, tau_hi + 1): + if (i, j, k, t, tau) in Z: + model.addConstr( + Z[i, j, k, t, tau] >= + alpha[i, j, tau] * P[i, k, t] + - alpha[i, j, tau] * (1 - Y[j, tau]), + f"C21_{i}_{j}_{k}_{t}_{tau}") + + # (22) Z >= 0 is already handled by lb=0.0 in variable definition. + + # ========================================================================= + # Solve + # ========================================================================= + model.optimize() + + # ========================================================================= + # Extract solution + # ========================================================================= + solution = {} + if model.SolCount > 0: + solution['objective_value'] = model.ObjVal + + # Extract tour: which site is visited each period + tour = {} + for t in range(1, T + 1): + for k in site_ids: + if t == 1: + if X[0, k, 1].X > 0.5: + tour[t] = k + break + else: + for j in site_ids: + if (j, k, t) in X and X[j, k, t].X > 0.5: + tour[t] = k + break + if t in tour: + break + + # Extract event plan + events = {} + for t in range(1, T + 1): + for k in site_ids: + if Y[k, t].X > 0.5: + events[t] = k + break + + solution['tour'] = {str(t): tour.get(t) for t in range(1, T + 1)} + solution['events'] = {str(t): (1 if t in events else 0) + for t in range(1, T + 1)} + solution['event_sites'] = {str(t): events.get(t) for t in range(1, T + 1)} + + # Attendance + attendance = {} + for k in site_ids: + for t in range(1, T + 1): + val = A[k, t].X + if val > 1e-6: + attendance[f"{k}_{t}"] = val + solution['attendance'] = attendance + + # Travel details + travel_cost = 0.0 + for k in site_ids: + if (0, k, 1) in X and X[0, k, 1].X > 0.5: + travel_cost += c * d_s.get((0, k), 0.0) + for t in range(2, T + 1): + for j in site_ids: + for k in site_ids: + if (j, k, t) in X and X[j, k, t].X > 0.5: + travel_cost += c * d_s.get((j, k), 0.0) + solution['total_travel_cost'] = travel_cost + + else: + solution['objective_value'] = None + + solution['solver_status'] = model.Status + if model.SolCount > 0: + solution['mip_gap'] = model.MIPGap + else: + solution['mip_gap'] = None + solution['num_solutions_found'] = model.SolCount + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the AtOP using Gurobi (Linearized MIP formulation)") + parser.add_argument('--instance_path', type=str, required=True, + help='Path to the JSON instance file.') + parser.add_argument('--solution_path', type=str, required=True, + help='Path to write the solution JSON file.') + parser.add_argument('--time_limit', type=int, required=True, + help='Maximum solver runtime in seconds.') + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + solution = build_and_solve(data, args) + + with open(args.solution_path, 'w') as fout: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, fout, indent=2) + + if solution['objective_value'] is not None: + print(f"Best objective value: {solution['objective_value']:.2f}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == '__main__': + main() diff --git a/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freeman2018/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freeman2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/freeman2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freeman2018/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freeman2018/gurobi_solution/large_solution_1.json b/tasks/freeman2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6344b48ddd5e16d07cdf7cef1da1ae615870f4e0 --- /dev/null +++ b/tasks/freeman2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50db98a3321e499f5f28058b18eb0bbc80a5b6cd4d396174de2fdc090e8f2e31 +size 646 diff --git a/tasks/freeman2018/gurobi_solution/large_solution_2.json b/tasks/freeman2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8aa3ad5f1d03d29fc527b6c11b82908d7c49c96d --- /dev/null +++ b/tasks/freeman2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40e0e57afcda62d991514312585880c1398abeef27f51281c2132ff8aac86d3a +size 827 diff --git a/tasks/freeman2018/gurobi_solution/large_solution_3.json b/tasks/freeman2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d9118fe8adbaff996548a1b575f0c09d4821163f --- /dev/null +++ b/tasks/freeman2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba21d1ecdd4143705a9c5e30c5d466c545c01cd19df48f9b8c6fabae3a3a2ce6 +size 672 diff --git a/tasks/freeman2018/gurobi_solution/large_solution_4.json b/tasks/freeman2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..208b151d1796701e7b0c519a201fa52024a7b1bd --- /dev/null +++ b/tasks/freeman2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ee69b0d9d8ffbc49cce7d96a5caa0dccf941ae523269031c64290e17f6683ff +size 663 diff --git a/tasks/freeman2018/gurobi_solution/large_solution_5.json b/tasks/freeman2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..740a677b4a098c68a5a47a0eabaac066d6eae56a --- /dev/null +++ b/tasks/freeman2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7250f02d5f077edc53cf9cb1aef47673671c38c38f450ce5a474e05bb1df6f65 +size 666 diff --git a/tasks/freeman2018/gurobi_solution/tiny_solution.json b/tasks/freeman2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..04c021b451af618ff261bcfcf7ca61c3cc0cf763 --- /dev/null +++ b/tasks/freeman2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b1a506a84b7b45c3cf73efb712c5508ffcf847aa26ed7b6c1f07d97cc38ac8e +size 509 diff --git a/tasks/freeman2018/gurobi_solution_log/large_log_1.jsonl b/tasks/freeman2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bb90f7647fdaac115b3c6b0c84668359175751bd --- /dev/null +++ b/tasks/freeman2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cb63d53085df088d520b4a931d61a18866709599c38cc34fee6a9ecc52f95a8 +size 56 diff --git a/tasks/freeman2018/gurobi_solution_log/large_log_2.jsonl b/tasks/freeman2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f2d3140e837b98d2f954f16fe85b14390cf9ab06 --- /dev/null +++ b/tasks/freeman2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dae7a37fdf2d6accd4be1ed18936ed875875ad333a001941c45193fa51a75245 +size 46 diff --git a/tasks/freeman2018/gurobi_solution_log/large_log_3.jsonl b/tasks/freeman2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a9df2ac8a4fac1d978ac5fd345013c8a9e042362 --- /dev/null +++ b/tasks/freeman2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8cc40544f3414caf9068ec294b4f6fa63c9446c0ab96f019deeb5970350b42be +size 56 diff --git a/tasks/freeman2018/gurobi_solution_log/large_log_4.jsonl b/tasks/freeman2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4fa6a708d29c06864fe33c30ba82dadfbe141cf7 --- /dev/null +++ b/tasks/freeman2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68b713a61d642d9c422dd91f8382b82e9648782d046d2032c9898a088b930557 +size 44 diff --git a/tasks/freeman2018/gurobi_solution_log/large_log_5.jsonl b/tasks/freeman2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2c6dd002a3d0a017bad082b365658e3d4556ff9a --- /dev/null +++ b/tasks/freeman2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6fb47855938a4dab4e6419b5e8eda701e50a3a82ffc28db86a58fd24b148d2f +size 46 diff --git a/tasks/freeman2018/gurobi_solution_log/tiny_log.jsonl b/tasks/freeman2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..34b66ae56396e369cb4a32c4e3a1891ac0245aaf --- /dev/null +++ b/tasks/freeman2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b32444d7a0827a8eae6265b0dc7dcd3f815bfb14f4b9ae69152c91d17367e259 +size 43 diff --git a/tasks/freeman2018/instance/large_instance_1.json b/tasks/freeman2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3846273d9c4a8ee75f915555069baec4d565f199 --- /dev/null +++ b/tasks/freeman2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31e816b354d4c18427a3113e55c96879b4f77cd2a43fe121449fbbc1e6d09fd6 +size 53419 diff --git a/tasks/freeman2018/instance/large_instance_2.json b/tasks/freeman2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..5ddee43e7484c0d7b7197a9007e939270e027ae5 --- /dev/null +++ b/tasks/freeman2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56e0993bc2a4325aeaa85060e9e2c1eeec9fb107fbbb1939f65f58cc09f2a9ba +size 53494 diff --git a/tasks/freeman2018/instance/large_instance_3.json b/tasks/freeman2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3d63afe5e4d5c8ed5b989ac8fbfd42af13630e35 --- /dev/null +++ b/tasks/freeman2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9b84f8ea2b95a5e145b7ebada3820fc1eab80f5aa1698c3e9f1d49ab19f0540 +size 53738 diff --git a/tasks/freeman2018/instance/large_instance_4.json b/tasks/freeman2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..3ffa0b35b4dee4ed721e6e2b8b9c8ebfe9bf2fc7 --- /dev/null +++ b/tasks/freeman2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9866ed1b2e472f561e71ce8f862afd7afa47eba3d9f36d6d74b2f8126179f41f +size 53761 diff --git a/tasks/freeman2018/instance/large_instance_5.json b/tasks/freeman2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3b02984fa232ca469cfdaa943ba365ae56dc1769 --- /dev/null +++ b/tasks/freeman2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a653489eb8bd221e743f35fcdc90d7eaa0c2e67ac65d231d44c4ab196c936139 +size 53342 diff --git a/tasks/freeman2018/instance/tiny_instance.json b/tasks/freeman2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..f72b332d7d5ddfab74a4bb512f0e12844c456378 --- /dev/null +++ b/tasks/freeman2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f445ce9acd1940ef3a3126593f771a9344e3123917fde8394e0efa67278ec80 +size 4865 diff --git a/tasks/freeman2018/instance_schema.json b/tasks/freeman2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5ae26ae83e9324b341f86f1f03f64675c718cc8d --- /dev/null +++ b/tasks/freeman2018/instance_schema.json @@ -0,0 +1,39 @@ +{ + "num_sites": " Number of candidate venue sites where events may be held.", + "num_customers": " Number of customer locations representing nearby population centers.", + "num_periods": " Number of time periods in the planning horizon.", + "parameters": { + "T": " Number of time periods in the planning horizon.", + "delta": " Maximum number of events that may be held in any window of delta-plus-one consecutive periods.", + "epsilon": " Number of periods before and after a given period considered when computing competitive interactions among events.", + "L": " Maximum travel distance allowed in any single period.", + "c": " Cost per unit distance traveled between sites.", + "q": " Distance decay exponent controlling how quickly customer attraction diminishes with distance.", + "weekly_attraction_cycle": " Relative attractiveness factor for each day of the week from Monday to Sunday, cycling over periods.", + "avg_businesses_customers": " Average number of businesses across all customer locations, used to normalize self-attraction values.", + "avg_businesses_sites": " Average number of businesses across all venue sites, used to normalize site attraction values." + }, + "sites": [ + { + "id": " Unique identifier for this venue site (1-indexed).", + "x": " Horizontal coordinate of the venue site in miles.", + "y": " Vertical coordinate of the venue site in miles.", + "capacity": " Maximum number of attendees the venue can accommodate at any single event.", + "num_businesses": " Number of businesses near the venue site, used to compute site attraction.", + "revenue_per_customer": " Revenue earned per customer attending an event at this site.", + "fixed_cost": " Fixed cost incurred each time an event is held at this site.", + "max_events": " Maximum number of events that may be held at this site over the entire planning horizon." + } + ], + "customers": [ + { + "id": " Unique identifier for this customer location (1-indexed).", + "x": " Horizontal coordinate of the customer location in miles.", + "y": " Vertical coordinate of the customer location in miles.", + "population": " Number of potential attendees residing at this customer location.", + "num_businesses": " Number of businesses at this customer location, used to compute self-attraction." + } + ], + "site_to_site_distances": " Travel distance between each pair of venue sites, including the dummy starting site 0 which has zero distance to all venues.", + "customer_to_site_distances": " Distance from each customer location to each venue site." +} \ No newline at end of file diff --git a/tasks/freeman2018/mathematical_formulation.md b/tasks/freeman2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..c821e2e963d768f6228162e4518a73d519a27e3c --- /dev/null +++ b/tasks/freeman2018/mathematical_formulation.md @@ -0,0 +1,89 @@ +# Original Formulation: Attractive Orienteering Problem (AtOP) + +*Source: The Attractive Orienteering Problem with Proximity and Timing Interactions, M. C. Freeman, B. B. Keskin, İ. Çapar, European Journal of Operational Research, 2018.* + +## Sets and Indices + +$$\begin{align*} +& i \in \mathcal{I} = \{1,\ldots,I\} && \text{customer location index} \\ +& j,k \in \mathcal{K} = \{1,\ldots,K\} && \text{site location indices} \\ +& t = 1,\ldots,T && \text{period index} +\end{align*}$$ Site $0$ is a dummy starting site with $d^s_{0k}=0$ for all $k\in\mathcal{K}$. + +## Parameters + +$$\begin{align*} +& d^s_{jk} && \text{distance between site } j \text{ and site } k, && \forall j,k\in\mathcal{K} \\ +& d^p_{ik} && \text{distance between customer } i \text{ and site } k, && \forall i\in\mathcal{I},\,k\in\mathcal{K} \\ +& c && \text{cost per unit distance traveled} \\ +& \delta && \text{maximum consecutive events} \\ +& m_k && \text{maximum number of events that may be held at site } k, && \forall k\in\mathcal{K} \\ +& r_k && \text{revenue per customer that attends an event at site } k, && \forall k\in\mathcal{K} \\ +& f_k && \text{fixed cost of holding an event at site } k, && \forall k\in\mathcal{K} \\ +& \gamma_i && \text{customer population at location } i, && \forall i\in\mathcal{I} \\ +& L && \text{maximum travel distance for a single period} \\ +& \theta_k && \text{capacity of site } k, && \forall k\in\mathcal{K} \\ +& s_{it} && \text{self-attraction of customer } i \text{ in period } t, && \forall i\in\mathcal{I},\,t=1,\ldots,T \\ +& \alpha_{ikt} && \text{attraction of customers at location } i \text{ to an} \\ +& && \text{event held at site } k \text{ in period } t, && \forall i\in\mathcal{I},\,k\in\mathcal{K},\,t=1,\ldots,T \\ +& \epsilon && \text{number of periods before/after } t \text{ defining the} \\ +& && \text{performance shadow window} +\end{align*}$$ The attraction parameter is defined (Eq. 1 context) as $\alpha_{ikt} = \dfrac{\tilde{t}\,a_{kt}}{(d^p_{ik})^q}$, where $\tilde{t}\in[0,1]$ is the relative attraction of period $t$, $a_{kt}$ is the attraction of site $k$ in period $t$, and $q>1$ is the distance decay exponent. + +## Decision Variables + +$$\begin{align*} +& X_{jkt} \in \{0,1\} && \text{1 if the tour moves from site } j \text{ to site } k \text{ in period } t, && \forall j,k\in\mathcal{K},\,t=1,\ldots,T \\ +& Y_{jt} \in \{0,1\} && \text{1 if an event is held at site } j \text{ in period } t, && \forall j\in\mathcal{K},\,t=1,\ldots,T +\end{align*}$$ Auxiliary variables: $$\begin{align*} +& P_{ikt} && \text{expected proportion of the population at customer } i\text{'s location} \\ +& && \text{that will attend an event held at venue } k \text{ on day } t, && \forall i\in\mathcal{I},\,k\in\mathcal{K},\,t=1,\ldots,T \\ +& A_{kt} && \text{expected total attendance of an event held at facility } k \text{ on day } t, && \forall k\in\mathcal{K},\,t=1,\ldots,T +\end{align*}$$ + +## Objective + +$$\begin{align} +\text{Maximize} \quad +\sum_{k\in\mathcal{K}}\sum_{t=1}^{T} r_k A_{kt} +- \sum_{k\in\mathcal{K}}\sum_{t=1}^{T} f_k Y_{kt} +- c \sum_{j\in\mathcal{K}}\sum_{k\in\mathcal{K}}\sum_{t=1}^{T} d^s_{jk} X_{jkt} +\notag +\end{align}$$ + +## Constraints + +$$\begin{align} +& \sum_{k\in\mathcal{K}} X_{0k1} = 1 \tag{2} \\ +& \sum_{j\in\mathcal{K}}\sum_{k\in\mathcal{K}} X_{jkt} = 1, && \forall t = 2,\ldots,T \tag{3} \\ +& X_{0k1} = \sum_{j\in\mathcal{K}} X_{kj2}, && \forall k\in\mathcal{K} \tag{4} \\ +& \sum_{j\in\mathcal{K}} X_{jkt} = \sum_{j\in\mathcal{K}} X_{kj,t+1}, && \forall k\in\mathcal{K},\,t=2,\ldots,T-1 \tag{5} \\ +& \sum_{j\in\mathcal{K}}\sum_{k\in\mathcal{K}} X_{jkt}\, d^s_{jk} \leq L, && \forall t = 1,\ldots,T \tag{6} \\ +& Y_{k1} \leq X_{0k1}, && \forall k\in\mathcal{K} \tag{7} \\ +& Y_{kt} \leq \sum_{j\in\mathcal{K}} X_{jkt}, && \forall k\in\mathcal{K},\,t=2,\ldots,T \tag{8} \\ +& \sum_{t=1}^{T} Y_{kt} \leq m_k, && \forall k\in\mathcal{K} \tag{9} \\ +& \sum_{k\in\mathcal{K}}\sum_{t'=t}^{t+\delta+1} Y_{kt'} \leq \delta, && \forall t = 1,\ldots,T-\delta-1 \tag{10} +\end{align}$$ + +$$\begin{align} +& \left( s_{it} + \sum_{j\in\mathcal{K}} \sum_{\tau=\max\{t-\epsilon,0\}}^{\min\{t+\epsilon,T\}} \alpha_{ij\tau} Y_{j\tau} \right) P_{ikt} = \alpha_{ikt} Y_{kt}, && \forall i\in\mathcal{I},\,k\in\mathcal{K},\,t=1,\ldots,T \tag{11} +\end{align}$$ + +$$\begin{align} +& A_{kt} \leq \sum_{i\in\mathcal{I}} P_{ikt} \gamma_i, && \forall k\in\mathcal{K},\,t=1,\ldots,T \tag{12} \\ +& A_{kt} \leq \theta_k, && \forall k\in\mathcal{K},\,t=1,\ldots,T \tag{13} \\ +& X_{jkt} \in \{0,1\}, && \forall j,k\in\mathcal{K},\,t=1,\ldots,T \tag{14} \\ +& Y_{kt} \in \{0,1\}, && \forall k\in\mathcal{K},\,t=1,\ldots,T \tag{15} \\ +& P_{ikt} \leq 1, && \forall i\in\mathcal{I},\,k\in\mathcal{K},\,t=1,\ldots,T \tag{16} \\ +& A_{kt} \geq 0, && \forall k\in\mathcal{K},\,t=1,\ldots,T \tag{17} +\end{align}$$ + +## Linearization (Section 3.2, paper’s own) + +The nonlinear constraint (11) is replaced by (18)–(22) via a new continuous variable $Z_{ijkt\tau} \geq 0$ that represents the product $P_{ikt}\,\alpha_{ij\tau} Y_{j\tau}$, with $\tau \in \Omega = \{\max\{0,t-\epsilon\},\ldots,\min\{t+\epsilon,T\}\}$. $$\begin{align} +& P_{ikt}\, s_{it} = \alpha_{ikt} Y_{kt} - \sum_{j\in\mathcal{K}} \sum_{\tau=\max\{t-\epsilon,0\}}^{\min\{t+\epsilon,T\}} Z_{ijkt\tau}, && \forall i\in\mathcal{I},\,k\in\mathcal{K},\,t=1,\ldots,T \tag{18} \\ +& Z_{ijkt\tau} \leq P_{ikt}\, \alpha_{ij\tau}, && \forall i\in\mathcal{I},\,j,k\in\mathcal{K},\,t=1,\ldots,T,\,\tau\in\Omega \tag{19} \\ +& Z_{ijkt\tau} \leq \alpha_{ij\tau} Y_{j\tau}, && \forall i\in\mathcal{I},\,j,k\in\mathcal{K},\,t=1,\ldots,T,\,\tau\in\Omega \tag{20} \\ +& Z_{ijkt\tau} \geq P_{ikt}\, \alpha_{ij\tau} - \alpha_{ij\tau}\,(1 - Y_{j\tau}), && \forall i\in\mathcal{I},\,j,k\in\mathcal{K},\,t=1,\ldots,T,\,\tau\in\Omega \tag{21} \\ +& Z_{ijkt\tau} \geq 0, && \forall i\in\mathcal{I},\,j,k\in\mathcal{K},\,t=1,\ldots,T,\,\tau\in\Omega \tag{22} +\end{align}$$ diff --git a/tasks/freeman2018/problem_description.txt b/tasks/freeman2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..200453e27001a929477fb613fd3a87ee30f7b12a --- /dev/null +++ b/tasks/freeman2018/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A touring entertainment company plans a multi-period tour across a set of candidate venue sites to hold events (such as concerts) that attract customers from nearby population centers. The company must decide, for each period in a fixed planning horizon, which site to visit and whether to hold an event there, with the goal of maximizing total profit. + +The problem involves three types of entities: venue sites where events may be held, customer locations representing nearby population centers, and time periods spanning the planning horizon. There is also a dummy starting site from which the tour departs in the first period; the distance from this dummy starting site to every venue site is zero. The input data specifies the following: the distance between every pair of venue sites, the distance between every customer location and every venue site, a cost per unit distance traveled, a maximum travel distance allowed in any single period, the population at each customer location, the capacity of each venue site (the maximum attendance it can accommodate), the revenue earned per customer attending an event at each site, the fixed cost incurred whenever an event is held at each site, the maximum number of events that may be held at each site over the entire horizon, a maximum number of consecutive periods that may contain events (denoted delta), and a performance shadow window size (denoted epsilon) that determines how many periods before and after a given period are considered when computing competitive interactions among events. Each customer location has a strictly positive self-attraction value for each period, representing the draw of substitute entertainment options in that area at that time. Each site has an attraction value for each period that reflects its inherent appeal. The attraction of customers at a given customer location to an event at a given site in a given period is computed as the product of that site's attraction value in that period and a relative time-of-week attractiveness factor, divided by the distance from that customer location to that site raised to a distance decay exponent greater than one. The relative time-of-week attractiveness factor is a value between zero and one that follows a weekly cycle, with higher values on weekends. + +The company must make two types of decisions: a routing decision specifying which site the tour moves to in each period, and an event-scheduling decision specifying whether an event is held at the visited site in each period. In the first period, the tour departs from the dummy starting site and travels to exactly one venue site. In every subsequent period, the tour moves from its current site to exactly one site (which may be the same site). The site where the tour arrives in one period must be the site from which it departs in the next period. The total distance traveled in any single period must not exceed the maximum per-period travel distance. An event can only be held at a site during a period if the tour is at that site in that period. The total number of events held at any site across the entire horizon must not exceed that site's maximum event count. To ensure rest days, for every starting period t from 1 to T-delta-1, the total number of events held across all sites within the window consisting of periods t, t+1, ..., t+delta+1 (a window of delta-plus-two consecutive periods) must be at most delta. + +Customer attendance at events is governed by a gravity-based attraction model that accounts for the performance shadow phenomenon, whereby events held at nearby sites within a close time window compete for the same customers. The expected proportion of the population at a given customer location that attends an event at a given site in a given period is determined by a ratio: the numerator is the attraction of that customer location to that event (which is zero if no event is held at that site in that period), and the denominator is the sum of the self-attraction of that customer location in that period plus the total attraction of that customer location to all events held at any site in any period within epsilon periods of that period (including that period itself). This proportion cannot exceed one. The expected attendance at an event held at a given site in a given period cannot exceed the sum over all customer locations of the product of each location's population and the proportion of that population attracted to the event. The attendance at any event also cannot exceed the venue's capacity. + +The goal is to maximize total profit, defined as total revenue minus total costs. Total revenue is the sum over all sites and periods of the product of the per-customer revenue at each site and the expected attendance at that site in that period. Total costs consist of two components: the sum over all sites and periods of the fixed event cost at each site multiplied by whether an event is held there in that period, and the total travel cost computed as the cost per unit distance multiplied by the sum of distances traveled across all site-to-site movements in all periods. diff --git a/tasks/freeman2018/solution_logger.py b/tasks/freeman2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/freeman2018/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/freeman2018/solution_schema.json b/tasks/freeman2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ee82da2b960c97d8b2660608363601a42d281d77 --- /dev/null +++ b/tasks/freeman2018/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Total profit from the tour, computed as total event revenue minus fixed event costs and travel costs.", + "tour": " Which venue site the tour visits in each period.", + "events": " Whether an event is held in each period (1 = yes, 0 = no).", + "event_sites": " Which venue site hosts the event in each period, if an event is held.", + "attendance": " Expected number of customers attending the event at each site in each period." +} \ No newline at end of file diff --git a/tasks/freling2003/feasibility_check.py b/tasks/freling2003/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..989e31687b95d20e73abdbf26ee2eb2c7690c269 --- /dev/null +++ b/tasks/freling2003/feasibility_check.py @@ -0,0 +1,445 @@ +""" +Feasibility Checker for the Multiperiod Single-Sourcing Problem (MPSSP) +from Freling, Romeijn, Romero Morales, Wagelmans (2003), +Operations Research 51(6):922-939. + +Checks each hard constraint of formulation (P_0) one by one: + Constraint 1: sigma_t * sum_j d_j x_{ij} + I_{it} <= b_{it} + I_{i,t-1} for all i,t + Constraint 2: sum_i x_{ij} = 1 for all j + Constraint 3: x_{ij} in {0,1} for all i,j + Constraint 4: I_{i0} = 0 for all i + Constraint 5: I_{it} >= 0 for all i,t + Constraint 6: objective consistency -- the reported objective_value must + equal the objective recomputed from the solution variables: + obj = sum_{i,j} (sum_t c_{ijt}) x_{ij} + sum_{i,t} h_{it} I_{it} + This is a Tier-C defense against fabricated objective values + (e.g. reporting obj=0 or obj=sys.float_info.max). All variables + that determine the objective (x from `assignment`, I from + `inventory`) are present in the solution, so a full recompute + is exact. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'inventory', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('inventory',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def save_json(path, obj): + with open(path, "w") as f: + json.dump(obj, f, indent=2) + + +def check_feasibility(instance, solution): + m = instance["parameters"]["num_facilities"] + n = instance["parameters"]["num_customers"] + T = instance["parameters"]["num_periods"] + sigma = instance["seasonal_factors"] + demands = instance["demands"] + capacities = instance["capacities"] # capacities[i][t] + + # Parse assignment: x_{ij} — solution stores {str(j): i} + assignment = solution["assignment"] # dict str(j) -> i + # Build x[i][j] + x = [[0] * n for _ in range(m)] + for j_str, i_val in assignment.items(): + j = int(j_str) + i = int(i_val) + if 0 <= i < m and 0 <= j < n: + x[i][j] = 1 + + # Parse inventory: I[i][t] — solution stores {str(i): [I_{i,1}, ..., I_{i,T}]} + inventory_raw = solution.get("inventory", {}) + # I_it indexed as I[i][t] for t=1..T (0-indexed: t=0..T-1) + # I_{i,0} = 0 by constraint 4 + I = [[0.0] * T for _ in range(m)] + for i_str, inv_list in inventory_raw.items(): + i = int(i_str) + if 0 <= i < m: + for t in range(min(T, len(inv_list))): + I[i][t] = float(inv_list[t]) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------ + # Constraint 1: sigma_t * sum_j(d_j * x_{ij}) + I_{it} <= b_{it} + I_{i,t-1} + # for i=1..m, t=1..T + # Rearranged: LHS = sigma_t * sum_j(d_j * x_{ij}) + I_{it} + # RHS = b_{it} + I_{i,t-1} + # ------------------------------------------------------------------ + for i in range(m): + for t in range(T): + demand_sum = sum(demands[j] * x[i][j] for j in range(n)) + lhs = sigma[t] * demand_sum + I[i][t] + I_prev = I[i][t - 1] if t > 0 else 0.0 + rhs = capacities[i][t] + I_prev + violation_amount = lhs - rhs # <= constraint + if violation_amount > TOL: + violated_constraints.add(1) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 1 violated: facility {i}, period {t+1}: " + f"LHS={lhs:.6f} > RHS={rhs:.6f} (excess={violation_amount:.6f})" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 2: sum_i x_{ij} = 1 for all j=1..n + # ------------------------------------------------------------------ + for j in range(n): + lhs = sum(x[i][j] for i in range(m)) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(2) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + if lhs == 0: + msg = f"Constraint 2 violated: customer {j} not assigned to any facility" + elif lhs > 1: + facs = [i for i in range(m) if x[i][j] == 1] + msg = ( + f"Constraint 2 violated: customer {j} assigned to multiple " + f"facilities {facs}" + ) + else: + msg = ( + f"Constraint 2 violated: customer {j} assignment sum={lhs:.6f} != 1" + ) + violations.append(msg) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(lhs), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 3: x_{ij} in {0, 1} for all i,j + # ------------------------------------------------------------------ + for i in range(m): + for j in range(n): + val = x[i][j] + # Check if val is binary (0 or 1) + violation_amount_0 = abs(val - 0.0) + violation_amount_1 = abs(val - 1.0) + violation_amount = min(violation_amount_0, violation_amount_1) + if violation_amount > TOL: + violated_constraints.add(3) + lhs = float(val) + # For binary constraint, closest bound + rhs = 0.0 if violation_amount_0 < violation_amount_1 else 1.0 + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 3 violated: x[{i}][{j}]={val} is not binary" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 4: I_{i,0} = 0 for all i + # ------------------------------------------------------------------ + # The solution stores inventory for t=1..T. I_{i,0} is implicitly 0. + # However, we check if the solution explicitly provides I_{i,0}. + # In the solution format, inventory[str(i)] is a list of T values + # corresponding to periods 1..T. I_{i,0} = 0 is implicit. + # We still verify: if the solution had an I_{i,0} field, it must be 0. + # Since the solution format gives [I_{i,1}, ..., I_{i,T}], I_{i,0}=0 + # is always satisfied by construction. But we check anyway for safety. + # The initial inventory is not stored in the solution — it is always 0. + # This constraint is always satisfied by the solution format. + # We still record the check for completeness. + # (No violation possible here since I_{i,0} is hardcoded as 0.) + + # ------------------------------------------------------------------ + # Constraint 5: I_{it} >= 0 for all i=1..m, t=1..T + # ------------------------------------------------------------------ + for i in range(m): + for t in range(T): + lhs = I[i][t] + rhs = 0.0 + violation_amount = rhs - lhs # >= constraint: how much RHS exceeds LHS + if violation_amount > TOL: + violated_constraints.add(5) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 5 violated: I[{i}][{t+1}]={lhs:.6f} < 0" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 6: objective consistency (Tier-C anti-gaming check). + # The reported objective_value must equal the objective recomputed + # from the solution variables: + # obj = sum_{i,j} (sum_t c_{ijt}) x_{ij} + sum_{i,t} h_{it} I_{it} + # All obj-determining variables (x from `assignment`, I from + # `inventory`) are present in the solution, so this is an exact + # full recompute. Tolerance: max(1e-3 absolute, 1e-3 relative). + # ------------------------------------------------------------------ + transport_costs = instance["transportation_costs"] # c_{ijt}, shape m x n x T + holding_costs = instance["holding_costs"] # h_{it}, shape m x T + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + transport_total = 0.0 + for i in range(m): + for j in range(n): + if x[i][j]: + transport_total += sum( + transport_costs[i][j][t] for t in range(T) + ) + holding_total = 0.0 + for i in range(m): + for t in range(T): + holding_total += holding_costs[i][t] * I[i][t] + true_obj = float(transport_total + holding_total) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(6) + normalizer = max(abs(true_obj), EPS) + ratio = abs_diff / normalizer + violations.append( + f"Constraint 6 violated: objective consistency: reported " + f"objective_value={reported} differs from recomputed " + f"sum_ij(sum_t c_ijt)x_ij + sum_it h_it I_it={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": ratio, + }) + + feasible = len(violated_constraints) == 0 + + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MPSSP (Freling et al. 2003)." + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance.", + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution.", + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result.", + ) + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + save_json(args.result_path, result) + print(f"Feasibility result written to {args.result_path}") + print(f"Feasible: {result['feasible']}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/freling2003/gurobi_code.py b/tasks/freling2003/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..1017af0a5f0832bedfde318a5b4d92152393a89d --- /dev/null +++ b/tasks/freling2003/gurobi_code.py @@ -0,0 +1,202 @@ +""" +Gurobi implementation of the Multiperiod Single-Sourcing Problem (MPSSP) +formulation (P_0) from Freling, Romeijn, Romero Morales, Wagelmans (2003). + +minimize sum_{t,i,j} c_{ijt} * x_{ij} + sum_{t,i} h_{it} * I_{it} +subject to + sigma_t * sum_j d_j * x_{ij} + I_{it} <= b_{it} + I_{i,t-1}, for all i,t (1) + sum_i x_{ij} = 1, for all j + x_{ij} in {0,1}, for all i,j + I_{i0} = 0, for all i + I_{it} >= 0, for all i,t +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load the MPSSP instance from a JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def solve_mpssp(instance_path, solution_path, time_limit): + """Build and solve the MPSSP using Gurobi.""" + data = load_instance(instance_path) + + m = data["parameters"]["num_facilities"] + n = data["parameters"]["num_customers"] + T = data["parameters"]["num_periods"] + + sigma = data["seasonal_factors"] # length T + demands = data["demands"] # length n (d_j) + capacities = data["capacities"] # m x T (b_{it}) + holding_costs = data["holding_costs"] # m x T (h_{it}) + transport_costs = data["transportation_costs"] # m x n x T (c_{ijt}) + + # ---------------------------------------------------------------- + # Build the Gurobi model + # ---------------------------------------------------------------- + model = gp.Model("MPSSP_P0") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i,j] : binary assignment variable + x = {} + for i in range(m): + for j in range(n): + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + # I[i,t] : inventory at facility i at end of period t (t=1..T, 0-indexed: 0..T-1) + I = {} + for i in range(m): + for t in range(T): + I[i, t] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"I_{i}_{t}") + + model.update() + + # ---------------------------------------------------------------- + # Objective: min sum_{t,i,j} c_{ijt} * x_{ij} + sum_{t,i} h_{it} * I_{it} + # ---------------------------------------------------------------- + obj = gp.LinExpr() + + # Transportation costs: sum_t sum_i sum_j c_{ijt} * x_{ij} + for i in range(m): + for j in range(n): + cost_ij = sum(transport_costs[i][j][t] for t in range(T)) + obj += cost_ij * x[i, j] + + # Inventory holding costs: sum_t sum_i h_{it} * I_{it} + for i in range(m): + for t in range(T): + obj += holding_costs[i][t] * I[i, t] + + model.setObjective(obj, GRB.MINIMIZE) + + # ---------------------------------------------------------------- + # Constraints + # ---------------------------------------------------------------- + + # (1) Capacity / flow balance constraints: + # sigma_t * sum_j d_j * x_{ij} + I_{it} <= b_{it} + I_{i,t-1} + # with I_{i,0} = 0 + for i in range(m): + for t in range(T): + lhs = gp.LinExpr() + # sigma_t * sum_j d_j * x_{ij} + for j in range(n): + lhs += sigma[t] * demands[j] * x[i, j] + # + I_{it} + lhs += I[i, t] + # RHS: b_{it} + I_{i,t-1} + if t == 0: + rhs = capacities[i][t] # I_{i,0} = 0 + else: + rhs = capacities[i][t] + I[i, t - 1] + model.addConstr(lhs <= rhs, name=f"cap_{i}_{t}") + + # Assignment constraints: sum_i x_{ij} = 1 for all j + for j in range(n): + model.addConstr( + gp.quicksum(x[i, j] for i in range(m)) == 1, + name=f"assign_{j}", + ) + + # ---------------------------------------------------------------- + # Optimize + # ---------------------------------------------------------------- + model.optimize() + + # ---------------------------------------------------------------- + # Extract solution + # ---------------------------------------------------------------- + solution = {} + if model.SolCount > 0: + obj_val = model.ObjVal + solution["objective_value"] = obj_val + + # Extract assignment + assignment = {} + for j in range(n): + for i in range(m): + if x[i, j].X > 0.5: + assignment[str(j)] = i + break + else: + assignment[str(j)] = -1 # should not happen + + solution["assignment"] = assignment + + # Extract inventory levels + inventory = {} + for i in range(m): + inventory[str(i)] = [I[i, t].X for t in range(T)] + solution["inventory"] = inventory + + # Solver status info + solution["status"] = model.Status + solution["mip_gap"] = model.MIPGap if model.Status != GRB.OPTIMAL else 0.0 + solution["runtime"] = model.Runtime + else: + solution["objective_value"] = None + solution["status"] = model.Status + solution["runtime"] = model.Runtime + solution["message"] = "No feasible solution found within time limit." + + # Write solution + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {solution_path}") + if model.SolCount > 0: + print(f"Objective value: {obj_val}") + return solution + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Solve MPSSP (P_0) with Gurobi." + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the JSON file containing the problem instance.", + ) + parser.add_argument( + "--solution_path", + type=str, + default="gurobi_solution_1.json", + help="Path where the final solution JSON file will be written.", + ) + parser.add_argument( + "--time_limit", + type=int, + default=3600, + help="Maximum solver runtime in seconds.", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + solve_mpssp(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/freling2003/gurobi_feasi_result/large_feasi_result_1.json b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freling2003/gurobi_feasi_result/large_feasi_result_2.json b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freling2003/gurobi_feasi_result/large_feasi_result_3.json b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freling2003/gurobi_feasi_result/large_feasi_result_4.json b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freling2003/gurobi_feasi_result/large_feasi_result_5.json b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freling2003/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freling2003/gurobi_feasi_result/tiny_feasi_result.json b/tasks/freling2003/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/freling2003/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/freling2003/gurobi_solution/large_solution_1.json b/tasks/freling2003/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..dc9bd99eb622ed8f9ea2b5016ea79b1010c1c9fe --- /dev/null +++ b/tasks/freling2003/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d325db1d476a6c34f2d1da58da4de127934c9af36de0c774e3cae9ad1fb956f8 +size 3696 diff --git a/tasks/freling2003/gurobi_solution/large_solution_2.json b/tasks/freling2003/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..63aea8bddfddb99c023b2f40286b664c37ba7350 --- /dev/null +++ b/tasks/freling2003/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3ab04c939f9e7476d1fb57e053d412fc4391b17dbb0269434e1b6172e63cbff +size 3667 diff --git a/tasks/freling2003/gurobi_solution/large_solution_3.json b/tasks/freling2003/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6b7a11b12fa6a6f4a601db84d47e13a693e8e653 --- /dev/null +++ b/tasks/freling2003/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab5e947d23a84e32c3985f7111b1c1fca7c3fc32450bbfce854de30c6eb92cfa +size 3728 diff --git a/tasks/freling2003/gurobi_solution/large_solution_4.json b/tasks/freling2003/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..6e65f79e89327d703073e127ea9356d559d55c5d --- /dev/null +++ b/tasks/freling2003/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bfae14402c7a07e9b7fb63e758c928bf2cc982d05abb0454a30446bf11af8ad +size 3606 diff --git a/tasks/freling2003/gurobi_solution/large_solution_5.json b/tasks/freling2003/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5fe26321f5c5c6eeed697cfe51169a13e1478f79 --- /dev/null +++ b/tasks/freling2003/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0c932cdaca1bab60162832c95730d393653f49d6eb0b65c6a2f73f45f76dead +size 3711 diff --git a/tasks/freling2003/gurobi_solution/tiny_solution.json b/tasks/freling2003/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2cf9d2c296fa59136dbe70215a6fd0e7b707ba7c --- /dev/null +++ b/tasks/freling2003/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b48af3852ee93df0d86669bb209dc843ff20827c6c129dd7b0d5c0aa57c6b555 +size 418 diff --git a/tasks/freling2003/gurobi_solution_log/large_log_1.jsonl b/tasks/freling2003/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd31c6e313ced22cc1cc7dd16c910a1fa960a50b --- /dev/null +++ b/tasks/freling2003/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:326e888faf052e0d59bc968de0a162922a31f70da226142606a6a6a54265ac74 +size 756 diff --git a/tasks/freling2003/gurobi_solution_log/large_log_2.jsonl b/tasks/freling2003/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..29160d3381c8d7b09c061786186233346a1e4c12 --- /dev/null +++ b/tasks/freling2003/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5778a8cf9867319c4b9d1f650f0641340182e974a1628951f50f199c54e6ae0 +size 382 diff --git a/tasks/freling2003/gurobi_solution_log/large_log_3.jsonl b/tasks/freling2003/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..06e4228c8cc3d30dbe6bfb415af31a49219303f6 --- /dev/null +++ b/tasks/freling2003/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f955511ad7b1ce95cc70c1b0c1fcad148fb20c4a2c92e602ff4849fa912d66df +size 771 diff --git a/tasks/freling2003/gurobi_solution_log/large_log_4.jsonl b/tasks/freling2003/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9afb60848a24cd2940eba83c3abfbbe3bc909b9b --- /dev/null +++ b/tasks/freling2003/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdab0ae8f12f344444c2e62f450b7c3fdab5d014cb8698c11158da8b0d14c37d +size 662 diff --git a/tasks/freling2003/gurobi_solution_log/large_log_5.jsonl b/tasks/freling2003/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ec68024e38892484112b5c427cd8260cd42a278 --- /dev/null +++ b/tasks/freling2003/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11114b22950c6a26ab29006b13c90af773a9e0cce2992fc3a642015a1535f8da +size 707 diff --git a/tasks/freling2003/gurobi_solution_log/tiny_log.jsonl b/tasks/freling2003/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3d923a7e7dddf4e551e3dcc2a0f3b60b2a96d414 --- /dev/null +++ b/tasks/freling2003/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:077b94a258048df771e480c7d6b23adba2017c62f5ae9dae985124f1eda9af43 +size 47 diff --git a/tasks/freling2003/instance/large_instance_1.json b/tasks/freling2003/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d6c1f91975eeb3128faa336e5a13467be67c8a75 --- /dev/null +++ b/tasks/freling2003/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6172bd6f16de3bcdc5481b9d8c0fd25e80b3a6f1641a122b42ee2ce5da9284c2 +size 264022 diff --git a/tasks/freling2003/instance/large_instance_2.json b/tasks/freling2003/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f67ac199717686121c2fdad5ec6db70e2b50ba76 --- /dev/null +++ b/tasks/freling2003/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a567d75827bed428f8befde4cbf53a102f365d0d8fea739d3c88a448b90e37a7 +size 264128 diff --git a/tasks/freling2003/instance/large_instance_3.json b/tasks/freling2003/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..07108f4d72885f7d3f52a664acaacb0a74d1c4c4 --- /dev/null +++ b/tasks/freling2003/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:291e6e90fe6e3a83f224127cf5913626447e4c6d771444b2d715cbfbbf7ad2df +size 263729 diff --git a/tasks/freling2003/instance/large_instance_4.json b/tasks/freling2003/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..17b63272cc330e6394a4d96fcf6202c891dc3d0b --- /dev/null +++ b/tasks/freling2003/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3b446b36531c9487a89d3c4d3345f372a96bb1e37012490356f045209baac79 +size 263563 diff --git a/tasks/freling2003/instance/large_instance_5.json b/tasks/freling2003/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8eae7b183d2f751c10a9f1ba04308c7c0037e666 --- /dev/null +++ b/tasks/freling2003/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c39b837e1b734f1b3c4227dad7c4328964e99bb3e427d3121f65f2e9d0f3e69 +size 262841 diff --git a/tasks/freling2003/instance/tiny_instance.json b/tasks/freling2003/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..1d57222725e5d70c0f217d070d7bf23612cfc2aa --- /dev/null +++ b/tasks/freling2003/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81f5b4fbd4f7630ef6a669a107bc77c77f33be12c6a4bc362729311e4dc5606e +size 4752 diff --git a/tasks/freling2003/instance_schema.json b/tasks/freling2003/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d98ae1c03e8614f5c25f42bd97ccd55780dc25a4 --- /dev/null +++ b/tasks/freling2003/instance_schema.json @@ -0,0 +1,14 @@ +{ + "parameters": { + "num_facilities": " Number of facilities (combined production plants and warehouses) in the distribution network.", + "num_customers": " Number of customers to be served in the distribution network.", + "num_periods": " Number of time periods in the planning horizon." + }, + "seasonal_factors": " Seasonal demand proportions shared by all customers, determining how each customer's total demand is distributed across periods.", + "facility_locations": " Two-dimensional coordinates of each facility in the service region.", + "customer_locations": " Two-dimensional coordinates of each customer in the service region.", + "demands": " Total demand of each customer over the entire planning horizon.", + "holding_costs": " Per-unit cost of storing inventory at each facility at the end of each period.", + "capacities": " Maximum production capacity available at each facility in each period.", + "transportation_costs": " Cost of supplying each customer from each facility in each period." +} diff --git a/tasks/freling2003/mathematical_formulation.md b/tasks/freling2003/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..2685bac73328f22192ad13c2f918ba95aac929fb --- /dev/null +++ b/tasks/freling2003/mathematical_formulation.md @@ -0,0 +1,42 @@ +# Sets and Parameters + +- $j = 1,\ldots,n$: customers. + +- $i = 1,\ldots,m$: facilities (each is a production plant with associated warehouse). + +- $t = 1,\ldots,T$: time periods in the planning horizon. + +- $d_j$: total demand of customer $j$ over the planning horizon. + +- $\sigma_t$: (nonnegative) seasonal factor for period $t$, with $\sum_{t=1}^{T} \sigma_t = 1$. Customer $j$’s demand in period $t$ equals $\sigma_t \, d_j$. + +- $b_{it}$: production capacity at facility $i$ in period $t$. + +- $c_{ijt}$: cost of supplying customer $j$ by facility $i$ in period $t$. + +- $h_{it}$: unit inventory holding cost at facility $i$ in period $t$. + +All parameters are nonnegative. + +# Decision Variables + +$$\begin{align*} +x_{ij} &\in \{0,1\} && i = 1,\ldots,m;\; j = 1,\ldots,n \quad (\text{1 if customer $j$ is assigned to facility $i$}) \\ +I_{it} &\geq 0 && i = 1,\ldots,m;\; t = 1,\ldots,T \quad (\text{inventory at facility $i$ at the end of period $t$}) +\end{align*}$$ + +# Objective + +$$\begin{equation} +\text{minimize} \quad \sum_{t=1}^{T} \sum_{i=1}^{m} \sum_{j=1}^{n} c_{ijt}\, x_{ij} \;+\; \sum_{t=1}^{T} \sum_{i=1}^{m} h_{it}\, I_{it} \tag{$P_0$} +\end{equation}$$ + +# Constraints + +$$\begin{align} +\sigma_t \sum_{j=1}^{n} d_j\, x_{ij} \;+\; I_{it} &\leq b_{it} + I_{i,t-1}, && i = 1,\ldots,m;\; t = 1,\ldots,T \tag{1} \\ +\sum_{i=1}^{m} x_{ij} &= 1, && j = 1,\ldots,n \notag \\ +x_{ij} &\in \{0,1\}, && i = 1,\ldots,m;\; j = 1,\ldots,n \notag \\ +I_{i0} &= 0, && i = 1,\ldots,m \notag \\ +I_{it} &\geq 0, && i = 1,\ldots,m;\; t = 1,\ldots,T \notag +\end{align}$$ diff --git a/tasks/freling2003/problem_description.txt b/tasks/freling2003/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..ff07947fe1a40e2bfb1766d8ebc1b3b295085527 --- /dev/null +++ b/tasks/freling2003/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A logistics distribution network consists of a set of facilities and a set of customers. Each facility is a combined production plant and warehouse. The number of facilities, the number of customers, and the number of time periods in the planning horizon are all given. Each customer has a known total demand over the entire planning horizon. All customers share a common seasonal demand pattern described by a set of seasonal factors, one per period, that are nonnegative and sum to one. The demand of a given customer in a given period equals that customer's total demand multiplied by the seasonal factor for that period. Each facility has a known production capacity in each period. The cost of supplying a given customer from a given facility in a given period is specified. A unit inventory holding cost is given for each facility in each period. + +Each customer must be assigned to exactly one facility for the entire planning horizon; a customer cannot split its demand across multiple facilities or switch facilities between periods. Each facility may serve any number of customers, as long as its production capacity and inventory levels permit. In each period, the total demand placed on a facility by its assigned customers, plus the inventory held at that facility at the end of that period, must not exceed the facility's production capacity in that period plus the inventory that was held at that facility at the end of the previous period. Every facility begins the planning horizon with zero inventory. Warehouses have unlimited physical storage space and unlimited throughput capacity, so any excess production can always be stored. Products may only be stored at facilities, never at customer locations. + +The goal is to minimize total cost, which is the sum of two components: the total supply cost, obtained by summing over all periods, all facilities, and all customers the supply cost for each customer-facility pair in each period weighted by whether that customer is assigned to that facility, and the total inventory holding cost, obtained by summing over all periods and all facilities the unit holding cost times the amount of product stored at that facility at the end of that period. diff --git a/tasks/freling2003/solution_logger.py b/tasks/freling2003/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/freling2003/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/freling2003/solution_schema.json b/tasks/freling2003/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..34b99b35b4281367931bb6896bef4e18e82b8ab7 --- /dev/null +++ b/tasks/freling2003/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total cost of the solution, combining supply costs across all customer-facility-period triples with inventory holding costs across all facilities and periods.", + "assignment": " Index of the single facility to which each customer is assigned for the entire planning horizon.", + "inventory": " Amount of product held at each facility at the end of each period." +} diff --git a/tasks/frey2017/feasibility_check.py b/tasks/frey2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c3de53e031578d70a6ea186f2175f24522bf3804 --- /dev/null +++ b/tasks/frey2017/feasibility_check.py @@ -0,0 +1,807 @@ +#!/usr/bin/env python3 +""" +Feasibility Checker for the Outbound Baggage Handling Problem (OBHP) +Based on Frey, Kolisch, and Artigues (2017) + +Checks hard constraints (2)-(9) from the TIF formulation: + Constraint (2): Flight assignment - each flight assigned exactly once + Constraint (3): Working station capacity per carousel per period + Constraint (4): Parking position capacity per carousel per period + Constraint (5): Central storage system capacity per period + Constraint (6): Utilization threshold linking constraint + Constraint (7): At most one threshold level per carousel per peak interval + Constraint (8): Binary domain for flight assignment variables x + Constraint (9): Binary domain for threshold violation variables y + Constraint (10): Objective consistency (Tier C anti-gaming check) - + reported objective_value must match the objective (1) + recomputed from the solution's y variables + +Objective (1) is not a hard constraint of the original model, but constraint +(10) below rejects solutions whose self-reported objective_value disagrees +with the value recomputed from the solution variables, defeating LLM +score-gaming exploits that return fabricated objective values. +""" + +import argparse +import json +import math +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', 'objective_value', 'utilization_violations') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('assignments',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +# --------------------------------------------------------------------------- +# Tolerance parameters +# --------------------------------------------------------------------------- +TOL = 1e-5 +EPS = 1e-5 + + +# --------------------------------------------------------------------------- +# Data loading helpers +# --------------------------------------------------------------------------- + +def load_instance(path): + with open(path, 'r') as f: + return json.load(f) + + +def load_solution(path): + with open(path, 'r') as f: + return json.load(f) + + +# --------------------------------------------------------------------------- +# Gamma / Phi computation (Online Appendix B simulation) +# Mirrors compute_gamma_phi in efficient_algorithm.py +# --------------------------------------------------------------------------- + +def compute_gamma_phi(flight, w, s_h, s_d, working_rate, depletion_rate): + """ + Compute Gamma^{i,w}_{t,tau} (belt workload) and Phi^{i}_{t,tau} + (central storage occupancy) for a flight. + + Returns: + gamma: dict {t: bags_on_belt} + phi: dict {t: bags_in_storage} + """ + es = flight['earliest_start_period'] + se = flight['end_period'] + profile = flight['arrival_profile'] + + gamma = {} + phi = {} + + stored = 0 + belt_bags = 0 + + for t in range(es, se): + idx = t - es + arrivals = profile[idx] if 0 <= idx < len(profile) else 0 + + if t < s_h: + stored += arrivals + phi[t] = stored + gamma[t] = 0 + else: + belt_bags += arrivals + if t >= s_d and stored > 0: + depleted = min(stored, depletion_rate) + belt_bags += depleted + stored -= depleted + loaded = min(belt_bags, w * working_rate) + belt_bags -= loaded + gamma[t] = belt_bags + phi[t] = stored + + return gamma, phi + + +# --------------------------------------------------------------------------- +# Build lookup structures from instance +# --------------------------------------------------------------------------- + +def build_carousel_map(instance): + """Return dict {carousel_id: carousel_dict}.""" + return {c['carousel_id']: c for c in instance['carousels']} + + +def build_flight_map(instance): + """Return dict {flight_id: flight_dict}.""" + return {f['flight_id']: f for f in instance['flights']} + + +# --------------------------------------------------------------------------- +# Normalise solution assignment keys across efficient / gurobi formats +# --------------------------------------------------------------------------- + +def normalise_assignment(a): + """Return (flight_id, carousel_id, w, s_h, s_d) regardless of format.""" + fid = a['flight_id'] + cid = a['carousel_id'] + w = a['working_stations'] + s_h = a.get('handling_start', a.get('handling_start_period')) + s_d = a.get('depletion_start', a.get('depletion_start_period')) + return fid, cid, w, s_h, s_d + + +# --------------------------------------------------------------------------- +# Violation recording helpers +# --------------------------------------------------------------------------- + +def make_magnitude(constraint_idx, lhs, rhs, raw_excess): + normalizer = max(abs(rhs), EPS) + return { + 'constraint': constraint_idx, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(raw_excess), + 'normalizer': float(normalizer), + 'ratio': float(raw_excess / normalizer), + } + + +# --------------------------------------------------------------------------- +# Precompute time-dependent storage capacity (Section 3.3 preprocessing) +# --------------------------------------------------------------------------- + +def precompute_storage_capacity(instance): + num_periods = instance['planning_horizon']['num_periods'] + Ks_base = instance['central_storage']['capacity_bags'] + flights = instance['flights'] + + Ks = [Ks_base] * num_periods + for t in range(num_periods): + reserved = 0 + for f in flights: + es = f['earliest_start_period'] + if t < es: + cum = 0 + for idx, bags in enumerate(f['arrival_profile']): + arr_period = es + idx + if arr_period > t: + break + cum += bags + reserved += cum + Ks[t] = max(0, Ks_base - reserved) + return Ks + + +# --------------------------------------------------------------------------- +# Main feasibility checks +# --------------------------------------------------------------------------- + +def check_feasibility(instance, solution): + violations = [] # textual messages + violated_set = set() # constraint indices (unique) + magnitudes = [] # violation magnitude dicts + + # Handle null / infeasible solutions – when the solver found no solution, + # feasibility is indeterminate (null), not false. + status = solution.get("status", solution.get("status_name", "")) + status_lower = str(status).lower() if status else "" + has_no_solution = ( + solution.get("objective_value") is None + or "infeasible" in status_lower + or "no_solution" in status_lower + or (not solution.get("assignments")) + ) + if has_no_solution: + return { + "feasible": None, + "violated_constraints": ["no_solution"], + "violations": ["No feasible solution provided"], + "violation_magnitudes": [], + } + + flights_map = build_flight_map(instance) + carousels_map = build_carousel_map(instance) + + num_periods = instance['planning_horizon']['num_periods'] + working_rate = instance['working_rate_bags_per_period'] + depletion_rate = instance['central_storage']['depletion_rate_bags_per_period'] + depletion_offset = instance['central_storage']['depletion_offset_periods'] + + assignments = solution.get('assignments', []) + + # Normalise assignments + norm_assignments = [] + for a in assignments: + fid, cid, w, s_h, s_d = normalise_assignment(a) + norm_assignments.append((fid, cid, w, s_h, s_d)) + + # ================================================================== + # Constraint (2): Each flight assigned to exactly one configuration + # sum_{c,w,tau} x_{i,c,w,tau} = 1 for all i in F + # ================================================================== + all_flight_ids = set(f['flight_id'] for f in instance['flights']) + assigned_counts = defaultdict(int) + for fid, cid, w, s_h, s_d in norm_assignments: + assigned_counts[fid] += 1 + + # Check: every flight must appear exactly once + for fid in sorted(all_flight_ids): + cnt = assigned_counts.get(fid, 0) + if cnt == 0: + lhs = 0.0 + rhs = 1.0 + excess = abs(lhs - rhs) + if excess > TOL: + violated_set.add(2) + violations.append(f"Constraint (2): Flight {fid} is not assigned (count=0, required=1)") + magnitudes.append(make_magnitude(2, lhs, rhs, excess)) + elif cnt > 1: + lhs = float(cnt) + rhs = 1.0 + excess = abs(lhs - rhs) + if excess > TOL: + violated_set.add(2) + violations.append(f"Constraint (2): Flight {fid} is assigned {cnt} times (required=1)") + magnitudes.append(make_magnitude(2, lhs, rhs, excess)) + + # Also check that each assignment uses a feasible start time tuple and + # valid working station count for the carousel type. These are part of + # the domain of constraint (2) (the sums range only over feasible tuples). + for fid, cid, w, s_h, s_d in norm_assignments: + flight = flights_map.get(fid) + car = carousels_map.get(cid) + if flight is None or car is None: + continue + + tr = str(car['type_r']) + ws_bounds = flight.get('working_station_bounds_by_carousel_type', {}).get(tr) + + # Check working station bounds + if ws_bounds is not None: + wmin = ws_bounds['Wmin'] + wmax = ws_bounds['Wmax'] + if w < wmin or w > wmax: + # working station count out of range – this means the + # assignment uses an (i,c,w) combination for which no + # x variable exists → violates constraint (2) + lhs_val = float(w) + rhs_val = float(wmax) # use upper bound for normalisation + excess = 0.0 + if w < wmin: + excess = float(wmin - w) + rhs_val = float(wmin) + else: + excess = float(w - wmax) + rhs_val = float(wmax) + if excess > TOL: + violated_set.add(2) + violations.append( + f"Constraint (2): Flight {fid} on carousel {cid}: " + f"working stations w={w} outside [{wmin},{wmax}] for type {tr}" + ) + magnitudes.append(make_magnitude(2, lhs_val, rhs_val, excess)) + + # Check handling start within time window + es = flight['earliest_start_period'] + ls = flight['latest_start_period'] + if s_h < es or s_h > ls: + excess = 0.0 + if s_h < es: + excess = float(es - s_h) + rhs_val = float(es) + else: + excess = float(s_h - ls) + rhs_val = float(ls) + if excess > TOL: + violated_set.add(2) + violations.append( + f"Constraint (2): Flight {fid}: handling_start={s_h} " + f"outside window [{es},{ls}]" + ) + magnitudes.append(make_magnitude(2, float(s_h), rhs_val, excess)) + + # Check depletion start feasibility: s_h <= s_d < S^e_i - depletion_offset + se = flight['end_period'] + s_d_max = se - depletion_offset - 1 + if s_d < s_h: + excess = float(s_h - s_d) + if excess > TOL: + violated_set.add(2) + violations.append( + f"Constraint (2): Flight {fid}: depletion_start={s_d} < handling_start={s_h}" + ) + magnitudes.append(make_magnitude(2, float(s_d), float(s_h), excess)) + if s_d > s_d_max: + excess = float(s_d - s_d_max) + if excess > TOL: + violated_set.add(2) + violations.append( + f"Constraint (2): Flight {fid}: depletion_start={s_d} > max allowed {s_d_max} " + f"(end_period={se}, depletion_offset={depletion_offset})" + ) + magnitudes.append(make_magnitude(2, float(s_d), float(s_d_max), excess)) + + # ================================================================== + # Constraint (3): Working station capacity per carousel per period + # sum_{eligible i} sum_w sum_tau w * x_{i,c,w,tau} <= K^ws_r + # for all r, c in C_r, t in T (only when s_h <= t and S^es_i <= t < S^e_i) + # ================================================================== + + # Group assignments by carousel + carousel_assignments = defaultdict(list) + for fid, cid, w, s_h, s_d in norm_assignments: + carousel_assignments[cid].append((fid, w, s_h, s_d)) + + for car in instance['carousels']: + cid = car['carousel_id'] + type_data = instance['carousel_types'][str(car['type_r'])] + Kws = type_data['Kws'] + assigns = carousel_assignments.get(cid, []) + if not assigns: + continue + + for t in range(num_periods): + ws_sum = 0 + for fid, w, s_h, s_d in assigns: + flight = flights_map.get(fid) + if flight is None: + continue + es = flight['earliest_start_period'] + se = flight['end_period'] + if es <= t < se and s_h <= t: + ws_sum += w + lhs = float(ws_sum) + rhs = float(Kws) + excess = lhs - rhs + if excess > TOL: + violated_set.add(3) + violations.append( + f"Constraint (3): Carousel {cid}, period {t}: " + f"working station usage {ws_sum} exceeds capacity {Kws}" + ) + magnitudes.append(make_magnitude(3, lhs, rhs, excess)) + + # ================================================================== + # Constraint (4): Parking position capacity per carousel per period + # sum_{eligible i} sum_w sum_tau P_i * x_{i,c,w,tau} <= K^pp_r + # for all r, c in C_r, t in T (only when s_h <= t and S^es_i <= t < S^e_i) + # ================================================================== + + for car in instance['carousels']: + cid = car['carousel_id'] + type_data = instance['carousel_types'][str(car['type_r'])] + Kpp = type_data['Kpp'] + assigns = carousel_assignments.get(cid, []) + if not assigns: + continue + + for t in range(num_periods): + pp_sum = 0 + for fid, w, s_h, s_d in assigns: + flight = flights_map.get(fid) + if flight is None: + continue + es = flight['earliest_start_period'] + se = flight['end_period'] + if es <= t < se and s_h <= t: + pp_sum += flight['num_containers'] + lhs = float(pp_sum) + rhs = float(Kpp) + excess = lhs - rhs + if excess > TOL: + violated_set.add(4) + violations.append( + f"Constraint (4): Carousel {cid}, period {t}: " + f"parking positions {pp_sum} exceeds capacity {Kpp}" + ) + magnitudes.append(make_magnitude(4, lhs, rhs, excess)) + + # ================================================================== + # Constraint (5): Central storage system capacity per period + # sum_{eligible i} sum_c sum_w sum_tau Phi^i_{t,tau} * x_{i,c,w,tau} <= K^s_t + # for all t in T + # ================================================================== + + storage_cap = precompute_storage_capacity(instance) + + for t in range(num_periods): + total_phi = 0.0 + for fid, cid, w, s_h, s_d in norm_assignments: + flight = flights_map.get(fid) + if flight is None: + continue + es = flight['earliest_start_period'] + se = flight['end_period'] + if not (es <= t < se): + continue + _, phi = compute_gamma_phi(flight, w, s_h, s_d, + working_rate, depletion_rate) + total_phi += phi.get(t, 0) + + lhs = float(total_phi) + rhs = float(storage_cap[t]) + excess = lhs - rhs + if excess > TOL: + violated_set.add(5) + violations.append( + f"Constraint (5): Period {t}: central storage usage " + f"{total_phi:.1f} exceeds capacity {storage_cap[t]:.1f}" + ) + magnitudes.append(make_magnitude(5, lhs, rhs, excess)) + + # ================================================================== + # Constraint (6): Utilization threshold linking constraint + # (1/K^cb_r) * sum Gamma * x - sum_k u_k * y_{c,k,m} <= u^ta + # for all r, c in C_r, 1 <= m <= M, t in T_m + # ================================================================== + peak_intervals = instance.get('peak_intervals', []) + obj_data = instance.get('objective', {}) + threshold_values = obj_data.get('threshold_values', []) + u_ta = float(obj_data.get('target_utilization', 0.0)) + + y_set = set() + for viol in solution.get('utilization_violations') or []: + y_set.add((viol['carousel_id'], + viol['threshold_level'] - 1, + viol['peak_interval'] - 1)) + + for m_idx, peak in enumerate(peak_intervals): + t_start = peak['start_period'] + t_end = peak['end_period'] + for car in instance['carousels']: + cid = car['carousel_id'] + type_data = instance['carousel_types'][str(car['type_r'])] + Kcb = type_data.get('Kcb') + if not Kcb: + continue + assigns = carousel_assignments.get(cid, []) + for t in range(t_start, t_end + 1): + total_gamma = 0.0 + for fid, w, s_h, s_d in assigns: + flight = flights_map.get(fid) + if flight is None: + continue + es = flight['earliest_start_period'] + se = flight['end_period'] + if not (es <= t < se) or s_h > t: + continue + gamma, _ = compute_gamma_phi( + flight, w, s_h, s_d, + working_rate, depletion_rate) + total_gamma += gamma.get(t, 0) + y_sum = sum(threshold_values[k] + for k in range(len(threshold_values)) + if (cid, k, m_idx) in y_set) + lhs = (total_gamma / Kcb) - y_sum + excess = lhs - u_ta + if excess > TOL: + violated_set.add(6) + violations.append( + f"Constraint (6): Carousel {cid}, peak " + f"{m_idx + 1}, period {t}: util " + f"{total_gamma / Kcb:.4f} - slack " + f"{y_sum:.4f} > u_ta={u_ta} by {excess:.4f}") + magnitudes.append( + make_magnitude(6, lhs, u_ta, excess)) + + # ================================================================== + # Constraint (7): At most one threshold level per carousel per peak + # sum_k y_{c,k,m} <= 1 for all c in C, 1 <= m <= M + # ================================================================== + for car in instance['carousels']: + cid = car['carousel_id'] + for m_idx in range(len(peak_intervals)): + y_count = sum(1 for k in range(len(threshold_values)) + if (cid, k, m_idx) in y_set) + if y_count > 1: + excess = float(y_count - 1) + violated_set.add(7) + violations.append( + f"Constraint (7): Carousel {cid}, peak " + f"{m_idx + 1}: {y_count} threshold levels " + f"activated (max 1)") + magnitudes.append( + make_magnitude(7, float(y_count), 1.0, excess)) + + # ================================================================== + # Constraint (8): Binary domain for x_{i,c,w,tau} + # Each assignment implicitly sets x=1; verify integer values and + # uniqueness of (flight, carousel, w, tau) combinations. + # ================================================================== + for fid, cid, w, s_h, s_d in norm_assignments: + for name, val in (('working_stations', w), + ('handling_start', s_h), + ('depletion_start', s_d)): + if val is None: + continue + fval = float(val) + excess = abs(fval - round(fval)) + if excess > TOL: + violated_set.add(8) + violations.append( + f"Constraint (8): Flight {fid}: non-integer " + f"{name}={val} (x must be binary)") + magnitudes.append( + make_magnitude(8, fval, float(round(fval)), excess)) + + x_key_counts = defaultdict(int) + for fid, cid, w, s_h, s_d in norm_assignments: + x_key_counts[(fid, cid, w, s_h, s_d)] += 1 + for key, cnt in x_key_counts.items(): + if cnt > 1: + excess = float(cnt - 1) + violated_set.add(8) + violations.append( + f"Constraint (8): x for {key} selected {cnt} times " + f"(must be binary)") + magnitudes.append( + make_magnitude(8, float(cnt), 1.0, excess)) + + # ================================================================== + # Constraint (9): Binary domain for y_{c,k,m} + # Each utilization_violation entry implicitly sets y=1; verify no + # (carousel, k, m) duplicates. + # ================================================================== + y_key_counts = defaultdict(int) + for viol in solution.get('utilization_violations') or []: + y_key_counts[(viol['carousel_id'], + viol['threshold_level'] - 1, + viol['peak_interval'] - 1)] += 1 + for key, cnt in y_key_counts.items(): + if cnt > 1: + excess = float(cnt - 1) + violated_set.add(9) + violations.append( + f"Constraint (9): y for {key} selected {cnt} times " + f"(must be binary)") + magnitudes.append( + make_magnitude(9, float(cnt), 1.0, excess)) + + # ================================================================== + # Constraint (10): Objective consistency (Tier C anti-gaming check) + # Recompute objective (1): sum_{c} sum_{k} sum_{m} p_k * y_{c,k,m} + # Every utilization_violations entry is exactly one activated + # y_{c,k,m}=1, and the penalty p_k equals penalties[k-1] (threshold_level + # is 1-indexed -- the same 1->0 offset the constraint (6)/(9) blocks use). + # The objective depends ONLY on the y variables, ALL of which are carried + # in the solution -> a full exact recompute applies (no second-stage + # variables, no LP subproblem). Reject when the self-reported + # objective_value disagrees with the recomputed value. + # ================================================================== + penalties = obj_data.get('penalties') + reported_obj = solution.get('objective_value') + if penalties is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + recompute_ok = True + for viol in solution.get('utilization_violations') or []: + try: + k = int(viol['threshold_level']) + except (TypeError, ValueError, KeyError): + # malformed y entry -- domain checks (9) cover this; + # skip the obj recompute rather than crash. + recompute_ok = False + break + if 1 <= k <= len(penalties): + true_obj += float(penalties[k - 1]) + else: + # threshold level outside the penalty table -> cannot + # recompute reliably; defer to constraint (6)/(9). + recompute_ok = False + break + if recompute_ok: + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_set.add(10) + violations.append( + f"Constraint (10): Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed sum_(c,k,m) p_k*y_(c,k,m)={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={tol:.3g})") + magnitudes.append( + make_magnitude(10, reported, true_obj, abs_diff)) + + # ================================================================== + # Build result + # ================================================================== + feasible = len(violated_set) == 0 + result = { + 'feasible': feasible, + 'violated_constraints': sorted(violated_set), + 'violations': violations, + 'violation_magnitudes': magnitudes, + } + return result + + +# --------------------------------------------------------------------------- +# CLI entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description='Feasibility checker for OBHP (Frey et al. 2017)' + ) + parser.add_argument('--instance_path', type=str, required=True, + help='Path to instance JSON file') + parser.add_argument('--solution_path', type=str, required=True, + help='Path to solution JSON file') + parser.add_argument('--result_path', type=str, required=True, + help='Path to write feasibility result JSON file') + args = parser.parse_args() + + instance = load_instance(args.instance_path) + solution = load_solution(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result['feasible'] is None: + tag = "INDETERMINATE (no solution)" + elif result['feasible']: + tag = "FEASIBLE" + else: + tag = "INFEASIBLE" + n_violated = len(result['violated_constraints']) + print(f"[{tag}] {n_violated} constraint(s) violated, " + f"{len(result['violation_magnitudes'])} violation instance(s).") + + +if __name__ == '__main__': + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/frey2017/gurobi_code.py b/tasks/frey2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..04cea17d3f90bc738f140b198880c530742d8d85 --- /dev/null +++ b/tasks/frey2017/gurobi_code.py @@ -0,0 +1,960 @@ +""" +Gurobi implementation of the Time-Indexed Formulation (TIF) for the +Outbound Baggage Handling Problem (OBHP). + +Reference: Frey, Kolisch, and Artigues (2017) +"Column Generation for Outbound Baggage Handling at Airports" +Transportation Science, Articles in Advance, pp. 1-16. + +The TIF assigns flights to carousels and schedules baggage handling +to minimize utilization peaks across peak intervals. The formulation +consists of: + - Objective (1): minimize penalty-weighted threshold violations + - Constraint (2): each flight assigned exactly once + - Constraint (3): working station capacity per carousel per period + - Constraint (4): parking position capacity per carousel per period + - Constraint (5): central storage capacity per period (preprocessed) + - Constraint (6): utilization threshold linking constraints + - Constraint (7): at most one threshold level per carousel per peak interval + - Constraints (8)-(9): binary domains + +ASSUMPTIONS: + - The arrival_profile for flight i gives arrivals starting at earliest_start_period. + i.e., A_{i, earliest_start_period + j} = arrival_profile[j]. + - Peak interval ranges are inclusive: [start_period, end_period]. + - The depletion offset Delta is taken from the instance JSON field + central_storage.depletion_offset_periods. + - Constraint (5) uses the baseline constant storage capacity K^s + (Section 3.1, eq. (5) of the paper). + - For constraints (3) and (4), a flight occupies a carousel during + periods [s^h_tau, S^e_i - 1] (i.e., from handling start to one period + before the end time). + - S_i(w) = S_i for all w, meaning the set of feasible start time tuples + does not depend on w (consistent with the paper's description where + the tuple tau = depends only on timing, not workers). + - For constraint (5), Phi^i_{t,tau} does not depend on carousel c or + working stations w. We use auxiliary variables z_{i,tau} = sum_c sum_w + x_{i,c,w,tau} to avoid expanding over carousels in this constraint, + which dramatically reduces the number of nonzeros. +""" + +import json +import argparse +import sys +import time +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +# ============================================================================= +# DATA LOADING AND PARSING +# ============================================================================= + +def load_instance(path): + """Load an OBHP instance from a JSON file.""" + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + + +def parse_instance(inst): + """ + Parse the instance JSON into structured data. + + Returns a dict with all sets, parameters, and derived data needed + for the TIF formulation. + """ + data = {} + + # Planning horizon + T = inst["planning_horizon"]["num_periods"] + data["T"] = T + + # Objective parameters + obj = inst["objective"] + data["u_ta"] = obj["target_utilization"] + data["threshold_values"] = obj["threshold_values"] # u_1, ..., u_K + data["penalties"] = obj["penalties"] # p_1, ..., p_K + K = len(data["threshold_values"]) + data["K"] = K + + # Peak intervals (M disjoint peak intervals) + peak_intervals = inst["peak_intervals"] + data["peak_intervals"] = peak_intervals + data["M"] = len(peak_intervals) + + # Central storage + cs = inst["central_storage"] + data["Ks"] = cs["capacity_bags"] + data["depletion_rate"] = cs["depletion_rate_bags_per_period"] + data["depletion_offset"] = cs["depletion_offset_periods"] + + # Working rate + data["working_rate"] = inst["working_rate_bags_per_period"] + + # Carousels + carousels = inst["carousels"] + data["carousels"] = carousels + data["num_carousels"] = len(carousels) + data["carousel_types"] = inst["carousel_types"] + + # Build carousel type -> carousel list mapping + Cr = defaultdict(list) # type_r -> list of carousel indices (0-based) + for idx, car in enumerate(carousels): + Cr[str(car["type_r"])].append(idx) + data["Cr"] = Cr + + # Build set of all carousel types present + data["R"] = sorted(Cr.keys()) + + # Flights + flights = inst["flights"] + data["flights"] = flights + data["num_flights"] = len(flights) + + return data + + +# ============================================================================= +# PREPROCESSING (Section 3.3) +# ============================================================================= + +def preprocess_storage_capacity(data): + """ + Compute time-dependent storage capacity K^s_t for constraint (5). + + K^s_t = K^s - sum_{i in F : t < S^es_i} (arrivals of i up to time t) + + This tightens the storage capacity by accounting for bags that are + guaranteed to be in storage at time t because their flights' handling + has not yet started and bags have already arrived. + """ + T = data["T"] + flights = data["flights"] + Ks_base = data["Ks"] + + # Precompute cumulative arrivals for each flight up to each period + # Only relevant for flights whose earliest start is in the future at time t + Ks_t = [Ks_base] * T + + for flight in flights: + S_es = flight["earliest_start_period"] + profile = flight["arrival_profile"] + earliest = flight["earliest_start_period"] + + # Compute cumulative arrivals of this flight at each period + cum_arr = 0 + for j in range(len(profile)): + arr_period = earliest + j + if arr_period >= T: + break + cum_arr += profile[j] + # For any t in [arr_period, S_es - 1], this flight has + # cum_arr bags guaranteed in storage + if arr_period < S_es: + # These bags are guaranteed to be in storage from arr_period + # until at least S_es - 1 + for t in range(arr_period, S_es): + if t < T: + Ks_t[t] -= profile[j] + + # The above double-counts. Let me redo this more carefully. + # Reset and recompute properly + Ks_t = [Ks_base] * T + for t in range(T): + reserved = 0 + for flight in flights: + S_es = flight["earliest_start_period"] + if t < S_es: + # This flight's handling hasn't started at time t. + # Count all arrivals of this flight up to and including time t. + profile = flight["arrival_profile"] + earliest = flight["earliest_start_period"] + cum = 0 + for j in range(len(profile)): + arr_period = earliest + j + if arr_period > t: + break + cum += profile[j] + reserved += cum + Ks_t[t] = max(Ks_base - reserved, 0) + + return Ks_t + + +def preprocess_tighten_start_times(data): + """ + Preprocessing from Section 3.3: + 1. Tighten earliest start time: if no bags have arrived by S^es_i, + shift it forward to the first period with arrivals. + + Modifies flights in-place and returns the updated data. + """ + flights = data["flights"] + + for flight in flights: + profile = flight["arrival_profile"] + earliest = flight["earliest_start_period"] + + # Tighten earliest start: shift forward if no bags have arrived + cumulative = 0 + new_earliest = earliest + for j in range(len(profile)): + arr_period = earliest + j + cumulative += profile[j] + if cumulative > 0: + new_earliest = min(arr_period, flight["latest_start_period"]) + break + + if new_earliest > flight["earliest_start_period"]: + flight["earliest_start_period"] = new_earliest + + return data + + +# ============================================================================= +# FEASIBLE START TIME TUPLES +# ============================================================================= + +def generate_feasible_tuples(flight, data): + """ + Generate all feasible start time tuples tau = (s_h, s_d) for a flight. + + A tuple is feasible iff: + - s_h in [S^es_i, S^ls_i] + - s_h <= s_d + - s_d < S^e_i - Delta (depletion must finish before end) + + Returns: + list of (s_h, s_d) tuples + """ + S_es = flight["earliest_start_period"] + S_ls = flight["latest_start_period"] + S_e = flight["end_period"] + Delta = data["depletion_offset"] + + tuples = [] + s_d_max = S_e - Delta - 1 + for s_h in range(S_es, S_ls + 1): + for s_d in range(s_h, s_d_max + 1): + tuples.append((s_h, s_d)) + + return tuples + + +# ============================================================================= +# DERIVED PARAMETERS: Gamma and Phi (Online Appendix B) +# ============================================================================= + +def compute_gamma(flight, w, tau, data): + """ + Compute Gamma^{i,w}_{t,tau}: workload on carousel during each period. + + The workload is the number of bags on the conveyor belt at the end of + each period t, given: + - w working stations (loading rate = w * working_rate bags/period) + - start time tuple tau = (s_h, s_d) + + Returns: + dict mapping period t -> workload value (only non-zero entries) + """ + s_h, s_d = tau + S_e = flight["end_period"] + profile = flight["arrival_profile"] + earliest = flight["earliest_start_period"] + working_rate = data["working_rate"] + depletion_rate = data["depletion_rate"] + + gamma = {} + + # Compute stored bags accumulated before handling starts + stored_bags = 0 + for j in range(len(profile)): + arr_period = earliest + j + if arr_period < s_h: + stored_bags += profile[j] + else: + break # profile starts at earliest, periods are contiguous + + # Simulate period by period from s_h to S_e - 1 + bags_on_belt = 0 + for t in range(s_h, S_e): + # New arrivals directly to carousel + arr_idx = t - earliest + if 0 <= arr_idx < len(profile): + bags_on_belt += profile[arr_idx] + + # Storage depletion + if t >= s_d and stored_bags > 0: + depleted = min(stored_bags, depletion_rate) + bags_on_belt += depleted + stored_bags -= depleted + + # Workers load bags into containers + loaded = min(bags_on_belt, w * working_rate) + bags_on_belt -= loaded + + if bags_on_belt > 0: + gamma[t] = bags_on_belt + + return gamma + + +def compute_phi(flight, tau, data): + """ + Compute Phi^{i}_{t,tau}: amount of flight i's baggage in central + storage during each period t. + + Returns: + dict mapping period t -> storage occupancy value (only non-zero entries) + """ + s_h, s_d = tau + profile = flight["arrival_profile"] + earliest = flight["earliest_start_period"] + S_e = flight["end_period"] + depletion_rate = data["depletion_rate"] + + phi = {} + stored_bags = 0 + + # Only iterate over the relevant range of periods + # Bags accumulate from earliest to s_h-1, then deplete from s_d onward + first_period = earliest + # Storage is empty once fully depleted; worst case is a bit after S_e + last_period = S_e + 20 # generous upper bound + last_period = min(last_period, data["T"]) + + for t in range(first_period, last_period): + # Arrivals that go to storage (only before handling starts) + arr_idx = t - earliest + if 0 <= arr_idx < len(profile) and t < s_h: + stored_bags += profile[arr_idx] + + # Depletion from storage to carousel + if t >= s_d and stored_bags > 0: + depleted = min(stored_bags, depletion_rate) + stored_bags -= depleted + + if stored_bags > 0: + phi[t] = stored_bags + elif t > s_d and stored_bags == 0: + break # Once depleted, storage stays at 0 + + return phi + + +# ============================================================================= +# MODEL BUILDING +# ============================================================================= + +def build_model(data, time_limit=3600): + """ + Build the Gurobi MIP model for the TIF formulation. + + Uses index structures to efficiently generate constraints, and introduces + auxiliary z_{i,tau} variables to reduce the size of constraint (5). + + Returns: + model: gurobipy.Model object + x_vars: dict mapping (i, c, w, tau_idx) -> gurobi variable + y_vars: dict mapping (c, k, m) -> gurobi variable + flight_tuples: dict mapping flight_index -> list of (s_h, s_d) + flight_w_range: dict mapping (flight_index, type_str) -> (Wmin, Wmax) + """ + T = data["T"] + flights = data["flights"] + carousels = data["carousels"] + num_flights = data["num_flights"] + num_carousels = data["num_carousels"] + K = data["K"] + M = data["M"] + u_ta = data["u_ta"] + threshold_values = data["threshold_values"] + penalties = data["penalties"] + peak_intervals = data["peak_intervals"] + Cr = data["Cr"] + R = data["R"] + carousel_types = data["carousel_types"] + + # ========================================================================= + # STEP 1: Precompute feasible tuples for each flight + # ========================================================================= + print("Precomputing feasible start time tuples...") + flight_tuples = {} + for i, flight in enumerate(flights): + flight_tuples[i] = generate_feasible_tuples(flight, data) + if len(flight_tuples[i]) == 0: + print(f" WARNING: Flight {flight['flight_id']} has no feasible " + f"start time tuples!") + + total_tuples = sum(len(v) for v in flight_tuples.values()) + print(f" Total tuples across all flights: {total_tuples}") + + # ========================================================================= + # STEP 2: Precompute working station ranges per flight per carousel type + # ========================================================================= + flight_w_range = {} # (flight_idx, type_str) -> (Wmin, Wmax) + for i, flight in enumerate(flights): + ws_bounds = flight["working_station_bounds_by_carousel_type"] + for type_str in R: + if type_str in ws_bounds: + wmin = ws_bounds[type_str]["Wmin"] + wmax = ws_bounds[type_str]["Wmax"] + flight_w_range[(i, type_str)] = (wmin, wmax) + + # ========================================================================= + # STEP 3: Precompute Gamma and Phi + # ========================================================================= + print("Precomputing Gamma (workload) and Phi (storage) parameters...") + gamma_vals = {} # (i, w, tau_idx) -> {t: workload} + phi_vals = {} # (i, tau_idx) -> {t: storage} + total_combos = 0 + + for i, flight in enumerate(flights): + tuples = flight_tuples[i] + + # Determine all w values needed for this flight + w_values = set() + for type_str in R: + if (i, type_str) in flight_w_range: + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + w_values.add(w) + + for tau_idx, tau in enumerate(tuples): + phi_vals[(i, tau_idx)] = compute_phi(flight, tau, data) + for w in w_values: + gamma_vals[(i, w, tau_idx)] = compute_gamma( + flight, w, tau, data + ) + total_combos += 1 + + print(f" Total (flight, w, tau) combinations: {total_combos}") + + # ========================================================================= + # STEP 5: Build index structures for efficient constraint generation + # ========================================================================= + print("Building index structures...") + + # For each period t, which flights could be active (S_es_i <= t < S_e_i)? + flights_active_at = defaultdict(list) # t -> list of flight indices + for i, flight in enumerate(flights): + S_es = flight["earliest_start_period"] + S_e = flight["end_period"] + for t in range(S_es, S_e): + flights_active_at[t].append(i) + + # For each (flight, tau_idx), which periods have s_h_tau <= t? + # We store tuples sorted by s_h so we can binary-search later, + # but for simplicity we just iterate. + + # ========================================================================= + # STEP 6: Create Gurobi model + # ========================================================================= + print("Building Gurobi model...") + model = gp.Model("OBHP_TIF") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + # Setting NumericFocus due to large penalty coefficients + model.setParam("NumericFocus", 1) + + # ---- Decision variables x_{i,c,w,tau_idx} ---- + x_vars = {} + num_x = 0 + for i in range(num_flights): + tuples = flight_tuples[i] + num_tau = len(tuples) + for c_idx in range(num_carousels): + type_str = str(carousels[c_idx]["type_r"]) + if (i, type_str) not in flight_w_range: + continue + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + for tau_idx in range(num_tau): + x_vars[(i, c_idx, w, tau_idx)] = model.addVar( + vtype=GRB.BINARY, + name=f"x_{i}_{c_idx}_{w}_{tau_idx}" + ) + num_x += 1 + + # ---- Decision variables y_{c,k,m} ---- + y_vars = {} + num_y = num_carousels * K * M + for c_idx in range(num_carousels): + for k in range(K): + for m_idx in range(M): + y_vars[(c_idx, k, m_idx)] = model.addVar( + vtype=GRB.BINARY, + name=f"y_{c_idx}_{k}_{m_idx}" + ) + + # ---- Auxiliary variables z_{i,tau_idx} for constraint (5) ---- + # z_{i,tau_idx} = sum_c sum_w x_{i,c,w,tau_idx} + # This aggregates over carousels and working stations, since Phi + # does not depend on c or w. This reduces constraint (5) from + # O(F * C * W * tau) nonzeros per period to O(F * tau) nonzeros. + z_vars = {} + for i in range(num_flights): + for tau_idx in range(len(flight_tuples[i])): + z_vars[(i, tau_idx)] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0.0, ub=1.0, + name=f"z_{i}_{tau_idx}" + ) + + model.update() + print(f" Variables: {num_x} x-vars, {num_y} y-vars, " + f"{len(z_vars)} z-vars (auxiliary)") + + # ========================================================================= + # OBJECTIVE (1) + # ========================================================================= + obj_expr = gp.LinExpr() + for c_idx in range(num_carousels): + for k in range(K): + for m_idx in range(M): + obj_expr.addTerms(penalties[k], y_vars[(c_idx, k, m_idx)]) + model.setObjective(obj_expr, GRB.MINIMIZE) + + # ========================================================================= + # CONSTRAINT (2): Each flight assigned exactly once + # sum_c sum_w sum_tau x_{i,c,w,tau} = 1 for all i + # ========================================================================= + print(" Adding constraint (2): flight assignment...") + for i in range(num_flights): + tuples = flight_tuples[i] + lhs = gp.LinExpr() + for c_idx in range(num_carousels): + type_str = str(carousels[c_idx]["type_r"]) + if (i, type_str) not in flight_w_range: + continue + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + for tau_idx in range(len(tuples)): + lhs.addTerms(1.0, x_vars[(i, c_idx, w, tau_idx)]) + model.addConstr(lhs == 1, name=f"assign_{i}") + + # ========================================================================= + # LINKING CONSTRAINTS for z variables + # z_{i,tau_idx} = sum_c sum_w x_{i,c,w,tau_idx} + # ========================================================================= + print(" Adding z-variable linking constraints...") + for i in range(num_flights): + tuples = flight_tuples[i] + for tau_idx in range(len(tuples)): + lhs = gp.LinExpr() + lhs.addTerms(-1.0, z_vars[(i, tau_idx)]) + for c_idx in range(num_carousels): + type_str = str(carousels[c_idx]["type_r"]) + if (i, type_str) not in flight_w_range: + continue + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + lhs.addTerms(1.0, x_vars[(i, c_idx, w, tau_idx)]) + model.addConstr(lhs == 0, name=f"link_z_{i}_{tau_idx}") + + # ========================================================================= + # CONSTRAINT (3): Working station capacity + # sum_{applicable i,w,tau: s_h<=t} w * x_{i,c,w,tau} <= K^ws_r + # for all r, c in C_r, t + # ========================================================================= + print(" Adding constraint (3): working station capacity...") + num_ws_constrs = 0 + for type_str in R: + Kws_r = carousel_types[type_str]["Kws"] + c_indices = Cr[type_str] + + for t in range(T): + # Collect the terms that apply for this type and period + # (shared across all carousels of this type) + terms = [] # list of (i, w, tau_idx, coeff=w) + for i in flights_active_at.get(t, []): + if (i, type_str) not in flight_w_range: + continue + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + for tau_idx, (s_h, _) in enumerate(flight_tuples[i]): + if s_h <= t: + terms.append((i, w, tau_idx)) + + if not terms: + continue + + # Add one constraint per carousel of this type + for c_idx in c_indices: + lhs = gp.LinExpr() + for (i, w, tau_idx) in terms: + lhs.addTerms(float(w), + x_vars[(i, c_idx, w, tau_idx)]) + model.addConstr(lhs <= Kws_r, + name=f"ws_{type_str}_{c_idx}_{t}") + num_ws_constrs += 1 + print(f" {num_ws_constrs} constraints added") + + # ========================================================================= + # CONSTRAINT (4): Parking position capacity + # sum_{applicable i,w,tau: s_h<=t} P_i * x_{i,c,w,tau} <= K^pp_r + # for all r, c in C_r, t + # ========================================================================= + print(" Adding constraint (4): parking position capacity...") + num_pp_constrs = 0 + for type_str in R: + Kpp_r = carousel_types[type_str]["Kpp"] + c_indices = Cr[type_str] + + for t in range(T): + terms = [] # list of (i, w, tau_idx, P_i) + for i in flights_active_at.get(t, []): + if (i, type_str) not in flight_w_range: + continue + P_i = flights[i]["num_containers"] + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + for tau_idx, (s_h, _) in enumerate(flight_tuples[i]): + if s_h <= t: + terms.append((i, w, tau_idx, P_i)) + + if not terms: + continue + + for c_idx in c_indices: + lhs = gp.LinExpr() + for (i, w, tau_idx, P_i) in terms: + lhs.addTerms(float(P_i), + x_vars[(i, c_idx, w, tau_idx)]) + model.addConstr(lhs <= Kpp_r, + name=f"pp_{type_str}_{c_idx}_{t}") + num_pp_constrs += 1 + print(f" {num_pp_constrs} constraints added") + + # ========================================================================= + # CONSTRAINT (5): Central storage capacity (using z-variables) + # sum_i sum_tau Phi^i_{t,tau} * z_{i,tau} <= K^s_t for all t + # ========================================================================= + print(" Adding constraint (5): central storage capacity...") + num_stor_constrs = 0 + for t in range(T): + lhs = gp.LinExpr() + has_terms = False + for i in range(num_flights): + for tau_idx in range(len(flight_tuples[i])): + phi_t = phi_vals[(i, tau_idx)].get(t, 0) + if phi_t > 0: + lhs.addTerms(float(phi_t), z_vars[(i, tau_idx)]) + has_terms = True + if has_terms: + model.addConstr(lhs <= data["Ks"], name=f"stor_{t}") + num_stor_constrs += 1 + print(f" {num_stor_constrs} constraints added") + + # ========================================================================= + # CONSTRAINT (6): Utilization threshold + # (1/K^cb_r) * sum_{applicable i,w,tau} Gamma * x_{i,c,w,tau} + # - sum_k u_k * y_{c,k,m} <= u^ta + # for all r, c in C_r, m, t in T_m + # ========================================================================= + print(" Adding constraint (6): utilization threshold...") + num_util_constrs = 0 + for type_str in R: + Kcb_r = carousel_types[type_str]["Kcb"] + inv_Kcb = 1.0 / Kcb_r + c_indices = Cr[type_str] + + for m_idx, peak in enumerate(peak_intervals): + t_start = peak["start_period"] + t_end = peak["end_period"] + + for t in range(t_start, t_end + 1): + # Collect gamma terms for this type and period + terms = [] # list of (i, w, tau_idx, gamma_coeff) + for i in flights_active_at.get(t, []): + if (i, type_str) not in flight_w_range: + continue + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + for tau_idx in range(len(flight_tuples[i])): + gamma_t = gamma_vals[(i, w, tau_idx)].get(t, 0) + if gamma_t > 0: + terms.append( + (i, w, tau_idx, gamma_t * inv_Kcb) + ) + + # Build y-term (same for all carousels of this type) + # This is subtracted: - sum_k u_k * y_{c,k,m} + + for c_idx in c_indices: + lhs = gp.LinExpr() + for (i, w, tau_idx, coeff) in terms: + lhs.addTerms(coeff, + x_vars[(i, c_idx, w, tau_idx)]) + for k in range(K): + lhs.addTerms(-threshold_values[k], + y_vars[(c_idx, k, m_idx)]) + model.addConstr(lhs <= u_ta, + name=f"util_{type_str}_{c_idx}_{m_idx}_{t}") + num_util_constrs += 1 + print(f" {num_util_constrs} constraints added") + + # ========================================================================= + # CONSTRAINT (7): At most one threshold level per carousel per peak interval + # sum_k y_{c,k,m} <= 1 for all c, m + # ========================================================================= + print(" Adding constraint (7): threshold uniqueness...") + for c_idx in range(num_carousels): + for m_idx in range(M): + lhs = gp.LinExpr() + for k in range(K): + lhs.addTerms(1.0, y_vars[(c_idx, k, m_idx)]) + model.addConstr(lhs <= 1, name=f"thresh_{c_idx}_{m_idx}") + + model.update() + print(f"\nModel summary:") + print(f" Total variables: {model.NumVars}") + print(f" Total constraints: {model.NumConstrs}") + print(f" Total nonzeros: {model.NumNZs}") + + return model, x_vars, y_vars, flight_tuples, flight_w_range + + +# ============================================================================= +# SOLUTION EXTRACTION +# ============================================================================= + +def extract_solution(model, x_vars, y_vars, data, flight_tuples, flight_w_range): + """ + Extract the solution from a solved Gurobi model. + + Returns a dict with: + - objective_value + - status / status_name + - flight assignments (flight -> carousel, w, start tuple) + - utilization violations + - solve statistics + """ + flights = data["flights"] + carousels = data["carousels"] + R = data["R"] + + solution = { + "solver": "Gurobi", + "status": model.Status, + "status_name": _status_name(model.Status), + } + + if model.Status in (GRB.OPTIMAL, GRB.SUBOPTIMAL, GRB.TIME_LIMIT): + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["best_bound"] = model.ObjBound + solution["mip_gap"] = model.MIPGap + solution["solve_time_seconds"] = model.Runtime + solution["num_solutions_found"] = model.SolCount + + # Extract flight assignments + assignments = [] + for i, flight in enumerate(flights): + tuples = flight_tuples[i] + assigned = False + for c_idx in range(len(carousels)): + type_str = str(carousels[c_idx]["type_r"]) + if (i, type_str) not in flight_w_range: + continue + wmin, wmax = flight_w_range[(i, type_str)] + for w in range(wmin, wmax + 1): + for tau_idx in range(len(tuples)): + key = (i, c_idx, w, tau_idx) + if key in x_vars and x_vars[key].X > 0.5: + s_h, s_d = tuples[tau_idx] + assignments.append({ + "flight_id": flight["flight_id"], + "carousel_id": carousels[c_idx][ + "carousel_id"], + "carousel_type": carousels[c_idx][ + "type_r"], + "working_stations": w, + "handling_start_period": s_h, + "depletion_start_period": s_d, + "end_period": flight["end_period"], + }) + assigned = True + break + if assigned: + break + if assigned: + break + if not assigned: + assignments.append({ + "flight_id": flight["flight_id"], + "carousel_id": None, + "note": "NOT ASSIGNED" + }) + + solution["assignments"] = assignments + + # Extract utilization violations + violations = [] + K = data["K"] + M_count = data["M"] + tv = data["threshold_values"] + for c_idx in range(data["num_carousels"]): + for m_idx in range(M_count): + for k in range(K): + key = (c_idx, k, m_idx) + if key in y_vars and y_vars[key].X > 0.5: + violations.append({ + "carousel_id": carousels[c_idx][ + "carousel_id"], + "peak_interval": m_idx + 1, + "threshold_level": k + 1, + "threshold_value": tv[k], + }) + solution["utilization_violations"] = violations + + else: + solution["objective_value"] = None + solution["note"] = ("No feasible solution found within " + "time limit") + elif model.Status == GRB.INFEASIBLE: + solution["objective_value"] = None + solution["note"] = "Model is infeasible" + try: + model.computeIIS() + iis_constrs = [ + c.ConstrName for c in model.getConstrs() if c.IISConstr + ] + solution["iis_constraints"] = iis_constrs[:20] + except Exception: + pass + else: + solution["objective_value"] = None + solution["note"] = f"Solver ended with status {model.Status}" + + solution["solve_time_seconds"] = model.Runtime + return solution + + +def _status_name(status): + """Map Gurobi status code to human-readable name.""" + names = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.CUTOFF: "CUTOFF", + GRB.ITERATION_LIMIT: "ITERATION_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.INTERRUPTED: "INTERRUPTED", + GRB.NUMERIC: "NUMERIC", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + GRB.LOADED: "LOADED", + } + return names.get(status, f"UNKNOWN_{status}") + + +# ============================================================================= +# MAIN +# ============================================================================= + +def main(): + parser = argparse.ArgumentParser( + description=("Solve OBHP using Time-Indexed Formulation (TIF) " + "with Gurobi") + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the instance JSON file" + ) + parser.add_argument( + "--solution_path", type=str, default=None, + help="Path to write the solution JSON file" + ) + parser.add_argument( + "--time_limit", type=int, default=3600, + help="Gurobi time limit in seconds (default: 3600)" + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # ---- Load instance ---- + print("=" * 70) + print("OBHP - Time-Indexed Formulation (TIF) Solver") + print("Frey, Kolisch, and Artigues (2017)") + print("=" * 70) + + print(f"\nLoading instance from: {args.instance_path}") + inst = load_instance(args.instance_path) + data = parse_instance(inst) + + print(f" Flights: {data['num_flights']}") + print(f" Carousels: {data['num_carousels']}") + print(f" Carousel types: {data['R']}") + print(f" Planning horizon: {data['T']} periods") + print(f" Peak intervals: {data['M']}") + print(f" Threshold levels (K): {data['K']}") + print(f" Target utilization: {data['u_ta']}") + + # ---- Preprocessing ---- + print("\nPreprocessing...") + data = preprocess_tighten_start_times(data) + + # ---- Build and solve model ---- + print(f"\nTime limit: {args.time_limit} seconds") + wall_start = time.time() + + model, x_vars, y_vars, flight_tuples, flight_w_range = build_model( + data, time_limit=args.time_limit + ) + + print("\nSolving...") + model.optimize() + + wall_elapsed = time.time() - wall_start + print(f"\nTotal wall time: {wall_elapsed:.2f} seconds") + print(f" Gurobi solve time: {model.Runtime:.2f} seconds") + print(f" Status: {_status_name(model.Status)}") + + # ---- Extract solution ---- + solution = extract_solution( + model, x_vars, y_vars, data, flight_tuples, flight_w_range + ) + + if solution["objective_value"] is not None: + print(f" Objective value: {solution['objective_value']}") + if "mip_gap" in solution: + print(f" MIP gap: {solution['mip_gap']:.6f}") + if "assignments" in solution: + print(f" Flights assigned: {len(solution['assignments'])}") + if "utilization_violations" in solution: + n_viol = len(solution["utilization_violations"]) + print(f" Utilization violations: {n_viol}") + else: + print(f" No solution found. Note: {solution.get('note', 'N/A')}") + + # ---- Save solution ---- + if args.solution_path: + print(f"\nSaving solution to: {args.solution_path}") + with open(args.solution_path, "w", encoding="utf-8") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2, default=str) + else: + print("\n" + json.dumps(solution, indent=2, default=str)) + + return solution + + +if __name__ == "__main__": + main() diff --git a/tasks/frey2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/frey2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..381283ca5b46f4ae2d2030dbfb9bdcd4f6888311 --- /dev/null +++ b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f34d78d70da831de1def4a9c7f5502009bbb5307a5f83066854dba362476b4f9 +size 103 diff --git a/tasks/frey2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..381283ca5b46f4ae2d2030dbfb9bdcd4f6888311 --- /dev/null +++ b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f34d78d70da831de1def4a9c7f5502009bbb5307a5f83066854dba362476b4f9 +size 103 diff --git a/tasks/frey2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..381283ca5b46f4ae2d2030dbfb9bdcd4f6888311 --- /dev/null +++ b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f34d78d70da831de1def4a9c7f5502009bbb5307a5f83066854dba362476b4f9 +size 103 diff --git a/tasks/frey2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..381283ca5b46f4ae2d2030dbfb9bdcd4f6888311 --- /dev/null +++ b/tasks/frey2017/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f34d78d70da831de1def4a9c7f5502009bbb5307a5f83066854dba362476b4f9 +size 103 diff --git a/tasks/frey2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/frey2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/frey2017/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/frey2017/gurobi_solution/large_solution_1.json b/tasks/frey2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..200c676da7411b16cdc43595d1b7759f2adb2292 --- /dev/null +++ b/tasks/frey2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36c11a35e4649d084eebd5f6717275c6207c2baf3a1824d6a7945940129e539f +size 63928 diff --git a/tasks/frey2017/gurobi_solution/large_solution_2.json b/tasks/frey2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..bd10c575defb4d95da3d208a212fdde49b9d851b --- /dev/null +++ b/tasks/frey2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb4020dcd0b9550a63fbf25049595a4be4cd43f1bccf814ca83a20ac4ecc83b7 +size 63970 diff --git a/tasks/frey2017/gurobi_solution/large_solution_3.json b/tasks/frey2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ace5d749b8e9d4c42acbb31495dd1c9382abe397 --- /dev/null +++ b/tasks/frey2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5bd23033bf5dc8a1eb5c06688235c00c97d295ccf21c9258c54dc2b40de53aa +size 63948 diff --git a/tasks/frey2017/gurobi_solution/large_solution_4.json b/tasks/frey2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..334c0eaf83849ad87ce35bf943d5e33ded68d9b6 --- /dev/null +++ b/tasks/frey2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbe23782aebec91b308f63e67ba2f36646f24f8956b5b546d8e1bbdb4022de6e +size 63926 diff --git a/tasks/frey2017/gurobi_solution/large_solution_5.json b/tasks/frey2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fd2dd18dae24d2dfbe6bb764a844b51f5287be62 --- /dev/null +++ b/tasks/frey2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57e6328a0cac0b8f8ce67a4b77543b05cf97befd7f2795926000037578a87720 +size 63957 diff --git a/tasks/frey2017/gurobi_solution/tiny_solution.json b/tasks/frey2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..5ffff918c39eeb327c5e2f6857122dee44c071fa --- /dev/null +++ b/tasks/frey2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9720d0b81f44c97b166f3fe7aac04833ac8a428a2b1d5666587f86eb5f017080 +size 5545 diff --git a/tasks/frey2017/gurobi_solution_log/large_log_1.jsonl b/tasks/frey2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c34c13523abb7895df4633786abfa627f64cec72 --- /dev/null +++ b/tasks/frey2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c3e9c62e24191bb2c199a9f0528b50d44017f521469da312adef2f2b0178b08 +size 42 diff --git a/tasks/frey2017/gurobi_solution_log/large_log_2.jsonl b/tasks/frey2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cc5502cdf26aadc3e973c5e1cd95952c9f38996f --- /dev/null +++ b/tasks/frey2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9a98d04fa9b3081dd81a4b213364cd9407d83d2b8db91d12230c6682c8450aa +size 40 diff --git a/tasks/frey2017/gurobi_solution_log/large_log_3.jsonl b/tasks/frey2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..06e971a3c2be76a6cbbbed4d235916e234fb255f --- /dev/null +++ b/tasks/frey2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2603931bdee7b0742b69bb60fcefc52ad25a7bf59af449b3c1a57de8f733cf33 +size 41 diff --git a/tasks/frey2017/gurobi_solution_log/large_log_4.jsonl b/tasks/frey2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8cd727ed9114850b35e970abda5aee17fa92911f --- /dev/null +++ b/tasks/frey2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51c2901019c591a43e91032e863159345d11744e6e1952319afa3b87664b796f +size 97 diff --git a/tasks/frey2017/gurobi_solution_log/large_log_5.jsonl b/tasks/frey2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ee91643ef7d48d95b62e166d617a668f537f46d0 --- /dev/null +++ b/tasks/frey2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2308c3dc74a9d2560dc0745b03a8549160634f8dc2f033b8574ff051296eb5f +size 84 diff --git a/tasks/frey2017/gurobi_solution_log/tiny_log.jsonl b/tasks/frey2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7bd5f21ad0eb75e4a5d20f18126819a954bc1451 --- /dev/null +++ b/tasks/frey2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4725d1dfd8a4d630154ea9a6aa590a7345b11a96c3d9fb4c3b17643b80b712e +size 40 diff --git a/tasks/frey2017/instance/large_instance_1.json b/tasks/frey2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..852a17f47b3328e1914b61f5389a4fc458f286b6 --- /dev/null +++ b/tasks/frey2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88c40436110dfef05fcd830e768aa479c8fda42a329669a92d90d02c0dab84a2 +size 128836 diff --git a/tasks/frey2017/instance/large_instance_2.json b/tasks/frey2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..42588ed1f153437f15d7121a30161121c8700d5e --- /dev/null +++ b/tasks/frey2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:045ead2fecc8747000a5c7207abd772c0bf72ffd838e2b7324ba8961868e8aa7 +size 128751 diff --git a/tasks/frey2017/instance/large_instance_3.json b/tasks/frey2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..a063f98baffc9dc07f00d56ddd966ffe72e466e3 --- /dev/null +++ b/tasks/frey2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45647af99476253805dc57f9ccc9de7bd2dcdc5ffa953c4d5dc5dcb406c09342 +size 127559 diff --git a/tasks/frey2017/instance/large_instance_4.json b/tasks/frey2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f170101db9e31e8e429721a912a5919d614b6dbc --- /dev/null +++ b/tasks/frey2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25d1345a354f71e95894d7285686138079ff5fcc97472b0696dac7f147645458 +size 128402 diff --git a/tasks/frey2017/instance/large_instance_5.json b/tasks/frey2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8c37c3b165e47a615697de02bb2e23b1b9d22cf0 --- /dev/null +++ b/tasks/frey2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a57d58439c3642ce15c7674a7ea64cb49fc2cec3773ac762f8c7533c22b3acbf +size 128963 diff --git a/tasks/frey2017/instance/tiny_instance.json b/tasks/frey2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..008eaf2004cab825ab2e5e5d3e23c12c8815f389 --- /dev/null +++ b/tasks/frey2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dea5416a7762824739dbca987082fc698fe3a5c518cfbf1380534c8fcb3c0c1b +size 17774 diff --git a/tasks/frey2017/instance_schema.json b/tasks/frey2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a6133e42177413fae9f65e6474c94029d456c462 --- /dev/null +++ b/tasks/frey2017/instance_schema.json @@ -0,0 +1,74 @@ +{ + "planning_horizon": { + "num_periods": " Total number of discrete time periods spanning the planning day.", + "period_length_minutes": " Duration of each time period in minutes." + }, + "objective": { + "target_utilization": " Target conveyor belt utilization ratio below which no penalty is incurred.", + "threshold_values": " Ordered utilization excess thresholds above the target at which penalties are triggered.", + "penalties": " Penalty cost associated with each utilization threshold level, increasing steeply with the threshold index." + }, + "peak_intervals": [ + { + "peak_id": " Identifier for this peak interval.", + "start_period": " First period of this peak interval during which carousel utilization is monitored.", + "end_period": " Last period (inclusive) of this peak interval during which carousel utilization is monitored." + } + ], + "central_storage": { + "capacity_bags": " Maximum number of bags that can be held in the central storage system at any time.", + "depletion_rate_bags_per_period": " Number of bags transferred from central storage to the carousel per period during depletion.", + "depletion_offset_periods": " Number of periods before the handling end by which storage depletion must commence." + }, + "working_rate_bags_per_period": " Number of bags each working station can load into containers per period.", + "baggage_transfer_time_periods": " Number of periods required to transfer baggage from storage to a carousel.", + "flight_end_offset_periods": " Number of periods before departure by which baggage handling must conclude.", + "quantile_used": " Quantile of the baggage arrival distribution used to estimate the arrival profile.", + "num_flights": " Total number of outgoing flights to be scheduled.", + "num_carousels": " Total number of carousels available for baggage handling.", + "carousel_config": [ + { + "type_r": " Carousel type identifier.", + "count": " Number of carousels of this type." + } + ], + "carousel_types": { + "{type_id}": { + "Kpp": " Maximum number of container parking positions at a carousel of this type.", + "Kws": " Maximum number of working stations at a carousel of this type.", + "Kppws": " Number of container parking positions per working station at a carousel of this type.", + "Kcb": " Conveyor belt capacity (maximum bags on the belt in any period) for a carousel of this type." + } + }, + "carousels": [ + { + "carousel_id": " Unique identifier for this carousel.", + "type_r": " Type of this carousel, referencing a key in carousel_types.", + "Kpp": " Maximum number of container parking positions at this carousel.", + "Kws": " Maximum number of working stations at this carousel.", + "Kppws": " Number of container parking positions per working station at this carousel.", + "Kcb": " Conveyor belt capacity (maximum bags on the belt in any period) for this carousel." + } + ], + "flights": [ + { + "flight_id": " Unique identifier for this flight.", + "departure_period": " Period in which this flight departs.", + "expected_baggage": " Expected total number of bags for this flight.", + "num_containers": " Number of containers required to hold this flight's baggage.", + "earliest_start_period": " Earliest period at which baggage handling may begin for this flight.", + "latest_start_period": " Latest period at which baggage handling may begin for this flight.", + "end_period": " Period by which all baggage handling must be completed for this flight.", + "handling_duration_periods": " Number of periods over which baggage arrives for this flight.", + "arrival_profile": " Number of bags arriving in each successive period of the handling window.", + "working_station_bounds_by_carousel_type": { + "{type_id}": { + "Wmin": " Minimum number of working stations required for this flight at a carousel of this type.", + "Wmax": " Maximum number of working stations allowed for this flight at a carousel of this type." + } + }, + "Wmin": " Minimum number of working stations required for this flight across all compatible carousel types.", + "Wmax": " Maximum number of working stations allowed for this flight across all compatible carousel types." + } + ] +} diff --git a/tasks/frey2017/mathematical_formulation.md b/tasks/frey2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..8e0834bab5cc4450d184004052663b21976a9465 --- /dev/null +++ b/tasks/frey2017/mathematical_formulation.md @@ -0,0 +1,82 @@ +# Original Formulation: Outbound Baggage Handling Problem (OBHP) — Time-Indexed Formulation (TIF) + +*Source: Column Generation for Outbound Baggage Handling at Airports, Markus Frey, Rainer Kolisch, Christian Artigues, Transportation Science (2017).* + +The paper states (Section 3) that it is sufficient to solve a Time-Indexed Formulation (TIF), presented in Section 3.1 as equations (1)–(9). This is the formulation that defines the problem the paper studies; its notation ($x_{i,c,w,\tau}$, $y_{c,k,m}$) is carried into the structural analysis, preprocessing, and computational experiments. The Dantzig–Wolfe master problem (10)–(14) and the pricing/scheduling subproblems are an *algorithmic* reformulation introduced in Section 4 and are therefore excluded here. + +## Sets and Indices + +$$\begin{align*} +\mathcal{F} &= \{1,\dots,F\} && \text{set of outgoing flights; index } i\\ +\mathcal{T} &= \{t_0,\dots,t_T\},\ t_0=01\}}(P_i \bmod K^{ppws}_r)\\ +[W^{\min}_i,W^{\max}_i] &&& \text{overall working-station bounds for } i \text{ across all types}\\ +[S^{es}_i,S^{ls}_i] &&& \text{time window for the start of flight } i\text{'s baggage handling}\\ +S^e_i &&& \text{end time of flight } i\text{'s baggage handling}\\ +K^s &&& \text{capacity of the central storage system}\\ +u^{ta}<1 &&& \text{target utilization}\\ +p_k,\ 0= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/frey2017/solution_schema.json b/tasks/frey2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..79e34b66336de50c08ed66bd77ad82cb2354d52f --- /dev/null +++ b/tasks/frey2017/solution_schema.json @@ -0,0 +1,22 @@ +{ + "objective_value": " Total penalty incurred from carousel utilization exceeding the target across all carousels, threshold levels, and peak intervals.", + "assignments": [ + { + "flight_id": " Identifier of the flight being scheduled.", + "carousel_id": " Identifier of the carousel chosen to handle this flight's baggage.", + "carousel_type": " Type of the chosen carousel, which determines its capacity characteristics.", + "working_stations": " Number of working stations allocated to this flight at the chosen carousel.", + "handling_start_period": " Period in which baggage handling for this flight begins at the carousel.", + "depletion_start_period": " Period in which transfer of this flight's bags from central storage to the carousel begins.", + "end_period": " Period by which baggage handling for this flight must conclude." + } + ], + "utilization_violations": [ + { + "carousel_id": " Identifier of the carousel whose utilization exceeded the target during the peak interval.", + "peak_interval": " Identifier of the peak interval in which the utilization overshoot is flagged.", + "threshold_level": " Index of the threshold level flagged as exceeded for this carousel and peak interval.", + "threshold_value": " Value of the flagged threshold used as the allowable overshoot above the target utilization." + } + ] +} diff --git a/tasks/furini2016/feasibility_check.py b/tasks/furini2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..82df792f8ab13bd86560ef2513db81c0250d2f9b --- /dev/null +++ b/tasks/furini2016/feasibility_check.py @@ -0,0 +1,492 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the PP-G2KP model (Furini, Malaguti, Thomopulos 2016). + +Checks each hard constraint from the mathematical formulation against a +candidate solution (y variables: items_selected with item_id, plate_dims, copies). + +Constraint numbering (top-to-bottom in the formulation section of math_model.txt): + Constraint 1 (eq 2): Flow-balance for item plates (j in J_bar, j != 0) + Constraint 2 (eq 3): Flow-balance for non-item plates (j in J \\ J_bar) + Constraint 3 (eq 4): Original panel used at most once + Constraint 4 (eq 5): Capacity y_j <= u_j + Constraint 5 (eq 6): x variables non-negative integer + Constraint 6 (eq 7): y variables non-negative integer + Constraint 7 (Tier C): Objective consistency -- reported objective_value + must equal the recomputed total profit + sum_{j in J_bar} p_j * y_j (eq 1). + +Since the solution only provides y values (items_selected), constraints involving +x variables (1, 2, 3, 5) are checked via necessary conditions derivable from the +flow-network structure: + - Total item area <= panel area (from constraints 1+2+3 combined) + - Each item fits within panel dimensions + - Constraint 5 (x integrality): not directly checkable from y-only solution + +Constraint 7 is an objective-recomputation defense: the objective (eq 1) is a +deterministic function of the y variables alone, and the solution carries every +y variable, so the true objective can be recomputed exactly and compared against +the program's self-reported objective_value. A mismatch beyond tolerance is a +score-gaming exploit and is reported as a constraint violation. +""" + +import json +import argparse + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('items_selected', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def compute_violation(lhs, rhs, op): + """ + Compute violation_amount for a constraint with given operator. + op: '<=', '>=', '=' + Returns violation_amount (0 if satisfied within tolerance). + """ + if op == '<=': + return max(0.0, lhs - rhs) + elif op == '>=': + return max(0.0, rhs - lhs) + elif op == '=': + return abs(lhs - rhs) + return 0.0 + + +def record_violation(violations_list, magnitudes_list, constraint_idx, lhs, rhs, message): + """Record a violation with normalized magnitude.""" + raw_excess = compute_violation(lhs, rhs, '<=') if lhs > rhs else compute_violation(lhs, rhs, '>=') + # Use the raw difference + raw_excess = abs(lhs - rhs) if raw_excess == 0 else raw_excess + normalizer = max(abs(rhs), EPS) + ratio = raw_excess / normalizer + + violations_list.append(message) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(raw_excess), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +def check_feasibility(instance, solution): + """ + Check all hard constraints of the PP-G2KP model. + Returns (feasible, violated_constraints, violations, violation_magnitudes). + """ + violated_constraints = set() + violations = [] + magnitudes = [] + + L = instance['panel']['length'] + W = instance['panel']['width'] + items = instance['items'] + panel_area = L * W + + # Build item lookup by id + item_by_id = {it['id']: it for it in items} + + # Parse solution + items_selected = solution.get('items_selected', []) + + # Aggregate y values per item_id + y_per_item = {} + for entry in items_selected: + iid = entry['item_id'] + copies = entry['copies'] + if iid in y_per_item: + y_per_item[iid] += copies + else: + y_per_item[iid] = copies + + # =================================================================== + # Constraint 6 (eq 7): y_j >= 0, integer for all j in J_bar + # =================================================================== + for entry in items_selected: + iid = entry['item_id'] + copies = entry['copies'] + + # Check non-negativity + if copies < -TOL: + lhs = copies + rhs = 0.0 + violated_constraints.add(6) + record_violation(violations, magnitudes, 6, lhs, rhs, + f"Constraint 6: y for item {iid} is negative ({copies})") + + # Check integrality + if abs(copies - round(copies)) > TOL: + lhs = abs(copies - round(copies)) + rhs = 0.0 + violated_constraints.add(6) + record_violation(violations, magnitudes, 6, lhs, rhs, + f"Constraint 6: y for item {iid} is not integer ({copies})") + + # Check item exists in instance + if iid not in item_by_id: + violated_constraints.add(6) + violations.append( + f"Constraint 6: item {iid} in solution not found in instance") + magnitudes.append({ + "constraint": 6, + "lhs": float(iid), + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + continue + + # Check plate_dims match item dimensions + item = item_by_id[iid] + pdims = entry.get('plate_dims', []) + if len(pdims) == 2: + if not (pdims[0] == item['length'] and pdims[1] == item['width']): + violated_constraints.add(6) + violations.append( + f"Constraint 6: plate_dims {pdims} for item {iid} " + f"do not match item dimensions [{item['length']}, {item['width']}]") + magnitudes.append({ + "constraint": 6, + "lhs": 0.0, + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + + # =================================================================== + # Constraint 4 (eq 5): y_j <= u_j for all j in J_bar + # =================================================================== + for iid, total_copies in y_per_item.items(): + if iid not in item_by_id: + continue # already flagged above + item = item_by_id[iid] + u_j = item['copies'] + lhs = total_copies + rhs = u_j + violation_amount = compute_violation(lhs, rhs, '<=') + if violation_amount > TOL: + violated_constraints.add(4) + record_violation(violations, magnitudes, 4, lhs, rhs, + f"Constraint 4: item {iid} uses {total_copies} copies " + f"but only {u_j} available") + + # =================================================================== + # Constraints 1-3 (eqs 2-4): flow balance + panel use, using x (cuts) + # + # Solution provides cuts_used (x variables) and a plates list with + # in_J_bar flags, so we check the actual hard constraints rather than + # derived necessary conditions. + # =================================================================== + cuts_used = solution.get('cuts_used', []) + plates_info = solution.get('plates', []) + in_J_bar = {p['id']: bool(p.get('in_J_bar', False)) for p in plates_info} + plate_ids = {p['id'] for p in plates_info} + + y_per_plate = {} + for entry in items_selected: + pid = entry.get('plate_id') + if pid is None: + continue + y_per_plate[pid] = y_per_plate.get(pid, 0) + entry['copies'] + + flow_in = {pid: 0 for pid in plate_ids} + flow_out = {pid: 0 for pid in plate_ids} + for c in cuts_used: + cnt = c.get('count', 0) + parent = c.get('parent_plate_id') + c1 = c.get('child1_plate_id') + c2 = c.get('child2_plate_id') + if parent is not None: + flow_out[parent] = flow_out.get(parent, 0) + cnt + if c1 is not None: + flow_in[c1] = flow_in.get(c1, 0) + cnt + if c2 is not None: + flow_in[c2] = flow_in.get(c2, 0) + cnt + + # Constraint 1 (eq 2): flow balance for item plates j in J_bar, j != 0 + for pid in plate_ids: + if pid == 0 or not in_J_bar.get(pid, False): + continue + fin = flow_in.get(pid, 0) + fout = flow_out.get(pid, 0) + yj = y_per_plate.get(pid, 0) + lhs = fin - fout - yj + if lhs < -TOL: + violated_constraints.add(1) + record_violation(violations, magnitudes, 1, lhs, 0.0, + f"Constraint 1 (eq 2): plate {pid} flow balance " + f"in({fin}) - out({fout}) - y({yj}) = {lhs} < 0") + + # Constraint 2 (eq 3): flow balance for non-item plates j in J \\ J_bar + for pid in plate_ids: + if pid == 0 or in_J_bar.get(pid, False): + continue + fin = flow_in.get(pid, 0) + fout = flow_out.get(pid, 0) + lhs = fin - fout + if lhs < -TOL: + violated_constraints.add(2) + record_violation(violations, magnitudes, 2, lhs, 0.0, + f"Constraint 2 (eq 3): plate {pid} flow balance " + f"in({fin}) - out({fout}) = {lhs} < 0") + + # Constraint 3 (eq 4): original panel (plate 0) used at most once + panel_lhs = flow_out.get(0, 0) + if in_J_bar.get(0, False): + panel_lhs += y_per_plate.get(0, 0) + if panel_lhs - 1 > TOL: + violated_constraints.add(3) + record_violation(violations, magnitudes, 3, panel_lhs, 1.0, + f"Constraint 3 (eq 4): panel use {panel_lhs} > 1") + + # =================================================================== + # Constraint 5 (eq 6): x variables non-negative integer + # Not directly checkable from solution (only y values provided). + # No violation recorded. + # =================================================================== + + # =================================================================== + # Constraint 7 (Tier C, objective consistency): + # The objective (eq 1) max sum_{j in J_bar} p_j * y_j is a + # deterministic function of the y variables alone, and the solution + # carries every y variable (items_selected -> copies). We therefore + # recompute the true objective exactly and reject as infeasible when + # the program's self-reported objective_value disagrees beyond a + # tight tolerance. This defends against LLM score-gaming exploits + # that fabricate objective_value (e.g. 0 or sys.float_info.max). + # + # Full recompute applies because no x / second-stage variable enters + # the objective -- p_j * y_j depends only on the items kept. + # + # The check is skipped (rather than firing a false positive) when the + # solution references an unknown item type: the recompute cannot be + # trusted, and such a solution is already infeasible via constraint 6, + # so no verdict is lost. + # =================================================================== + reported_obj = solution.get('objective_value') + if reported_obj is not None: + obj_checkable = True + reported = None + true_obj = 0.0 + try: + reported = float(reported_obj) + for iid, total_copies in y_per_item.items(): + if iid not in item_by_id: + obj_checkable = False + break + true_obj += float(item_by_id[iid]['profit']) * float(total_copies) + except (TypeError, ValueError): + obj_checkable = False + + if obj_checkable and reported is not None: + abs_diff = abs(reported - true_obj) + # The objective is an integer (sum of integer profits times + # integer copies); doubles represent it exactly at this scale. + # Absolute floor 0.5 catches any integer-level mismatch; the + # relative term guards huge objectives against solver float noise. + tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(7) + record_violation(violations, magnitudes, 7, reported, true_obj, + f"Constraint 7 (objective consistency): reported " + f"objective_value={reported} differs from recomputed " + f"sum_j(p_j*y_j)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})") + + # Build final result + violated_list = sorted(violated_constraints) + feasible = len(violated_list) == 0 + + return feasible, violated_list, violations, magnitudes + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for PP-G2KP model solutions." + ) + parser.add_argument("--instance_path", required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + feasible, violated_constraints, violations, magnitudes = check_feasibility( + instance, solution + ) + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": magnitudes, + } + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + print(f"Feasibility: {feasible}") + if violated_constraints: + print(f"Violated constraints: {violated_constraints}") + for v in violations: + print(f" - {v}") + print(f"Result written to: {args.result_path}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/furini2016/gurobi_code.py b/tasks/furini2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..0aca6c3a57de1f0bc7f0f40cdef745538521ffdb --- /dev/null +++ b/tasks/furini2016/gurobi_code.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +""" +PP-G2KP Model for the Guillotine Two-Dimensional Knapsack Problem (G2KP). + +Based on: Furini, Malaguti, Thomopulos (2016) +"Modeling Two-Dimensional Guillotine Cutting Problems via Integer Programming" +INFORMS Journal on Computing 28(4): 736-751. + +Implements the complete PP-G2KP MIP model (constraints 1-7) with Gurobi. +""" + +import json +import argparse +import sys +from collections import deque + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +# --------------------------------------------------------------------------- +# Bounded Subset Sum (DP for complete cut-position set) +# --------------------------------------------------------------------------- + +def bounded_subset_sum(sizes, copies, max_val): + """ + Compute all achievable positive sums < max_val using at most copies[i] + copies of sizes[i], for each i. + + Uses a bitset (Python big-integer) approach for efficiency: + - reachable is an integer whose k-th bit is set iff sum k is achievable. + - For each item i with size s and count c, we accumulate shifts of + the current reachable set by s, s+s, ..., c*s (bounded copies). + + Returns a set of integers. + """ + if not sizes or max_val <= 1: + return set() + + mask = (1 << max_val) - 1 + reachable = 1 # bit 0 set: sum 0 is achievable + + for size, count in zip(sizes, copies): + if size <= 0 or size >= max_val: + continue + new_reachable = reachable + temp = reachable + for _ in range(count): + temp = (temp << size) & mask + new_reachable |= temp + if not temp: + break + reachable = new_reachable + + return {s for s in range(1, max_val) if (reachable >> s) & 1} + + +# --------------------------------------------------------------------------- +# Cut-position computation +# --------------------------------------------------------------------------- + +def compute_complete_positions(plate_l, plate_w, items): + """ + Compute the complete position sets Q(j,h) and Q(j,v) for a plate of + dimensions plate_l x plate_w. + + Q(j,h) = achievable sums of item widths for fitting items, filtered to + q < plate_w / 2 (symmetric positions removed). + Q(j,v) = achievable sums of item lengths for fitting items, filtered to + q < plate_l / 2. + + Returns (h_positions, v_positions) as sorted lists. + """ + fitting = [(it['length'], it['width'], it['copies']) + for it in items + if it['length'] <= plate_l and it['width'] <= plate_w] + + if not fitting: + return [], [] + + h_sizes = [w for (l, w, c) in fitting] + h_copies = [c for (l, w, c) in fitting] + v_sizes = [l for (l, w, c) in fitting] + v_copies = [c for (l, w, c) in fitting] + + h_all = bounded_subset_sum(h_sizes, h_copies, plate_w) + v_all = bounded_subset_sum(v_sizes, v_copies, plate_l) + + # Remove symmetric positions: keep only q < dim/2 + h_pos = sorted(q for q in h_all if 2 * q < plate_w) + v_pos = sorted(q for q in v_all if 2 * q < plate_l) + + return h_pos, v_pos + + +def can_fit_any_item(plate_l, plate_w, items): + return any(it['length'] <= plate_l and it['width'] <= plate_w + for it in items) + + +# --------------------------------------------------------------------------- +# Plate and variable enumeration (Procedure 1 from the paper) +# --------------------------------------------------------------------------- + +def enumerate_plates_and_cuts(L, W, items): + """ + Procedure 1: Plate-and-variable enumeration. + + Starting from plate 0 (L x W), generate all reachable sub-plates through + guillotine cuts at complete-position-set positions. A new plate is added + to J only if it can fit at least one item. + + Returns + ------- + plates : list of (l, w) tuples indexed by plate id + plate_map : dict (l, w) -> plate_id + cuts : list of (parent_id, orientation, position, child1_id, child2_id) + child_id may be None if that child cannot fit any item (waste). + J_bar : dict plate_id -> item dict (plates matching an item's dims) + """ + # Build item dimension map: (l, w) -> item (highest profit wins ties) + item_map = {} + for it in items: + key = (it['length'], it['width']) + if key not in item_map or it['profit'] > item_map[key]['profit']: + item_map[key] = it + + plates = [(L, W)] + plate_map = {(L, W): 0} + cuts = [] + + queue = deque([0]) + processed = set() + + while queue: + pid = queue.popleft() + if pid in processed: + continue + processed.add(pid) + + pl, pw = plates[pid] + h_pos, v_pos = compute_complete_positions(pl, pw, items) + + # Horizontal cuts: split width into q and pw-q + for q in h_pos: + c1_dims = (pl, q) + c2_dims = (pl, pw - q) + + c1_id = _get_or_add_plate(c1_dims, plates, plate_map, queue, items) + c2_id = _get_or_add_plate(c2_dims, plates, plate_map, queue, items) + + cuts.append((pid, 'h', q, c1_id, c2_id)) + + # Vertical cuts: split length into q and pl-q + for q in v_pos: + c1_dims = (q, pw) + c2_dims = (pl - q, pw) + + c1_id = _get_or_add_plate(c1_dims, plates, plate_map, queue, items) + c2_id = _get_or_add_plate(c2_dims, plates, plate_map, queue, items) + + cuts.append((pid, 'v', q, c1_id, c2_id)) + + # Determine J_bar (item plates) + J_bar = {pid: item_map[dims] + for pid, dims in enumerate(plates) + if dims in item_map} + + return plates, plate_map, cuts, J_bar + + +def _get_or_add_plate(dims, plates, plate_map, queue, items): + """ + If dims can fit some item and is not yet in J, add it. + Returns plate_id or None (if the plate is waste). + """ + pl, pw = dims + if pl <= 0 or pw <= 0: + return None + if not can_fit_any_item(pl, pw, items): + return None + if dims not in plate_map: + new_id = len(plates) + plate_map[dims] = new_id + plates.append(dims) + queue.append(new_id) + return plate_map[dims] + + +# --------------------------------------------------------------------------- +# Main solver +# --------------------------------------------------------------------------- + +def solve_g2kp(instance_path, solution_path, time_limit): + # ------------------------------------------------------------------ + # Load instance + # ------------------------------------------------------------------ + with open(instance_path) as f: + inst = json.load(f) + + L = inst['panel']['length'] + W = inst['panel']['width'] + items = inst['items'] + + print(f"Instance: {inst.get('instance_name', instance_path)}") + print(f"Panel: {L} x {W}, n={len(items)} item types") + + # ------------------------------------------------------------------ + # Enumerate plates and cuts + # ------------------------------------------------------------------ + plates, plate_map, cuts, J_bar = enumerate_plates_and_cuts(L, W, items) + + n_plates = len(plates) + n_cuts = len(cuts) + print(f"Plates: {n_plates}, Cuts (x-variables): {n_cuts}, " + f"Item plates (y-variables): {len(J_bar)}") + + # ------------------------------------------------------------------ + # Build Gurobi model + # ------------------------------------------------------------------ + model = gp.Model("PP-G2KP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + + # y variables: for each item plate j in J_bar + y = {} + for pid, item in J_bar.items(): + y[pid] = model.addVar( + vtype=GRB.INTEGER, lb=0, + name=f"y[{pid}]" + ) + + # x variables: for each cut + x = {} + for idx, (pid, orient, q, c1_id, c2_id) in enumerate(cuts): + x[idx] = model.addVar( + vtype=GRB.INTEGER, lb=0, + name=f"x[{pid},{orient},{q}]" + ) + + # Objective (1): maximize sum of p_j * y_j + model.setObjective( + gp.quicksum(item['profit'] * y[pid] for pid, item in J_bar.items()), + GRB.MAXIMIZE + ) + + # ------------------------------------------------------------------ + # Build flow-balance structures + # ------------------------------------------------------------------ + # flow_in[j] = LinExpr (sum of x variables whose cuts PRODUCE plate j) + # flow_out[j] = LinExpr (sum of x variables that CUT plate j) + flow_in = {pid: [] for pid in range(n_plates)} + flow_out = {pid: [] for pid in range(n_plates)} + + for idx, (pid, orient, q, c1_id, c2_id) in enumerate(cuts): + flow_out[pid].append(x[idx]) + if c1_id is not None: + flow_in[c1_id].append(x[idx]) + if c2_id is not None: + flow_in[c2_id].append(x[idx]) + + # ------------------------------------------------------------------ + # Add constraints + # ------------------------------------------------------------------ + + # Constraint (4): original panel used at most once + # sum_{o,q} x^o_{q,0} (+y_0 if 0 in J_bar) <= 1 + lhs_panel = gp.quicksum(flow_out[0]) + if 0 in J_bar: + lhs_panel = lhs_panel + y[0] + model.addConstr(lhs_panel <= 1, name="panel_use") + + # Constraints (2) and (3): flow balance for all plates j != 0 + for pid in range(1, n_plates): + in_expr = gp.quicksum(flow_in[pid]) if flow_in[pid] else gp.LinExpr() + out_expr = gp.quicksum(flow_out[pid]) if flow_out[pid] else gp.LinExpr() + lhs = in_expr - out_expr + + if pid in J_bar: + # Constraint (2): for item plates + model.addConstr(lhs - y[pid] >= 0, name=f"flow[{pid}]") + else: + # Constraint (3): for non-item plates + if flow_in[pid] or flow_out[pid]: + model.addConstr(lhs >= 0, name=f"flow[{pid}]") + + # Constraint (5): capacity y_j <= u_j + for pid, item in J_bar.items(): + model.addConstr(y[pid] <= item['copies'], name=f"cap[{pid}]") + + # ------------------------------------------------------------------ + # Solve + # ------------------------------------------------------------------ + model.optimize() + + # ------------------------------------------------------------------ + # Extract and write solution + # ------------------------------------------------------------------ + status = model.Status + + if model.SolCount == 0: + obj_val = 0.0 + items_selected = [] + cuts_used = [] + sol_status = "infeasible_or_no_solution" + else: + obj_val = model.ObjVal + items_selected = [] + for pid, item in J_bar.items(): + val = y[pid].X + if val > 0.5: + items_selected.append({ + "item_id": item['id'], + "plate_id": pid, + "plate_dims": list(plates[pid]), + "copies": int(round(val)) + }) + cuts_used = [] + for idx, (pid, orient, q, c1_id, c2_id) in enumerate(cuts): + val = x[idx].X + if val > 0.5: + cuts_used.append({ + "parent_plate_id": pid, + "orientation": orient, + "position": q, + "child1_plate_id": c1_id, + "child2_plate_id": c2_id, + "count": int(round(val)) + }) + sol_status = "optimal" if status == GRB.OPTIMAL else "time_limit" + + solution = { + "objective_value": obj_val, + "status": sol_status, + "items_selected": items_selected, + "cuts_used": cuts_used, + "plates": [{"id": pid, "length": pl, "width": pw, + "in_J_bar": pid in J_bar} + for pid, (pl, pw) in enumerate(plates)], + "num_plates": n_plates, + "num_cuts": n_cuts, + } + + with open(solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Status: {sol_status}") + print(f"Objective value: {obj_val}") + print(f"Solution written to: {solution_path}") + return obj_val + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Solve G2KP via the PP-G2KP MIP model using Gurobi." + ) + parser.add_argument( + "--instance_path", required=True, + help="Path to the JSON instance file." + ) + parser.add_argument( + "--solution_path", required=True, + help="Path where the solution JSON will be written." + ) + parser.add_argument( + "--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds (default: 3600)." + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_g2kp(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/furini2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2016/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/furini2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2016/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2016/gurobi_solution/large_solution_1.json b/tasks/furini2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..900fb0c565034594a1e1aac62b431944ebf8517f --- /dev/null +++ b/tasks/furini2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:898ab20d11e6510c61d2b1bfde37627c502949c4e5395df7cd8b174ec6d376b3 +size 148 diff --git a/tasks/furini2016/gurobi_solution/large_solution_2.json b/tasks/furini2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4c8f55e906766ddd1dc36158d293fdd33b1137e5 --- /dev/null +++ b/tasks/furini2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bbb2fe55c14934feaf33b041cc73abc9a4e4cdc16a67675996e1c373745fa40 +size 3823899 diff --git a/tasks/furini2016/gurobi_solution/large_solution_3.json b/tasks/furini2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d3f3004e86c08598ac9761c6f932929758a6f75c --- /dev/null +++ b/tasks/furini2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4d60fd75c54658fd3ac2236a515cb30573c393bca9e62515b05e6285d974cc9 +size 3559749 diff --git a/tasks/furini2016/gurobi_solution/large_solution_4.json b/tasks/furini2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..fee611e9c7b3d3080ef93feebda85ba1aace990f --- /dev/null +++ b/tasks/furini2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fed52f3ce82620ec2d9e7b1772738c08469356834a1baf6d9c64ea1ecbb3daf +size 3668582 diff --git a/tasks/furini2016/gurobi_solution/large_solution_5.json b/tasks/furini2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c1c88ec2a248105fe3fc825cca32abbff8fcf460 --- /dev/null +++ b/tasks/furini2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b7742af938a818ec34e56f8b94e81c659ae17c21c81278da3820d906a58030d +size 3592722 diff --git a/tasks/furini2016/gurobi_solution/tiny_solution.json b/tasks/furini2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..57ca369c1f00578d9be0cddd6e1e486fef76a218 --- /dev/null +++ b/tasks/furini2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43fb60c04a7ed4fead3c7d1e69307c069ed974f5b5232191a6cd04dd23812ab6 +size 138698 diff --git a/tasks/furini2016/gurobi_solution_log/large_log_1.jsonl b/tasks/furini2016/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d259c11632099f27ab2738eb782cb6f42ee22520 --- /dev/null +++ b/tasks/furini2016/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f5c31d35ed34ad3181012976ce31084d2ff779fee8023fa5cf9e5af4cc4bb19 +size 42 diff --git a/tasks/furini2016/gurobi_solution_log/large_log_2.jsonl b/tasks/furini2016/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2e00df324248bb1bf97041ca43cc4d945290b228 --- /dev/null +++ b/tasks/furini2016/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80a2fd86beee23e1d662801bb101c6407f891b8126b193670d2174593f14cf95 +size 41 diff --git a/tasks/furini2016/gurobi_solution_log/large_log_3.jsonl b/tasks/furini2016/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..971ec3d435571cb4ca22e1c7f677bfffadb5c422 --- /dev/null +++ b/tasks/furini2016/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f316035f87be89eea884225b57763e94ef28960bb39119dc3c851532884a0f1b +size 42 diff --git a/tasks/furini2016/gurobi_solution_log/large_log_4.jsonl b/tasks/furini2016/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f17e04b050372f9fe1c699a8ca60f91f885c27f --- /dev/null +++ b/tasks/furini2016/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8cc61d5ea8417cf55265ee0d11bb443fe9262414e19002c1ad9241632849d3d +size 41 diff --git a/tasks/furini2016/gurobi_solution_log/large_log_5.jsonl b/tasks/furini2016/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..42b81436a7ffa6de43add1fd9fe3b10c35b6ced6 --- /dev/null +++ b/tasks/furini2016/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97d13c3a94f7aec109033607c7e2fdbbe0ea1af4d2eb6fb6b94255a550ac964d +size 42 diff --git a/tasks/furini2016/gurobi_solution_log/tiny_log.jsonl b/tasks/furini2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9318157dfee06e50118c2d753d68ff294fd7efde --- /dev/null +++ b/tasks/furini2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44eedd25a4ffe844c31594fd2bbba473a934f6c1398f79674bdcae0a336ef6e9 +size 41 diff --git a/tasks/furini2016/instance/large_instance_1.json b/tasks/furini2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..1f0f126d0abd47c47382e30ec697b51920755b1c --- /dev/null +++ b/tasks/furini2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0783d81d16703cd0fe5a8f0847ab2aa2c02df5eb187b9c3ca6dd2a382927fa2 +size 5033 diff --git a/tasks/furini2016/instance/large_instance_2.json b/tasks/furini2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1cf710fe5d08b15a2847cffff8bf74b66f7dab76 --- /dev/null +++ b/tasks/furini2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7d17bbe0b88555aec6f75d6eb9383216b335d394daab4b91ebd4525e4504c90 +size 3775 diff --git a/tasks/furini2016/instance/large_instance_3.json b/tasks/furini2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..dcb71c15df4ec9ad6e7f3017903d3115b1688011 --- /dev/null +++ b/tasks/furini2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c435885a7c8aa3625c142fd42f7e10d0c2410e2c9de086984ae8bf04f2284ca1 +size 5040 diff --git a/tasks/furini2016/instance/large_instance_4.json b/tasks/furini2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9c042e52a0514189d0000bc062db2d1415206592 --- /dev/null +++ b/tasks/furini2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92ecce346a2499e48bfbf0c04c04391f0f67f379191725fabdd98a1f62917290 +size 3800 diff --git a/tasks/furini2016/instance/large_instance_5.json b/tasks/furini2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..dc9c4d789a781e4f8ca344abf248cc0fd83765ea --- /dev/null +++ b/tasks/furini2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ed314c1afa6a61da3256b60873eb2926a54cc8e9e00c230031da0c6197ddb8b +size 5106 diff --git a/tasks/furini2016/instance/tiny_instance.json b/tasks/furini2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..0c81fe410178e5182fbfca89caea51806f27365e --- /dev/null +++ b/tasks/furini2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e157c9f43089641e90198adc13cc32f45702c00962f0cb3b581021ab3fcfdbf6 +size 1455 diff --git a/tasks/furini2016/instance_schema.json b/tasks/furini2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8e44da11d62a66f6ff6d04427c953824ddf015bb --- /dev/null +++ b/tasks/furini2016/instance_schema.json @@ -0,0 +1,18 @@ +{ + "panel": { + "length": " Horizontal dimension of the rectangular panel to be cut.", + "width": " Vertical dimension of the rectangular panel to be cut." + }, + "n": " Number of distinct item types that may be cut from the panel.", + "n_tilde": " Total number of item copies across all item types.", + "rho": " Ratio of the largest panel dimension to the largest item dimension.", + "items": [ + { + "id": " Unique identifier for this item type.", + "length": " Horizontal dimension of this item type.", + "width": " Vertical dimension of this item type.", + "profit": " Profit earned for each copy of this item type that is cut from the panel.", + "copies": " Maximum number of copies of this item type that may be cut." + } + ] +} diff --git a/tasks/furini2016/mathematical_formulation.md b/tasks/furini2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..6a1226c154115d564149cb8cda753748f0fe9c1e --- /dev/null +++ b/tasks/furini2016/mathematical_formulation.md @@ -0,0 +1,57 @@ +# Original Formulation: Guillotine Two-Dimensional Knapsack Problem (G2KP) + +*Source: Modeling Two-Dimensional Guillotine Cutting Problems via Integer Programming, Fabio Furini, Enrico Malaguti, Dimitri Thomopulos, 2016.* + +## Sets and Indices + +- $J$ : set of plates (the original rectangular panel together with the smaller rectangular residual plates obtained from sequences of guillotine cuts). The panel is indexed by $j=0$ and has dimensions $L,W$; each plate $j\in J$ has dimensions $(l_j,w_j)$ with $1\le w_j\le W$ and $1\le l_j\le L$. + +- $\bar J\subseteq J$ : subset of plates whose dimensions equal one of the items to obtain; with a slight abuse of notation $\bar J$ also denotes the set of items. Without loss of generality $0\in\bar J$ (if the panel does not correspond to an item, set $u_0=0$). + +- $O=\{h,v\}$ : set of possible cut orientations (horizontal and vertical), with $o\in O$ the generic orientation. + +- $Q(j,o)$ : set of positions where plate $j$ can be cut with orientation $o\in O$. In the model, $Q(j,h)=\{1,\dots,w_j-1\}$ and $Q(j,v)=\{1,\dots,l_j-1\}$. + +## Parameters + +- $L,W$ : length and width of the original rectangular panel. + +- $n$ : number of item types. + +- $l_i,\,w_i$ : length and width of item $i$, $i=1,\dots,n$. + +- $p_i$ : profit of item $i$, $i=1,\dots,n$. + +- $u_i$ : number of available copies of item $i$, $i=1,\dots,n$. + +- $a^o_{qkj}$ : coefficient taking value $1$ when a plate of type $k$ produces a plate of type $j$ by a cut at position $q$ with orientation $o$, and $0$ otherwise. + +All problem data are assumed, without loss of generality, to be positive integers. + +## Decision Variables + +- $x^o_{qj}$ : integer variable, number of times a plate of type $j$ is cut at position $q$ through a guillotine cut with orientation $o$, for $j\in J,\ o\in O,\ q\in Q(j,o)$. + +- $y_j$ : integer variable, number of plates of type $j$ kept as final items (equivalently, number of items of type $j$ obtained), for $j\in\bar J$. + +## Objective + +$$\begin{equation} + \text{(PP-G2KP):}\qquad \max \sum_{j\in\bar J} p_j\, y_j \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} + &\sum_{k\in J}\sum_{o\in O}\sum_{q\in Q(k,o)} a^o_{qkj}\, x^o_{qk} + \;-\; \sum_{o\in O}\sum_{q\in Q(j,o)} x^o_{qj} \;-\; y_j \;\ge\; 0, + && j\in\bar J,\ j\neq 0 \tag{2}\\[4pt] + &\sum_{k\in J}\sum_{o\in O}\sum_{q\in Q(k,o)} a^o_{qkj}\, x^o_{qk} + \;-\; \sum_{o\in O}\sum_{q\in Q(j,o)} x^o_{qj} \;\ge\; 0, + && j\in J\setminus\bar J \tag{3}\\[4pt] + &\sum_{o\in O}\sum_{q\in Q(0,o)} x^o_{q0} \;+\; y_0 \;\le\; 1 + && \tag{4}\\[4pt] + &y_j \;\le\; u_j, && j\in\bar J \tag{5}\\[4pt] + &x^o_{qj} \;\ge\; 0\ \text{integer}, && j\in J,\ o\in O,\ q\in Q(j,o) \tag{6}\\[4pt] + &y_j \;\ge\; 0\ \text{integer}, && j\in\bar J \tag{7} +\end{align}$$ diff --git a/tasks/furini2016/problem_description.txt b/tasks/furini2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..77d3536478526f1352bec42a2fa538d0c61605fa --- /dev/null +++ b/tasks/furini2016/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A manufacturer must cut rectangular items from a single large rectangular panel of known length and width. There are several item types, each defined by a length, a width, a profit, and a maximum number of available copies. All dimensions and profits are positive integers. The goal is to select and cut a subset of items from the panel so as to maximize the total profit of the items obtained. + +All cuts must be guillotine cuts, meaning each cut is a straight line that runs parallel to one side of the rectangle being cut and extends completely from one edge to the opposite edge, splitting that rectangle into exactly two smaller rectangles. There is no limit on the number of sequential cutting stages, and cuts need not be restricted (that is, the position of a cut need not coincide with the boundary of any item). Cuts may be either horizontal or vertical. + +The cutting process works as follows. The original panel is the initial plate. Any plate may be split by a single guillotine cut into two smaller plates. Each of those smaller plates may in turn be split again, and so on recursively. A plate whose dimensions exactly match those of some item type may instead be kept as a finished item rather than being cut further. Any plate that is too small to contain any item is discarded. The process continues until every remaining plate has either been kept as an item or discarded. + +The manufacturer must decide how to recursively cut the original panel and which resulting item-sized plates to retain as finished items. The number of finished items of each type kept cannot exceed that type's maximum available copies. The quantity to maximize is the sum over all retained items of the item's profit times the number of copies retained. diff --git a/tasks/furini2016/solution_logger.py b/tasks/furini2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/furini2016/solution_logger.py @@ -0,0 +1,61 @@ +""" +Convergence logger for optimization algorithms. + +Records incumbent solutions with timestamps to a JSONL file. +This module is provided to LLM-generated programs — they only need to call +`log(objective_value)` whenever a better feasible solution is found. + +Usage in generated code: + from solution_logger import SolutionLogger + logger = SolutionLogger(log_path, sense="minimize") # or "maximize" + # ... inside algorithm loop: + logger.log(objective_value) +""" + +import json +import time + + +class SolutionLogger: + def __init__(self, log_path, sense="minimize"): + """ + Args: + log_path: Path to the JSONL output file. + sense: "minimize" or "maximize". + """ + self.log_path = log_path + self.sense = sense + self.start_time = time.time() + self.best_obj = None + self.min_interval = 0.1 # seconds, avoid excessive writes + + self._last_log_time = 0.0 + # Clear the file + with open(self.log_path, "w") as f: + pass + + def log(self, objective_value): + """Record a new incumbent if it improves on the best known.""" + if objective_value is None: + return + + # Check if this is an improvement + if self.best_obj is not None: + if self.sense == "minimize" and objective_value >= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/furini2016/solution_schema.json b/tasks/furini2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b815c0a3a1b16021b80cb55f32d12afd15036b99 --- /dev/null +++ b/tasks/furini2016/solution_schema.json @@ -0,0 +1,10 @@ +{ + "objective_value": " Total profit of the items retained from the panel.", + "items_selected": [ + { + "item_id": " Identifier of the item type that is kept as a finished item.", + "plate_dims": " Length and width of the finished item kept.", + "copies": " Number of finished copies retained of this item type." + } + ] +} diff --git a/tasks/furini2017/feasibility_check.py b/tasks/furini2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..db57b57fe1a71ab4e50041f95bac4963e1445d31 --- /dev/null +++ b/tasks/furini2017/feasibility_check.py @@ -0,0 +1,406 @@ +""" +Feasibility checker for the Vertex Coloring Problem (VCP). + +Based on: Furini, Gabrel, Ternier (2017) — "An Improved DSATUR-Based +Branch-and-Bound Algorithm for the Vertex Coloring Problem" + +Mathematical formulation constraints (MSSP on auxiliary graph G_A): + Constraint (1): x_u + x_v <= 1 for all (u, v) in E_A [tag 6] + Constraint (2): x_v in {0, 1} for all v in V_A [tag 7] + +These map to the VCP coloring solution as: + Constraint (1): Proper coloring — for each edge (u,v) in E, + color(u) != color(v). + Constraint (2): Valid assignment — every vertex v in V is assigned + exactly one non-negative integer color. + Constraint (3): Objective consistency — the reported objective_value + (min number of colors k) must equal the number of + distinct colors actually used in the coloring. This is + a Tier C defense against score-gaming exploits where a + candidate submits a valid coloring but reports a + fabricated objective_value. + +NOTE: this is the obj-recompute variant of feasibility_check.py. It is a +strict superset of the original — it never removes a violation the +original reports and only ever adds constraint index 3. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('color_classes', 'coloring', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('color_classes',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def check_feasibility(instance, solution): + """Check all hard constraints of the VCP coloring solution.""" + violations = [] + violation_magnitudes = [] + + graph = instance["graph"] + n = graph["n"] + edges = graph["edges"] + + # Extract coloring from solution + coloring = solution.get("coloring", None) + num_colors_used = solution.get("num_colors_used", None) + + if coloring is None: + # Solution only has objective_value (e.g., efficient_algorithm output). + # No structural solution to verify — report feasible. + return violations, violation_magnitudes + + # Convert string keys to int keys if needed + coloring = {int(k): v for k, v in coloring.items()} + + # ------------------------------------------------------------------ + # Constraint (1): Proper coloring — x_u + x_v <= 1 for all (u,v) in E_A + # Mapped to: for each edge (u,v) in E, color(u) != color(v). + # When both endpoints share color c, the assignment indicator + # y_{u,c} + y_{v,c} = 2 > 1, so LHS=2, RHS=1, violation_amount=1. + # ------------------------------------------------------------------ + conflict_edges = [] + for edge in edges: + u, v = edge[0], edge[1] + cu = coloring.get(u, None) + cv = coloring.get(v, None) + if cu is not None and cv is not None and cu == cv: + conflict_edges.append((u, v, cu)) + + if conflict_edges: + lhs = 2.0 + rhs = 1.0 + raw_excess = lhs - rhs # = 1.0 + normalizer = max(abs(rhs), EPS) + ratio = raw_excess / normalizer + + edge_strs = [f"({u},{v}) both color {c}" for u, v, c in conflict_edges] + msg = ( + f"Constraint (1) [proper coloring]: {len(conflict_edges)} edge(s) " + f"have both endpoints with the same color: " + + "; ".join(edge_strs[:10]) + ) + if len(conflict_edges) > 10: + msg += f" ... and {len(conflict_edges) - 10} more" + violations.append(msg) + + for u, v, c in conflict_edges: + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint (2): Valid assignment — x_v in {0,1} for all v in V_A + # Mapped to: every vertex v in V must be assigned exactly one + # non-negative integer color in {0, ..., k-1}. + # ------------------------------------------------------------------ + + # 2a. Check that every vertex is colored + uncolored = [v for v in range(n) if v not in coloring] + if uncolored: + # Each uncolored vertex violates the assignment constraint. + # LHS = 0 (number of colors assigned), RHS = 1, this is a >= constraint. + lhs_val = 0.0 + rhs_val = 1.0 + raw_excess = rhs_val - lhs_val # = 1.0 + normalizer = max(abs(rhs_val), EPS) + ratio = raw_excess / normalizer + + msg = ( + f"Constraint (2) [valid assignment]: {len(uncolored)} vertex/vertices " + f"not assigned any color: {uncolored[:10]}" + ) + if len(uncolored) > 10: + msg += f" ... and {len(uncolored) - 10} more" + violations.append(msg) + + for v in uncolored: + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + }) + + # 2b. Check that all color values are non-negative integers + invalid_colors = [] + for v, c in coloring.items(): + if not isinstance(c, int) or c < 0: + invalid_colors.append((v, c)) + + if invalid_colors: + # LHS = actual value, RHS = 0 (lower bound), >= constraint + msg = ( + f"Constraint (2) [valid assignment]: {len(invalid_colors)} vertex/vertices " + f"have invalid color values: " + + "; ".join(f"vertex {v} -> {c}" for v, c in invalid_colors[:10]) + ) + if len(invalid_colors) > 10: + msg += f" ... and {len(invalid_colors) - 10} more" + violations.append(msg) + + for v, c in invalid_colors: + raw_excess = 1.0 # binary domain violation + normalizer = max(abs(1.0), EPS) + ratio = raw_excess / normalizer + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(c) if isinstance(c, (int, float)) else 0.0, + "rhs": 0.0, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint (3): Objective consistency (Tier C obj-recompute). + # The VCP objective is min k = the number of distinct colors used. + # Every variable the objective depends on (the per-vertex coloring) + # is present in the solution, so a FULL recompute applies: + # true_obj = number of distinct color labels in `coloring`. + # Reject when the reported objective_value disagrees. The objective + # is an integer color count, so a tolerance of 0.5 fires on any + # integer mismatch by >= 1 while tolerating float round-trip noise. + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value", None) + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(len(set(coloring.values()))) + abs_diff = abs(reported - true_obj) + tol = 0.5 + if abs_diff > tol: + raw_excess = abs_diff + normalizer = max(abs(true_obj), EPS) + ratio = raw_excess / normalizer + msg = ( + f"Constraint (3) [objective consistency]: reported " + f"objective_value={reported_obj} differs from the " + f"recomputed number of distinct colors used in the " + f"coloring ({int(true_obj)}) " + f"(|diff|={abs_diff:.6g}, tol={tol})" + ) + violations.append(msg) + violation_magnitudes.append({ + "constraint": 3, + "lhs": reported, + "rhs": true_obj, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + }) + + return violations, violation_magnitudes + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Vertex Coloring Problem (Furini et al. 2017)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + violations, violation_magnitudes = check_feasibility(instance, solution) + + # Collect unique violated constraint indices + violated_constraints = sorted( + set(vm["constraint"] for vm in violation_magnitudes) + ) + + feasible = len(violated_constraints) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if feasible else "INFEASIBLE" + print(f"Result: {status}") + if not feasible: + for v in violations: + print(f" - {v}") + print(f"Written to {args.result_path}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/furini2017/gurobi_code.py b/tasks/furini2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..f724b9bcbadff5d0f1fdfe8b4e20d4f39c30db61 --- /dev/null +++ b/tasks/furini2017/gurobi_code.py @@ -0,0 +1,428 @@ +""" +Vertex Coloring Problem (VCP) via auxiliary graph formulation. + +Based on: Furini, Gabrel, Ternier (2017) +Uses the relationship chi(G) = |V| - alpha(G_A) where G_A is an auxiliary graph +and alpha(G_A) is the maximum stable set size on G_A. + +The auxiliary graph G_A is constructed as: +1. Build complement graph of G +2. Orient complement edges acyclically: arc (v_i, v_j) if i < j +3. Build line graph L of oriented complement +4. Remove simplicial pair edges from L + +The MSSP (Maximum Stable Set Problem) on G_A is solved via Gurobi ILP. +""" + +import argparse +import json +import sys +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(instance_path): + """Load graph instance from JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + graph = data["graph"] + n = graph["n"] + edges = [tuple(e) for e in graph["edges"]] + return n, edges + + +def build_adjacency_set(n, edges): + """Build adjacency set for quick lookup.""" + adj = set() + for u, v in edges: + adj.add((u, v)) + adj.add((v, u)) + return adj + + +def build_auxiliary_graph(n, edges): + """ + Build auxiliary graph G_A following Furini et al. (2017). + + Returns: + arc_list: list of complement arcs (i, j) with i < j + aux_edges: list of edges in G_A (pairs of arc indices) + """ + adj_set = build_adjacency_set(n, edges) + + # Step 1-2: Build oriented complement arcs (i, j) where i < j and (i, j) not in E + arc_list = [] + for i in range(n): + for j in range(i + 1, n): + if (i, j) not in adj_set: + arc_list.append((i, j)) + + if len(arc_list) == 0: + return arc_list, [] + + # Index arcs by their endpoints for line graph construction + # arc_from_endpoint[v] = list of arc indices that have v as an endpoint + arc_from_source = defaultdict(list) + arc_from_target = defaultdict(list) + for idx, (u, v) in enumerate(arc_list): + arc_from_source[u].append(idx) + arc_from_target[v].append(idx) + + # Collect all arc indices touching each vertex + arc_at_vertex = defaultdict(list) + for idx, (u, v) in enumerate(arc_list): + arc_at_vertex[u].append(idx) + arc_at_vertex[v].append(idx) + + # Step 3: Build line graph edges - two arcs are adjacent if they share an endpoint + line_edges_set = set() + for vertex, arc_indices in arc_at_vertex.items(): + for ii in range(len(arc_indices)): + for jj in range(ii + 1, len(arc_indices)): + a = arc_indices[ii] + b = arc_indices[jj] + key = (min(a, b), max(a, b)) + line_edges_set.add(key) + + # Step 4: Remove simplicial pair edges + # A pair {a, b} is simplicial if: + # a = (u, v), b = (u, w) (same source u), and + # (min(v, w), max(v, w)) is also a complement arc (i.e., v and w are non-adjacent in G) + simplicial = set() + for u, arc_indices in arc_from_source.items(): + # All arcs from source u: (u, v1), (u, v2), ... + targets = [(idx, arc_list[idx][1]) for idx in arc_indices] + for ii in range(len(targets)): + for jj in range(ii + 1, len(targets)): + idx_a, v = targets[ii] + idx_b, w = targets[jj] + # Check if (min(v,w), max(v,w)) is a complement arc + # i.e., v and w are non-adjacent in G + if (v, w) not in adj_set and (w, v) not in adj_set and v != w: + key = (min(idx_a, idx_b), max(idx_a, idx_b)) + simplicial.add(key) + + aux_edges = [e for e in line_edges_set if e not in simplicial] + + return arc_list, aux_edges + + +def solve_mssp(arc_list, aux_edges, time_limit): + """ + Solve Maximum Stable Set Problem on auxiliary graph G_A using Gurobi. + + Returns: + alpha: size of maximum stable set (or best found) + selected: list of selected arc indices + optimal: whether solution is proven optimal + """ + num_vars = len(arc_list) + + if num_vars == 0: + return 0, [], True + + model = gp.Model("MSSP") + model.setParam("Threads", 1) + model.setParam("OutputFlag", 0) + model.setParam("TimeLimit", time_limit) + + # Binary variables x_v for each vertex in G_A (each complement arc) + x = model.addVars(num_vars, vtype=GRB.BINARY, name="x") + + # Objective: maximize sum of x_v + model.setObjective(gp.quicksum(x[v] for v in range(num_vars)), GRB.MAXIMIZE) + + # Constraints: x_u + x_v <= 1 for each edge (u, v) in G_A + for u, v in aux_edges: + model.addConstr(x[u] + x[v] <= 1) + + model.optimize() + + if model.SolCount == 0: + return 0, [], False + + optimal = model.Status == GRB.OPTIMAL + alpha = int(round(model.ObjVal)) + selected = [i for i in range(num_vars) if x[i].X > 0.5] + + return alpha, selected, optimal + + +class UnionFind: + """Union-Find data structure for merging vertices into color classes.""" + + def __init__(self, n): + self.parent = list(range(n)) + self.rank = [0] * n + + def find(self, x): + while self.parent[x] != x: + self.parent[x] = self.parent[self.parent[x]] + x = self.parent[x] + return x + + def union(self, x, y): + rx, ry = self.find(x), self.find(y) + if rx == ry: + return + if self.rank[rx] < self.rank[ry]: + rx, ry = ry, rx + self.parent[ry] = rx + if self.rank[rx] == self.rank[ry]: + self.rank[rx] += 1 + + +def extract_coloring_from_stable_set(n, edges, arc_list, selected): + """ + Extract a vertex coloring from the selected stable set arcs. + + Each selected arc (i, j) in the complement means i and j are non-adjacent in G, + so they can share a color. We merge endpoints via union-find. + + Returns: + coloring: dict mapping vertex -> color (0-indexed) + valid: whether the coloring is valid + """ + uf = UnionFind(n) + for idx in selected: + u, v = arc_list[idx] + uf.union(u, v) + + # Assign colors based on connected components + root_to_color = {} + color_counter = 0 + coloring = {} + for v in range(n): + root = uf.find(v) + if root not in root_to_color: + root_to_color[root] = color_counter + color_counter += 1 + coloring[v] = root_to_color[root] + + # Verify coloring validity + adj_set = build_adjacency_set(n, edges) + valid = True + for u, v in edges: + if coloring[u] == coloring[v]: + valid = False + break + + return coloring, valid + + +def dsatur_coloring(n, edges): + """ + DSATUR greedy heuristic for vertex coloring. + + At each step, color the uncolored vertex with the highest saturation degree + (number of distinct colors in its neighborhood). Break ties by highest + uncolored degree. + + Returns: + coloring: dict mapping vertex -> color (0-indexed) + num_colors: number of colors used + """ + adj_list = defaultdict(set) + for u, v in edges: + adj_list[u].add(v) + adj_list[v].add(u) + + coloring = {} + neighbor_colors = defaultdict(set) # vertex -> set of colors used by neighbors + colored = [False] * n + + for _ in range(n): + # Pick uncolored vertex with max saturation, break ties by degree + best_v = -1 + best_sat = -1 + best_deg = -1 + for v in range(n): + if colored[v]: + continue + sat = len(neighbor_colors[v]) + deg = len(adj_list[v]) + if sat > best_sat or (sat == best_sat and deg > best_deg): + best_v = v + best_sat = sat + best_deg = deg + + # Assign smallest available color + used = neighbor_colors[best_v] + c = 0 + while c in used: + c += 1 + coloring[best_v] = c + colored[best_v] = True + + # Update neighbor saturation + for w in adj_list[best_v]: + if not colored[w]: + neighbor_colors[w].add(c) + + num_colors = max(coloring.values()) + 1 if coloring else 0 + return coloring, num_colors + + +def solve_k_coloring_ilp(n, edges, k, time_limit): + """ + Solve a k-coloring assignment ILP to find a valid coloring with exactly k colors. + + Variables: + x_{v,c} in {0,1}: vertex v gets color c + Constraints: + sum_c x_{v,c} = 1 for all v (each vertex gets exactly one color) + x_{u,c} + x_{v,c} <= 1 for all (u,v) in E, for all c + + Returns: + coloring: dict mapping vertex -> color, or None if infeasible/timeout + """ + model = gp.Model("KColoring") + model.setParam("Threads", 1) + model.setParam("OutputFlag", 0) + model.setParam("TimeLimit", time_limit) + + # Variables + x = model.addVars(n, k, vtype=GRB.BINARY, name="x") + + # Each vertex gets exactly one color + for v in range(n): + model.addConstr(gp.quicksum(x[v, c] for c in range(k)) == 1) + + # Adjacent vertices get different colors + for u, v in edges: + for c in range(k): + model.addConstr(x[u, c] + x[v, c] <= 1) + + # Symmetry breaking: color 0 assigned to vertex 0 + if n > 0 and k > 0: + model.addConstr(x[0, 0] == 1) + + # Feasibility problem + model.setObjective(0, GRB.MINIMIZE) + + model.optimize() + + if model.SolCount == 0: + return None + + coloring = {} + for v in range(n): + for c in range(k): + if x[v, c].X > 0.5: + coloring[v] = c + break + + return coloring + + +def main(): + parser = argparse.ArgumentParser( + description="Solve Vertex Coloring Problem using auxiliary graph formulation " + "(Furini, Gabrel, Ternier 2017)" + ) + parser.add_argument( + "--instance_path", type=str, required=True, help="Path to instance JSON file" + ) + parser.add_argument( + "--solution_path", type=str, required=True, help="Path to output solution JSON file" + ) + parser.add_argument( + "--time_limit", type=int, default=3600, help="Time limit in seconds (default: 3600)" + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # Load instance + n, edges = load_instance(args.instance_path) + + # Build auxiliary graph G_A + arc_list, aux_edges = build_auxiliary_graph(n, edges) + + # Handle edge case: complete graph (no complement edges) + if len(arc_list) == 0: + # Every pair is adjacent, need n colors + chi = n + coloring = {v: v for v in range(n)} + else: + # Solve MSSP on G_A + alpha, selected, optimal = solve_mssp(arc_list, aux_edges, args.time_limit) + + # chi(G) = |V| - alpha(G_A) + chi = n - alpha + + # Extract coloring from stable set solution + coloring, valid = extract_coloring_from_stable_set(n, edges, arc_list, selected) + + if not valid: + # Fallback 1: try k-coloring ILP with k = chi + remaining_time = max(args.time_limit / 4, 60.0) + ilp_coloring = solve_k_coloring_ilp(n, edges, chi, remaining_time) + if ilp_coloring is not None: + coloring = ilp_coloring + valid = True + + if not valid: + # Fallback 2: DSATUR greedy heuristic + coloring, num_colors_dsatur = dsatur_coloring(n, edges) + # If DSATUR uses more colors than chi, update chi to be safe + # (chi from MSSP is a lower bound if optimal, but coloring must be feasible) + if num_colors_dsatur > chi: + chi = num_colors_dsatur + + # Build color classes + num_colors_used = max(coloring.values()) + 1 if coloring else 0 + color_classes = defaultdict(list) + for v in range(n): + color_classes[coloring[v]].append(v) + + # Final validation + adj_set = build_adjacency_set(n, edges) + coloring_valid = True + for u, v in edges: + if coloring[u] == coloring[v]: + coloring_valid = False + break + + # Prepare solution + solution = { + "objective_value": chi, + "num_colors_used": num_colors_used, + "coloring_valid": coloring_valid, + "coloring": coloring, + "color_classes": {str(c): verts for c, verts in sorted(color_classes.items())}, + "auxiliary_graph": { + "num_complement_arcs": len(arc_list), + "num_aux_edges": len(aux_edges), + "stable_set_size": chi and (n - chi) or 0, + }, + } + + # Write solution + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Chromatic number (chi): {chi}") + print(f"Colors used in coloring: {num_colors_used}") + print(f"Coloring valid: {coloring_valid}") + print(f"Auxiliary graph: {len(arc_list)} arcs, {len(aux_edges)} edges") + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/furini2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/furini2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2017/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/furini2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2017/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/furini2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/furini2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/furini2017/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102