diff --git a/tasks/kang2021/instance_schema.json b/tasks/kang2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5e84fa3b849aa414fd56c379a4465e5298628879 --- /dev/null +++ b/tasks/kang2021/instance_schema.json @@ -0,0 +1,23 @@ +{ + "num_customers": " Number of customers to be served.", + "num_nodes": " Total number of nodes including the depot and all customers.", + "parameters": { + "truck_speed": " Travel speed of the truck.", + "truck_service_time": " Time the truck spends servicing at each visited customer location.", + "num_drones": " Number of drones carried by the truck.", + "drone_speed_parameters_alpha": " Speed parameter for each drone, where higher values indicate faster but more energy-consuming drones.", + "drone_battery_capacities": " Maximum total battery energy available to each drone across all its assigned deliveries.", + "standard_drone_speed": " Travel speed of the baseline standard drone.", + "standard_drone_flight_duration": " Maximum flight duration of the baseline standard drone.", + "standard_drone_service_time": " Time a drone spends servicing at each customer location." + }, + "depot_index": " Index of the depot node where the truck starts and ends its route.", + "customer_indices": " Indices of all customer nodes that must be served.", + "node_positions": { + "x": " Horizontal coordinate of each node.", + "y": " Vertical coordinate of each node." + }, + "truck_travel_times": " Truck travel time from each node to every other node, including service time at the destination.", + "drone_battery_consumption": " Battery energy consumed by each drone for a round-trip delivery from a launch node to a customer and back.", + "drone_delivery_time": " Elapsed time for each drone to complete a round-trip delivery from a launch node to a customer and back." +} diff --git a/tasks/kang2021/mathematical_formulation.md b/tasks/kang2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..df96363f0c88b9a04efc5a5d552bcc79e2a9cc69 --- /dev/null +++ b/tasks/kang2021/mathematical_formulation.md @@ -0,0 +1,67 @@ +# Original Formulation: Heterogeneous Drone-Truck Routing Problem (HDTRP) + +*Source: An Exact Algorithm for Heterogeneous Drone-Truck Routing Problem, Munjeong Kang and Chungmok Lee, Transportation Science 55(5):1088–1112, 2021.* + +## Sets and Indices + +- $N$ : set of customers. + +- $d$ : the (single) depot node, duplicated into two identical nodes $s$ and $t$. + +- $s,\, t$ : duplicated depot nodes ($s$ = origin/start, $t$ = destination/end); both represent the physical depot $d$. + +- $N_s := N \cup \{s\}$. + +- $N_t := N \cup \{t\}$. + +- $N_{st} := N \cup \{s, t\}$. + +- $G(N_{st}, A)$ : directed graph. + +- $A := \{(i,j) \mid i \in N_s,\, j \in N_t,\, i \neq j\}$ : set of arcs. + +- $L$ : set of drones. + +## Parameters + +- $t^v_{ij}$ : truck travel time of arc $(i,j) \in A$ (includes the service time at node $j$). + +- $B^l$ : battery capacity of drone $l \in L$ (how long the drone can be used for deliveries). + +- $b^l_{ij}$ : total battery consumption required for drone $l \in L$ to complete the delivery operation from waiting node $i \in N_s$ for the demand of customer $j \in N$. + +- $\tau^l_{ij}$ : total required time for drone $l \in L$ to complete the delivery from $i$ to $j$. + +- $M$ : a sufficiently large number (big-$M$). + +## Decision Variables + +- $x_{ij} \in \{0,1\}$ : $1$ if the truck moves from $i$ to $j$, $0$ otherwise, $\forall (i,j) \in A$. + +- $h^l_{ij} \in \{0,1\}$ : $1$ if drone $l \in L$ is dispatched at node $i$ for the delivery of customer $j$, $0$ otherwise, $\forall (i,j) \in A$. + +- $v_i$ : continuous variable representing the visiting order of the truck at node $i$. + +- $w_i$ : continuous variable representing the truck waiting time at node $i$. + +## Objective + +$$\begin{equation} + \text{(P)} \quad \min \ \sum_{(i,j) \in A} t^v_{ij}\, x_{ij} \;+\; \sum_{i \in N_s} w_i \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} + & \sum_{j \in N} x_{sj} = 1, \tag{2}\\[2pt] + & \sum_{i \in N} x_{it} = 1, \tag{3}\\[2pt] + & \sum_{j \in N_t:\, j \neq i} x_{ij} = \sum_{j \in N_s:\, j \neq i} x_{ji}, && \forall\, i \in N, \tag{4}\\[2pt] + & v_i - v_j \leq M(1 - x_{ij}) - 1, && \forall\, (i,j) \in A, \tag{5}\\[2pt] + & \sum_{i \in N_s:\, i \neq j} x_{ij} + \sum_{i \in N_s:\, i \neq j} \sum_{l \in L} h^l_{ij} = 1, && \forall\, j \in N, \tag{6}\\[2pt] + & M \sum_{j \in N_t:\, j \neq i} x_{ij} \geq \sum_{j \in N:\, j \neq i} \sum_{l \in L} h^l_{ij}, && \forall\, i \in N_s, \tag{7}\\[2pt] + & \sum_{i \in N_s} \sum_{j \in N:\, j \neq i} b^l_{ij}\, h^l_{ij} \leq B^l, && \forall\, l \in L, \tag{8}\\[2pt] + & w_i \geq \sum_{j \in N:\, j \neq i} \tau^l_{ij}\, h^l_{ij}, && \forall\, i \in N_s,\, l \in L, \tag{9}\\[2pt] + & v_s = 0, \tag{10}\\[2pt] + & x_{ij} \in \{0,1\}, && \forall\, (i,j) \in A, \tag{11}\\[2pt] + & h^l_{ij} \in \{0,1\}, && \forall\, (i,j) \in A,\, l \in L. \tag{12} +\end{align}$$ diff --git a/tasks/kang2021/problem_description.txt b/tasks/kang2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..1cc930908cf4aa4d17056c19ce5c233f2275203c --- /dev/null +++ b/tasks/kang2021/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A delivery company operates a single truck equipped with a fleet of heterogeneous drones to serve a set of customers from a single depot. Each drone has its own speed parameter and battery capacity, meaning faster drones consume more energy per unit distance and consequently have shorter maximum flight durations. The truck departs from the depot, visits a subset of customer locations along a route, and returns to the depot. At any node the truck visits, one or more drones may be dispatched simultaneously to serve nearby customers. A drone delivery from a given node consists of a round trip: the drone flies from the truck's current location to the assigned customer, delivers the demand, and returns to the same node. Each drone carries exactly one customer's demand per trip but may make multiple such round trips from the same or different nodes over the course of the route, provided its total battery consumption across all assigned deliveries does not exceed its battery capacity. While drones are out making deliveries, the truck must wait at the dispatch node until every drone dispatched from that node has returned; only then may the truck proceed to its next stop. + +The input data specifies the number of customers, the number of drones, the two-dimensional coordinates of the depot and all customers, the truck travel time for every ordered pair of nodes (which includes the service time at the destination node), and for each drone and every ordered pair of a potential launch node and a customer, both the total battery consumption and the total elapsed time for the round-trip delivery. Each drone's battery capacity is also given. + +The company must determine the truck's route through a subset of customer locations starting and ending at the depot, which customers are served directly by the truck along its route versus served by a drone, and for each drone-served customer, from which node the drone is launched and which specific drone performs the delivery. The truck's waiting time at each visited node must also be determined. + +Every customer must be served exactly once, either by the truck visiting that customer directly on its route or by exactly one drone making a delivery to that customer from some node on the truck's route. Drones may only be dispatched from nodes that the truck actually visits. The truck's route must form a single connected tour from the depot through the truck-visited customers and back to the depot, and no customer appears more than once on the truck's route (customers served by drones are not visited by the truck at all). The total battery consumed by each drone across all of its assigned deliveries must not exceed that drone's battery capacity. The truck's waiting time at each node must be at least as large as the combined round-trip delivery time of each drone for all deliveries that drone performs from that node. Because this must hold for every drone independently, the truck effectively waits for whichever drone has the longest total delivery time from that node before departing. + +The goal is to minimize the total completion time, defined as the sum of the truck's travel times along all arcs of its route plus the sum of the truck's waiting times at all nodes it visits. diff --git a/tasks/kang2021/solution_logger.py b/tasks/kang2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/kang2021/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/kang2021/solution_schema.json b/tasks/kang2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1d7bfbdbc71464704803244be3c089c540a9f17d --- /dev/null +++ b/tasks/kang2021/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total completion time, comprising the truck's travel time along its route plus all waiting times at visited nodes.", + "truck_route": " Arcs traversed by the truck, where each entry is a pair of origin and destination node indices forming the route from depot to depot.", + "drone_assignments": " Drone-to-customer delivery assignments, where each entry specifies which drone delivers to which customer from which node on the truck's route.", + "drone_assignments[*].drone": " Index of the drone performing this delivery.", + "drone_assignments[*].dispatch_node": " Node on the truck's route from which the drone is launched for this delivery.", + "drone_assignments[*].delivery_node": " Customer node served by the drone on this delivery.", + "waiting_times": " Time the truck waits at each visited node for all dispatched drones to return." +} diff --git a/tasks/klose2005/feasibility_check.py b/tasks/klose2005/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf06ba0fb7678043c79d0fae58623d152ea7ce6 --- /dev/null +++ b/tasks/klose2005/feasibility_check.py @@ -0,0 +1,466 @@ +""" +Feasibility checker for the Capacitated Facility Location Problem (CFLP). + +Reference: Klose & Drexl (2005), "Lower Bounds for the Capacitated Facility +Location Problem Based on Column Generation", Management Science 51(11):1689-1705. + +Constraints (numbered top-to-bottom from the formulation): + (1) Demand: sum_j x_{ij} = 1 for all i in I + (2) Capacity: sum_i d_i x_{ij} <= s_j y_j for all j in J + (3) Var bounds: 0 <= x_{ij} <= 1 for all i in I, j in J + (4) Var bounds: 0 <= y_j <= 1 for all j in J + (5) Integrality: y_j in {0, 1} for all j in J + (6) Objective consistency: the reported objective_value must equal the + objective recomputed from the solution variables, + Z = sum_{i,j} c_{ij} x_{ij} + sum_j f_j y_j. + This is a Tier C defense against score-gaming exploits where a + candidate returns a fabricated objective_value while the routes / + assignments remain technically feasible. Both x_{ij} and y_j are + fully present in the solution, so a full recompute is possible. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', 'objective_value', 'open_plants') +_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, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + n_cust = instance["num_customers"] + n_plant = instance["num_plants"] + demands = instance["customers"]["demands"] + capacities = instance["plants"]["capacities"] + + open_plants = set(solution["open_plants"]) + assignments = solution["assignments"] + + # Build y vector: y_j = 1 if j in open_plants, else 0 + y = [1.0 if j in open_plants else 0.0 for j in range(n_plant)] + + # Build x matrix from assignments (sparse dict of dicts) + # assignments is keyed by customer index (string) -> {plant_index (string): fraction} + x = [[0.0] * n_plant for _ in range(n_cust)] + for i_str, alloc in assignments.items(): + i = int(i_str) + for j_str, val in alloc.items(): + j = int(j_str) + x[i][j] = val + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint (1): Demand -- sum_j x_{ij} = 1 for all i in I + # ========================================================================= + for i in range(n_cust): + lhs = sum(x[i][j] for j in range(n_plant)) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(1) + violations.append( + f"Constraint (1) violated: customer {i} demand fraction sum = {lhs:.8f}, expected 1.0" + ) + 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): Capacity -- sum_i d_i x_{ij} <= s_j y_j for all j in J + # ========================================================================= + for j in range(n_plant): + lhs = sum(demands[i] * x[i][j] for i in range(n_cust)) + rhs = capacities[j] * y[j] + violation_amount = lhs - rhs # positive when LHS > RHS + if violation_amount > TOL: + violated_constraints.add(2) + violations.append( + f"Constraint (2) violated: plant {j} load = {lhs:.8f} exceeds capacity {rhs:.8f}" + ) + 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): Variable bounds on x -- 0 <= x_{ij} <= 1 for all i, j + # ========================================================================= + for i in range(n_cust): + for j in range(n_plant): + val = x[i][j] + # Check lower bound: 0 <= x_{ij} => x_{ij} >= 0 + if val < -TOL: + violation_amount = -val # how much below 0 + violated_constraints.add(3) + violations.append( + f"Constraint (3) violated: x[{i}][{j}] = {val:.8f} < 0" + ) + rhs = 0.0 + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 3, + "lhs": val, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + # Check upper bound: x_{ij} <= 1 + if val > 1.0 + TOL: + violation_amount = val - 1.0 # how much above 1 + violated_constraints.add(3) + violations.append( + f"Constraint (3) violated: x[{i}][{j}] = {val:.8f} > 1" + ) + rhs = 1.0 + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 3, + "lhs": val, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (4): Variable bounds on y -- 0 <= y_j <= 1 for all j in J + # ========================================================================= + for j in range(n_plant): + val = y[j] + if val < -TOL: + violation_amount = -val + violated_constraints.add(4) + violations.append( + f"Constraint (4) violated: y[{j}] = {val:.8f} < 0" + ) + rhs = 0.0 + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": val, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + if val > 1.0 + TOL: + violation_amount = val - 1.0 + violated_constraints.add(4) + violations.append( + f"Constraint (4) violated: y[{j}] = {val:.8f} > 1" + ) + rhs = 1.0 + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": val, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (5): Integrality -- y_j in {0, 1} for all j in J + # ========================================================================= + for j in range(n_plant): + val = y[j] + dist_to_int = min(abs(val - 0.0), abs(val - 1.0)) + if dist_to_int > TOL: + violated_constraints.add(5) + violations.append( + f"Constraint (5) violated: y[{j}] = {val:.8f} is not binary" + ) + # For integrality, LHS is the value, RHS is nearest integer + nearest_int = round(val) + rhs = float(nearest_int) + violation_amount = abs(val - rhs) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 5, + "lhs": val, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (6): Objective consistency -- the reported objective_value + # must equal the objective recomputed from the solution variables: + # Z = sum_{i,j} c_{ij} x_{ij} + sum_j f_j y_j + # where c_{ij} = shipping_costs[i][j] (cost of supplying ALL of customer + # i's demand from plant j, so c_{ij} x_{ij} already accounts for demand) + # and f_j = plants.fixed_costs[j]. Both x_{ij} and y_j are present in the + # solution, so this is an exact full recompute. A 0.1% relative tolerance + # (with a 1e-3 absolute floor) absorbs floating-point accumulation while + # still rejecting fabricated objective values (e.g. 0 or float-max). + # ========================================================================= + fixed_costs = instance["plants"]["fixed_costs"] + shipping_costs = instance["shipping_costs"] + 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 and math.isfinite(reported): + shipping_total = 0.0 + for i in range(n_cust): + row = shipping_costs[i] + xrow = x[i] + for j in range(n_plant): + xv = xrow[j] + if xv != 0.0: + shipping_total += row[j] * xv + fixed_total = sum(fixed_costs[j] * y[j] for j in range(n_plant)) + true_obj = shipping_total + fixed_total + violation_amount = abs(reported - true_obj) + tol = max(1e-3, 1e-3 * abs(true_obj)) + if violation_amount > tol: + violated_constraints.add(6) + violations.append( + f"Constraint (6) violated: reported objective_value = {reported:.8f} " + f"differs from recomputed total cost {true_obj:.8f} " + f"(|diff| = {violation_amount:.6g}, tol = {tol:.6g})" + ) + rhs = true_obj + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 6, + "lhs": reported, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + elif reported is not None: + # Non-finite reported objective (inf / nan) can never match a + # finite recomputed cost -- treat as an objective inconsistency. + shipping_total = 0.0 + for i in range(n_cust): + row = shipping_costs[i] + xrow = x[i] + for j in range(n_plant): + xv = xrow[j] + if xv != 0.0: + shipping_total += row[j] * xv + fixed_total = sum(fixed_costs[j] * y[j] for j in range(n_plant)) + true_obj = shipping_total + fixed_total + violated_constraints.add(6) + violations.append( + f"Constraint (6) violated: reported objective_value = {reported} " + f"is not finite; recomputed total cost = {true_obj:.8f}" + ) + normalizer = max(abs(true_obj), EPS) + violation_magnitudes.append({ + "constraint": 6, + "lhs": reported, + "rhs": true_obj, + "raw_excess": float("inf"), + "normalizer": normalizer, + "ratio": float("inf"), + }) + + 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 the Capacitated Facility Location Problem (CFLP)." + ) + parser.add_argument("--instance_path", required=True, help="Path to the instance JSON file.") + parser.add_argument("--solution_path", required=True, help="Path to the solution JSON file.") + parser.add_argument("--result_path", required=True, help="Path to write the feasibility result JSON file.") + 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) + + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. 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/klose2005/gurobi_code.py b/tasks/klose2005/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c2997b23c7bc17b9802452be8bffc89953dddf57 --- /dev/null +++ b/tasks/klose2005/gurobi_code.py @@ -0,0 +1,183 @@ +""" +Gurobi MIP implementation of the Capacitated Facility Location Problem (CFLP). + +Reference: Klose & Drexl (2005), "Lower Bounds for the Capacitated Facility +Location Problem Based on Column Generation", Management Science 51(11):1689-1705. + +The model: + min sum_{i,j} c_{ij} x_{ij} + sum_j f_j y_j + s.t. sum_j x_{ij} = 1 for all i (D) demand + sum_i d_i x_{ij} <= s_j y_j for all j (C) capacity + 0 <= x_{ij} <= 1 for all i,j (N) + y_j in {0,1} for all j (I) + +Optionally, valid inequalities (B) x_{ij} <= y_j and (T) sum_j s_j y_j >= d^I +are added as cuts to tighten the LP relaxation. +""" + +import argparse +import json +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 + + +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + return data + + +def build_model(data, time_limit): + n_cust = data["num_customers"] + n_plant = data["num_plants"] + d = data["customers"]["demands"] + s = data["plants"]["capacities"] + f = data["plants"]["fixed_costs"] + c = data["shipping_costs"] # c[i][j] + total_demand = sum(d) + + I = range(n_cust) + J = range(n_plant) + + model = gp.Model("CFLP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + x = {} + for i in I: + for j in J: + x[i, j] = model.addVar(lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, + name=f"x_{i}_{j}") + y = {} + for j in J: + y[j] = model.addVar(vtype=GRB.BINARY, name=f"y_{j}") + + model.update() + + # Objective + model.setObjective( + gp.quicksum(c[i][j] * x[i, j] for i in I for j in J) + + gp.quicksum(f[j] * y[j] for j in J), + GRB.MINIMIZE + ) + + # (D) Demand constraints + for i in I: + model.addConstr( + gp.quicksum(x[i, j] for j in J) == 1, + name=f"demand_{i}" + ) + + # (C) Capacity constraints + for j in J: + model.addConstr( + gp.quicksum(d[i] * x[i, j] for i in I) <= s[j] * y[j], + name=f"capacity_{j}" + ) + + # (B) Variable upper bound constraints (valid inequality to tighten LP) + for i in I: + for j in J: + model.addConstr(x[i, j] <= y[j], name=f"vub_{i}_{j}") + + # (T) Aggregate capacity constraint (valid inequality) + model.addConstr( + gp.quicksum(s[j] * y[j] for j in J) >= total_demand, + name="agg_capacity" + ) + + return model, x, y + + +def solve_and_export(model, x, y, data, solution_path): + n_cust = data["num_customers"] + n_plant = data["num_plants"] + + model.optimize() + + result = {} + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["gap"] = model.MIPGap + result["status"] = model.Status + result["solve_time"] = model.Runtime + + # Extract solution + y_sol = {} + for j in range(n_plant): + val = y[j].X + if val > 0.5: + y_sol[j] = 1 + result["open_plants"] = sorted(y_sol.keys()) + + x_sol = {} + for i in range(n_cust): + assignments = {} + for j in range(n_plant): + val = x[i, j].X + if val > 1e-6: + assignments[j] = val + x_sol[i] = assignments + result["assignments"] = {str(i): {str(j): v for j, v in assigns.items()} + for i, assigns in x_sol.items()} + else: + result["objective_value"] = None + result["status"] = model.Status + result["solve_time"] = model.Runtime + + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve CFLP using Gurobi MIP (Klose & Drexl 2005)") + 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) + + data = load_instance(args.instance_path) + print(f"Loaded instance: {data['num_customers']} customers x " + f"{data['num_plants']} plants, r={data['capacity_tightness_ratio']}") + + model, x, y = build_model(data, args.time_limit) + result = solve_and_export(model, x, y, data, args.solution_path) + + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']:.4f}") + print(f"Best bound: {result['best_bound']:.4f}") + print(f"Gap: {result['gap']:.6f}") + print(f"Open plants: {len(result['open_plants'])}") + else: + print("No feasible solution found.") + print(f"Solve time: {result['solve_time']:.2f}s") + + +if __name__ == "__main__": + main() diff --git a/tasks/klose2005/gurobi_feasi_result/large_feasi_result_1.json b/tasks/klose2005/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/klose2005/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/klose2005/gurobi_feasi_result/large_feasi_result_2.json b/tasks/klose2005/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/klose2005/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/klose2005/gurobi_feasi_result/large_feasi_result_3.json b/tasks/klose2005/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/klose2005/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/klose2005/gurobi_feasi_result/large_feasi_result_4.json b/tasks/klose2005/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/klose2005/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/klose2005/gurobi_feasi_result/large_feasi_result_5.json b/tasks/klose2005/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/klose2005/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/klose2005/gurobi_feasi_result/tiny_feasi_result.json b/tasks/klose2005/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/klose2005/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/klose2005/gurobi_solution/large_solution_1.json b/tasks/klose2005/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9fc2c5be29d0915527d12fc12fde792ce8f618c5 --- /dev/null +++ b/tasks/klose2005/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cef24f507fee51a8055b784944294dd323f6e812699767e86ecf2bfab8f96220 +size 69905 diff --git a/tasks/klose2005/gurobi_solution/large_solution_2.json b/tasks/klose2005/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..40a23d4d2ab55171d6c20b5e74b2fd1bdf413bda --- /dev/null +++ b/tasks/klose2005/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d7e412b1e7e419b9ace55177ba1810936c04dab7084e6cf74ffd3e2611b01a8 +size 65836 diff --git a/tasks/klose2005/gurobi_solution/large_solution_3.json b/tasks/klose2005/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d7b24120cb2afe632472d793c7dc4e872470e3cd --- /dev/null +++ b/tasks/klose2005/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea3857a63df56db5e3a22505396365353dc4b7ecb9b5deab21adbffea8619a16 +size 69753 diff --git a/tasks/klose2005/gurobi_solution/large_solution_4.json b/tasks/klose2005/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9da0999276a96a4e1fc166bd34be5826edabe6aa --- /dev/null +++ b/tasks/klose2005/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:900ef8dadffcea2fdb239d63f4486ca369d7e42c9e517a7f7e4607e2cbc74fb1 +size 69451 diff --git a/tasks/klose2005/gurobi_solution/large_solution_5.json b/tasks/klose2005/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..1e9745b3e919abc6de9b8e0fc4e04942ba465942 --- /dev/null +++ b/tasks/klose2005/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90990a399f2143eaa01c9ef2e67e3d9195589d0f3a27ef0a3053040fb92b1bf6 +size 69935 diff --git a/tasks/klose2005/gurobi_solution/tiny_solution.json b/tasks/klose2005/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..0f980e95bca7b4548f98e059ed4c5c7099870c3b --- /dev/null +++ b/tasks/klose2005/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c5c4d4489a0a35eab782105aed47196d24e3c91f69de82d685a824375153ac9 +size 5392 diff --git a/tasks/klose2005/gurobi_solution_log/large_log_1.jsonl b/tasks/klose2005/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..110898f6534761fb1209d74db35a401ba36355bb --- /dev/null +++ b/tasks/klose2005/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a688d526c508e29621a67299c2a2e5f22f5e3b220cf5cd5d5ecb0d2858226241 +size 613 diff --git a/tasks/klose2005/gurobi_solution_log/large_log_2.jsonl b/tasks/klose2005/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bcb52ccd14dbeb276b818492d9836a87ce5454ac --- /dev/null +++ b/tasks/klose2005/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ada12b39d96613f2e0ddbdc82014a8aca16c432e33c8d6f124039b9d56c12cc1 +size 1859 diff --git a/tasks/klose2005/gurobi_solution_log/large_log_3.jsonl b/tasks/klose2005/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4231dee59646d72b53f2de593c94002376fcba92 --- /dev/null +++ b/tasks/klose2005/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d127f209c56cfdfd246cc75bc29033ecf9c3939c809552551a17f68b30dfbe2 +size 386 diff --git a/tasks/klose2005/gurobi_solution_log/large_log_4.jsonl b/tasks/klose2005/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..68738b426ff2b15e3b2f6c458e98a8b27c65e188 --- /dev/null +++ b/tasks/klose2005/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cdafeed8e880cf4ccbeacf3e385d46b52026ed89195ea57255535eeeefacdba +size 720 diff --git a/tasks/klose2005/gurobi_solution_log/large_log_5.jsonl b/tasks/klose2005/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..036dc0d4ea516de282e8734ece88f2c1980ccf21 --- /dev/null +++ b/tasks/klose2005/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ed6eada164ab0c369e8b545a4cf64cfeb5113f9dcdcf7edc8c394af65599fff +size 727 diff --git a/tasks/klose2005/gurobi_solution_log/tiny_log.jsonl b/tasks/klose2005/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..74ecca82717c2303924d403f1379cbb7fe305598 --- /dev/null +++ b/tasks/klose2005/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3d6c7075223f98d74a6bae7021073454f4fd6a79b43dbd42ce2bf7dbbb99ea7 +size 541 diff --git a/tasks/klose2005/instance/large_instance_1.json b/tasks/klose2005/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..fd9d43f32ffe1182684dc20247f1a2419bf348f3 --- /dev/null +++ b/tasks/klose2005/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffe1dac206046cc68e2f307cce2631655e49b695b72328cde2ae02aea7381020 +size 17350517 diff --git a/tasks/klose2005/instance/large_instance_2.json b/tasks/klose2005/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..3331a141301491eed64dd7864013ccbc6503eaf9 --- /dev/null +++ b/tasks/klose2005/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4657041dac5b37033fe5651bec41f56a69610f1d102d288a0687de980f099c9 +size 17570617 diff --git a/tasks/klose2005/instance/large_instance_3.json b/tasks/klose2005/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..57eeb94f0b03701e1c2cbd097fe1b89bd77e9231 --- /dev/null +++ b/tasks/klose2005/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70db76284dee72895ddc3fff307db6ec772b862775c2ca598a601db06ce96ef0 +size 16571343 diff --git a/tasks/klose2005/instance/large_instance_4.json b/tasks/klose2005/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..b61b26f85d27b0c5ff926d00efc267dbfb5ecd53 --- /dev/null +++ b/tasks/klose2005/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b632eef0938468716382ca6e54ecb4b8ade4e57999ff49b6a51209844165e33 +size 17612283 diff --git a/tasks/klose2005/instance/large_instance_5.json b/tasks/klose2005/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e7cfd1d7afaa78af7962cacdd7b6c976aa359ff0 --- /dev/null +++ b/tasks/klose2005/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:534dea190879d91ac429e0b36d69aa9934754af021bf8b632692a1e7837ee93b +size 17355457 diff --git a/tasks/klose2005/instance/tiny_instance.json b/tasks/klose2005/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b248bf5a49bff1cf7e7eb8e1bbc2b311ebce70ae --- /dev/null +++ b/tasks/klose2005/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2002dc3c96c39b21bf80e2db91c1de641f259c7a7653fa3d5efa6b664495c12a +size 175678 diff --git a/tasks/klose2005/instance_schema.json b/tasks/klose2005/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7f54d61b730b047ab31f6f3581d53832af7be838 --- /dev/null +++ b/tasks/klose2005/instance_schema.json @@ -0,0 +1,19 @@ +{ + "num_customers": " Number of customers whose demands must be fulfilled.", + "num_plants": " Number of candidate plant sites that may be opened.", + "capacity_tightness_ratio": " Ratio of total plant capacity to total customer demand, controlling how tight capacity constraints are.", + "total_demand": " Sum of all customer demands.", + "total_capacity": " Sum of all plant capacities.", + "customers": { + "demands": " Quantity of goods demanded by each customer.", + "x_coords": " Horizontal coordinate of each customer's location.", + "y_coords": " Vertical coordinate of each customer's location." + }, + "plants": { + "fixed_costs": " Fixed cost incurred for opening each candidate plant.", + "capacities": " Maximum total demand each plant can serve if opened.", + "x_coords": " Horizontal coordinate of each candidate plant's location.", + "y_coords": " Vertical coordinate of each candidate plant's location." + }, + "shipping_costs": " Cost of supplying a customer's entire demand from a given plant, proportional to demand and Euclidean distance." +} \ No newline at end of file diff --git a/tasks/klose2005/mathematical_formulation.md b/tasks/klose2005/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..cadd9db8d41f9d0e26fa7bf011b3f98e341c3559 --- /dev/null +++ b/tasks/klose2005/mathematical_formulation.md @@ -0,0 +1,37 @@ +# Sets and Parameters + +- $I$: set of customers, indexed by $i$. + +- $J$: set of potential plant (facility) locations, indexed by $j$. + +- $c_{ij} \geq 0$: cost of supplying all of customer $i$’s demand from $j$. + +- $f_j \geq 0$: fixed cost of opening facility $j$. + +- $d_i \geq 0$: demand of customer $i$. + +- $s_j > 0$: capacity of facility $j$ when open. + +- $d^{I} = \sum_{i \in I} d_i$: total demand. Assumed: $\sum_{j \in J} s_j > d^{I}$. + +# Decision Variables + +- $y_j \in \{0,1\}$ for $j \in J$: $=1$ iff facility $j$ is open. + +- $x_{ij} \in [0,1]$ for $i \in I,\ j \in J$: fraction of customer $i$’s demand met from $j$. + +# Formulation + +$$\begin{align} +Z = \min \quad & \sum_{i \in I}\sum_{j \in J} c_{ij}\, x_{ij} + \sum_{j \in J} f_j\, y_j \\ +\text{s.t.}\quad & \sum_{j \in J} x_{ij} = 1, + && \forall i \in I, \tag{D}\\ +& \sum_{i \in I} d_i\, x_{ij} \leq s_j\, y_j, + && \forall j \in J, \tag{C}\\ +& 0 \leq x_{ij} \leq 1, + && \forall i \in I,\ j \in J, \tag{N}\\ +& y_j \in \{0,1\}, + && \forall j \in J. \tag{I} +\end{align}$$ + +\(D\) enforces full demand satisfaction; (C) enforces capacity and links allocation to opening; (N) are bounds on the continuous allocation variables; (I) is integrality of the location variables. diff --git a/tasks/klose2005/problem_description.txt b/tasks/klose2005/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce910fd2b1ee99ed0d92522cdbf605f539ef3035 --- /dev/null +++ b/tasks/klose2005/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A company must decide which plants to open from a set of potential facility locations and how to assign customers to those open plants in order to satisfy all customer demands at minimum total cost. There are a given number of customers and a given number of candidate plant sites. Each customer has a known non-negative demand, and each candidate plant has a known strictly positive capacity and a known non-negative fixed cost that is incurred if and only if that plant is opened. For every customer-plant pair, there is a known non-negative shipping cost that represents the cost of supplying that customer's entire demand from that plant. A customer's demand may be split across multiple open plants; specifically, any fraction of a customer's demand between zero and one hundred percent may be served by any single open plant, and the shipping cost for that plant-customer pair scales proportionally with the fraction served. The total capacity across all candidate plants strictly exceeds total customer demand, ensuring that a feasible supply plan exists. + +The company must make two types of choices: which plants to open and what fraction of each customer's demand to fulfill from each open plant. Every customer's demand must be met in full, meaning the fractions assigned to that customer across all plants must sum to exactly one. The total demand assigned to each open plant, computed as the sum over all customers of each customer's demand multiplied by the fraction of that demand assigned to the plant, must not exceed that plant's capacity. A closed plant cannot serve any customer at all. + +The goal is to minimize total cost, which is the sum of two components: total shipping cost, computed as the sum over all customer-plant pairs of the shipping cost times the fraction of that customer's demand served by that plant, and total fixed cost, computed as the sum of the fixed opening costs of all plants that are chosen to be opened. diff --git a/tasks/klose2005/solution_logger.py b/tasks/klose2005/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/klose2005/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/klose2005/solution_schema.json b/tasks/klose2005/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f2608f199b3fb947d44caafd2e6ee053480c32bc --- /dev/null +++ b/tasks/klose2005/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total cost of the solution, including fixed costs of opened plants and shipping costs from plants to customers.", + "open_plants": " Indices of the plants that are opened to serve customers.", + "assignments": " Fraction of each customer's demand supplied by each plant." +} diff --git a/tasks/knueven2020/feasibility_check.py b/tasks/knueven2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a57a5e699ff00fb5a7a11ec1cc4eb54970e2c621 --- /dev/null +++ b/tasks/knueven2020/feasibility_check.py @@ -0,0 +1,693 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Unit Commitment (UC) problem. + +Paper: Knueven, Ostrowski, Watson (2020) + "On Mixed Integer Programming Formulations for the Unit Commitment Problem" + +Checks ORIGINAL 1-bin formulation constraints (the first concrete model the +paper writes, Slide 4, with decision variables u, p, pb). The 3-bin +auxiliaries v, w (startup/shutdown indicators) are NOT part of the +original and are derived internally from u only when needed for +min-up / min-down verification. Constraints: + + 1. Power balance: sum_g p[g,t] = demand[t] + 2. [SKIPPED — 3-bin definitional linking u(t)-u(t-1)=v(t)-w(t) + is a reformulation artifact, not an original-1-bin constraint] + 3. Minimum up-time: via u consecutive-on-runs (derived v) + 4. Minimum down-time: via u consecutive-off-runs (derived w) + 5. Generation lower bound: p[g,t] >= p_min * u[g,t] + 6. Generation upper bound: pb[g,t] <= p_max * u[g,t] + 7. Power <= available: p[g,t] <= pb[g,t] + 8. Ramp-up: p[g,t] - p[g,t-1] <= RU * u[g,t-1] + SU * v[g,t] + 9. Ramp-down: p[g,t-1] - p[g,t] <= RD * u[g,t] + SD * w[g,t] + 10. VUB inequality (Slide 10, when UT >= TRU + TRD + 2) + 11. Piecewise cost sum feasibility: 0 <= p[g,t] - p_min*u[g,t] <= (p_max-p_min)*u[g,t] + 12. Piecewise segment bound (requires pl variables - not in solution, skip) + 13. Startup tier partition (requires delta variables - not in solution, skip) + 14. Startup tier window (requires delta variables - not in solution, skip) + 15. Reserve requirement: sum_g pb[g,t] >= demand[t] + reserve[t] + 16. Binary constraints: u, v, w in {0, 1} + 17. Non-negativity: p >= 0, pb >= 0 + 18. Initial up/down time obligations + 19. Objective consistency (Tier C defense against score-gaming): the + self-reported objective_value must equal the cost recomputed from + the committed schedule. The objective is + min sum_g sum_t [ NL_g*u + sum_l f^l*pl + sum_k SC_k*delta ]. + Since the piecewise-segment variables pl and the startup-tier + variables delta are cost-minimised auxiliaries (no constraint + binds them other than their definitions), they are fully + determined by (u, p): pl is the cheapest segment fill of + p-p_min*u, and delta picks the cheapest eligible startup tier. + This makes a FULL exact recompute possible from the solution's + u and p alone. A reported objective that disagrees with the + recompute (beyond a tight relative tolerance) is rejected. + +NOTE: feasibility_check_new.py adds only constraint 19 on top of the +original feasibility_check.py; constraints 1-18 are byte-for-byte the +original checks. The eval-pipeline JSON shape (feasible / +violated_constraints / violations / violation_magnitudes) is unchanged. +""" + +import argparse +import json +import math +import sys + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'schedule') +_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 parse_args(): + parser = argparse.ArgumentParser( + description="Check feasibility of a UC candidate solution." + ) + 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.") + return parser.parse_args() + + +def compute_startup_windows(startup_costs): + """ + Compute [lo, hi] downtime windows for each startup cost tier. + + Mirrors gurobi_code.compute_startup_windows exactly: consecutive tiers + partition the downtime axis, lo_k = prev_hi + 1, hi_k = max_downtime_hours + of tier k. The last (cold) tier has hi=None (no upper bound). + """ + windows = [] + prev_max = 0 + for tier in startup_costs: + lo = prev_max + 1 + hi = tier["max_downtime_hours"] # None for the last (cold) tier + windows.append((lo, hi)) + if hi is not None: + prev_max = hi + return windows + + +def recompute_objective(data, sol): + """ + Recompute the UC objective exactly from the reported schedule (u, p). + + Objective (gurobi_code.py): for every generator g and period t, + NL_g * u[g,t] (no-load cost) + + sum_l marginal_cost_l * pl[g,t,l] (piecewise production cost) + + sum_k SC_k * delta[g,t,k] (downtime-dependent startup) + + pl and delta are cost-minimised LP auxiliaries with no binding + constraint other than their definitions, so they are determined by + (u, p): + * production cost = cheapest segment fill of p-p_min*u; segments are + contiguous and monotone in marginal cost, so the greedy positional + fill is optimal. + * startup cost = cheapest eligible tier for each startup event, + where tier k (< cold) is eligible iff a shutdown lies in its + downtime window [lo_k, hi_k] (in-horizon w events or, for an + initially-off generator, the pre-horizon shutdown). The cold tier + is always eligible. This replicates the matching-formulation delta + constraints in gurobi_code.py. + + Returns the recomputed objective (float). + """ + generators = data["generators"] + demand = data["demand"] + T = len(demand) + schedule = sol["schedule"] + + total = 0.0 + for gd in generators: + g_id = gd["id"] + s = schedule[g_id] + u_arr = s["u"] + p_arr = s["p"] + + p_min = gd["p_min"] + NL = gd["no_load_cost"] + segs = gd["production_cost_segments"] + tiers = gd["startup_costs"] + windows = compute_startup_windows(tiers) + n_tiers = len(tiers) + init = int(gd["initial_status"]) + + # Derive v, w from u exactly as constraints 3/4/8/9 do above. + u0 = 1 if init > 0 else 0 + u_prev_arr = [u0] + list(u_arr[:-1]) + v_arr = [max(0, u_arr[t] - u_prev_arr[t]) for t in range(T)] + w_arr = [max(0, u_prev_arr[t] - u_arr[t]) for t in range(T)] + + for t in range(T): + ut = u_arr[t] + + # --- No-load cost -------------------------------------------- + total += NL * ut + + # --- Piecewise production cost (greedy / cheapest fill) ------ + # When the generator is off, pl is pinned to 0 in the MIP, so + # there is no production cost regardless of p. + if ut >= 0.5: + remaining = p_arr[t] - p_min * ut + for seg in segs: + width = seg["output_mw_end"] - seg["output_mw_start"] + take = min(max(remaining, 0.0), width) + total += take * seg["marginal_cost_per_mwh"] + remaining -= take + + # --- Downtime-dependent startup cost ------------------------- + if v_arr[t] >= 0.5: + best_cost = None + for k in range(n_tiers): + if k == n_tiers - 1: + eligible = True # cold tier: residual, no window UB + else: + lo, hi = windows[k] + eligible = False + for i in range(lo, hi + 1): + prev_t = t - i + if prev_t >= 0: + if w_arr[prev_t] >= 0.5: + eligible = True + break + elif init < 0: + # pre-horizon shutdown |init| periods before t=0 + shutdown_ago = t + abs(init) + if lo <= shutdown_ago <= hi: + eligible = True + break + if eligible: + c = tiers[k]["cost"] + if best_cost is None or c < best_cost: + best_cost = c + if best_cost is not None: + total += best_cost + + return total + + +def main(): + args = parse_args() + + with open(args.instance_path) as f: + data = json.load(f) + with open(args.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(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + tol = 1e-5 + eps = 1e-5 + + generators = data["generators"] + demand = data["demand"] + reserve = data.get("reserve_requirement", [0.0] * len(demand)) + T = len(demand) + G = len(generators) + schedule = sol["schedule"] + gen_ids = [gd["id"] for gd in generators] + + violated_set = set() + violation_messages = [] # (constraint_idx, message) + violation_magnitudes = [] + + def record(constraint_idx, msg, lhs, rhs, operator): + """Check a constraint and record violation if any.""" + if operator == "<=": + violation_amount = lhs - rhs + elif operator == ">=": + violation_amount = rhs - lhs + elif operator == "=": + violation_amount = abs(lhs - rhs) + else: + return + + if violation_amount > tol: + violated_set.add(constraint_idx) + violation_messages.append((constraint_idx, msg)) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Initial condition helpers + def u0(g_idx): + return 1 if generators[g_idx]["initial_status"] > 0 else 0 + + def p0(g_idx): + gd = generators[g_idx] + return gd["initial_power"] if gd["initial_status"] > 0 else 0.0 + + # ========================================================================== + # Constraint 1: Power balance sum_g p[g,t] = demand[t] + # ========================================================================== + for t in range(T): + total_p = sum(schedule[gen_ids[g]]["p"][t] for g in range(G)) + record(1, + f"Power balance violated at t={t+1}: sum_p={total_p:.4f}, demand={demand[t]:.4f}", + total_p, demand[t], "=") + + # ========================================================================== + # Per-generator constraints (2-10, 11, 16-18) + # ========================================================================== + for g_idx in range(G): + gd = generators[g_idx] + g_id = gd["id"] + s = schedule[g_id] + u_arr = s["u"] + p_arr = s["p"] + pb_arr = s["pb"] + + # Derive v, w from u (1-bin projection): v(t)=1 iff u(t)=1 and u(t-1)=0 + # (startup event), w(t)=1 iff u(t-1)=1 and u(t)=0 (shutdown event). + # If the solver chose to export v, w explicitly, we still use the + # derived values since only u is in the original formulation. + u_prev_arr = [1 if generators[g_idx]["initial_status"] > 0 else 0] + list(u_arr[:-1]) + v_arr = [max(0, u_arr[t] - u_prev_arr[t]) for t in range(T)] + w_arr = [max(0, u_prev_arr[t] - u_arr[t]) for t in range(T)] + + p_min = gd["p_min"] + p_max = gd["p_max"] + RU = gd["ramp_up_limit"] + RD = gd["ramp_down_limit"] + SU = gd["startup_ramp_limit"] + SD = gd["shutdown_ramp_limit"] + UT = int(gd["min_up_time"]) + DT = int(gd["min_down_time"]) + init = int(gd["initial_status"]) + + # Compute TRU, TRD for VUB + TRU = max(0, math.ceil((p_max - SU) / RU)) if RU > 0 else 0 + TRD_val = max(0, math.ceil((p_max - SD) / RD)) if RD > 0 else 0 + apply_vub = (UT >= TRU + TRD_val + 2) + + for t in range(T): + ut = u_arr[t] + vt = v_arr[t] + wt = w_arr[t] + pt = p_arr[t] + pbt = pb_arr[t] + u_prev = u_arr[t - 1] if t > 0 else u0(g_idx) + p_prev = p_arr[t - 1] if t > 0 else p0(g_idx) + + # ------------------------------------------------------------------ + # Constraint 2 INTENTIONALLY SKIPPED: the 3-bin definitional + # identity u(t)-u(t-1) = v(t)-w(t) is not an original 1-bin + # constraint. With v, w derived from u above, it is trivially + # satisfied by construction. + # ------------------------------------------------------------------ + # Constraint 3: Minimum up-time + # sum_{s=max(1,t-UT+1)}^{t} v[g,s] <= u[g,t] + # ------------------------------------------------------------------ + start_ut = max(0, t - UT + 1) + sum_v = sum(v_arr[ss] for ss in range(start_ut, t + 1)) + record(3, + f"Min up-time violated for {g_id} at t={t+1}: sum_v={sum_v:.4f}, u={ut:.4f}", + sum_v, ut, "<=") + + # ------------------------------------------------------------------ + # Constraint 4: Minimum down-time + # sum_{s=max(1,t-DT+1)}^{t} w[g,s] <= 1 - u[g,t] + # ------------------------------------------------------------------ + start_dt = max(0, t - DT + 1) + sum_w = sum(w_arr[ss] for ss in range(start_dt, t + 1)) + record(4, + f"Min down-time violated for {g_id} at t={t+1}: sum_w={sum_w:.4f}, 1-u={1-ut:.4f}", + sum_w, 1 - ut, "<=") + + # ------------------------------------------------------------------ + # Constraint 5: Generation lower bound p[g,t] >= p_min * u[g,t] + # ------------------------------------------------------------------ + record(5, + f"Gen lower limit violated for {g_id} at t={t+1}: " + f"p={pt:.4f} < p_min*u={p_min * ut:.4f}", + p_min * ut, pt, "<=") + + # ------------------------------------------------------------------ + # Constraint 6: Generation upper bound pb[g,t] <= p_max * u[g,t] + # ------------------------------------------------------------------ + record(6, + f"Gen upper limit violated for {g_id} at t={t+1}: " + f"pb={pbt:.4f} > p_max*u={p_max * ut:.4f}", + pbt, p_max * ut, "<=") + + # ------------------------------------------------------------------ + # Constraint 7: Power <= available p[g,t] <= pb[g,t] + # ------------------------------------------------------------------ + record(7, + f"p > pb for {g_id} at t={t+1}: p={pt:.4f}, pb={pbt:.4f}", + pt, pbt, "<=") + + # ------------------------------------------------------------------ + # Constraint 8: Ramp-up + # p[g,t] - p[g,t-1] <= RU * u[g,t-1] + SU * v[g,t] + # ------------------------------------------------------------------ + ramp_up_lhs = pt - p_prev + ramp_up_rhs = RU * u_prev + SU * vt + record(8, + f"Ramp-up violated for {g_id} at t={t+1}: " + f"delta_p={ramp_up_lhs:.4f}, limit={ramp_up_rhs:.4f}", + ramp_up_lhs, ramp_up_rhs, "<=") + + # ------------------------------------------------------------------ + # Constraint 9: Ramp-down + # p[g,t-1] - p[g,t] <= RD * u[g,t] + SD * w[g,t] + # ------------------------------------------------------------------ + ramp_dn_lhs = p_prev - pt + ramp_dn_rhs = RD * ut + SD * wt + record(9, + f"Ramp-down violated for {g_id} at t={t+1}: " + f"delta_p={ramp_dn_lhs:.4f}, limit={ramp_dn_rhs:.4f}", + ramp_dn_lhs, ramp_dn_rhs, "<=") + + # ------------------------------------------------------------------ + # Constraint 10: VUB inequality (Slide 10) + # p(t) <= p_max*u(t) - sum_i coeff_i*v(t-i) - sum_i coeff_i*w(t+1+i) + # Only when UT >= TRU + TRD + 2 + # ------------------------------------------------------------------ + if apply_vub: + startup_sum = 0.0 + for i in range(TRU + 1): + coeff = max(0.0, p_max - (SU + i * RU)) + ti = t - i + if 0 <= ti < T: + startup_sum += coeff * v_arr[ti] + + shutdown_sum = 0.0 + for i in range(TRD_val + 1): + coeff = max(0.0, p_max - (SD + i * RD)) + ti = t + 1 + i + if 0 <= ti < T: + shutdown_sum += coeff * w_arr[ti] + + vub_rhs = p_max * ut - startup_sum - shutdown_sum + record(10, + f"VUB violated for {g_id} at t={t+1}: " + f"p={pt:.4f}, VUB_limit={vub_rhs:.4f}", + pt, vub_rhs, "<=") + + # ------------------------------------------------------------------ + # Constraint 11: Piecewise sum feasibility (implied) + # p_above_min = p[g,t] - p_min*u[g,t] must be in [0, (p_max-p_min)*u[g,t]] + # Lower part (>= 0) is constraint 5; upper part checked here. + # ------------------------------------------------------------------ + p_above_min = pt - p_min * ut + max_above_min = (p_max - p_min) * ut + record(11, + f"Piecewise sum feasibility violated for {g_id} at t={t+1}: " + f"p_above_min={p_above_min:.4f}, max={max_above_min:.4f}", + p_above_min, max_above_min, "<=") + + # ------------------------------------------------------------------ + # Constraint 16: Binary constraint u in {0, 1} (original variable). + # v, w are derived from u, so their domain is automatic. + # ------------------------------------------------------------------ + rounded = round(ut) + if rounded not in (0, 1): + dev = min(abs(ut), abs(ut - 1)) + record(16, + f"Binary violated for {g_id}.u at t={t+1}: val={ut:.6f}", + dev, 0.0, "=") + else: + dev = abs(ut - rounded) + record(16, + f"Binary violated for {g_id}.u at t={t+1}: val={ut:.6f}", + dev, 0.0, "=") + + # ------------------------------------------------------------------ + # Constraint 17: Non-negativity p >= 0, pb >= 0 + # ------------------------------------------------------------------ + record(17, + f"Negative p for {g_id} at t={t+1}: p={pt:.6f}", + 0.0, pt, "<=") + record(17, + f"Negative pb for {g_id} at t={t+1}: pb={pbt:.6f}", + 0.0, pbt, "<=") + + # ---------------------------------------------------------------------- + # Constraint 18: Initial up/down time obligations + # If init > 0: u[g,t] must be 1 for t=1..max(0, UT-init) + # If init < 0: u[g,t] must be 0 for t=1..max(0, DT-|init|) + # ---------------------------------------------------------------------- + if init > 0: + must_on = max(0, UT - init) + for t in range(min(must_on, T)): + if u_arr[t] < 1 - tol: + record(18, + f"Initial up-time obligation violated for {g_id} at t={t+1}: " + f"u={u_arr[t]:.4f}, must be 1", + 1.0, u_arr[t], "<=") + elif init < 0: + must_off = max(0, DT - abs(init)) + for t in range(min(must_off, T)): + if u_arr[t] > tol: + record(18, + f"Initial down-time obligation violated for {g_id} at t={t+1}: " + f"u={u_arr[t]:.4f}, must be 0", + u_arr[t], 0.0, "<=") + + # ========================================================================== + # Constraint 15: Reserve requirement sum_g pb[g,t] >= demand[t] + reserve[t] + # ========================================================================== + for t in range(T): + total_pb = sum(schedule[gen_ids[g]]["pb"][t] for g in range(G)) + rhs_val = demand[t] + reserve[t] + record(15, + f"Reserve violated at t={t+1}: sum_pb={total_pb:.4f}, " + f"demand+reserve={rhs_val:.4f}", + rhs_val, total_pb, "<=") + + # ========================================================================== + # Constraint 19: Objective consistency (Tier C anti-score-gaming check) + # + # Recompute the objective exactly from (u, p) and reject when the + # self-reported objective_value disagrees. The recompute is exact + # because the cost-only auxiliaries pl (piecewise segments) and delta + # (startup tiers) are fully determined by (u, p) under minimisation + # (see recompute_objective docstring). Tolerance: 1e-6 relative with a + # 1e-3 absolute floor -- loose enough to absorb float summation noise + # (observed |rel diff| <= 1e-13 on Gurobi references), tight enough to + # catch any fabricated objective_value. + # ========================================================================== + reported_raw = sol.get("objective_value") + reported = None + if reported_raw is not None: + try: + reported = float(reported_raw) + except (TypeError, ValueError): + reported = None + + if reported is not None: + true_obj = recompute_objective(data, sol) + # Map a non-finite reported objective onto an effective value that + # always trips the tolerance test (still a fabricated objective). + if math.isnan(reported): + eff = true_obj + max(1.0, abs(true_obj)) + elif math.isinf(reported): + eff = math.copysign(sys.float_info.max, reported) + else: + eff = reported + abs_diff = abs(eff - true_obj) + obj_tol = max(1e-3, 1e-6 * abs(true_obj)) + if abs_diff > obj_tol: + violated_set.add(19) + msg = (f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed cost " + f"(no-load + piecewise production + startup) =" + f"{true_obj:.6f} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})") + violation_messages.append((19, msg)) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 19, + "lhs": float(eff), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + # ========================================================================== + # Compile results + # ========================================================================== + violated_constraints = sorted(violated_set) + + # Aggregate messages: collect unique messages per constraint + aggregated_violations = [] + for c_idx in violated_constraints: + msgs = [msg for ci, msg in violation_messages if ci == c_idx] + if len(msgs) <= 3: + aggregated_violations.extend(msgs) + else: + aggregated_violations.extend(msgs[:2]) + aggregated_violations.append( + f"... and {len(msgs) - 2} more constraint {c_idx} violations" + ) + + result = { + "feasible": len(violated_constraints) == 0, + "violated_constraints": violated_constraints, + "violations": aggregated_violations, + "violation_magnitudes": violation_magnitudes, + } + + 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: {violated_constraints}") + print(f"Total violation instances: {len(violation_magnitudes)}") + + 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/knueven2020/gurobi_code.py b/tasks/knueven2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..595b1cb6e909a944e05373e6f6d1e52ed74a6058 --- /dev/null +++ b/tasks/knueven2020/gurobi_code.py @@ -0,0 +1,437 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Unit Commitment (UC) mathematical model. + +Paper: Knueven, Ostrowski, Watson (2020) + "On Mixed Integer Programming Formulations for the Unit Commitment Problem" + +This program implements the standard 3-binary-variable (3-bin) UC formulation +as the base mathematical model described in the paper. It uses: + - Binary variables u(g,t), v(g,t), w(g,t) for on/off, startup, shutdown + - Logical linking constraints + - Minimum up/down time constraints (Rajan and Takriti 2005 style) + - Generation limits + - Startup/shutdown ramping constraints + - Piecewise linear production costs (disaggregated) + - Downtime-dependent startup costs (matching formulation) + - Power balance and reserve constraints + +NOT SPECIFIED IN PAPER (SLIDES): The exact constraint forms for min up/down time, +ramping, generation limits, and startup costs are not written out in the slides. +We use the standard forms from the literature referenced in the paper (Rajan-Takriti +2005, Carrion-Arroyo 2006 style) as inferred assumptions. +""" + +import argparse +import json +import math +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 parse_args(): + parser = argparse.ArgumentParser( + description="Solve UC problem with Gurobi (standard 3-bin 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.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + return parser.parse_args() + + +def compute_startup_windows(startup_costs): + """ + Compute [lo, hi] downtime windows for each startup cost tier. + + The matching formulation assigns a startup to tier k if the unit was offline + for lo_k to hi_k periods. The last tier (cold) has hi=None (no upper bound). + + Inferred assumption: consecutive tiers partition the downtime axis, where + lo_k = prev_hi + 1 and hi_k = max_downtime_hours for tier k. + """ + windows = [] + prev_max = 0 + for tier in startup_costs: + lo = prev_max + 1 + hi = tier["max_downtime_hours"] # None for the last (cold) tier + windows.append((lo, hi)) + if hi is not None: + prev_max = hi + return windows + + +def build_and_solve(data, time_limit): + """ + Build and solve the standard 3-bin UC MIP using Gurobi. + + Returns the Gurobi model and key variable dictionaries. + """ + generators = data["generators"] + demand = data["demand"] + reserve = data.get("reserve_requirement", [0.0] * len(demand)) + T = len(demand) + G = len(generators) + + # Pre-process generator parameters + gen = [] + for gd in generators: + g = { + "id": gd["id"], + "p_max": gd["p_max"], + "p_min": gd["p_min"], + "RU": gd["ramp_up_limit"], + "RD": gd["ramp_down_limit"], + "SU": gd["startup_ramp_limit"], # max power at first period online + "SD": gd["shutdown_ramp_limit"], # max power at last period online + "UT": int(gd["min_up_time"]), + "DT": int(gd["min_down_time"]), + "NL": gd["no_load_cost"], + "init": int(gd["initial_status"]), # >0: on for n periods, <0: off for |n| periods + "p0": gd["initial_power"], + "tiers": gd["startup_costs"], + "segs": gd["production_cost_segments"], + "windows": compute_startup_windows(gd["startup_costs"]), + } + gen.append(g) + + # ------------------------------------------------------------------------- + # Create Gurobi model + # ------------------------------------------------------------------------- + model = gp.Model("UC_Standard_3bin") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("MIPGap", 1e-4) # 0.01% optimality gap (as in paper) + model.setParam("OutputFlag", 1) + + # ------------------------------------------------------------------------- + # Decision Variables (indexed t=1..T) + # ------------------------------------------------------------------------- + # Binary status, startup, shutdown + u = model.addVars(G, range(1, T + 1), vtype=GRB.BINARY, name="u") + v = model.addVars(G, range(1, T + 1), vtype=GRB.BINARY, name="v") + w = model.addVars(G, range(1, T + 1), vtype=GRB.BINARY, name="w") + + # Power output and available power (for reserve) + p = model.addVars(G, range(1, T + 1), lb=0.0, name="p") + pb = model.addVars(G, range(1, T + 1), lb=0.0, name="pb") + + # Piecewise segment power pl[g, t, l] + pl = {} + for g_idx in range(G): + n_segs = len(gen[g_idx]["segs"]) + for t in range(1, T + 1): + for l in range(n_segs): + pl[(g_idx, t, l)] = model.addVar(lb=0.0, name=f"pl_{g_idx}_{t}_{l}") + + # Startup cost tier indicators delta[g, t, k] + delta = {} + for g_idx in range(G): + n_tiers = len(gen[g_idx]["tiers"]) + for t in range(1, T + 1): + for k in range(n_tiers): + delta[(g_idx, t, k)] = model.addVar(lb=0.0, ub=1.0, + name=f"delta_{g_idx}_{t}_{k}") + + model.update() + + # ------------------------------------------------------------------------- + # Enforce initial up/down time obligations + # ------------------------------------------------------------------------- + # Inferred assumption: if init_status > 0 (on for n periods), the unit must + # remain on for max(0, UT - n) more periods; similarly for off. + for g_idx in range(G): + g = gen[g_idx] + init = g["init"] + if init > 0: + must_on = max(0, g["UT"] - init) + for t in range(1, min(must_on, T) + 1): + u[g_idx, t].lb = 1.0 + elif init < 0: + must_off = max(0, g["DT"] - abs(init)) + for t in range(1, min(must_off, T) + 1): + u[g_idx, t].ub = 0.0 + + model.update() + + # ------------------------------------------------------------------------- + # Helper: get initial-condition values as Python scalars for t=0 + # ------------------------------------------------------------------------- + def u0(g_idx): + return 1 if gen[g_idx]["init"] > 0 else 0 + + def p0(g_idx): + return gen[g_idx]["p0"] if gen[g_idx]["init"] > 0 else 0.0 + + # ------------------------------------------------------------------------- + # Logical linking: u[g,t] - u[g,t-1] = v[g,t] - w[g,t] + # ------------------------------------------------------------------------- + for g_idx in range(G): + for t in range(1, T + 1): + u_prev = u[g_idx, t - 1] if t > 1 else u0(g_idx) + model.addConstr( + u[g_idx, t] - u_prev == v[g_idx, t] - w[g_idx, t], + name=f"link_{g_idx}_{t}" + ) + + # ------------------------------------------------------------------------- + # Minimum up-time constraints (Rajan-Takriti 2005 style) + # sum_{s=max(1,t-UT+1)}^{t} v[g,s] <= u[g,t] + # ------------------------------------------------------------------------- + for g_idx in range(G): + UT = gen[g_idx]["UT"] + for t in range(1, T + 1): + start = max(1, t - UT + 1) + model.addConstr( + gp.quicksum(v[g_idx, s] for s in range(start, t + 1)) <= u[g_idx, t], + name=f"minup_{g_idx}_{t}" + ) + + # ------------------------------------------------------------------------- + # Minimum down-time constraints (Rajan-Takriti 2005 style) + # sum_{s=max(1,t-DT+1)}^{t} w[g,s] <= 1 - u[g,t] + # ------------------------------------------------------------------------- + for g_idx in range(G): + DT = gen[g_idx]["DT"] + for t in range(1, T + 1): + start = max(1, t - DT + 1) + model.addConstr( + gp.quicksum(w[g_idx, s] for s in range(start, t + 1)) <= 1 - u[g_idx, t], + name=f"mindn_{g_idx}_{t}" + ) + + # ------------------------------------------------------------------------- + # Generation limits + # p_min * u[g,t] <= p[g,t] <= pb[g,t] <= p_max * u[g,t] + # ------------------------------------------------------------------------- + for g_idx in range(G): + g = gen[g_idx] + for t in range(1, T + 1): + model.addConstr(p[g_idx, t] >= g["p_min"] * u[g_idx, t], + name=f"pmin_{g_idx}_{t}") + model.addConstr(pb[g_idx, t] <= g["p_max"] * u[g_idx, t], + name=f"pmax_{g_idx}_{t}") + model.addConstr(p[g_idx, t] <= pb[g_idx, t], + name=f"p_le_pb_{g_idx}_{t}") + + # ------------------------------------------------------------------------- + # Ramping constraints with startup/shutdown ramp rates + # Ramp-up: p[g,t] - p[g,t-1] <= RU * u[g,t-1] + SU * v[g,t] + # Ramp-down: p[g,t-1] - p[g,t] <= RD * u[g,t] + SD * w[g,t] + # ------------------------------------------------------------------------- + for g_idx in range(G): + g = gen[g_idx] + for t in range(1, T + 1): + p_prev = p[g_idx, t - 1] if t > 1 else p0(g_idx) + u_prev = u[g_idx, t - 1] if t > 1 else u0(g_idx) + + model.addConstr( + p[g_idx, t] - p_prev <= g["RU"] * u_prev + g["SU"] * v[g_idx, t], + name=f"rampup_{g_idx}_{t}" + ) + model.addConstr( + p_prev - p[g_idx, t] <= g["RD"] * u[g_idx, t] + g["SD"] * w[g_idx, t], + name=f"rampdn_{g_idx}_{t}" + ) + + # ------------------------------------------------------------------------- + # Piecewise linear production cost disaggregation + # sum_l pl[g,t,l] = p[g,t] - p_min * u[g,t] + # 0 <= pl[g,t,l] <= (P^l - P^{l-1}) * u[g,t] (standard upper bound) + # ------------------------------------------------------------------------- + for g_idx in range(G): + g = gen[g_idx] + segs = g["segs"] + n_segs = len(segs) + for t in range(1, T + 1): + # Output above minimum = sum of segment outputs + model.addConstr( + gp.quicksum(pl[(g_idx, t, l)] for l in range(n_segs)) + == p[g_idx, t] - g["p_min"] * u[g_idx, t], + name=f"pwsum_{g_idx}_{t}" + ) + for l, seg in enumerate(segs): + seg_width = seg["output_mw_end"] - seg["output_mw_start"] + model.addConstr( + pl[(g_idx, t, l)] <= seg_width * u[g_idx, t], + name=f"pwub_{g_idx}_{t}_{l}" + ) + + # ------------------------------------------------------------------------- + # Downtime-dependent startup costs (matching formulation) + # + # delta[g,t,k] = 1 iff generator g starts at time t with startup tier k. + # Partition: sum_k delta[g,t,k] = v[g,t] + # Window: delta[g,t,k] <= sum_{i=lo_k}^{hi_k} w[g,t-i] (for k < last tier) + # (unit must have shut down in the window [lo_k, hi_k] periods ago) + # + # Inferred assumption: matching formulation assigns the cheapest eligible tier. + # The last (cold) tier is the residual and has no window upper bound. + # Pre-horizon shutdowns are treated as a constant contribution if they fall + # within a tier's window (based on initial_status). + # ------------------------------------------------------------------------- + for g_idx in range(G): + g = gen[g_idx] + tiers = g["tiers"] + windows = g["windows"] + n_tiers = len(tiers) + init = g["init"] + + for t in range(1, T + 1): + # Partition constraint + model.addConstr( + gp.quicksum(delta[(g_idx, t, k)] for k in range(n_tiers)) + == v[g_idx, t], + name=f"tiersum_{g_idx}_{t}" + ) + + # Window upper bounds for all but the last (cold) tier + for k in range(n_tiers - 1): + lo, hi = windows[k] + w_terms = [] + for i in range(lo, hi + 1): + prev_t = t - i + if prev_t >= 1: + w_terms.append(w[g_idx, prev_t]) + elif prev_t <= 0 and init < 0: + # Pre-horizon shutdown: unit was off for |init| periods before t=1. + # At period t, that shutdown occurred (t-1) + |init| periods ago. + shutdown_ago = (t - 1) + abs(init) + if lo <= shutdown_ago <= hi: + w_terms.append(1.0) # constant: pre-horizon shutdown in window + + if w_terms: + model.addConstr( + delta[(g_idx, t, k)] <= gp.quicksum(w_terms), + name=f"tierwin_{g_idx}_{t}_{k}" + ) + else: + # No valid shutdown in this window: tier k is infeasible at this t + model.addConstr( + delta[(g_idx, t, k)] == 0, + name=f"tierinf_{g_idx}_{t}_{k}" + ) + + # ------------------------------------------------------------------------- + # Power balance (copper-plate, equality) + # sum_g p[g,t] = D[t] + # ------------------------------------------------------------------------- + for t in range(1, T + 1): + model.addConstr( + gp.quicksum(p[g_idx, t] for g_idx in range(G)) == demand[t - 1], + name=f"balance_{t}" + ) + + # ------------------------------------------------------------------------- + # Reserve requirement + # sum_g pb[g,t] >= D[t] + R[t] + # ------------------------------------------------------------------------- + for t in range(1, T + 1): + model.addConstr( + gp.quicksum(pb[g_idx, t] for g_idx in range(G)) + >= demand[t - 1] + reserve[t - 1], + name=f"reserve_{t}" + ) + + # ------------------------------------------------------------------------- + # Objective function + # min sum_g sum_t [ NL_g * u[g,t] + # + sum_l f^l * pl[g,t,l] + # + sum_k SC_k * delta[g,t,k] ] + # ------------------------------------------------------------------------- + obj_terms = [] + for g_idx in range(G): + g = gen[g_idx] + for t in range(1, T + 1): + obj_terms.append(g["NL"] * u[g_idx, t]) + for l, seg in enumerate(g["segs"]): + obj_terms.append(seg["marginal_cost_per_mwh"] * pl[(g_idx, t, l)]) + for k, tier in enumerate(g["tiers"]): + obj_terms.append(tier["cost"] * delta[(g_idx, t, k)]) + + model.setObjective(gp.quicksum(obj_terms), GRB.MINIMIZE) + + # ------------------------------------------------------------------------- + # Solve + # ------------------------------------------------------------------------- + model.optimize() + + return model, u, v, w, p, pb, pl, delta, gen, G, T + + +def extract_solution(model, u, v, w, p, pb, pl, delta, gen, G, T): + """Extract solution values from Gurobi model.""" + status = model.Status + + # Attempt to get best objective value + obj_val = None + if model.SolCount > 0: + obj_val = model.ObjVal + + solution = { + "objective_value": obj_val, + "status": status, + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + "solve_time": model.Runtime, + "schedule": {} + } + + if model.SolCount > 0: + # Expose only the 1-bin original variables (u, p, pb); v, w are 3-bin + # internal auxiliaries derivable from u as v(t)=max(0,u(t)-u(t-1)), + # w(t)=max(0,u(t-1)-u(t)). pl and delta are piecewise/tier auxiliaries. + for g_idx in range(G): + g_id = gen[g_idx]["id"] + solution["schedule"][g_id] = { + "u": [round(u[g_idx, t].X) for t in range(1, T + 1)], + "p": [p[g_idx, t].X for t in range(1, T + 1)], + "pb": [pb[g_idx, t].X for t in range(1, T + 1)], + } + + return solution + + +def main(): + args = parse_args() + install_gurobi_logger(args.log_path) + + with open(args.instance_path) as f: + data = json.load(f) + + model, u, v, w, p, pb, pl, delta, gen, G, T = build_and_solve(data, args.time_limit) + solution = extract_solution(model, u, v, w, p, pb, pl, delta, gen, G, T) + + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']:.4f}") + print(f"MIP gap: {solution['mip_gap']:.6%}") + else: + print("No feasible solution found within the time limit.") + + print(f"Solution written to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/knueven2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/knueven2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/knueven2020/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/knueven2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/knueven2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/knueven2020/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/knueven2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/knueven2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/knueven2020/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/knueven2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/knueven2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/knueven2020/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/knueven2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/knueven2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/knueven2020/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/knueven2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/knueven2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/knueven2020/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/knueven2020/gurobi_solution/large_solution_1.json b/tasks/knueven2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..76a56e4580c7be2819f968e5948e807c329dea65 --- /dev/null +++ b/tasks/knueven2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b42a22967be08c5ec9b2267327f058e637166cfb9413b510f7ec617e1f47d7cf +size 1795538 diff --git a/tasks/knueven2020/gurobi_solution/large_solution_2.json b/tasks/knueven2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..604baaf9ba85fe9076dcf3afb177331d0198e0b0 --- /dev/null +++ b/tasks/knueven2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48b09f42cd47cf8d47d7b420298bfc2fa2c984526110e9afc496f2b69ecf2be0 +size 1903310 diff --git a/tasks/knueven2020/gurobi_solution/large_solution_3.json b/tasks/knueven2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..724e406c4bf024fac23e14efe954a8b7a38155e6 --- /dev/null +++ b/tasks/knueven2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4a08ec1485cbe2d2bbcc96fba2acee65ac25ae99dc3ecf3897a06575da90e44 +size 1921782 diff --git a/tasks/knueven2020/gurobi_solution/large_solution_4.json b/tasks/knueven2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..1a31b5e22b4bdea41b3ffcd47d1105f9da0794bf --- /dev/null +++ b/tasks/knueven2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82477095bb07ccdcf0340b9150bff46a7266a979912b6959ccc921b24bb20c55 +size 1898417 diff --git a/tasks/knueven2020/gurobi_solution/large_solution_5.json b/tasks/knueven2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a31feb4911f4e04c28b5d45b4ddaa56f286d5b01 --- /dev/null +++ b/tasks/knueven2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c98b97b4d74c11d57c93514b8b4019164274296b2d6ded159f67c62bbd197c6f +size 1938911 diff --git a/tasks/knueven2020/gurobi_solution/tiny_solution.json b/tasks/knueven2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..a4c7f661701a6cf3a81ed6d7333af755e4e5abad --- /dev/null +++ b/tasks/knueven2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12b67f5c217e924369335cd837997ac696a6b1d1eaea2c392206566ad437be10 +size 147319 diff --git a/tasks/knueven2020/gurobi_solution_log/large_log_1.jsonl b/tasks/knueven2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fe2f318a5903a7d51a8dcca6d8046a38239ccdda --- /dev/null +++ b/tasks/knueven2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a23dfcd15b8b2fe62312cfe313b33120e36b0ca9ad8bc3b183206e4d8abd0e8d +size 946 diff --git a/tasks/knueven2020/gurobi_solution_log/large_log_2.jsonl b/tasks/knueven2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..25b2754195b3006c1e7cb854f3b55549c7cfcca3 --- /dev/null +++ b/tasks/knueven2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36a351d150bf4173fc8beec42f8bdfaea72bf072e9827a452b92fe7f4107c690 +size 1178 diff --git a/tasks/knueven2020/gurobi_solution_log/large_log_3.jsonl b/tasks/knueven2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3dd06af634fff81dff9ba3fda8072045f0f1440d --- /dev/null +++ b/tasks/knueven2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7dd8a7b048585a30bc88c426eafb38068477b32f52acc491c85cc351df01731c +size 1246 diff --git a/tasks/knueven2020/gurobi_solution_log/large_log_4.jsonl b/tasks/knueven2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ed0c8c5f2377dfcea4c77007d91a628d61d5df0e --- /dev/null +++ b/tasks/knueven2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d36d72ca4805c5da71bbf3ac2ff7f70c457127dd8cf0e347eb7097bea2fa9a2 +size 778 diff --git a/tasks/knueven2020/gurobi_solution_log/large_log_5.jsonl b/tasks/knueven2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..273f1decb46e722be08a3a68ee42a6e4782b537c --- /dev/null +++ b/tasks/knueven2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5495c465ec37e6b263c000e646ad3e4bd2c1a88ae717ad8acc6183efd37a5b67 +size 1180 diff --git a/tasks/knueven2020/gurobi_solution_log/tiny_log.jsonl b/tasks/knueven2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f1c6996c9ac6d6dc914987ce0d7f2b5f37dada87 --- /dev/null +++ b/tasks/knueven2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:102e1bcba28ab1da578879e08d4583242ba26556942276f70742945b17cb05dd +size 601 diff --git a/tasks/knueven2020/instance/large_instance_1.json b/tasks/knueven2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e0f63a360c54407efa61c0eea17d7b34c69f4346 --- /dev/null +++ b/tasks/knueven2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3095237242deafd3e9155fe3ca5278b169cd70dc062d32a9e5aeba35b5df73d7 +size 647013 diff --git a/tasks/knueven2020/instance/large_instance_2.json b/tasks/knueven2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..06bb10c21851b3a524667e9787119916be0c3ad2 --- /dev/null +++ b/tasks/knueven2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61b65698d1fe99743be1032eedb3b136e6910fd3ed42c635cc0b1f4c6fdc0032 +size 647164 diff --git a/tasks/knueven2020/instance/large_instance_3.json b/tasks/knueven2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..13eeacc1de2eb9add1887057fd8d6d4b5569535e --- /dev/null +++ b/tasks/knueven2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f74a51ac737b1a7bdb295602e9649c161f184f55cc5b6be6e3b15846544496c +size 647182 diff --git a/tasks/knueven2020/instance/large_instance_4.json b/tasks/knueven2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8415375e62603ac3cce4b1ee2575520c34d9f84c --- /dev/null +++ b/tasks/knueven2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e5a6eb6eeddfb1cd88300d5fb76fe0da8da5af6801c0ed03a354dc41a584e0a +size 647133 diff --git a/tasks/knueven2020/instance/large_instance_5.json b/tasks/knueven2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..60b72041cfb2ab80c5c7e33c736bf0ead4605978 --- /dev/null +++ b/tasks/knueven2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10153d7c153a9f58f4904e014f1667592bc3d14da148b051190936e72098110e +size 647202 diff --git a/tasks/knueven2020/instance/tiny_instance.json b/tasks/knueven2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c2d0f82a77bef900e9765cb17f0a0c5851db7ae3 --- /dev/null +++ b/tasks/knueven2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b196cf2503dea008e53038aba34b9a8aa6019cbebcb6ff43178f8db8a9d949d +size 81418 diff --git a/tasks/knueven2020/instance_schema.json b/tasks/knueven2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..63f75f6428cc387583feed9fcf66f7ac64e44193 --- /dev/null +++ b/tasks/knueven2020/instance_schema.json @@ -0,0 +1,38 @@ +{ + "num_generators": " Total number of thermal generators in the fleet.", + "num_time_periods": " Number of consecutive hourly time periods in the planning horizon.", + "time_period_hours": " Duration of each time period in hours.", + "generators": [ + { + "id": " Unique identifier for the generator.", + "type": " Technology type of the generator (e.g., gas_ct, gas_cc, coal, steam, nuclear).", + "p_min": " Minimum stable power output in MW when the generator is on.", + "p_max": " Maximum power output in MW when the generator is on.", + "ramp_up_limit": " Maximum increase in power output (MW) allowed from one period to the next while online.", + "ramp_down_limit": " Maximum decrease in power output (MW) allowed from one period to the next while online.", + "startup_ramp_limit": " Maximum power output (MW) the generator can produce in the first period it comes online.", + "shutdown_ramp_limit": " Maximum power output (MW) the generator can produce in the last period before going offline.", + "min_up_time": " Minimum number of consecutive periods the generator must remain on once started.", + "min_down_time": " Minimum number of consecutive periods the generator must remain off once shut down.", + "no_load_cost": " Fixed cost ($) incurred per period whenever the generator is on, independent of power output.", + "startup_costs": [ + { + "label": " Name of the startup cost tier (e.g., hot, warm, cold).", + "max_downtime_hours": " Maximum prior downtime (hours) for this tier to apply; null for the final cold tier which has no upper bound.", + "cost": " Cost ($) incurred when the generator starts up under this tier." + } + ], + "production_cost_segments": [ + { + "output_mw_start": " Lower power output breakpoint (MW) of this cost segment.", + "output_mw_end": " Upper power output breakpoint (MW) of this cost segment.", + "marginal_cost_per_mwh": " Marginal cost ($/MWh) for each MW produced within this segment." + } + ], + "initial_status": " Initial state of the generator before the planning horizon: positive means it has been on for that many periods, negative means it has been off for that many periods.", + "initial_power": " Power output (MW) of the generator immediately before the planning horizon; zero if the generator was off." + } + ], + "demand": " Electricity demand (MW) that must be met in each time period.", + "reserve_requirement": " Additional reserve capacity (MW) above demand that must be available from online generators in each time period." +} diff --git a/tasks/knueven2020/mathematical_formulation.md b/tasks/knueven2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..c4d7c2244a6651b36b52e6b2b1a716d1380b5beb --- /dev/null +++ b/tasks/knueven2020/mathematical_formulation.md @@ -0,0 +1,91 @@ +# Original Formulation: Unit Commitment (1-binary-variable model) + +*Source*: Knueven, Ostrowski, Watson (2020), “On Mixed Integer Programming Formulations for the Unit Commitment Problem”. The first concrete formulation presented in the paper (Slide 4) is the *1-bin* (one-binary-variable) unit commitment formulation. + +## Sets and Indices + +- $\mathcal{G}$: set of thermal generators, index $g \in \mathcal{G}$. + +- $\mathcal{T}$: set of time periods, index $t \in \mathcal{T}$. + +- $\mathcal{L}$: set of piecewise-linear production-cost segments, index $l \in \mathcal{L}$. + +## Parameters (per generator $g$, indices suppressed) + +- $\overline{P},\,\underline{P}$: maximum / minimum power output. + +- $SU,\,SD$: start-up / shut-down ramp rates. + +- $RU,\,RD$: ramp-up / ramp-down rates. + +- $UT,\,DT$: minimum up-time / down-time. + +- $L(t)$: system load (demand) at time $t$. + +- $N(s)$: net injection from slack / transmission (possibly zero). + +- $f^l$: marginal cost (slope) of piecewise segment $l$; $\overline{P}^{\,l}$ and $\overline{P}^{\,l-1}$: upper and lower breakpoints of segment $l$. + +## Decision Variables (1-bin model) + +- $p_g(t) \ge 0$: power output of generator $g$ at time $t$ (continuous). + +- $\overline{p}_g(t) \ge 0$: power available / reserve-capable output of generator $g$ at time $t$ (continuous). + +- $u_g(t) \in \{0,1\}$: on/off commitment status of generator $g$ at time $t$. + +- $c_g(t) \ge 0$: production cost of generator $g$ at time $t$ (continuous). + +## Objective + +$$\begin{equation} + \min \ \sum_{g \in \mathcal{G}} \sum_{t \in \mathcal{T}} c_g(t) + \tag{1} +\end{equation}$$ + +## Constraints + +#### Power balance (system level). + +$$\begin{equation} + \sum_{g \in \mathcal{G}} A_g\bigl(p_g,\,\overline{p}_g,\,u_g\bigr) + N(s) \;=\; L, + \tag{2} +\end{equation}$$ where $A_g(\cdot)$ is the mapping from generator output variables to net power injection (reduces to $A_g(p_g,\overline{p}_g,u_g)(t) = p_g(t)$ in the copper-plate case). + +#### Generator technical constraints. + +For each generator $g \in \mathcal{G}$, $$\begin{equation} + (p_g,\;\overline{p}_g,\;u_g,\;c_g) \;\in\; \Pi_g, + \tag{3} +\end{equation}$$ where $\Pi_g$ encodes all generator-level technical restrictions on $(p_g(\cdot),\overline{p}_g(\cdot),u_g(\cdot),c_g(\cdot))$, namely: $$\begin{align} + \underline{P}\, u_g(t) \;\le\; p_g(t) \;\le\; \overline{p}_g(t) + &\;\le\; \overline{P}\, u_g(t), + &&\forall t \in \mathcal{T}, \tag{4}\\[2pt] + p_g(t) - p_g(t-1) &\;\le\; RU\, u_g(t-1) + SU\bigl(u_g(t) - u_g(t-1)\bigr), + &&\forall t \in \mathcal{T}, \tag{5}\\[2pt] + p_g(t-1) - p_g(t) &\;\le\; RD\, u_g(t) + SD\bigl(u_g(t-1) - u_g(t)\bigr), + &&\forall t \in \mathcal{T}, \tag{6}\\[2pt] + \sum_{\tau = t-UT+1}^{t} u_g(\tau) &\;\ge\; UT\bigl[u_g(t) - u_g(t-1)\bigr]^{+}, + &&\forall t \in \mathcal{T}, \tag{7}\\[2pt] + \sum_{\tau = t-DT+1}^{t} \bigl(1-u_g(\tau)\bigr) + &\;\ge\; DT\bigl[u_g(t-1) - u_g(t)\bigr]^{+}, + &&\forall t \in \mathcal{T}, \tag{8}\\[2pt] + c_g(t) &\;=\; \sum_{l \in \mathcal{L}} f^l\, p_g^{\,l}(t) + (\text{no-load and start-up costs}), + &&\forall t \in \mathcal{T}, \tag{9}\\[2pt] + \sum_{l \in \mathcal{L}} p_g^{\,l}(t) &\;=\; p_g(t) - \underline{P}\, u_g(t), + &&\forall t \in \mathcal{T}, \tag{10}\\[2pt] + 0 \;\le\; p_g^{\,l}(t) + &\;\le\; \overline{P}^{\,l} - \overline{P}^{\,l-1}, + &&\forall l \in \mathcal{L},\, t \in \mathcal{T}. \tag{11} +\end{align}$$ + +## Variable Domains + +$$\begin{equation} + u_g(t) \in \{0,1\}, \qquad + p_g(t),\,\overline{p}_g(t),\,p_g^{\,l}(t),\,c_g(t) \ge 0, + \quad \forall g,t,l. + \tag{12} +\end{equation}$$ + +*Note.* This is the 1-bin original formulation as presented on Slide 4 of Knueven, Ostrowski, Watson (2020). Start-up / shut-down indicators $v_g(t),\,w_g(t)$ and shortest-path / extended formulations are *reformulations* of this model and are not included here. diff --git a/tasks/knueven2020/problem_description.txt b/tasks/knueven2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..ab0b6b04190656ca6507195e45118f5a93df167e --- /dev/null +++ b/tasks/knueven2020/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A power system operator manages a fleet of thermal generators over a planning horizon of consecutive hourly time periods (typically 48 hours). Each generator is characterized by a minimum stable power output, a maximum power output, a ramp-up rate limiting the increase in power output from one period to the next, a ramp-down rate limiting the decrease, a startup ramp limit specifying the maximum power the generator can produce in the first period it comes online, a shutdown ramp limit specifying the maximum power it can produce in the last period before going offline, a minimum up-time stating the fewest consecutive periods the generator must remain on once started, and a minimum down-time stating the fewest consecutive periods it must remain off once shut down. Each generator also has a no-load cost incurred per period whenever it is online, a piecewise linear production cost curve defined by breakpoints and marginal cost slopes, and a downtime-dependent startup cost function (cheaper after shorter off-periods, more expensive after longer off-periods, with a finite number of cost levels). The system specifies an electricity demand for each period and a reserve requirement for each period. + +For each generator in each period, the operator must decide whether the generator is on or off, the power output of the generator, and the maximum power the generator can make available for reserve in that period. When a generator is on, its power output must be at least its minimum stable output and at most its maximum output, and the power available for reserve must be at least as large as the actual power output and at most the maximum output. When a generator is off, its power output and reserve-available power must both be zero. + +Generator on/off decisions over time are constrained by ramping and minimum up/down times. Between consecutive periods in which a generator remains on, the change in its power output from one period to the next must not exceed the ramp-up rate, and any decrease must not exceed the ramp-down rate. When a generator transitions from off to on between two consecutive periods, its power output in the first on-period is bounded above by the startup ramp limit. When a generator transitions from on to off between two consecutive periods, its power output in the last on-period is bounded above by the shutdown ramp limit. Once a generator starts running (i.e., its on/off status changes from off in the previous period to on in the current period), it must remain on for at least as many consecutive periods as its minimum up-time; symmetrically, once it shuts down, it must remain off for at least as many consecutive periods as its minimum down-time. A generator that was already on before the planning horizon began and has not yet satisfied its minimum up-time must remain on for the required number of remaining periods; a generator that was already off and has not yet satisfied its minimum down-time must remain off. + +In every period, the total power output of all generators must exactly equal the system demand. In every period, the total power available for reserve across all generators must be at least the system demand plus the reserve requirement. + +The goal is to minimize the total operating cost over the planning horizon. For each generator and each period in which the generator is on, the operating cost for that period consists of a no-load cost plus the piecewise linear production cost evaluated at the generator's power output. In addition, whenever a generator transitions from off to on, a startup cost is incurred that depends on how many consecutive periods the generator had been off before restarting, determined by the generator's downtime-dependent startup cost function. The objective sums these no-load, production, and startup costs across all generators and all periods. diff --git a/tasks/knueven2020/solution_logger.py b/tasks/knueven2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/knueven2020/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/knueven2020/solution_schema.json b/tasks/knueven2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e09907a1fa45e5fb1a25fe4ca81647b6128259d8 --- /dev/null +++ b/tasks/knueven2020/solution_schema.json @@ -0,0 +1,10 @@ +{ + "objective_value": " Total operating cost ($) over the planning horizon, comprising no-load costs, piecewise linear production costs, and startup costs.", + "schedule": { + "": { + "u": " Whether the generator is on (1) or off (0) in each time period.", + "p": " Power output (MW) of the generator in each time period.", + "pb": " Maximum power (MW) available from the generator for reserve purposes in each time period." + } + } +} diff --git a/tasks/kobayashi2021/feasibility_check.py b/tasks/kobayashi2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..98d5f087049dde61d6a770b07599c0fa4a0129ee --- /dev/null +++ b/tasks/kobayashi2021/feasibility_check.py @@ -0,0 +1,385 @@ +""" +Feasibility checker for Cardinality-constrained Mean-CVaR Portfolio Optimization. +Kobayashi, Takano, Nakata (2021) — Problem (7). + +Constraints numbered top-to-bottom from the formulation section: + 1. (7b) CVaR: v >= (1/(1-beta)) * sum_s p_s * max(0, -(r^(s))^T x - a) + 2. (7c) Logical linking: z_n = 0 => x_n = 0 (for all n) + 3. Expected return: mu^T x >= mu_bar (Eq. 6, part of x in X) + 4. Budget: sum x_n = 1 (part of x in X) + 5. Non-negativity: x_n >= 0 for all n (part of x in X) + 6. Binary: z_n in {0,1} for all n (part of z in Z_N^k) + 7. Cardinality: sum z_n <= k (part of z in Z_N^k) + 8. v >= 0 (variable domain) + 9. Objective consistency (Tier C): reported objective_value must equal the + recomputed objective (7a) = (1/(2*gamma)) * x^T x + a + v. Guards against + LLM score-gaming exploits that report a fabricated objective_value while + keeping the routes/decisions feasible. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('a', 'objective_value', 'v', 'x', 'z') +_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_instance(path): + with open(path) as f: + data = json.load(f) + N = data["N"] + S = data["S"] + k = data["k"] + beta = data["beta"] + gamma = data["gamma"] + mu_bar = data["mu_bar"] + mu = data["mu"] + p_s_raw = data["p_s"] + if isinstance(p_s_raw, list): + p = p_s_raw + else: + p = [p_s_raw] * S + scenarios = data["scenarios"] + return N, S, k, beta, gamma, mu_bar, mu, p, scenarios + + +def load_solution(path): + with open(path) as f: + return json.load(f) + + +def add_violation(violations_list, magnitudes_list, constraint_idx, message, lhs, rhs, violation_amount): + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations_list.append((constraint_idx, message)) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + +def check_feasibility(instance_path, solution_path): + N, S, k, beta, gamma, mu_bar, mu, p, scenarios = 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 + + x = sol.get("x") + z = sol.get("z") + a = sol.get("a") + v = sol.get("v") + + # Handle null/missing solution + if x is None or z is None: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Solution contains null values (no feasible solution found)"], + "violation_magnitudes": [], + } + + # If a or v not in solution, try to infer or mark infeasible + if a is None or v is None: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Solution missing auxiliary variables a and/or v"], + "violation_magnitudes": [], + } + + violations = [] # list of (constraint_idx, message) + magnitudes = [] # list of dicts + + # --- Constraint 1: (7b) CVaR --- + # v >= (1/(1-beta)) * sum_s p_s * max(0, -(r^(s))^T x - a) + cvar_rhs = 0.0 + for s in range(S): + loss_s = -sum(scenarios[s][n] * x[n] for n in range(N)) - a + cvar_rhs += p[s] * max(0.0, loss_s) + cvar_rhs /= (1.0 - beta) + lhs_val = v + rhs_val = cvar_rhs + viol = rhs_val - lhs_val # >= constraint: violation if RHS > LHS + if viol > TOL: + add_violation(violations, magnitudes, 1, + f"CVaR constraint violated: v={lhs_val:.6f} < required {rhs_val:.6f}", + lhs_val, rhs_val, viol) + + # --- Constraint 2: (7c) Logical linking --- + # z_n = 0 => x_n = 0, equivalently x_n <= z_n when z_n = 0 + for n in range(N): + if abs(z[n]) < TOL and x[n] > TOL: + # x_n should be 0 but isn't; treat as x_n <= 0 violated + viol_amt = x[n] + add_violation(violations, magnitudes, 2, + f"Linking violated: z[{n}]=0 but x[{n}]={x[n]:.6f}", + x[n], 0.0, viol_amt) + + # --- Constraint 3: Expected return --- + # mu^T x >= mu_bar + mu_x = sum(mu[n] * x[n] for n in range(N)) + viol = mu_bar - mu_x # >= constraint: violation if RHS > LHS + if viol > TOL: + add_violation(violations, magnitudes, 3, + f"Expected return violated: mu^T x={mu_x:.6f} < mu_bar={mu_bar:.6f}", + mu_x, mu_bar, viol) + + # --- Constraint 4: Budget --- + # sum x_n = 1 + sum_x = sum(x[n] for n in range(N)) + viol = abs(sum_x - 1.0) + if viol > TOL: + add_violation(violations, magnitudes, 4, + f"Budget violated: sum(x)={sum_x:.6f} != 1.0", + sum_x, 1.0, viol) + + # --- Constraint 5: Non-negativity --- + # x_n >= 0 for all n + for n in range(N): + if x[n] < -TOL: + viol_amt = -x[n] + add_violation(violations, magnitudes, 5, + f"Non-negativity violated: x[{n}]={x[n]:.6f} < 0", + x[n], 0.0, viol_amt) + + # --- Constraint 6: Binary --- + # z_n in {0,1} for all n + for n in range(N): + dist = min(abs(z[n] - 0.0), abs(z[n] - 1.0)) + if dist > TOL: + add_violation(violations, magnitudes, 6, + f"Binary violated: z[{n}]={z[n]} not in {{0,1}}", + z[n], round(z[n]), dist) + + # --- Constraint 7: Cardinality --- + # sum z_n <= k + sum_z = sum(z[n] for n in range(N)) + viol = sum_z - k # <= constraint: violation if LHS > RHS + if viol > TOL: + add_violation(violations, magnitudes, 7, + f"Cardinality violated: sum(z)={sum_z} > k={k}", + float(sum_z), float(k), viol) + + # --- Constraint 8: v >= 0 --- + if v < -TOL: + viol_amt = -v + add_violation(violations, magnitudes, 8, + f"v non-negativity violated: v={v:.6f} < 0", + v, 0.0, viol_amt) + + # --- Constraint 9: Objective consistency (Tier C: obj recompute) --- + # (7a) objective = (1/(2*gamma)) * x^T x + a + v. + # Every variable the objective depends on (x, a, v) is present in the + # solution and gamma is in the instance, so a full recompute is exact. + # Reject when the self-reported objective_value disagrees with the + # recomputed value beyond a 0.1% relative tolerance (1e-3 absolute floor). + 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 and math.isfinite(reported): + reg_term = sum(x[n] * x[n] for n in range(N)) / (2.0 * gamma) + true_obj = reg_term + a + v + abs_diff = abs(reported - true_obj) + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + add_violation(violations, magnitudes, 9, + f"Objective consistency violated: reported objective_value={reported} " + f"differs from recomputed (1/(2*gamma))*x^T x + a + v={true_obj:.6f} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})", + reported, true_obj, abs_diff) + elif reported is not None: + # Non-finite reported objective (inf / nan) — a degenerate exploit form. + reg_term = sum(x[n] * x[n] for n in range(N)) / (2.0 * gamma) + true_obj = reg_term + a + v + add_violation(violations, magnitudes, 9, + f"Objective consistency violated: reported objective_value={reported} " + f"is non-finite; recomputed (1/(2*gamma))*x^T x + a + v={true_obj:.6f}", + reported, true_obj, float("inf")) + + # Build result + violated_indices = sorted(set(entry[0] for entry in violations)) + # Aggregate messages per constraint index + messages = [] + for idx in violated_indices: + msgs = [msg for (ci, msg) in violations if ci == idx] + messages.append("; ".join(msgs)) + + feasible = len(violated_indices) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": messages, + "violation_magnitudes": magnitudes if not feasible else [], + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Cardinality-constrained Mean-CVaR Portfolio Optimization" + ) + parser.add_argument("--instance_path", required=True, help="Path to instance JSON file") + parser.add_argument("--solution_path", required=True, help="Path to solution JSON file") + parser.add_argument("--result_path", required=True, help="Path for output feasibility result JSON file") + 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) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Result: {status}") + if not result["feasible"]: + for msg in result["violations"]: + print(f" - {msg}") + 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/kobayashi2021/gurobi_code.py b/tasks/kobayashi2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..b5568f9c6e999e07f870fec016d9007b3924bafd --- /dev/null +++ b/tasks/kobayashi2021/gurobi_code.py @@ -0,0 +1,193 @@ +""" +Gurobi MIO implementation of Cardinality-constrained Mean-CVaR Portfolio Optimization. +Kobayashi, Takano, Nakata (2021). + +Uses the BigM formulation (Eq. 32) with linearized CVaR (lifting representation, Eqs. 10b-10d). +""" + +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) + N = data["N"] + S = data["S"] + k = data["k"] + beta = data["beta"] + gamma = data["gamma"] + mu_bar = data["mu_bar"] + mu = data["mu"] # length N + # p_s may be stored as scalar (uniform) or list + p_s_raw = data["p_s"] + if isinstance(p_s_raw, list): + p = p_s_raw + else: + p = [p_s_raw] * S + scenarios = data["scenarios"] # S x N + # Optional generic linear constraints A x <= b (feasible portfolio set X) + A = data.get("A") + b = data.get("b") + return N, S, k, beta, gamma, mu_bar, mu, p, scenarios, A, b + + +def build_and_solve(instance_path, solution_path, time_limit): + N, S, k, beta, gamma, mu_bar, mu, p, scenarios, A, b = load_instance(instance_path) + + m = gp.Model("MeanCVaR_BigM") + m.setParam("Threads", 1) + m.setParam("TimeLimit", time_limit) + # Use primal-dual interior point for QP (consistent with paper) + # Gurobi handles MIQP automatically; set OutputFlag for cleaner runs + m.setParam("OutputFlag", 1) + + # ---------------------------------------------------------------- + # Decision variables + # ---------------------------------------------------------------- + x = m.addVars(N, lb=0.0, name="x") # portfolio weights + z = m.addVars(N, vtype=GRB.BINARY, name="z") # asset selection + a = m.addVar(lb=-GRB.INFINITY, name="a") # VaR auxiliary + v = m.addVar(lb=0.0, name="v") # CVaR upper bound + # Lifting variables q_s >= 0 for linearized CVaR (Eqs. 10c-10d) + q = m.addVars(S, lb=0.0, name="q") + + # ---------------------------------------------------------------- + # Objective: (1/(2*gamma)) * x^T x + a + v (Eq. 7a) + # ---------------------------------------------------------------- + obj = gp.QuadExpr() + for n in range(N): + obj += (1.0 / (2.0 * gamma)) * x[n] * x[n] + obj += a + v + m.setObjective(obj, GRB.MINIMIZE) + + # ---------------------------------------------------------------- + # CVaR constraint via lifting (Eqs. 10b, 10c, 10d) + # ---------------------------------------------------------------- + # (10b): v >= 1/(1-beta) * sum_s p_s * q_s + m.addConstr( + v >= (1.0 / (1.0 - beta)) * gp.quicksum(p[s] * q[s] for s in range(S)), + name="cvar_ub" + ) + # (10c): q_s >= -(r^(s))^T x - a for all s + for s in range(S): + r_s = scenarios[s] + m.addConstr( + q[s] >= -gp.quicksum(r_s[n] * x[n] for n in range(N)) - a, + name=f"q_lb_{s}" + ) + # (10d): q_s >= 0 already enforced by lb=0 + + # ---------------------------------------------------------------- + # Budget constraint: sum x_n = 1 (Eq. 1) + # ---------------------------------------------------------------- + m.addConstr(gp.quicksum(x[n] for n in range(N)) == 1.0, name="budget") + + # ---------------------------------------------------------------- + # Expected return constraint: mu^T x >= mu_bar (Eq. 6) + # ---------------------------------------------------------------- + m.addConstr( + gp.quicksum(mu[n] * x[n] for n in range(N)) >= mu_bar, + name="return" + ) + + # ---------------------------------------------------------------- + # Generic linear portfolio constraints: A x <= b (feasible set X) + # ---------------------------------------------------------------- + if A is not None and b is not None: + for i in range(len(b)): + m.addConstr( + gp.quicksum(A[i][n] * x[n] for n in range(N)) <= b[i], + name=f"Ax_b_{i}" + ) + + # ---------------------------------------------------------------- + # BigM cardinality linking: 0 <= x_n <= z_n (Eq. 32) + # (valid since x_n <= 1 from budget and x_n >= 0; z_n in {0,1}) + # ---------------------------------------------------------------- + for n in range(N): + m.addConstr(x[n] <= z[n], name=f"bigm_{n}") + + # ---------------------------------------------------------------- + # Cardinality constraint: sum z_n <= k (Eq. 4) + # ---------------------------------------------------------------- + m.addConstr(gp.quicksum(z[n] for n in range(N)) <= k, name="cardinality") + + # ---------------------------------------------------------------- + # Optimize + # ---------------------------------------------------------------- + m.optimize() + + # ---------------------------------------------------------------- + # Extract solution + # ---------------------------------------------------------------- + status = m.Status + has_solution = m.SolCount > 0 + + if not has_solution: + print("No feasible solution found within time limit.", file=sys.stderr) + result = { + "objective_value": None, + "status": status, + "x": None, + "z": None, + } + else: + obj_val = m.ObjVal + x_sol = [x[n].X for n in range(N)] + z_sol = [int(round(z[n].X)) for n in range(N)] + a_sol = a.X + v_sol = v.X + result = { + "objective_value": obj_val, + "status": status, + "x": x_sol, + "z": z_sol, + "a": a_sol, + "v": v_sol, + "gap": m.MIPGap if status != GRB.OPTIMAL else 0.0, + } + print(f"Objective value: {obj_val:.8f}") + selected = [n for n in range(N) if z_sol[n] == 1] + print(f"Selected assets ({len(selected)}): {selected}") + + 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}") + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi MIO for Cardinality-constrained Mean-CVaR Portfolio Optimization" + ) + parser.add_argument("--instance_path", required=True, help="Path to instance JSON file") + parser.add_argument("--solution_path", required=True, help="Path for output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, 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) + + build_and_solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/kobayashi2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/kobayashi2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobayashi2021/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/kobayashi2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/kobayashi2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobayashi2021/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/kobayashi2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/kobayashi2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobayashi2021/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/kobayashi2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/kobayashi2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobayashi2021/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/kobayashi2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/kobayashi2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobayashi2021/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/kobayashi2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/kobayashi2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobayashi2021/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/kobayashi2021/gurobi_solution/large_solution_1.json b/tasks/kobayashi2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4de65f12e7d75785af20c1f4911336a40d5919b1 --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed01bf69295243ebc824db5c89730e96dea973d713be141233be8d1600861546 +size 3934 diff --git a/tasks/kobayashi2021/gurobi_solution/large_solution_2.json b/tasks/kobayashi2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..187ca14455f20d701eac50e344e34281759bd007 --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d3ec85fcfe636e14ae1c45b22972b11d61e707f4c09007786f393c5a642343a +size 3931 diff --git a/tasks/kobayashi2021/gurobi_solution/large_solution_3.json b/tasks/kobayashi2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..0d08decbb231e626032f0148e8f5c347a4e4bd3d --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80a8c27a78a7c9119fa6b083cc09356f2984c356d885211b2edec6aa7c787cf7 +size 3944 diff --git a/tasks/kobayashi2021/gurobi_solution/large_solution_4.json b/tasks/kobayashi2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4ee79839a3dbabbc5a130da824fcb9da5ac9d63e --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae5b905751411d713757366820b3a2b5ba2461e699c5524b88d752e27439e76e +size 3931 diff --git a/tasks/kobayashi2021/gurobi_solution/large_solution_5.json b/tasks/kobayashi2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..0d1f0b83f42fade3ed2260f1c8c44ed691f0815e --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c271c56ee50f038c6c8b92a2c225f24a397f3062ed4d4e4bb720dcd633eaa42f +size 3930 diff --git a/tasks/kobayashi2021/gurobi_solution/tiny_solution.json b/tasks/kobayashi2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..a5c1ab0ec7edb0b1bd1048f63896f3b0b9e11c56 --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78d300988c5f36805c8f44a3f6e864c2b1b4326520dac3ea7c4b1c89f1c07236 +size 655 diff --git a/tasks/kobayashi2021/gurobi_solution_log/large_log_1.jsonl b/tasks/kobayashi2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..aeda7b16418e00c62cedebc424502fdea675ea6e --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5174248d2b144bd7a205c4671ab2990c37cbd78bf14420bea2577fe4bfab3a19 +size 337 diff --git a/tasks/kobayashi2021/gurobi_solution_log/large_log_2.jsonl b/tasks/kobayashi2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..85032722fd593599bc52348a387b3cb6442b14a0 --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a570cbc6e981d31d84b777d0cb567af83777086ea623c98c92393cae9a2c05c4 +size 216 diff --git a/tasks/kobayashi2021/gurobi_solution_log/large_log_3.jsonl b/tasks/kobayashi2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b7c036a0a48f7760ebf4160f27600aadf94c4a3c --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a35417b144259279a454a7275f4203281d8fc0056370544409f60bdc674a9de +size 782 diff --git a/tasks/kobayashi2021/gurobi_solution_log/large_log_4.jsonl b/tasks/kobayashi2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..23bcbc71a66c44bf2e67ee75e69bb09a02c22c22 --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f74998f9ed0bd75e4510d35554966dda2e03dc2f8c3a021ade988fc448faf8e +size 279 diff --git a/tasks/kobayashi2021/gurobi_solution_log/large_log_5.jsonl b/tasks/kobayashi2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..617a9530d14856c1d076a16c7ebe201628a69816 --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f64b65efdd9419aada2114db1d47f139e9fff88e0a56130591b1b58a5f5f09f +size 218 diff --git a/tasks/kobayashi2021/gurobi_solution_log/tiny_log.jsonl b/tasks/kobayashi2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f848156fac48a28a8b18af83d2972f4a4019f19f --- /dev/null +++ b/tasks/kobayashi2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63c56c9d48ac90f7a6fa78070f4238e11cb27a00168408d425ffd76b80c7f6f5 +size 112 diff --git a/tasks/kobayashi2021/instance/large_instance_1.json b/tasks/kobayashi2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..7b3f2e0ecaea4ac59ae876c63c4e493b14aba569 --- /dev/null +++ b/tasks/kobayashi2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea39a352e111a817f686d1fc5c19a58894d43fb087cb9079f93bf0bd2516a889 +size 42546824 diff --git a/tasks/kobayashi2021/instance/large_instance_2.json b/tasks/kobayashi2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4f56b37b6db940110861f71cf1351a06c3610b69 --- /dev/null +++ b/tasks/kobayashi2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a9165ae34ba8ade8250011ae4ade80ec1ae93fd065d3113121aadb0a1eee498 +size 42884579 diff --git a/tasks/kobayashi2021/instance/large_instance_3.json b/tasks/kobayashi2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..34c559081c83553485c1560f975e5fb6fbb99bfe --- /dev/null +++ b/tasks/kobayashi2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34d0ef9a38b6dc0e77882c5046db051ec18ddea3189df95d2531a0fcb7b88f9a +size 42537243 diff --git a/tasks/kobayashi2021/instance/large_instance_4.json b/tasks/kobayashi2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..fe389e4ff94c2a20d521f85bdbdb13b9413d13aa --- /dev/null +++ b/tasks/kobayashi2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d34e19ad3f73766674b4fb935c0e6677a28a7d97512cc24f0dc28ed2a9ee294 +size 42514744 diff --git a/tasks/kobayashi2021/instance/large_instance_5.json b/tasks/kobayashi2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7696bb0a1ea4a64ae2f74a0ec4c776f25d3b69d9 --- /dev/null +++ b/tasks/kobayashi2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af27fb464e7ae8b5b0ed6f4273ee5beb2b6f183804ff45756f5229e7cd0a7c3a +size 43056929 diff --git a/tasks/kobayashi2021/instance/tiny_instance.json b/tasks/kobayashi2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..40573c1210fc99771f4c71ee72450117df3cebf7 --- /dev/null +++ b/tasks/kobayashi2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:018fde91613480b8092a882b91f9ba9a8cb6af02904ea127ee30f3bfa3145e40 +size 476102 diff --git a/tasks/kobayashi2021/instance_schema.json b/tasks/kobayashi2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..80e776237683ec2a116915bd8ba2759eed05085e --- /dev/null +++ b/tasks/kobayashi2021/instance_schema.json @@ -0,0 +1,11 @@ +{ + "N": " Number of assets available for investment.", + "S": " Number of return scenarios used to estimate portfolio risk.", + "k": " Maximum number of assets that may be held in the portfolio.", + "beta": " Probability level for the conditional value-at-risk measure.", + "gamma": " Regularization strength controlling the penalty on concentrated portfolio weights.", + "mu_bar": " Minimum required expected return that the portfolio must achieve.", + "mu": " Expected return for each asset.", + "p_s": " Probability assigned to each return scenario (uniform across all scenarios).", + "scenarios": " Simulated return of each asset under each scenario." +} \ No newline at end of file diff --git a/tasks/kobayashi2021/mathematical_formulation.md b/tasks/kobayashi2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f386a6ec2651d0825419c6bf955656b29353bc4c --- /dev/null +++ b/tasks/kobayashi2021/mathematical_formulation.md @@ -0,0 +1,57 @@ +# Original Formulation: Cardinality-constrained Mean-CVaR Portfolio Optimization (CCMC) + +*Source: Bilevel Cutting-plane Algorithm for Solving Cardinality-constrained Mean-CVaR Portfolio Optimization Problems, Ken Kobayashi, Yuichi Takano, Kazuhide Nakata, 2021.* + +## Sets and Indices + +$$\begin{align*} +\mathcal{N} &:= \{1, 2, \ldots, N\} && \text{index set of $N$ assets ($n \in \mathcal{N}$),}\\ +\mathcal{S} &:= \{1, 2, \ldots, S\} && \text{index set of $S$ return scenarios ($s \in \mathcal{S}$).} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +k &\in \mathbb{Z}_{>0} && \text{cardinality limit (max number of assets held),}\\ +\beta &\in (0,1) && \text{probability level for CVaR (set close to one),}\\ +\gamma &> 0 && \text{$\ell_2$-regularization parameter,}\\ +\boldsymbol{\mu} &:= (\mu_1,\ldots,\mu_N)^\top && \text{vector of expected returns of assets,}\\ +\bar{\mu} &\in \mathbb{R} && \text{required return level,}\\ +\boldsymbol{A} &\in \mathbb{R}^{M \times N},\ \boldsymbol{b} \in \mathbb{R}^{M} && \text{matrix/vector defining linear portfolio constraints $\boldsymbol{A}\boldsymbol{x}\le\boldsymbol{b}$,}\\ +\boldsymbol{r}^{(s)} &:= (r_1^{(s)},\ldots,r_N^{(s)})^\top && \text{asset return vector in scenario $s$,}\\ +p_s &\ge 0,\ \boldsymbol{p}:=(p_1,\ldots,p_S)^\top && \text{occurrence probability of scenario $s$.} +\end{align*}$$ + +The feasible portfolio set and the cardinality feasible set are $$\begin{align} +\mathcal{X} &:= \{\boldsymbol{x} \in \mathbb{R}^N \mid \boldsymbol{A}\boldsymbol{x} \le \boldsymbol{b},\ \boldsymbol{1}^\top \boldsymbol{x} = 1,\ \boldsymbol{x} \ge \boldsymbol{0}\}, \tag{1}\\ +\mathcal{Z}_N^k &:= \left\{\boldsymbol{z} \in \{0,1\}^N \;\middle|\; \sum_{n \in \mathcal{N}} z_n \le k \right\}, +\end{align}$$ where $\boldsymbol{A}\boldsymbol{x} \le \boldsymbol{b}$ is supposed to contain the expected return constraint $$\begin{equation} +\boldsymbol{\mu}^\top \boldsymbol{x} \ge \bar{\mu}. \tag{6} +\end{equation}$$ + +## Decision Variables + +$$\begin{align*} +\boldsymbol{x} &:= (x_1,\ldots,x_N)^\top \in \mathbb{R}^N_{\ge 0} && \text{portfolio weights ($x_n$ = investment weight of asset $n$),}\\ +\boldsymbol{z} &:= (z_1,\ldots,z_N)^\top \in \{0,1\}^N && \text{asset selection ($z_n=1$ iff asset $n$ is selected),}\\ +a &\in \mathbb{R} && \text{auxiliary variable corresponding to $\beta$-VaR,}\\ +v &\ge 0 && \text{auxiliary variable (tail-risk / CVaR contribution).} +\end{align*}$$ + +## Objective + +$$\begin{equation} +\underset{a,\, v,\, \boldsymbol{x},\, \boldsymbol{z}}{\text{minimize}} \quad + \frac{1}{2\gamma}\boldsymbol{x}^\top \boldsymbol{x} + a + v +\tag{7a} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\text{subject to} \quad + & v \ge \frac{1}{1-\beta} \sum_{s \in \mathcal{S}} p_s + \left[\, -(\boldsymbol{r}^{(s)})^\top \boldsymbol{x} - a \,\right]_+, \tag{7b}\\ + & z_n = 0 \;\Rightarrow\; x_n = 0 \quad (\forall n \in \mathcal{N}), \tag{7c}\\ + & \boldsymbol{x} \in \mathcal{X}, \quad \boldsymbol{z} \in \mathcal{Z}_N^k, \tag{7d} +\end{align}$$ where $[\xi]_+ := \max\{0,\xi\}$ denotes the positive part of $\xi$, $v$ is an auxiliary decision variable, and $\gamma>0$ is a regularization parameter. diff --git a/tasks/kobayashi2021/problem_description.txt b/tasks/kobayashi2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..58b98b7d05f68303ef8db725a95fc7bd7a2a7907 --- /dev/null +++ b/tasks/kobayashi2021/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +An investor selects a portfolio from a universe of N assets. The investor must allocate wealth across these assets by choosing a fractional weight for each asset, where all weights sum to one and no weight is negative (short selling is prohibited). For each asset, the investor also makes a yes-or-no inclusion decision. To limit monitoring and transaction costs, the investor may include at most k assets; any asset not included must receive zero weight. + +The input data specifies the number of assets N, a cardinality limit k on how many assets may be held, a CVaR probability level beta (a value strictly between zero and one, typically set to 0.9), and an ell-2 regularization parameter gamma (a positive scalar). For each asset, an expected return is provided, collected into a vector of length N. A required return level mu_bar is given, and the portfolio's expected return (the sum of each asset's weight times its expected return) must be at least mu_bar. Additionally, a set of S return scenarios is provided, where each scenario contains a return value for every asset. Each scenario has an associated occurrence probability p_s; in the standard setting all scenarios are equally likely with probability one over S. + +The goal is to minimize the sum of three terms: a regularization term equal to one over twice gamma times the sum of squared portfolio weights, a value a that may be any real number and represents the value-at-risk threshold, and a value v that must be zero or greater and represents the tail-risk contribution beyond the threshold. The value v must be at least as large as one over one minus beta times the probability-weighted sum, across all scenarios, of the amount by which the scenario loss exceeds a, or zero if the scenario loss does not exceed a. The scenario loss for a given scenario is the negative of the sum of each asset's scenario return multiplied by its portfolio weight. Equivalently, for each scenario, one computes the negative portfolio return under that scenario minus a, takes the larger of this value and zero, multiplies by the scenario probability, sums over all scenarios, divides by one minus beta, and requires v to be no smaller than the result. + +If an asset is not included (that is, if the investor's inclusion decision for that asset is no), then its portfolio weight must be zero. The total number of included assets must not exceed k. Beyond the budget and nonnegativity requirements, the only linear inequality imposed on the portfolio weights is the expected-return requirement described above (namely, the portfolio's expected return must be at least mu_bar); no further linear inequalities are imposed. The portfolio weights must all be nonnegative and must sum to exactly one. diff --git a/tasks/kobayashi2021/solution_logger.py b/tasks/kobayashi2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/kobayashi2021/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/kobayashi2021/solution_schema.json b/tasks/kobayashi2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..4455a9ebc4156b7749b7a8465743b32ebabef4fe --- /dev/null +++ b/tasks/kobayashi2021/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Total portfolio cost combining the regularization penalty, the value-at-risk threshold, and the conditional value-at-risk contribution.", + "x": " Fraction of total wealth allocated to each asset.", + "z": " Whether each asset is selected for inclusion in the portfolio (1 = included, 0 = excluded).", + "a": " Value-at-risk threshold representing the loss level below which tail losses are measured.", + "v": " Conditional value-at-risk contribution capturing the expected severity of losses beyond the value-at-risk threshold." +} \ No newline at end of file diff --git a/tasks/kobeaga2024/feasibility_check.py b/tasks/kobeaga2024/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d08166f003a800446813eb4f87024506db7fee37 --- /dev/null +++ b/tasks/kobeaga2024/feasibility_check.py @@ -0,0 +1,476 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Orienteering Problem (OP). + +Based on Kobeaga et al. (2024) formulation: + Constraint 1 (2b): sum_e d_e * x_e <= d_0 (distance limit) + Constraint 2 (2c): x(delta(v)) - 2*y_v = 0, for all v (degree) + Constraint 3 (2d): SEC - no disconnected subtours (subtour elimination) + Constraint 4 (2e): y_v - x_e >= 0, for v in V, e in delta(v) (logical) + Constraint 5 (2f): 0 <= y_v <= 1, for all v (vertex bounds) + Constraint 6 (2g): 0 <= x_e <= 1, for all e (edge bounds) + Constraint 7 (2h): y_o = 1 (depot visited) + Constraint 8 (2i): x_e in Z, for all e (integrality) + + Constraint 9 (objective): the program's reported objective_value must + match the true objective sum_v(scores[v]*y_v) + recomputed from the solution variables; this + blocks score-exploits where the program returns + an inflated obj that the scorer would trust. +""" + +import argparse +import json +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'tour_edges', 'visited_vertices') +_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 edge_key(u, v): + return (min(u, v), max(u, v)) + + +def record_violation(violations_list, magnitudes_list, constraint_idx, message, lhs, rhs, violation_amount): + """Record a single violation instance.""" + violations_list.append(message) + normalizer = max(abs(rhs), EPS) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + +def extract_solution(instance, solution): + """ + Extract y (vertex) and x (edge) variables from either efficient or gurobi + solution format. + Returns: y dict {v: value}, x dict {(u,v): value} with u < v + """ + n = instance["num_nodes"] + y = {v: 0 for v in range(n)} + x = {} + + if "tour" in solution: + # Efficient algorithm format: tour is ordered vertex list forming a cycle + tour = solution["tour"] + for v in tour: + y[v] = 1 + for i in range(len(tour)): + u = tour[i] + v = tour[(i + 1) % len(tour)] + ek = edge_key(u, v) + x[ek] = x.get(ek, 0) + 1 + elif "visited_vertices" in solution and "tour_edges" in solution: + # Gurobi format + for v in solution["visited_vertices"]: + y[v] = 1 + for e in solution["tour_edges"]: + ek = edge_key(e[0], e[1]) + x[ek] = x.get(ek, 0) + 1 + else: + raise ValueError("Unrecognized solution format") + + return y, x + + +def check_feasibility(instance, solution): + n = instance["num_nodes"] + depot = instance["depot_vertex"] + d0 = instance["distance_limitation_d0"] + dist = instance["distance_matrix"] + + y, x = extract_solution(instance, solution) + + violated_constraints = set() + violations = [] + magnitudes = [] + + # ------------------------------------------------------------------ + # Constraint 1 (2b): sum_e d_e * x_e <= d_0 + # ------------------------------------------------------------------ + total_dist = 0.0 + for (u, v), x_val in x.items(): + total_dist += dist[u][v] * x_val + violation_amount = total_dist - d0 + if violation_amount > TOL: + violated_constraints.add(1) + record_violation(violations, magnitudes, 1, + f"Distance limit exceeded: total distance {total_dist} > limit {d0}", + total_dist, d0, violation_amount) + + # ------------------------------------------------------------------ + # Constraint 2 (2c): x(delta(v)) - 2*y_v = 0 for all v + # ------------------------------------------------------------------ + for v in range(n): + degree_sum = 0.0 + for (u, w), x_val in x.items(): + if u == v or w == v: + degree_sum += x_val + lhs = degree_sum - 2 * y[v] + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(2) + record_violation(violations, magnitudes, 2, + f"Degree constraint violated at vertex {v}: " + f"x(delta({v}))={degree_sum}, 2*y_{v}={2*y[v]}", + lhs, rhs, violation_amount) + + # ------------------------------------------------------------------ + # Constraint 3 (2d): Subtour elimination - solution edges must form + # a single connected cycle containing the depot. + # SEC: x(delta(H)) - 2*y_l - 2*y_r >= -2 for l in H, r in V\H + # Violated when there exist disconnected subtours. + # ------------------------------------------------------------------ + # Build adjacency from edges with x_e > 0 + adj = defaultdict(set) + active_vertices = set() + for (u, v), x_val in x.items(): + if x_val > TOL: + adj[u].add(v) + adj[v].add(u) + active_vertices.add(u) + active_vertices.add(v) + + # Find connected components among active vertices + visited_set = set() + components = [] + for start in active_vertices: + if start in visited_set: + continue + component = set() + stack = [start] + while stack: + node = stack.pop() + if node in visited_set: + continue + visited_set.add(node) + component.add(node) + for nb in adj[node]: + if nb not in visited_set: + stack.append(nb) + components.append(component) + + # Check for subtours not containing depot + for comp in components: + if depot in comp: + continue + if len(comp) < 2: + continue + # This component H forms a subtour disconnected from depot. + # Pick any l in H and any r not in H. + # x(delta(H)) = 0 (disconnected), so LHS = 0 - 2*y_l - 2*y_r + # For l in H with y_l = 1, and r = depot with y_r = 1: + # LHS = 0 - 2 - 2 = -4, RHS = -2, violation = -2 - (-4) = 2 + l_node = next(iter(comp)) + r_node = depot + lhs_val = 0 - 2 * y[l_node] - 2 * y[r_node] + rhs_val = -2.0 + violation_amount = rhs_val - lhs_val # >= constraint: RHS - LHS when violated + if violation_amount > TOL: + violated_constraints.add(3) + record_violation(violations, magnitudes, 3, + f"Subtour elimination violated: disconnected component " + f"{sorted(comp)} not connected to depot {depot}", + lhs_val, rhs_val, violation_amount) + + # ------------------------------------------------------------------ + # Constraint 4 (2e): y_v - x_e >= 0 for all v in V, e in delta(v) + # ------------------------------------------------------------------ + for (u, v), x_val in x.items(): + # Check for endpoint u + lhs_u = y[u] - x_val + if -lhs_u > TOL: # y_u - x_e < 0 + violation_amount = -lhs_u + violated_constraints.add(4) + record_violation(violations, magnitudes, 4, + f"Logical constraint violated: y_{u}={y[u]} < x_({u},{v})={x_val}", + y[u] - x_val, 0.0, violation_amount) + # Check for endpoint v + lhs_v = y[v] - x_val + if -lhs_v > TOL: + violation_amount = -lhs_v + violated_constraints.add(4) + record_violation(violations, magnitudes, 4, + f"Logical constraint violated: y_{v}={y[v]} < x_({u},{v})={x_val}", + y[v] - x_val, 0.0, violation_amount) + + # ------------------------------------------------------------------ + # Constraint 5 (2f): 0 <= y_v <= 1 for all v + # ------------------------------------------------------------------ + for v in range(n): + if y[v] < -TOL: + violation_amount = -y[v] + violated_constraints.add(5) + record_violation(violations, magnitudes, 5, + f"Vertex bound violated: y_{v}={y[v]} < 0", + y[v], 0.0, violation_amount) + elif y[v] > 1 + TOL: + violation_amount = y[v] - 1 + violated_constraints.add(5) + record_violation(violations, magnitudes, 5, + f"Vertex bound violated: y_{v}={y[v]} > 1", + y[v], 1.0, violation_amount) + + # ------------------------------------------------------------------ + # Constraint 6 (2g): 0 <= x_e <= 1 for all e + # ------------------------------------------------------------------ + for (u, v), x_val in x.items(): + if x_val < -TOL: + violation_amount = -x_val + violated_constraints.add(6) + record_violation(violations, magnitudes, 6, + f"Edge bound violated: x_({u},{v})={x_val} < 0", + x_val, 0.0, violation_amount) + elif x_val > 1 + TOL: + violation_amount = x_val - 1 + violated_constraints.add(6) + record_violation(violations, magnitudes, 6, + f"Edge bound violated: x_({u},{v})={x_val} > 1", + x_val, 1.0, violation_amount) + + # ------------------------------------------------------------------ + # Constraint 7 (2h): y_o = 1 + # ------------------------------------------------------------------ + y_depot = y[depot] + violation_amount = abs(y_depot - 1) + if violation_amount > TOL: + violated_constraints.add(7) + record_violation(violations, magnitudes, 7, + f"Depot constraint violated: y_{depot}={y_depot} != 1", + y_depot, 1.0, violation_amount) + + # ------------------------------------------------------------------ + # Constraint 8 (2i): x_e in Z (integer) for all e + # ------------------------------------------------------------------ + for (u, v), x_val in x.items(): + frac = abs(x_val - round(x_val)) + if frac > TOL: + violated_constraints.add(8) + rhs_val = round(x_val) + record_violation(violations, magnitudes, 8, + f"Integrality violated: x_({u},{v})={x_val} is not integer", + x_val, rhs_val, frac) + + # ------------------------------------------------------------------ + # Constraint 9 (objective consistency): + # The program's reported ``objective_value`` must match the true OP + # objective recomputed from the solution variables: + # true_obj = sum_v(scores[v] * y_v) + # A mismatch means the program is *lying* about how good its solution + # is -- a score-gaming exploit (e.g. returning obj=1.8e308 or obj=128141 + # while the actual route collects only ~30 points). Reject as infeasible + # so the scorer doesn't credit the fake objective. + # ------------------------------------------------------------------ + scores = instance.get("scores") + reported_obj = solution.get("objective_value") + if scores 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 = float(sum(int(scores[v]) * y[v] for v in range(n))) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance or 1e-3 absolute, whichever is larger + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(9) + record_violation( + violations, magnitudes, 9, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum_v(scores[v]*y_v)=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={tol:.3g})", + reported, true_obj, abs_diff, + ) + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the Orienteering Problem (Kobeaga et al. 2024)") + 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 to the solution JSON file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the feasibility result JSON file") + 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 + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE") + else: + print(f"INFEASIBLE - 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/kobeaga2024/gurobi_code.py b/tasks/kobeaga2024/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c049e0a76a6a8505669b541886c18b2fc4ed1aff --- /dev/null +++ b/tasks/kobeaga2024/gurobi_code.py @@ -0,0 +1,302 @@ +#!/usr/bin/env python3 +""" +Orienteering Problem (OP) solver using Gurobi. + +Implements the MIP formulation from Kobeaga et al. (2024): + max sum_v s_v * y_v (2a) + s.t. sum_e d_e * x_e <= d_0 (2b) + x(delta(v)) - 2*y_v = 0 for all v (2c) + x(delta(H)) - 2*y_l - 2*y_r >= -2 (SECs, lazy) (2d) + y_v - x_e >= 0 for v in V, e in delta(v)(2e) + y_o = 1 (2h) + x_e in {0,1} (2i) + +Subtour elimination constraints (2d) are added dynamically via +Gurobi lazy constraint callbacks using connected component detection. +""" + +import argparse +import json +import sys +from itertools import combinations + +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 parse_args(): + parser = argparse.ArgumentParser( + description="Solve the Orienteering Problem using 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="gurobi_solution_1.json", + help="Path to write the solution JSON file.", + ) + parser.add_argument( + "--time_limit", + type=int, + default=None, + help="Time limit in seconds for Gurobi.", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + return parser.parse_args() + + +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + return data + + +def get_edges(n): + """Return list of undirected edges (i, j) with i < j.""" + return [(i, j) for i in range(n) for j in range(i + 1, n)] + + +def delta(v, edges): + """Return indices of edges incident to vertex v.""" + return [idx for idx, (i, j) in enumerate(edges) if i == v or j == v] + + +def find_connected_components(n, selected_edges): + """Find connected components among vertices that have at least one + selected edge, using union-find.""" + parent = list(range(n)) + + def find(u): + while parent[u] != u: + parent[u] = parent[parent[u]] + u = parent[u] + return u + + def union(u, v): + pu, pv = find(u), find(v) + if pu != pv: + parent[pu] = pv + + active_vertices = set() + for i, j in selected_edges: + union(i, j) + active_vertices.add(i) + active_vertices.add(j) + + components = {} + for v in active_vertices: + root = find(v) + if root not in components: + components[root] = set() + components[root].add(v) + + return list(components.values()) + + +def solve_op(instance, time_limit=None): + n = instance["num_nodes"] + depot = instance["depot_vertex"] + d0 = instance["distance_limitation_d0"] + scores = instance["scores"] + dist = instance["distance_matrix"] + + edges = get_edges(n) + edge_index = {e: idx for idx, e in enumerate(edges)} + num_edges = len(edges) + + # Precompute delta sets for each vertex + delta_v = [delta(v, edges) for v in range(n)] + + # Build model + model = gp.Model("OrienteeringProblem") + model.setParam("Threads", 1) + + # Variables + y = model.addVars(n, vtype=GRB.BINARY, name="y") + x = model.addVars(num_edges, vtype=GRB.BINARY, name="x") + + # Objective (2a): maximize total score + model.setObjective( + gp.quicksum(scores[v] * y[v] for v in range(n)), GRB.MAXIMIZE + ) + + # Constraint (2b): distance limit + model.addConstr( + gp.quicksum(dist[edges[e][0]][edges[e][1]] * x[e] for e in range(num_edges)) + <= d0, + name="distance_limit", + ) + + # Constraints (2c): degree constraints + for v in range(n): + model.addConstr( + gp.quicksum(x[e] for e in delta_v[v]) - 2 * y[v] == 0, + name=f"degree_{v}", + ) + + # Constraints (2e): logical constraints y_v - x_e >= 0 for e in delta(v) + for v in range(n): + for e in delta_v[v]: + model.addConstr( + y[v] - x[e] >= 0, + name=f"logical_{v}_{e}", + ) + + # Constraint (2h): depot must be visited + model.addConstr(y[depot] == 1, name="depot_visited") + + # Gurobi parameters + if time_limit is not None: + model.Params.TimeLimit = time_limit + model.Params.LazyConstraints = 1 + + def subtour_callback(model, where): + """Lazy constraint callback: detect subtours and add SECs (2d).""" + if where != GRB.Callback.MIPSOL: + return + + x_vals = model.cbGetSolution(x) + y_vals = model.cbGetSolution(y) + + # Collect selected edges (those with x_e ~ 1) + selected_edges = [edges[e] for e in range(num_edges) if x_vals[e] > 0.5] + + if not selected_edges: + return + + components = find_connected_components(n, selected_edges) + + # If there is only one component containing the depot, no subtour + if len(components) <= 1: + return + + # Find which component contains the depot + depot_comp = None + for comp in components: + if depot in comp: + depot_comp = comp + break + + # For each component that does NOT contain the depot, add SEC (2d): + # x(delta(H)) - 2*y_l - 2*y_r >= -2 for l in H, r in V\H + + for comp in components: + if depot in comp: + continue + + # Compute delta(H): edges with exactly one endpoint in H + comp_set = comp + delta_H_indices = [] + for e_idx, (i, j) in enumerate(edges): + if (i in comp_set) != (j in comp_set): + delta_H_indices.append(e_idx) + + # V \ H + outside_H = [v for v in range(n) if v not in comp_set] + + # Add violated SEC (2d): x(delta(H)) - 2*y_l - 2*y_r >= -2 + delta_H_expr = gp.quicksum(x[e] for e in delta_H_indices) + for l in comp: + if y_vals[l] < 0.5: + continue + for r in outside_H: + if y_vals[r] < 0.5: + continue + model.cbLazy( + delta_H_expr - 2 * y[l] - 2 * y[r] >= -2 + ) + + # Optimize + model.optimize(subtour_callback) + + # Extract solution + result = { + "objective_value": None, + "status": model.Status, + "status_name": None, + "runtime": model.Runtime, + "mip_gap": None, + "visited_vertices": [], + "tour_edges": [], + "tour_distance": None, + } + + status_map = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.INTERRUPTED: "INTERRUPTED", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + } + result["status_name"] = status_map.get(model.Status, f"UNKNOWN_{model.Status}") + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["mip_gap"] = model.MIPGap + + visited = [v for v in range(n) if y[v].X > 0.5] + result["visited_vertices"] = visited + + tour_edges = [ + list(edges[e]) for e in range(num_edges) if x[e].X > 0.5 + ] + result["tour_edges"] = tour_edges + + tour_dist = sum( + dist[edges[e][0]][edges[e][1]] + for e in range(num_edges) + if x[e].X > 0.5 + ) + result["tour_distance"] = tour_dist + + return result + + +def main(): + args = parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + + result = solve_op(instance, time_limit=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) + + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Visited vertices ({len(result['visited_vertices'])}): " + f"{result['visited_vertices']}") + print(f"Tour distance: {result['tour_distance']}") + print(f"Status: {result['status_name']}") + print(f"Runtime: {result['runtime']:.2f}s") + else: + print(f"No solution found. Status: {result['status_name']}") + + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/kobeaga2024/gurobi_feasi_result/large_feasi_result_1.json b/tasks/kobeaga2024/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobeaga2024/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/kobeaga2024/gurobi_feasi_result/large_feasi_result_2.json b/tasks/kobeaga2024/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobeaga2024/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/kobeaga2024/gurobi_feasi_result/large_feasi_result_3.json b/tasks/kobeaga2024/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobeaga2024/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/kobeaga2024/gurobi_feasi_result/large_feasi_result_4.json b/tasks/kobeaga2024/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobeaga2024/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/kobeaga2024/gurobi_feasi_result/large_feasi_result_5.json b/tasks/kobeaga2024/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobeaga2024/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/kobeaga2024/gurobi_feasi_result/tiny_feasi_result.json b/tasks/kobeaga2024/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kobeaga2024/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/kobeaga2024/gurobi_solution/large_solution_1.json b/tasks/kobeaga2024/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..2fdfc106d8cad68995c41aac38f4632e2d0ae28e --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b256b36339ec1bcad393b624b1f14bd06775f38fd87ccfe3ed7fc5993b69dfa +size 904 diff --git a/tasks/kobeaga2024/gurobi_solution/large_solution_2.json b/tasks/kobeaga2024/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6efd06e9349da7ceafd2d39f49146c6b4fd1f2ec --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b086494a2b31d8876be97d38ac489ecb27ccd4ed36a388226b1c0c1a9990e82 +size 858 diff --git a/tasks/kobeaga2024/gurobi_solution/large_solution_3.json b/tasks/kobeaga2024/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c1b762eee1c34ee5e050bf27fc449a540b726511 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab1bf874e857447806e833f4089a6b6607939f33b2b06ff5158f476e27721222 +size 4203 diff --git a/tasks/kobeaga2024/gurobi_solution/large_solution_4.json b/tasks/kobeaga2024/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..cf89b7e308b26009d09f186eba9b7374ea3dc065 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:243843048de306f06894fc78062db4751c4c83f2a969851657ec59f86a03634f +size 1621 diff --git a/tasks/kobeaga2024/gurobi_solution/large_solution_5.json b/tasks/kobeaga2024/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8a936ff26be65f3db8d950a4bf38e3a52087b7ac --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c23b621f541da8b7d96aea59bf0a7d93d9835c08a2f769eb83cd69d63621a01d +size 648 diff --git a/tasks/kobeaga2024/gurobi_solution/tiny_solution.json b/tasks/kobeaga2024/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..950062d76cfce350e500fd8c954588f7d5137f98 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d178433b54b9e75f2a3bed4e6fad83b15bf9daace77724e1e28168ee9250db7f +size 422 diff --git a/tasks/kobeaga2024/gurobi_solution_log/large_log_1.jsonl b/tasks/kobeaga2024/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..980e4c8455a10dd7eed7dad5683bdbbe667cf984 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32a4ad2318e152f3627e633809213f0e8a5cc268130250787d9c1431be16ccfa +size 40 diff --git a/tasks/kobeaga2024/gurobi_solution_log/large_log_2.jsonl b/tasks/kobeaga2024/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8111839069443034e0f3435e78379880b1148d9a --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c99db58f48b1e386670e60cfe1af1ec5d49e95d999d30a1428d2fdfc536e2f79 +size 40 diff --git a/tasks/kobeaga2024/gurobi_solution_log/large_log_3.jsonl b/tasks/kobeaga2024/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6d8b48f08c86df8b93fbbb5e345ee08224620215 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:281708c437a2ffec56c08c35dfc22e39f1c9a30bf82b9c18f20fa259ff3e6dc7 +size 39 diff --git a/tasks/kobeaga2024/gurobi_solution_log/large_log_4.jsonl b/tasks/kobeaga2024/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6bd0622cfd0d0300c8c679c457b2f7ab84637440 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0a2e6955b458c1d8cdfb11846c6aa8f9532aa258e868d1edea60fbfad365bf5 +size 40 diff --git a/tasks/kobeaga2024/gurobi_solution_log/large_log_5.jsonl b/tasks/kobeaga2024/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5bfce58bdbc14475355be50170cc2f3f1169c762 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b87286771a3402d1614147e66191e8fef967ddbdc4e4a252fb51b9f8c1403b2a +size 40 diff --git a/tasks/kobeaga2024/gurobi_solution_log/tiny_log.jsonl b/tasks/kobeaga2024/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce551d5e621709dfabf0173cd4542863ae597226 --- /dev/null +++ b/tasks/kobeaga2024/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b5aac8c634d2c6c6bf47c5a7471f1097c1fdd142f60e55f9a6de74c05ce166e +size 40 diff --git a/tasks/kobeaga2024/instance/large_instance_1.json b/tasks/kobeaga2024/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..54fe0d260ff2bd1a9735944ab25c66e5f5745004 --- /dev/null +++ b/tasks/kobeaga2024/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f40f2b9848f1e3ffde0c658523575a6656572106820b557302cc88944c582332 +size 544896 diff --git a/tasks/kobeaga2024/instance/large_instance_2.json b/tasks/kobeaga2024/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..dd7dc98c26932e1ec42174e51582a8019836daaf --- /dev/null +++ b/tasks/kobeaga2024/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ad30ca024561aec79ce99157cfae6274efea302c76628e4773db9e24c2ba2dd +size 535720 diff --git a/tasks/kobeaga2024/instance/large_instance_3.json b/tasks/kobeaga2024/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..eccb1eab97439fa7294ec771a66bac4085c368a1 --- /dev/null +++ b/tasks/kobeaga2024/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32ae2689733dbcdb035b04a7222a1ed2ef3aebcf6ad3c510083b4c6985c38427 +size 546813 diff --git a/tasks/kobeaga2024/instance/large_instance_4.json b/tasks/kobeaga2024/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..cc0171a6454795224b84dc523b1d9cb4e517c862 --- /dev/null +++ b/tasks/kobeaga2024/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4293dfe985ab903bea2cd47734344fcdd0a3c31b7cc1877d3b92743012dd90b9 +size 541706 diff --git a/tasks/kobeaga2024/instance/large_instance_5.json b/tasks/kobeaga2024/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8a2488b479732ccba87fb48de7b8419da99eeb5f --- /dev/null +++ b/tasks/kobeaga2024/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f08ad2f0fd09e0f922459cdf03e98cf19e84d386b55b6bac06bfc1eed9e4bed8 +size 530114 diff --git a/tasks/kobeaga2024/instance/tiny_instance.json b/tasks/kobeaga2024/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..eb5d227400cfaa2ef128add7bbf694f0ef3589e0 --- /dev/null +++ b/tasks/kobeaga2024/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cac4059de5fc148daaa50a7c353e87832c5057ba726e72f5af9ca41d3551ad86 +size 6185 diff --git a/tasks/kobeaga2024/instance_schema.json b/tasks/kobeaga2024/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3e91ee17f5a67227e8ab67038b4bbc96a1fe0dcb --- /dev/null +++ b/tasks/kobeaga2024/instance_schema.json @@ -0,0 +1,8 @@ +{ + "num_nodes": " Total number of locations in the network, including the depot.", + "distance_limitation_d0": " Maximum total travel distance allowed for the round-trip route.", + "depot_vertex": " Index of the home depot location where the route must start and end.", + "coordinates": " Two-dimensional position of each location, used to define the network geography.", + "scores": " Reward collected by visiting each location, with the depot always having a score of zero.", + "distance_matrix": " Symmetric matrix of rounded Euclidean travel distances between every pair of locations." +} \ No newline at end of file diff --git a/tasks/kobeaga2024/mathematical_formulation.md b/tasks/kobeaga2024/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..180feeb44e7c467076949d0a5f941279617be04d --- /dev/null +++ b/tasks/kobeaga2024/mathematical_formulation.md @@ -0,0 +1,52 @@ +# Original Formulation: Orienteering Problem (OP) + +*Source: A revisited branch-and-cut algorithm for large-scale orienteering problems, Gorka Kobeaga, Jairo Rojas-Delgado, María Merino, Jose A. Lozano, European Journal of Operational Research 313 (2024) 44–68.* + +## Sets and Parameters + +The OP is defined by the 5-tuple $(G, d, s, o, d_0)$, where: + +- $G = K_n = (V, E)$ is a complete graph with vertex set $V$ and edge set $E$. + +- $d = (d_e)$, where $d_e > 0$ is the distance value (time or weight) associated with each edge $e \in E$. + +- $s = (s_v)$, where $s_v > 0$ is the score (profit) of vertex $v \in V$. + +- $o \in V$ is the vertex selected as the depot. + +- $d_0 > 0$ is the value that limits the cycle length. + +The following edge/vertex sets are used: $$\begin{align} +(Q : W) &:= \{[u, v] \in E : u \in Q,\, v \in W\}, & Q, W &\subseteq V \tag{1a} \\ +\delta(Q) &:= (Q : V - Q), & Q &\subseteq V \tag{1b} \\ +E(Q) &:= (Q : Q), & Q &\subseteq V \tag{1c} \\ +V(T) &:= \{v \in V : T \cap (v : V) \neq \emptyset\}, & T &\subseteq E \tag{1d} +\end{align}$$ where $(Q:W)$ is the set of edges connecting $Q$ and $W$, $\delta(Q)$ is the coboundary (star-set) of $Q$, $E(Q)$ is the set of edges between the vertices of $Q$, and $V(T)$ is the set of vertices incident with an edge set $T$. For $S \subseteq V$ and $T \subseteq E$, we write $y(S) = \sum_{v \in S} y_v$ and $x(T) = \sum_{e \in T} x_e$. + +## Decision Variables + +Two types of variables, $y = (y_v) \in \mathbb{R}^V$ and $x = (x_e) \in \mathbb{R}^E$, associated with the nodes and edges of $G$ respectively: $$\begin{align*} +y_v &= \begin{cases} 1 & \text{if node } v \text{ is visited} \\ 0 & \text{otherwise} \end{cases} & v &\in V \\[4pt] +x_e &= \begin{cases} 1 & \text{if edge } e \text{ is traversed} \\ 0 & \text{otherwise} \end{cases} & e &\in E +\end{align*}$$ + +## Objective + +Maximize the total collected profit (sum of the scores of the visited vertices): $$\begin{align} +\max \quad & \sum_{v \in V} s_v y_v \tag{2a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.} \quad +& \sum_{e \in E} d_e x_e \leq d_0 \tag{2b} \\ +& x(\delta(v)) - 2 y_v = 0, & v &\in V \tag{2c} \\ +& x(\delta(H)) - 2 y_l - 2 y_r \geq -2, & l &\in H \subseteq V,\ r \in V - H \tag{2d} \\ +& \qquad 3 \leq |H| \leq |V| - 3 \notag \\ +& y_v - x_e \geq 0, & v &\in V,\ e \in \delta(v) \tag{2e} \\ +& 0 \leq y_v \leq 1, & v &\in V \tag{2f} \\ +& 0 \leq x_e \leq 1, & e &\in E \tag{2g} \\ +& y_o = 1 \tag{2h} \\ +& x_e \in \mathbb{Z}, & e &\in E \tag{2i} +\end{align}$$ diff --git a/tasks/kobeaga2024/problem_description.txt b/tasks/kobeaga2024/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca6e7f6e83963cd999cf4137d136c8a695594276 --- /dev/null +++ b/tasks/kobeaga2024/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A traveler operates on a network of locations, one of which is designated as the home depot. Every pair of locations is connected by a direct link, and each link has a known positive travel distance. Each location has a known positive score representing the profit or reward collected by visiting it. The traveler must plan a single round-trip route that starts and ends at the depot, visiting a subset of the other locations along the way, where the total travel distance of the route must not exceed a given distance budget. + +The traveler must decide which locations to visit and which links to traverse. The route must form a single closed loop: it must pass through the depot, and every visited location must be entered and exited exactly once, so the route has no branches, dead-ends, or disconnected pieces. A location that is not visited must not have any links of the route touching it. The route must consist of exactly one connected cycle; it is not permitted to break the journey into multiple separate loops. The depot is always visited. + +The goal is to choose the route that maximizes the total score collected from all visited locations, while ensuring that the sum of the distances of all traversed links does not exceed the distance budget. diff --git a/tasks/kobeaga2024/solution_logger.py b/tasks/kobeaga2024/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/kobeaga2024/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/kobeaga2024/solution_schema.json b/tasks/kobeaga2024/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b849d0b0ef7ea4c62475f227a6fc9386fb7a4c95 --- /dev/null +++ b/tasks/kobeaga2024/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total score collected from all locations visited by the chosen round-trip route.", + "visited_vertices": " Locations included in the chosen route, including the depot.", + "tour_edges": " Pairs of locations connected by the direct links traversed in the chosen route." +} diff --git a/tasks/kowalczyk2018/feasibility_check.py b/tasks/kowalczyk2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c45a6c414265ba4e935741c07ffb84d1c4f4579b --- /dev/null +++ b/tasks/kowalczyk2018/feasibility_check.py @@ -0,0 +1,544 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Pm||sum w_j C_j set-covering formulation +from Kowalczyk & Leus (2018). + +Hard constraints (from the mathematical model, in order): + Constraint 1 (6b): sum_{s in F: j in s} lambda_s >= 1 for all j in J + Every job must be assigned to at least one machine. + Constraint 2 (6c): sum_{s in F} lambda_s <= m + At most m machines (schedules) are used. + Constraint 3 (6d): lambda_s in {0,1} for all s in F + Binary integrality of schedule selection variables. + Constraint 4 (SWPT order): jobs in each selected schedule s must be + sequenced in nonincreasing w_j/p_j order (Smith's rule). + Constraint 5 (release/deadline): r_j + p_j <= C_j(s) <= d_bar_j for + every job j in each selected schedule s (with r_j, d_bar_j + tightened per Properties 5-6 of the paper). + Constraint 6 (makespan bound): H_min <= makespan(s) <= H_max for + every selected schedule s (Properties 3-4). + Constraint 7 (objective consistency): the self-reported + objective_value must equal the recomputed total weighted + completion time min sum_s c_s with c_s = sum_{j in s} w_j C_j(s) + (Eqs. 5, 6a). C_j(s) is the prefix sum of processing times in the + listed order on the machine; w_j and p_j are taken from the + INSTANCE (not the self-reported solution fields), so the check + cannot be gamed by fabricating a small objective_value alongside + fake per-job p/w/C entries. This is a Tier-C defense against + LLM score-gaming exploits. + +NOTE: this is the obj-recompute ("_new") variant. It is identical to +feasibility_check.py except for the added Constraint 7 block; the +original file is kept untouched until this variant is validated by the +differential test (feasibility_check_new_diff_test.json). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('machines', '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 + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def parse_solution_machines(sol_data): + """ + Parse solution into a unified list of machines. + Each machine is a list of (job_id, p, w, C) tuples. + Handles both efficient_solution and gurobi_solution formats. + """ + machines = [] + for machine in sol_data["machines"]: + if isinstance(machine, list): + # efficient_algorithm format: list of dicts with original_job_id, p, w, C + jobs = [(j["original_job_id"], j["p"], j["w"], j["C"]) + for j in machine] + elif isinstance(machine, dict): + # gurobi_code format: dict with "jobs" key + jobs = [(j["j_orig"], j["p"], j["w"], j["C_j"]) + for j in machine["jobs"]] + else: + jobs = [] + machines.append(jobs) + return machines + + +def compute_schedule_bounds(instance): + """ + Replicate the per-schedule feasibility envelope used by the column + generator (gurobi_code.preprocess): SWPT positions, tightened + release dates r_j and deadlines d_bar_j (Properties 5-6), and the + global makespan window [H_min, H_max] (Properties 3-4 of + Belouadah & Potts 1994; Azizoglu & Kirca 1999). + + Returns: + pos : dict j_orig -> SWPT position index in [0, n) + p, w : processing times and weights in SWPT order + r : tightened release dates in SWPT order + d_bar : tightened deadlines in SWPT order + H_min, H_max : global makespan bounds + """ + m = instance["m"] + jobs = instance["jobs"] + n = len(jobs) + + sorted_jobs = sorted(jobs, key=lambda jj: (-jj["w"] / jj["p"], jj["p"])) + pos = {jj["j"]: i for i, jj in enumerate(sorted_jobs)} + p = [jj["p"] for jj in sorted_jobs] + w = [jj["w"] for jj in sorted_jobs] + + total_p = sum(p) + p_max = max(p) + p_sorted_asc = sorted(p) + + H_max_real = total_p / m + (m - 1) / m * p_max + H_max = math.ceil(H_max_real) + + sum_m1_largest = sum(p_sorted_asc[-(m - 1):]) if m > 1 else 0 + H_min_real = (total_p - sum_m1_largest) / m + H_min = math.ceil(H_min_real) + + r = [0] * n + d_bar = [H_max] * n + + prefix_p = [0] * (n + 1) + for i in range(n): + prefix_p[i + 1] = prefix_p[i] + p[i] + suffix_p = [0] * (n + 1) + for i in range(n - 1, -1, -1): + suffix_p[i] = suffix_p[i + 1] + p[i] + + threshold = (total_p + sum_m1_largest) / m + + for jj in range(n): + P_j = set() + for k in range(n): + if k == jj: + continue + if (w[k] > w[jj] and p[k] <= p[jj]) or (w[k] >= w[jj] and p[k] < p[jj]): + P_j.add(k) + rhs_p2 = threshold - suffix_p[jj] + for k in range(jj): + if prefix_p[k] <= rhs_p2: + P_j.add(k) + if len(P_j) >= m - 1: + p_in_P = sorted([p[k] for k in P_j]) + count = len(P_j) - m + 1 + rho_j = sum(p_in_P[:count]) + r[jj] = math.ceil(rho_j / m) + + for jj in range(n): + E_j = set() + for k in range(n): + if k == jj: + continue + if (w[k] < w[jj] and p[k] >= p[jj]) or (w[k] <= w[jj] and p[k] > p[jj]): + E_j.add(k) + for k in range(jj + 1, n): + if prefix_p[k] <= threshold - suffix_p[k]: + E_j.add(k) + sum_E_p = sum(p[k] for k in E_j) + delta_j = H_max - math.ceil((sum_E_p + p[jj]) / m) + if delta_j + p[jj] < d_bar[jj]: + d_bar[jj] = delta_j + p[jj] + + return pos, p, w, r, d_bar, H_min, H_max + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["n"] + m = instance["m"] + instance_jobs = {j["j"]: j for j in instance["jobs"]} + + machines = parse_solution_machines(solution) + + violations = [] + violation_magnitudes = [] + violated_constraints_set = set() + + # ------------------------------------------------------------------ + # Constraint 1 (6b): sum_{s: j in s} lambda_s >= 1 for all j in J + # Every job must be covered by at least one selected schedule. + # ------------------------------------------------------------------ + job_coverage = {jid: 0 for jid in instance_jobs} + for machine_jobs in machines: + for (job_id, p, w, C) in machine_jobs: + if job_id in job_coverage: + job_coverage[job_id] += 1 + + uncovered = [] + for jid in sorted(job_coverage): + lhs = float(job_coverage[jid]) + rhs = 1.0 + # >= constraint: violation_amount = max(0, rhs - lhs) + violation_amount = max(0.0, rhs - lhs) + if violation_amount > tol: + uncovered.append(jid) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + if uncovered: + violated_constraints_set.add(1) + violations.append( + f"Constraint 1 (covering): job(s) {uncovered} not assigned to any machine" + ) + + # ------------------------------------------------------------------ + # Constraint 2 (6c): sum_{s in F} lambda_s <= m + # At most m schedules (machines) are used. + # ------------------------------------------------------------------ + num_used = float(len(machines)) + rhs2 = float(m) + # <= constraint: violation_amount = max(0, lhs - rhs) + violation_amount_2 = max(0.0, num_used - rhs2) + if violation_amount_2 > tol: + violated_constraints_set.add(2) + violations.append( + f"Constraint 2 (capacity): {int(num_used)} machines used, " + f"limit is {m}" + ) + normalizer2 = max(abs(rhs2), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": num_used, + "rhs": rhs2, + "raw_excess": violation_amount_2, + "normalizer": normalizer2, + "ratio": violation_amount_2 / normalizer2 + }) + + # ------------------------------------------------------------------ + # Constraint 3 (6d): lambda_s in {0,1} for all s in F + # Binary integrality. The solution format encodes selected schedules + # explicitly (one per machine entry), so each lambda is implicitly 1. + # We verify that no fractional or non-binary values sneak in by + # checking that each schedule selection is integral (always satisfied + # by the discrete machine list, but we confirm no anomalies). + # ------------------------------------------------------------------ + # In the solution representation each listed machine corresponds to + # lambda_s = 1 and all others are 0 -- inherently binary. + # We still confirm by treating each listed machine as lambda=1.0 and + # checking |lambda - round(lambda)| <= tol. + lambda_values = [1.0] * len(machines) + for idx, lv in enumerate(lambda_values): + nearest_int = round(lv) + violation_amount_3 = abs(lv - nearest_int) + if violation_amount_3 > tol: + violated_constraints_set.add(3) + violations.append( + f"Constraint 3 (integrality): schedule {idx} has " + f"lambda={lv}, not binary" + ) + rhs3 = nearest_int + normalizer3 = max(abs(rhs3), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lv, + "rhs": float(rhs3), + "raw_excess": violation_amount_3, + "normalizer": normalizer3, + "ratio": violation_amount_3 / normalizer3 + }) + + # ------------------------------------------------------------------ + # Constraints 4, 5, 6 SKIPPED (Rule 4 cleanup): + # - Constraint 4 (SWPT order) is a proven-optimal ordering for + # single-machine weighted completion time; enforcing it as a hard + # constraint rejects valid but sub-optimal orderings that an LLM + # algorithm (e.g., LPT, random) might produce. The global objective + # check below catches sub-optimality. + # - Constraint 5 (tightened r_j, d_bar_j from Properties 5-6) is a + # dominance-based pruning bound, not an original-problem constraint. + # - Constraint 6 (H_min <= makespan <= H_max from Properties 3-4) is + # also a dominance bound, not a business rule. + # Replaced by Constraint 4 below: completion-time consistency within a + # schedule (C_j accumulates processing times in listed order). + # ------------------------------------------------------------------ + + # ------------------------------------------------------------------ + # Constraint 4 (completion-time consistency on listed order): + # For each machine, if jobs are listed in processing order, then: + # C of first job = p of first job + # C of k-th job = C of (k-1)-th job + p of k-th job + # The listed order defines the schedule; permuting does NOT affect + # feasibility, only the objective value. + # ------------------------------------------------------------------ + for s_idx, machine_jobs in enumerate(machines): + if not machine_jobs: + continue + expected_C = 0 + for idx, (job_id, p_j, _, C_j) in enumerate(machine_jobs): + expected_C += p_j + if abs(C_j - expected_C) > tol: + violated_constraints_set.add(4) + violations.append( + f"Constraint 4 (completion-time consistency): schedule " + f"{s_idx} position {idx}, job {job_id} has C_j={C_j} " + f"but expected {expected_C} = sum of p's up to position" + ) + excess = float(abs(C_j - expected_C)) + normalizer = max(abs(float(expected_C)), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(C_j), + "rhs": float(expected_C), + "raw_excess": excess, + "normalizer": normalizer, + "ratio": excess / normalizer + }) + + # ------------------------------------------------------------------ + # Constraint 7 (objective consistency -- Tier-C anti-gaming check): + # The reported objective_value must equal the recomputed total + # weighted completion time + # obj = sum_{s} c_s , c_s = sum_{j in s} w_j * C_j(s) (Eqs. 5, 6a) + # where C_j(s) is the prefix sum of processing times along the listed + # order on the machine that carries job j. + # + # Both p_j and w_j are taken from the INSTANCE (indexed by the job's + # one-based original id) -- never from the self-reported solution + # fields -- so an LLM candidate cannot pass this check by fabricating + # a small objective_value together with matching fake per-job p/w/C + # entries. If a listed job id is absent from the instance the + # solution-reported p/w are used as a last-resort fallback (such a + # solution is already flagged elsewhere via the covering constraint). + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value") + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + for machine_jobs in machines: + elapsed = 0 + for (job_id, sol_p, sol_w, sol_C) in machine_jobs: + inst_job = instance_jobs.get(job_id) + p_j = inst_job["p"] if inst_job is not None else sol_p + w_j = inst_job["w"] if inst_job is not None else sol_w + elapsed += p_j + true_obj += w_j * elapsed + abs_diff = abs(reported - true_obj) + # The objective is an exact integer sum of w_j*C_j; a 0.5 absolute + # floor makes any integer-level fabrication fire, while the 1e-6 + # relative term only absorbs floating-point noise at large scale. + obj_tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints_set.add(7) + violations.append( + f"Constraint 7 (objective consistency): reported " + f"objective_value={reported} differs from recomputed total " + f"weighted completion time sum_s sum_j w_j*C_j(s)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + normalizer7 = max(abs(float(true_obj)), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": normalizer7, + "ratio": float(abs_diff) / normalizer7 + }) + + # ------------------------------------------------------------------ + # Build result + # ------------------------------------------------------------------ + feasible = len(violated_constraints_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes if not feasible else [] + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Pm||sum w_j C_j " + "(Kowalczyk & Leus 2018)" + ) + 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() + + 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) + + if result["feasible"]: + print(f"FEASIBLE — no constraint violations.") + else: + print(f"INFEASIBLE — 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/kowalczyk2018/gurobi_code.py b/tasks/kowalczyk2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..f818d0726d76494e2258b2124e13ad420cc1d40b --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_code.py @@ -0,0 +1,362 @@ +r""" +Gurobi implementation of the Set Covering ILP for Pm||sum w_j C_j +from Kowalczyk & Leus (2018), "A Branch-and-Price Algorithm for Parallel +_GUROBI_CODE_START_TIME = time.time() +Machine Scheduling Using ZDDs and Generic Branching", +INFORMS Journal on Computing 30(4):768-782. + +The problem is modeled as a set covering formulation: + min sum_{s in F} c_s * lambda_s (6a) + s.t. sum_{s in F: j in s} lambda_s >= 1 for all j in J (6b) + sum_{s in F} lambda_s <= m (6c) + lambda_s in {0,1} for all s in F (6d) + +where F is the set of all feasible single-machine schedules, and c_s is +the total weighted completion time of the jobs in schedule s when sequenced +in SWPT (nonincreasing w_j/p_j) order. + +A schedule s is feasible if: + - Jobs are sequenced in SWPT order + - r_j + p_j <= C_j(s) <= d_bar_j for all j in s + - H_min <= makespan(s) <= H_max + +Release dates r_j and deadlines d_bar_j are tightened using Properties 3-6 +from the paper (Belouadah & Potts 1994; Azizoglu & Kirca 1999; +Elmaghraby & Park 1974). + +For n=20, all 2^20 subsets are enumerated with feasibility pruning. +""" + +import json +import argparse +import math +from itertools import combinations + +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/). +_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, "r") as f: + data = json.load(f) + return data + + +def preprocess(jobs, m): + """ + Sort jobs by SWPT rule and compute release dates r_j, deadlines d_bar_j, + and global bounds H_min, H_max. + + Returns (sorted_jobs, r, d_bar, H_min, H_max) where sorted_jobs is a list + of dicts with keys 'j_orig', 'p', 'w', and r/d_bar are lists indexed by + position in sorted order. + """ + n = len(jobs) + + # Sort in nonincreasing order of w_j / p_j (SWPT rule). + # Ties broken by nondecreasing p_j (jobs with smaller p first). + sorted_jobs = sorted(jobs, key=lambda j: (-j["w"] / j["p"], j["p"])) + + p = [j["p"] for j in sorted_jobs] + w = [j["w"] for j in sorted_jobs] + + total_p = sum(p) + p_max = max(p) + + # Sorted processing times (ascending) for selecting m-1 largest + p_sorted_asc = sorted(p) + + # Property 3: H_max = sum(p)/m + (m-1)/m * p_max + H_max_real = total_p / m + (m - 1) / m * p_max + H_max = math.ceil(H_max_real) + + # Property 4: H_min = (1/m) * (sum(p) - sum of (m-1) largest p) + # The (m-1) largest processing times are the last (m-1) in ascending sort + sum_m1_largest = sum(p_sorted_asc[-(m - 1):]) if m > 1 else 0 + H_min_real = (total_p - sum_m1_largest) / m + H_min = math.ceil(H_min_real) + + # Initialize release dates and deadlines + r = [0] * n + d_bar = [H_max] * n + + # Precompute prefix sums of processing times in SWPT order + # prefix_p[k] = sum_{h=0}^{k-1} p[h] (sum of first k jobs) + prefix_p = [0] * (n + 1) + for i in range(n): + prefix_p[i + 1] = prefix_p[i] + p[i] + + # suffix_p[k] = sum_{h=k}^{n-1} p[h] + suffix_p = [0] * (n + 1) + for i in range(n - 1, -1, -1): + suffix_p[i] = suffix_p[i + 1] + p[i] + + # Threshold for P^2 and E^2 conditions + # (1/m) * (sum p + sum of m-1 largest p) + threshold = (total_p + sum_m1_largest) / m + + # Tighten release dates (Properties 5, 6) + for j in range(n): + # P^1_j: {k | (w_k > w_j and p_k <= p_j) or (w_k >= w_j and p_k < p_j)} + P_j = set() + for k in range(n): + if k == j: + continue + if (w[k] > w[j] and p[k] <= p[j]) or (w[k] >= w[j] and p[k] < p[j]): + P_j.add(k) + + # P^2_j: {k | k < j and prefix_p[k] <= threshold - suffix_p[j]} + # k < j means k has a smaller index in SWPT order (higher priority) + # sum_{h=1}^{k-1} p_h in paper is prefix_p[k] (0-indexed: sum of first k items) + # sum_{h=j}^{n} p_h in paper is suffix_p[j] + rhs_p2 = threshold - suffix_p[j] + for k in range(j): + if prefix_p[k] <= rhs_p2: + P_j.add(k) + + if len(P_j) >= m - 1: + # rho_j = sum of (|P_j| - m + 1) smallest p_k in P_j + p_in_P = sorted([p[k] for k in P_j]) + count = len(P_j) - m + 1 + rho_j = sum(p_in_P[:count]) + r[j] = math.ceil(rho_j / m) + + # Tighten deadlines + for j in range(n): + # E^1_j: {k | (w_k < w_j and p_k >= p_j) or (w_k <= w_j and p_k > p_j)} + E_j = set() + for k in range(n): + if k == j: + continue + if (w[k] < w[j] and p[k] >= p[j]) or (w[k] <= w[j] and p[k] > p[j]): + E_j.add(k) + + # E^2_j: {k | k > j and prefix_p[k] <= threshold - suffix_p[k]} + # sum_{h=1}^{k-1} p_h = prefix_p[k], sum_{h=k}^{n} p_h = suffix_p[k] + for k in range(j + 1, n): + if prefix_p[k] <= threshold - suffix_p[k]: + E_j.add(k) + + # delta_j = H_max - ceil((sum_{j' in E_j} p_{j'} + p_j) / m) + sum_E_p = sum(p[k] for k in E_j) + delta_j = H_max - math.ceil((sum_E_p + p[j]) / m) + if delta_j + p[j] < d_bar[j]: + d_bar[j] = delta_j + p[j] + + return sorted_jobs, p, w, r, d_bar, H_min, H_max + + +def enumerate_feasible_schedules(n, p, w, r, d_bar, H_min, H_max): + """ + Enumerate all feasible single-machine schedules using recursive + enumeration with pruning. Jobs are in SWPT order (indices 0..n-1). + + A schedule is a subset of jobs sequenced in SWPT order. For each + feasible schedule, we return (job_set_as_frozenset, cost). + + Returns a list of (frozenset_of_job_indices, cost) tuples. + """ + feasible = [] + + # Recursive DFS: at position `pos`, accumulated processing time `t`, + # current cost `cost_so_far`, current job set `current`. + # We decide whether to include job `pos` or skip it. + def dfs(pos, t, cost_so_far, current): + # We can terminate the schedule here (if current is nonempty) + if current and H_min <= t <= H_max: + feasible.append((frozenset(current), cost_so_far)) + + if pos >= n: + return + + # Try including job `pos` + new_t = t + p[pos] + # Check feasibility: r[pos] + p[pos] <= C_pos(s) = new_t and new_t <= d_bar[pos] + if r[pos] + p[pos] <= new_t <= d_bar[pos]: + # Prune: new_t must not exceed H_max (can't finish schedule legally) + if new_t <= H_max: + new_cost = cost_so_far + w[pos] * new_t + current.append(pos) + dfs(pos + 1, new_t, new_cost, current) + current.pop() + + # Try excluding job `pos` + dfs(pos + 1, t, cost_so_far, current) + + dfs(0, 0, 0, []) + return feasible + + +def solve_wct(instance_path, solution_path, time_limit): + data = load_instance(instance_path) + + n = data["n"] + m = data["m"] + jobs = data["jobs"] + + # Preprocess: sort by SWPT, compute bounds + sorted_jobs, p, w, r, d_bar, H_min, H_max = preprocess(jobs, m) + + print(f"Instance: n={n}, m={m}") + print(f"H_min={H_min}, H_max={H_max}") + print(f"Release dates: {r}") + print(f"Deadlines: {d_bar}") + + # Enumerate all feasible single-machine schedules + print("Enumerating feasible schedules...") + schedules = enumerate_feasible_schedules(n, p, w, r, d_bar, H_min, H_max) + print(f"Found {len(schedules)} feasible schedules.") + + if len(schedules) == 0: + solution = { + "objective_value": None, + "status_str": "NO_FEASIBLE_SCHEDULES" + } + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + print("No feasible schedules found.") + return + + # Build the set covering ILP + model = gp.Model("WCT_SetCovering") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + # OOM mitigation: spill B&B node data to disk after 2GB RAM. Without + # this the model OOMed @ 640G within ~26-40 min on large_21/_31 in the + # 2026-05-03 rerun. + model.setParam("NodefileStart", 2) + import os as _o, tempfile as _t + model.setParam("NodefileDir", + _o.environ.get("NODEFILE_DIR") or _t.gettempdir()) + + # Decision variables: lambda_s in {0,1} for each schedule s + lam = {} + for s_idx, (job_set, cost) in enumerate(schedules): + lam[s_idx] = model.addVar( + vtype=GRB.BINARY, + obj=cost, + name=f"lam_{s_idx}" + ) + + model.update() + + # Objective: minimize sum c_s * lambda_s (already set via obj= in addVar) + model.setAttr("ModelSense", GRB.MINIMIZE) + + # Covering constraints (6b): each job must be covered at least once + for j in range(n): + # Find all schedules containing job j + covering_vars = [] + for s_idx, (job_set, cost) in enumerate(schedules): + if j in job_set: + covering_vars.append(lam[s_idx]) + if covering_vars: + model.addConstr( + gp.quicksum(covering_vars) >= 1, + name=f"cover_{j}" + ) + else: + # Job j is not in any feasible schedule - problem is infeasible + print(f"Warning: job {j} (orig={sorted_jobs[j]['j']}) not covered " + f"by any feasible schedule.") + + # Capacity constraint (6c): at most m machines + model.addConstr( + gp.quicksum(lam[s_idx] for s_idx in range(len(schedules))) <= m, + name="capacity" + ) + + # Optimize + print("Solving ILP...") + model.optimize() + + # Extract solution + if model.SolCount > 0: + obj_val = model.ObjVal + solution = { + "objective_value": obj_val, + "status": model.Status, + "status_str": { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + }.get(model.Status, f"STATUS_{model.Status}"), + "n": n, + "m": m, + "H_min": H_min, + "H_max": H_max, + "num_feasible_schedules": len(schedules), + "machines": [] + } + + # Report which schedules are selected + for s_idx in range(len(schedules)): + if lam[s_idx].X > 0.5: + job_set, cost = schedules[s_idx] + # Reconstruct the schedule details + job_indices = sorted(job_set) + machine_info = { + "schedule_cost": cost, + "jobs": [] + } + cumulative_p = 0 + for ji in job_indices: + cumulative_p += p[ji] + machine_info["jobs"].append({ + "j_orig": sorted_jobs[ji]["j"], + "p": p[ji], + "w": w[ji], + "C_j": cumulative_p + }) + solution["machines"].append(machine_info) + + 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}") + print(f"Objective value: {obj_val}") + else: + solution = { + "objective_value": None, + "status": model.Status, + "status_str": "NO_SOLUTION_FOUND" + } + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + print("No feasible solution found.") + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for Pm||sum w_j C_j (Set Covering 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") + 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_wct(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/kowalczyk2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/kowalczyk2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2018/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/kowalczyk2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/kowalczyk2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2018/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/kowalczyk2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/kowalczyk2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2018/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/kowalczyk2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/kowalczyk2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2018/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/kowalczyk2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/kowalczyk2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2018/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/kowalczyk2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/kowalczyk2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2018/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/kowalczyk2018/gurobi_solution/large_solution_1.json b/tasks/kowalczyk2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a33df9ce9a5db8c6fa364a387697603bbbc8f794 --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c57590c9c31c8c23fb13dc7a88fc0b9cd71f14debee5cb09892a6757ee3cd2c +size 3867 diff --git a/tasks/kowalczyk2018/gurobi_solution/large_solution_2.json b/tasks/kowalczyk2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6bdaa432a55a12c12c446516cdcdfa1a8eb181b1 --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4eee8e9a2e84841826b90d4c819e19843ddb30512a43521a93f68d0f9ff8f7c4 +size 3810 diff --git a/tasks/kowalczyk2018/gurobi_solution/large_solution_3.json b/tasks/kowalczyk2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..707dc1926d0e4ecb04d70d717dee679a8d08d7e5 --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad0625082ee5faa9a4ee7c387f3d4420ee572b48412ad60821524056d4686ebd +size 3854 diff --git a/tasks/kowalczyk2018/gurobi_solution/large_solution_4.json b/tasks/kowalczyk2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..24521c78b015ccebd6ac1281601a4b6bd48e6e07 --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07d7f62904440fce69076b9adf70e02188060f47a6c0295dea3e07b82168fc63 +size 3905 diff --git a/tasks/kowalczyk2018/gurobi_solution/large_solution_5.json b/tasks/kowalczyk2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8583f5594a13995b30c45a5a2031b97a9e5a382c --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3228008ae37e1aab234a7b54909b176b9ec728215c4279ce0b18da021cbee88 +size 3924 diff --git a/tasks/kowalczyk2018/gurobi_solution/tiny_solution.json b/tasks/kowalczyk2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..dff28e2d7007e537076b0b71149fe216773bb6bb --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a424dd7b2342619757e3ac1b53efe2dfd5ae097cc7887bc1f0e8a51d21744736 +size 2421 diff --git a/tasks/kowalczyk2018/gurobi_solution_log/large_log_1.jsonl b/tasks/kowalczyk2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fe4a99afbdca3fec2d83b1cd4df1bf29065ce520 --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b81ed83a809eae43a6adbe5282946ef2ef69d5a92d8499a8024af0bdab62eb9b +size 43 diff --git a/tasks/kowalczyk2018/gurobi_solution_log/large_log_2.jsonl b/tasks/kowalczyk2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4b0a87c2e94ed6c87e8f9752402cd6b9642e691a --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b73e432c0b5a679fed5c66213035239fe043355ee224e695d86d50a950d1cbc3 +size 90 diff --git a/tasks/kowalczyk2018/gurobi_solution_log/large_log_3.jsonl b/tasks/kowalczyk2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e0707b9b299b1c621833eebee706c8a919fc9aba --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52c8682eac1c5c0688010e17090a1c0d3e94faf1b32ebf05992dc798f3a18383 +size 186 diff --git a/tasks/kowalczyk2018/gurobi_solution_log/large_log_4.jsonl b/tasks/kowalczyk2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..24e1b2c8206b034d6bd357a97d8c018e36feff6d --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:818035924774d98273dd0ed5fb9a84e5403b7b3cd0b0e796fbc387c06b92d823 +size 44 diff --git a/tasks/kowalczyk2018/gurobi_solution_log/large_log_5.jsonl b/tasks/kowalczyk2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..740fb9445fb059c8951c8d7c7e0686792ef9a674 --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c05db89a1585bd129ae01d0035171503a2f635e7b4827a22864b1909bb21802 +size 45 diff --git a/tasks/kowalczyk2018/gurobi_solution_log/tiny_log.jsonl b/tasks/kowalczyk2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..146a445f1ced0254a62da49ead9b743ba09bbad0 --- /dev/null +++ b/tasks/kowalczyk2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5058bde776fc8e1118f1ebffe2b7d744645a2ebfe85e0b048b91d2e4dbaa77f +size 44 diff --git a/tasks/kowalczyk2018/instance/large_instance_1.json b/tasks/kowalczyk2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..467643d21fbff39763d0f8e3716679ee3cc474f6 --- /dev/null +++ b/tasks/kowalczyk2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3c1d7b2e7e7bb9fa33ccb9665f6d77b7675bab1f61c324f9397775e43438c3f +size 1124 diff --git a/tasks/kowalczyk2018/instance/large_instance_2.json b/tasks/kowalczyk2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ea38eba3ffa871bee63177781ee2528f166fef56 --- /dev/null +++ b/tasks/kowalczyk2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c1e777301b177d4b466c3b5d7a17e7167f1021b42754a9e1cf2f7502e8bb4cf +size 1094 diff --git a/tasks/kowalczyk2018/instance/large_instance_3.json b/tasks/kowalczyk2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..334ae1bef51d4f76a43f3faf89b722b1186e481b --- /dev/null +++ b/tasks/kowalczyk2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:283a5f357399dc4e5664ab7bc43e0237d736cb55bbc2c7cb03d8bf88b195a21e +size 1113 diff --git a/tasks/kowalczyk2018/instance/large_instance_4.json b/tasks/kowalczyk2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..271cccf0198dc0645775d5b5efbc591eecf6fad4 --- /dev/null +++ b/tasks/kowalczyk2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c3a938c375408b46e4f19add7fafe7c85114d18831b9d2774d54dbf4c33b88b +size 1130 diff --git a/tasks/kowalczyk2018/instance/large_instance_5.json b/tasks/kowalczyk2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..dd7093bc63d680742194c674fee3c36e5004df03 --- /dev/null +++ b/tasks/kowalczyk2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9a3191bab52463331efcf69de7bfdad5b4926309a93fd020f6c6d516911bfa9 +size 1146 diff --git a/tasks/kowalczyk2018/instance/tiny_instance.json b/tasks/kowalczyk2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..0cc4aeeec090463eb4ec24d5c9d5a6e92f20fdec --- /dev/null +++ b/tasks/kowalczyk2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3919063f642cf311395d8095b031af79c793831856844045f724d1f5549ec6d2 +size 1376 diff --git a/tasks/kowalczyk2018/instance_schema.json b/tasks/kowalczyk2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7335efe4cb9d44bd64ba0c479be79d51927402aa --- /dev/null +++ b/tasks/kowalczyk2018/instance_schema.json @@ -0,0 +1,11 @@ +{ + "n": " Total number of independent jobs to be processed.", + "m": " Number of identical parallel machines available for processing.", + "jobs": [ + { + "j": " One-based index of the job, ordered by nonincreasing weight-to-processing-time ratio.", + "p": " Processing time required to complete the job on any machine.", + "w": " Weight representing the priority or importance of the job." + } + ] +} diff --git a/tasks/kowalczyk2018/mathematical_formulation.md b/tasks/kowalczyk2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..8e0fa61a7bf4ea083e2ec4216d8439cce83b2e0d --- /dev/null +++ b/tasks/kowalczyk2018/mathematical_formulation.md @@ -0,0 +1,44 @@ +# Original Formulation: Parallel Machine Scheduling with Weighted Completion Times ($Pm\,||\,\sum w_j C_j$, WCT) + +*Source: A Branch-and-Price Algorithm for Parallel Machine Scheduling Using ZDDs and Generic Branching, Daniel Kowalczyk, Roel Leus, 2018 (INFORMS Journal on Computing 30(4):768–782).* + +## Sets and Indices + +$$\begin{align*} +J &= \{1,\dots,n\} && \text{set of $n$ independent jobs, index $j$}\\ +M &= \{1,\dots,m\} && \text{set of $m$ identical parallel machines}\\ +\mathscr{F} &\subseteq 2^{J} && \text{set of all subsets $s\subset J$ that lead to a \emph{feasible} single-machine schedule} +\end{align*}$$ Jobs are indexed in nonincreasing order of the ratio $w_j/p_j$, i.e. $w_1/p_1 \ge w_2/p_2 \ge \cdots \ge w_n/p_n$ (Smith’s SWPT rule, Property 1); the unique schedule of a subset $s$ sequences its jobs in this order. + +## Parameters + +$$\begin{align*} +p_j \in \mathbb{N}_0 &&& \text{processing time of job $j\in J$}\\ +w_j \in \mathbb{N}_0 &&& \text{weight (priority) of job $j\in J$}\\ +p_{[i]} &&& \text{$i$-th smallest processing time among jobs in $J$; } p_{\max}=p_{[n]}\\ +H_{\max} &= \sum_{j\in J}\tfrac{p_j}{m} + \tfrac{(m-1)}{m}\,p_{\max} && \text{(Property~3) max.\ latest completion time on any machine}\\ +H_{\min} &= \tfrac{1}{m}\!\left(\sum_{j\in J}p_j - \sum_{h=1}^{m-1}p_{[n-h+1]}\right) && \text{(Property~4) min.\ latest completion time on any machine}\\ +r_j,\ \bar{d}_j &&& \text{release date and deadline of job $j$ (time window)} +\end{align*}$$ For each $s\in\mathscr{F}$ and $j\in s$, the completion time of $j$ in $s$ is $C_j(s)=\sum_{k\in s:\,k\le j} p_k$, and the cost of schedule $s$ is $$\begin{equation} +c_s = \sum_{j\in s} w_j\!\left(\sum_{k\in s:\,k\le j} p_k\right). \tag{5} +\end{equation}$$ A subset $s\subset J$ belongs to $\mathscr{F}$ iff $r_j + p_j \le C_j(s) \le \bar{d}_j$ for all $j\in s$ and the completion time of the last job lies in $[H_{\min},H_{\max}]$. + +## Decision Variables + +$$\begin{align*} +\lambda_s \in \{0,1\}, \quad s\in\mathscr{F} &&& \lambda_s = 1 \text{ iff schedule } s \text{ is assigned to one machine} +\end{align*}$$ + +## Objective + +$$\begin{equation} +\text{minimize}\quad \sum_{s\in\mathscr{F}} c_s\,\lambda_s \tag{6a} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{s\in\mathscr{F}:\,j\in s} \lambda_s &\ge 1 && \forall\, j\in J \tag{6b}\\ +\sum_{s\in\mathscr{F}} \lambda_s &\le m \tag{6c}\\ +\lambda_s &\in \{0,1\} && \forall\, s\in\mathscr{F} \tag{6d} +\end{align}$$ Constraints (6b) are the $n$ covering (assignment) constraints ensuring every job is assigned to at least one machine; (6c) is the single capacity constraint limiting the solution to $m$ machines; (6d) states the binary nature of the variables. diff --git a/tasks/kowalczyk2018/problem_description.txt b/tasks/kowalczyk2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..f8388d4012084f2c4db01b40a1ce4290614d3e78 --- /dev/null +++ b/tasks/kowalczyk2018/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A facility must process a set of n independent jobs on m identical parallel machines. Each job has a known nonnegative integer processing time and a known nonnegative integer weight that represents its priority or importance. Each machine can process at most one job at a time, preemption is not allowed, and every job must be assigned to exactly one machine. On each machine, jobs are processed contiguously starting from time zero with no idle time inserted between them. + +The planner must decide how to assign the jobs to the machines and, for each machine, in what order to process the jobs assigned to it. The completion time of a job is the time at which its processing finishes, which equals the sum of the processing times of that job and of all jobs processed before it on the same machine. + +The objective is to minimize the total weighted completion time across all jobs, that is, the sum over all jobs of the product of each job's weight and its completion time. + +The input data for an instance consists of the number of jobs n, the number of machines m, and for each job its processing time and its weight. A solution is an assignment of every job to one machine together with a processing order on each machine, and its cost is the total weighted completion time. diff --git a/tasks/kowalczyk2018/solution_logger.py b/tasks/kowalczyk2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/kowalczyk2018/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/kowalczyk2018/solution_schema.json b/tasks/kowalczyk2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b6614a8d22732f1a8beaacee5fd73e8f9e5e6d13 --- /dev/null +++ b/tasks/kowalczyk2018/solution_schema.json @@ -0,0 +1,16 @@ +{ + "objective_value": " Total weighted completion time summed across all jobs and machines.", + "machines": [ + { + "schedule_cost": " Weighted completion time summed over all jobs assigned to this machine.", + "jobs": [ + { + "j_orig": " One-based index of the job from the input instance.", + "p": " Processing time of the job.", + "w": " Weight of the job.", + "C_j": " Completion time of the job on this machine." + } + ] + } + ] +} diff --git a/tasks/kowalczyk2024/feasibility_check.py b/tasks/kowalczyk2024/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b7ea7df86209e025c525a5ec643693b6e6c5b5 --- /dev/null +++ b/tasks/kowalczyk2024/feasibility_check.py @@ -0,0 +1,510 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Pm||sum w_j T_j (Kowalczyk et al., 2024). + +Checks a candidate schedule against the BDDF formulation (Eq. 6), the +model that gurobi_code.py actually implements. The solver exports only +the chosen start time per job (schedule = {job_id: start_time}); BDDF +flow equations (6c)/(6d)/(6f) cannot be verified from edge flows, so we +enforce the equivalent schedule-level necessary conditions: + Constraint 1 (6b): sum_{e in A^1 : p_B(e)=j} x_e = 1 => each job is + scheduled exactly once. + Constraint 2 (machine capacity; implied by BDD construction + (6d)): + at most m jobs processing simultaneously at any time in [0, T]. + Constraint 3 (BDD node domain + (6e)): 0 <= start_j <= T - p_j so + every scheduled job completes within the planning horizon T. + Constraint 4 (objective consistency; Tier C anti-gaming defense): + the reported objective_value must equal the total weighted + tardiness recomputed from the exported schedule, + obj = sum_{j in J} w_j * max(0, start_j + p_j - d_j) (Eq. 6a / 1a). + All objective-determining variables (the start times) are present + in the solution, so this is a full recompute, not a lower bound. + +This file is a side-by-side obj-recompute variant of feasibility_check.py; +the original is left untouched (see docs/data_review_fix/ +checker_add_obj_recompute.md). Constraints 1-3 are byte-for-byte identical +to the original; constraint 4 is the only addition. +""" + +import json +import argparse +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'schedule') +_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 + + + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def compute_planning_horizon(jobs, m): + """T = ceil((sum p_j - p_max) / m) + p_max""" + P = sum(j['p'] for j in jobs) + p_max = max(j['p'] for j in jobs) + return math.ceil((P - p_max) / m) + p_max + + +def extract_start_times(instance, solution): + """ + Extract {job_id: start_time} from the solution, handling both formats. + + Efficient format: schedule is {machine_str: [job_id_list]}, jobs run + sequentially on each machine starting from time 0. + + Gurobi format: schedule is {job_id_str: start_time}. + """ + schedule = solution.get("schedule", {}) + if not schedule: + return {} + + # Detect format: if values are lists, it's efficient format; + # if values are ints/floats, it's Gurobi format. + first_val = next(iter(schedule.values())) + + jobs_by_id = {j['id']: j for j in instance['jobs']} + + if isinstance(first_val, list): + # Efficient format: machine -> ordered job list + start_times = {} + for machine_str, job_list in schedule.items(): + t = 0 + for jid in job_list: + start_times[jid] = t + t += jobs_by_id[jid]['p'] + return start_times + else: + # Gurobi format: job_id_str -> start_time + return {int(k): int(v) for k, v in schedule.items()} + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + jobs = instance['jobs'] + m = instance['m'] + n = instance['n'] + T = instance.get('T', compute_planning_horizon(jobs, m)) + jobs_by_id = {j['id']: j for j in jobs} + job_ids = set(j['id'] for j in jobs) + + start_times = extract_start_times(instance, solution) + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # ---------------------------------------------------------------- + # Constraint 1 (BDDF 6b): sum_{e in A^1 : p_B(e)=j} x_e = 1, j in J + # => each job is scheduled exactly once in the exported schedule. + # ---------------------------------------------------------------- + scheduled_ids = set(start_times.keys()) + + # Jobs not scheduled + missing = job_ids - scheduled_ids + for jid in sorted(missing): + violated_constraints.add(1) + violations.append(f"Job {jid} is not scheduled (assigned 0 times, expected 1)") + lhs = 0.0 + rhs = 1.0 + raw_excess = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # Jobs scheduled that don't exist + extra = scheduled_ids - job_ids + for jid in sorted(extra): + violated_constraints.add(1) + violations.append(f"Job {jid} is scheduled but does not exist in the instance") + lhs = 1.0 + rhs = 0.0 + raw_excess = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # Check for duplicate job assignments (efficient format can have duplicates) + schedule = solution.get("schedule", {}) + first_val = next(iter(schedule.values()), None) + if isinstance(first_val, list): + all_assigned = [] + for machine_str, job_list in schedule.items(): + all_assigned.extend(job_list) + from collections import Counter + counts = Counter(all_assigned) + for jid, cnt in counts.items(): + if cnt > 1 and jid in job_ids: + violated_constraints.add(1) + violations.append( + f"Job {jid} is scheduled {cnt} times (expected 1)" + ) + lhs = float(cnt) + rhs = 1.0 + raw_excess = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # ---------------------------------------------------------------- + # Constraint 2 (BDDF machine capacity; implied by BDD construction + # and eq (6d) sum_{e in delta^-(1)} x_e = m): at most m jobs + # processing simultaneously at any time in [0, T]. + # ---------------------------------------------------------------- + # For each time period t (1-indexed), count how many jobs are processing. + # Job j starting at period s (1-indexed, time s-1) is processing during + # periods s, s+1, ..., s+p_j-1. A job with start_time st (0-indexed) + # starts at period st+1. + for t in range(1, T + 1): + count = 0 + for jid, st in start_times.items(): + if jid not in jobs_by_id: + continue + p_j = jobs_by_id[jid]['p'] + period_start = st + 1 # TIF period + # Job processes during periods period_start .. period_start + p_j - 1 + if period_start <= t <= period_start + p_j - 1: + count += 1 + + lhs = float(count) + rhs = float(m) + violation_amount = max(0.0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"At time period {t}, {count} jobs are processing (capacity is {m})" + ) + 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 (BDDF node-domain / eq (6e) x_e in {0,1} restricts + # high edges to valid BDD nodes): for every scheduled job j the + # start time t satisfies 0 <= t <= T - p_j (job fits in horizon). + # ---------------------------------------------------------------- + for jid, st in start_times.items(): + if jid not in jobs_by_id: + continue + p_j = jobs_by_id[jid]['p'] + period = st + 1 # TIF period (1-indexed) + + # Check lower bound: period >= 1 (start_time >= 0) + if period < 1: + violated_constraints.add(3) + violations.append( + f"Job {jid} starts at time {st} (period {period}), " + f"which is before the valid range [1, {T - p_j + 1}]" + ) + lhs = float(period) + rhs = 1.0 + raw_excess = max(0.0, rhs - lhs) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # Check upper bound: period <= T - p_j + 1 (job completes within horizon) + max_period = T - p_j + 1 + if period > max_period: + violated_constraints.add(3) + violations.append( + f"Job {jid} starts at period {period} but must start by period " + f"{max_period} to complete within horizon T={T} " + f"(completion time {st + p_j} > {T})" + ) + lhs = float(period) + rhs = float(max_period) + raw_excess = max(0.0, lhs - rhs) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # ---------------------------------------------------------------- + # Constraint 4 (objective consistency; Tier C anti-gaming defense): + # The reported objective_value must equal the total weighted + # tardiness recomputed from the exported schedule. A job j with + # 0-indexed start time st completes at time st + p_j (BDDF cost + # c_e = w_j * max{0, t + p_j - d_j}; equivalently TIF c~_{jt} with + # period = st + 1 yields completion st + p_j). The objective (6a): + # obj = sum_{j in J} w_j * max(0, start_j + p_j - d_j) + # Every objective-determining variable (the start times) is present + # in the solution, so this is a FULL recompute. We compare the + # reported value to the recomputed value within a tight tolerance. + # The objective is integer-valued (p, d, w, start times are all + # integers), so a tolerance of 0.5 fires on any genuine mismatch + # of >= 1 while tolerating float round-trip noise. + # ---------------------------------------------------------------- + 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 = 0.0 + for jid, st in start_times.items(): + if jid not in jobs_by_id: + # Non-existent jobs are flagged by constraint 1; they + # contribute nothing to a well-defined objective. + continue + job = jobs_by_id[jid] + completion = st + job['p'] + tardiness = max(0, completion - job['d']) + true_obj += job['w'] * tardiness + true_obj = float(true_obj) + abs_diff = abs(reported - true_obj) + # 0.5 absolute floor (integer objective) with a 1e-6 relative + # term as a safety net for very large objectives. + obj_tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(4) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed total weighted tardiness " + f"sum_j w_j*max(0, start_j+p_j-d_j)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + rhs = true_obj + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": reported, + "rhs": rhs, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + # ---------------------------------------------------------------- + # Build result + # ---------------------------------------------------------------- + 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 Pm||sum w_j T_j (Kowalczyk et al., 2024)" + ) + 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) + + print(f"Feasibility result written to {args.result_path}") + if result['feasible']: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. 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/kowalczyk2024/gurobi_code.py b/tasks/kowalczyk2024/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3bba732bb18d0e50bd77dcb0f83c7bd6d7e063 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_code.py @@ -0,0 +1,455 @@ +#!/usr/bin/env python3 +""" +BDDF (BDD-based Flow Formulation) for Pm||sum w_j T_j +Based on: Kowalczyk, Leus, Hojny, Ropke (2024) +"A flow-based formulation for parallel machine scheduling using decision diagrams" + +Implements Formulation (6) - the paper's PRIMARY new formulation (BDDF). +Constructs a BDD representing all valid job sequences, then solves the +resulting MIP with Gurobi. +""" + +import json +import argparse +import math +from collections import defaultdict, 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 +def load_instance(path): + with open(path) as f: + return json.load(f) + + +def compute_planning_horizon(jobs, m): + """T = ceil((sum p_j - p_max) / m) + p_max (Pessoa et al., 2010).""" + P = sum(j['p'] for j in jobs) + p_max = max(j['p'] for j in jobs) + return math.ceil((P - p_max) / m) + p_max + + +def build_ordering_for_interval(jobs, e_left, e_right): + """ + Build sigma_r for interval (e_left, e_right] following Baptiste & Sadykov (2009). + + Rules for short jobs i, j: + - Long jobs (p_j >= interval length) come first + - Late jobs (d_j <= e_left) before on-time jobs (d_j >= e_right) + - Among on-time: LPT (p_i > p_j => i first) + - Among late: WSPT (p_i/w_i < p_j/w_j => i first), ties by LPT + + Jobs where e_left < d_j < e_right are treated as late (conservative). + ** INFERRED ASSUMPTION: ambiguous jobs (e_left < d_j < e_right) are treated + as late, since they may be tardy for some completion times in the interval. ** + """ + interval_length = e_right - e_left + + long_jobs = [] + short_late = [] + short_ontime = [] + + for j in jobs: + if j['p'] >= interval_length: + long_jobs.append(j) + elif j['d'] >= e_right: + short_ontime.append(j) + else: + # Late: d_j <= e_left, or ambiguous: e_left < d_j < e_right + short_late.append(j) + + # Sort long jobs by LPT (descending processing time), ties by job id + long_jobs.sort(key=lambda j: (-j['p'], j['id'])) + + # Sort late short jobs by WSPT: p/w ascending, ties by p descending, then id + short_late.sort(key=lambda j: (j['p'] / j['w'], -j['p'], j['id'])) + + # Sort on-time short jobs by LPT: p descending, ties by id + short_ontime.sort(key=lambda j: (-j['p'], j['id'])) + + return long_jobs + short_late + short_ontime + + +def build_appropriate_partition(jobs, T): + """ + Build an appropriate partition satisfying Theorem 1 (Baptiste & Sadykov, 2009). + + Start with due-date-based partition, then iteratively subdivide intervals + that contain "special pairs" violating conditions (4) and (5). + + ** NOT SPECIFIED IN PAPER: The exact Clement (2015) procedure for minimum + intervals is not reproduced. We use iterative subdivision instead. ** + """ + # Step (a): partition based on distinct due dates + due_dates = sorted(set(j['d'] for j in jobs if j['d'] < T)) + endpoints = sorted(set([0] + due_dates + [T])) + + intervals = [(endpoints[i], endpoints[i + 1]) for i in range(len(endpoints) - 1)] + orderings = [build_ordering_for_interval(jobs, e_l, e_r) for e_l, e_r in intervals] + + # Step (c)/(d): Check Theorem 1 and subdivide + max_iterations = 200 # safety bound + for _ in range(max_iterations): + changed = False + new_intervals = [] + new_orderings = [] + + for (e_left, e_right), ordering in zip(intervals, orderings): + split_point = None + for i_pos in range(len(ordering)): + for j_pos in range(i_pos + 1, len(ordering)): + ji = ordering[i_pos] + jj = ordering[j_pos] + # Condition (4): e_r <= e_{r-1} + p_j + cond4 = e_right <= e_left + jj['p'] + # Condition (5): e_{r-1} >= d_i + ceil(w_j * p_i / w_i) - p_i + cond5 = e_left >= ji['d'] + math.ceil(jj['w'] * ji['p'] / ji['w']) - ji['p'] + if not cond4 and not cond5: + # Split to make condition (4) hold for left sub-interval + candidate = e_left + jj['p'] + if e_left < candidate < e_right: + split_point = candidate + break + # Fallback: midpoint + mid = (e_left + e_right) // 2 + if e_left < mid < e_right: + split_point = mid + break + # If interval is length 1, can't split further + break + if split_point is not None: + break + + if split_point is not None: + changed = True + new_intervals.append((e_left, split_point)) + new_orderings.append(build_ordering_for_interval(jobs, e_left, split_point)) + new_intervals.append((split_point, e_right)) + new_orderings.append(build_ordering_for_interval(jobs, split_point, e_right)) + else: + new_intervals.append((e_left, e_right)) + new_orderings.append(ordering) + + intervals = new_intervals + orderings = new_orderings + if not changed: + break + + return intervals, orderings + + +def build_bdd(jobs, intervals, orderings, T, m): + """ + Build BDD following Algorithm 1 (Appendix A). + + Each node has configuration (global_pos, t). + global_pos indexes into the global ordering of job representations. + t is the cumulative processing time (= start time of the job at this node). + + Returns: root_id, nodes dict, high_edges, low_edges, edge_costs, edge_job_ids, incoming + """ + n = len(jobs) + q = len(intervals) + job_by_id = {j['id']: j for j in jobs} + + # Build global ordering: all n jobs in interval 0 order, then interval 1, etc. + # global_order[pos] = (job_id, interval_index) + global_order = [] + for r in range(q): + for j in orderings[r]: + global_order.append((j['id'], r)) + + nq = len(global_order) # = n * q + + def minjob(current_pos, t): + """Find minimum successor in global order where t + p_job falls in its interval.""" + for pos in range(current_pos + 1, nq): + jid, r = global_order[pos] + e_left, e_right = intervals[r] + p_j = job_by_id[jid]['p'] + if e_left < t + p_j <= e_right: + return pos + return nq # sentinel: no valid successor + + # Find root: first job representation whose processing time fits in its interval + root_pos = None + for pos in range(nq): + jid, r = global_order[pos] + e_left, e_right = intervals[r] + p_j = job_by_id[jid]['p'] + if e_left < 0 + p_j <= e_right: + root_pos = pos + break + + if root_pos is None: + # Fallback: use first position + # ** INFERRED ASSUMPTION: if no job fits from t=0, use first position ** + root_pos = 0 + + TERMINAL = (-1, -1) # sentinel for terminal node + + # BDD construction via BFS with memoization + # Nodes identified by (global_pos, t) + nodes = {} # node_key -> node_id (int) + node_id_counter = [0] + + def get_node_id(key): + if key not in nodes: + nodes[key] = node_id_counter[0] + node_id_counter[0] += 1 + return nodes[key] + + root_key = (root_pos, 0) + root_id = get_node_id(root_key) + terminal_id = get_node_id(TERMINAL) + + high_child = {} # node_id -> child_node_id + low_child = {} # node_id -> child_node_id + high_cost = {} # node_id -> cost of high edge + high_job = {} # node_id -> job_id associated with high edge + node_job = {} # node_id -> job_id at this node + node_start = {} # node_id -> start time t at this node + incoming = defaultdict(list) # node_id -> list of (parent_id, edge_type) + + queue = deque([root_key]) + visited = set() + + while queue: + key = queue.popleft() + if key in visited or key == TERMINAL: + continue + visited.add(key) + + nid = get_node_id(key) + pos, t = key + jid, r = global_order[pos] + p_j = job_by_id[jid]['p'] + + node_job[nid] = jid + node_start[nid] = t + + # High edge: schedule job j at time t + t_high = t + p_j + next_pos_high = minjob(pos, t_high) + if next_pos_high >= nq: + child_high_key = TERMINAL + else: + child_high_key = (next_pos_high, t_high) + + child_high_id = get_node_id(child_high_key) + high_child[nid] = child_high_id + high_cost[nid] = job_by_id[jid]['w'] * max(0, t + p_j - job_by_id[jid]['d']) + high_job[nid] = jid + incoming[child_high_id].append((nid, 'high')) + + if child_high_key != TERMINAL and child_high_key not in visited: + queue.append(child_high_key) + + # Low edge: skip job j + t_low = t + next_pos_low = minjob(pos, t_low) + if next_pos_low >= nq: + child_low_key = TERMINAL + else: + child_low_key = (next_pos_low, t_low) + + child_low_id = get_node_id(child_low_key) + low_child[nid] = child_low_id + incoming[child_low_id].append((nid, 'low')) + + if child_low_key != TERMINAL and child_low_key not in visited: + queue.append(child_low_key) + + return (root_id, terminal_id, nodes, high_child, low_child, + high_cost, high_job, node_job, node_start, incoming) + + +def solve_bddf(instance, time_limit): + """Solve Pm||sum w_j T_j using the BDDF formulation (Eq. 6) with Gurobi.""" + jobs = instance['jobs'] + m = instance['m'] + n = instance['n'] + T_val = instance.get('T', compute_planning_horizon(jobs, m)) + + # Build appropriate partition + intervals, orderings = build_appropriate_partition(jobs, T_val) + + # Build BDD + (root_id, terminal_id, nodes, high_child, low_child, + high_cost, high_job, node_job, node_start, incoming) = \ + build_bdd(jobs, intervals, orderings, T_val, m) + + print(f"BDD constructed: {len(nodes)} nodes") + + # All non-terminal, non-root internal nodes + all_node_ids = set() + for key, nid in nodes.items(): + if key != (-1, -1): # not terminal + all_node_ids.add(nid) + + # Create Gurobi model + model = gp.Model("BDDF") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Variables for high edges (binary): x_h[nid] + x_h = {} + for nid in all_node_ids: + if nid in high_child: + x_h[nid] = model.addVar( + vtype=GRB.BINARY, + obj=high_cost.get(nid, 0), + name=f"xh_{nid}" + ) + + # Variables for low edges (continuous >= 0): x_l[nid] + x_l = {} + for nid in all_node_ids: + if nid in low_child: + x_l[nid] = model.addVar( + vtype=GRB.CONTINUOUS, + lb=0.0, + name=f"xl_{nid}" + ) + + model.update() + + # Constraint (6b): each job scheduled exactly once + # sum_{e in A^1 : p_B(e) = j} x_e = 1 for all j in J + job_high_edges = defaultdict(list) + for nid in x_h: + jid = high_job[nid] + job_high_edges[jid].append(nid) + + for j in jobs: + jid = j['id'] + if jid in job_high_edges and job_high_edges[jid]: + model.addConstr( + gp.quicksum(x_h[nid] for nid in job_high_edges[jid]) == 1, + name=f"assign_{jid}" + ) + else: + print(f"WARNING: job {jid} has no high edges in BDD") + + # Constraint (6c): flow conservation for internal nodes (not root, not terminal) + # x_{e^1_v} + x_{e^0_v} = sum_{e in delta^-(v)} x_e + for nid in all_node_ids: + if nid == root_id: + continue + + # Outgoing flow + out_vars = [] + if nid in x_h: + out_vars.append(x_h[nid]) + if nid in x_l: + out_vars.append(x_l[nid]) + + # Incoming flow + in_vars = [] + for parent_id, etype in incoming.get(nid, []): + if etype == 'high' and parent_id in x_h: + in_vars.append(x_h[parent_id]) + elif etype == 'low' and parent_id in x_l: + in_vars.append(x_l[parent_id]) + + if out_vars and in_vars: + model.addConstr( + gp.quicksum(out_vars) == gp.quicksum(in_vars), + name=f"flow_{nid}" + ) + + # Constraint (6d): sum of incoming edges to terminal = m + terminal_in = [] + for parent_id, etype in incoming.get(terminal_id, []): + if etype == 'high' and parent_id in x_h: + terminal_in.append(x_h[parent_id]) + elif etype == 'low' and parent_id in x_l: + terminal_in.append(x_l[parent_id]) + + if terminal_in: + model.addConstr( + gp.quicksum(terminal_in) == m, + name="terminal_flow" + ) + + # Redundant constraint (7): root outgoing = m + root_out = [] + if root_id in x_h: + root_out.append(x_h[root_id]) + if root_id in x_l: + root_out.append(x_l[root_id]) + if root_out: + model.addConstr( + gp.quicksum(root_out) == m, + name="root_flow" + ) + + # Solve + model.optimize() + + # Extract solution + result = {"solver": "Gurobi_BDDF", "status": model.Status} + + if model.SolCount > 0: + result['objective_value'] = model.ObjVal + + # Extract scheduled jobs and their start times + schedule = {} + for nid in x_h: + if x_h[nid].X > 0.5: + jid = high_job[nid] + t = node_start[nid] + schedule[jid] = t + result['schedule'] = {str(k): v for k, v in schedule.items()} + else: + result['objective_value'] = None + result['schedule'] = {} + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="BDDF formulation for Pm||sum w_j T_j (Kowalczyk et al., 2024)" + ) + 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 for 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) + + instance = load_instance(args.instance_path) + result = solve_bddf(instance, args.time_limit) + + # Write solution + 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/kowalczyk2024/gurobi_feasi_result/large_feasi_result_1.json b/tasks/kowalczyk2024/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2024/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/kowalczyk2024/gurobi_feasi_result/large_feasi_result_2.json b/tasks/kowalczyk2024/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2024/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/kowalczyk2024/gurobi_feasi_result/large_feasi_result_3.json b/tasks/kowalczyk2024/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2024/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/kowalczyk2024/gurobi_feasi_result/large_feasi_result_4.json b/tasks/kowalczyk2024/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2024/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/kowalczyk2024/gurobi_feasi_result/large_feasi_result_5.json b/tasks/kowalczyk2024/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2024/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/kowalczyk2024/gurobi_feasi_result/tiny_feasi_result.json b/tasks/kowalczyk2024/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kowalczyk2024/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/kowalczyk2024/gurobi_solution/large_solution_1.json b/tasks/kowalczyk2024/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a991de95c2bc27357435aa03d5febf2b9eddc42f --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64499977970b73ba50312028927974ce6885e953d834a88307c1a92ff2fb093a +size 863 diff --git a/tasks/kowalczyk2024/gurobi_solution/large_solution_2.json b/tasks/kowalczyk2024/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..0725587c2d1591b97d2832c46992abf3c5c78cc1 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fa1d0b33086b3c3d787629444aac43662042d88787deae3789aaff0d88ee223 +size 840 diff --git a/tasks/kowalczyk2024/gurobi_solution/large_solution_3.json b/tasks/kowalczyk2024/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..87c1fc6801297bd8a90f401af65888df2d49d063 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79ba14ec15d22702142d4eb0af9eaf03f042045f104cd2f7dd5179dfcbccccbb +size 848 diff --git a/tasks/kowalczyk2024/gurobi_solution/large_solution_4.json b/tasks/kowalczyk2024/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..1bb871f6633cfbada083a64e100d723788b57b83 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e68300ea7afdf4646fe019af38fc070314252cf19b4646094b97b6e53fe4ab86 +size 853 diff --git a/tasks/kowalczyk2024/gurobi_solution/large_solution_5.json b/tasks/kowalczyk2024/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7a9bf12edd9ee46e8bac2cac1915d541921d4c74 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f07ce0399f113f40ef3e31a4723c216f48dbceabeb88057a87aea54ef9f1ad2 +size 845 diff --git a/tasks/kowalczyk2024/gurobi_solution/tiny_solution.json b/tasks/kowalczyk2024/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..3482cbe606e6f301db9afbfe0b44f104a41a5e71 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69b177fa9615ac838ab5c7ccd005ee8a88d808411d0029ab134ed0202fb3a910 +size 688 diff --git a/tasks/kowalczyk2024/gurobi_solution_log/large_log_1.jsonl b/tasks/kowalczyk2024/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4b26767b9752d3b1fb18cc6cfd6f74fd40991f39 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29572cd23f172109e7473a6d26a32a3de460dd7036abc8901e34bafb3bcda1ea +size 46 diff --git a/tasks/kowalczyk2024/gurobi_solution_log/large_log_2.jsonl b/tasks/kowalczyk2024/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dff427e85fb9c6d8002a378edd905b3a0108e890 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c2a1ff35f28f58fedf370b70291fe95ca25eddacb4b77fe129c24fd99fd087e +size 84 diff --git a/tasks/kowalczyk2024/gurobi_solution_log/large_log_3.jsonl b/tasks/kowalczyk2024/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4788ad10f4f5f0002ae8a42602e595ead0089c25 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f772d368580db5fc78a76c3981bf982b17beb468f888fd5569505e47f5adc46 +size 460 diff --git a/tasks/kowalczyk2024/gurobi_solution_log/large_log_4.jsonl b/tasks/kowalczyk2024/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bb3ea43901f1bc77c7ae8e7bda857b7c4d04786a --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed861f8b5bb70557027325329f11ba6a147531316b3922a6a14709b2cb905ecf +size 46 diff --git a/tasks/kowalczyk2024/gurobi_solution_log/large_log_5.jsonl b/tasks/kowalczyk2024/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0a0acdebfa4de09183429ff7d67b90af0a35bd0f --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c5e9ffd7110d4847eaa1d22140426b340e8dabbe1e5f1297b3d9323b94e6bb7 +size 331 diff --git a/tasks/kowalczyk2024/gurobi_solution_log/tiny_log.jsonl b/tasks/kowalczyk2024/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f93dab1619adb59afff4b9b3a5629e890bc86d09 --- /dev/null +++ b/tasks/kowalczyk2024/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48016357c7b23af3c640e4dc926378c2c1528cbbbf8c5c5415da582e734fb7f3 +size 210 diff --git a/tasks/kowalczyk2024/instance/large_instance_1.json b/tasks/kowalczyk2024/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c3414788b88d22cdf62a2afe73998e0195cc2228 --- /dev/null +++ b/tasks/kowalczyk2024/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c32f5bfe003222d73e9b1e0c71f6067a6f3820e0c2ceef4a75eea9692ea1217d +size 3993 diff --git a/tasks/kowalczyk2024/instance/large_instance_2.json b/tasks/kowalczyk2024/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..550c026229f7d0a8f54fb98721c8fabd84bb7678 --- /dev/null +++ b/tasks/kowalczyk2024/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e23fd23e92073c71429c9580d721e3dbaf64153f90a131c0fb6637e9156be00 +size 3994 diff --git a/tasks/kowalczyk2024/instance/large_instance_3.json b/tasks/kowalczyk2024/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1d4b2ba59a4363db50bb337b7fd4004f7ac9c662 --- /dev/null +++ b/tasks/kowalczyk2024/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2da6dee04b4f9ed12ab8567dac1cef3c138ac5cd4eaac348d09822897cad2ce1 +size 3993 diff --git a/tasks/kowalczyk2024/instance/large_instance_4.json b/tasks/kowalczyk2024/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..3ad0ca0486b9c0a4ffe605aabfc3e5a45cf0a8ab --- /dev/null +++ b/tasks/kowalczyk2024/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f70bbc6ee1d28e12f049fa786533d96de901629e52c09216f66997dfb9fb9981 +size 3976 diff --git a/tasks/kowalczyk2024/instance/large_instance_5.json b/tasks/kowalczyk2024/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7c66e0d8b1a63d77a128eece6d853c3051ef8269 --- /dev/null +++ b/tasks/kowalczyk2024/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:950848e116ffd6e5cf713aadac58abf9bcee481aab9ee6c2a103f143f4ea8373 +size 3967 diff --git a/tasks/kowalczyk2024/instance/tiny_instance.json b/tasks/kowalczyk2024/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..e6b0ea9cee399b278a6ffb89ee4de99b53970479 --- /dev/null +++ b/tasks/kowalczyk2024/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c55d41215a6db9c64e227ecd6d49c33422208b9bc95ec421046b4641bd17b466 +size 3075 diff --git a/tasks/kowalczyk2024/instance_schema.json b/tasks/kowalczyk2024/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..da309eaa8d7376af751ad11dc3abb58b859e8895 --- /dev/null +++ b/tasks/kowalczyk2024/instance_schema.json @@ -0,0 +1,13 @@ +{ + "n": " Number of jobs to be scheduled.", + "m": " Number of identical parallel machines available.", + "T": " Planning horizon within which all jobs must complete.", + "jobs": [ + { + "id": " Unique identifier for the job.", + "p": " Processing time required to complete the job.", + "d": " Due date by which the job should ideally be completed.", + "w": " Priority weight of the job, reflecting the cost per unit of tardiness." + } + ] +} diff --git a/tasks/kowalczyk2024/mathematical_formulation.md b/tasks/kowalczyk2024/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..4acf71d1c22f96e8bfb154ad254b941c4d9d3ef1 --- /dev/null +++ b/tasks/kowalczyk2024/mathematical_formulation.md @@ -0,0 +1,53 @@ +# Original Formulation: Identical Parallel Machine Scheduling, Total Weighted Tardiness (TIF) + +*Source: A flow-based formulation for parallel machine scheduling using decision diagrams, Daniel Kowalczyk, Roel Leus, Christopher Hojny, Stefan Røpke, 2024.* + +The paper studies $Pm\,||\,\sum_{j} w_j T_j$ (identical parallel machine scheduling, minimize total weighted tardiness, no idle time). The first complete MILP that defines this problem in the paper’s own job-start variables is the *Time-Indexed Formulation* (TIF), Eq. (1) of Section 2.1. This is the canonical formulation reproduced below. The paper’s new flow/decision-diagram formulation (BDDF) and the arc-time-indexed formulation (ATIF) — alternative formulations of the *same* problem — are listed under **Variants**. + +## Sets and Indices + +$$\begin{align*} +J &= \{1,\dots,n\} && \text{set of $n$ jobs} \\ +M &= \{1,\dots,m\} && \text{set of $m$ identical parallel machines} \\ +j &\in J && \text{job index} \\ +t &\in \{1,\dots,T\} && \text{period index; period $t$ starts at time $t-1$ and ends at $t$} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +p_j &\in \mathbb{N}\setminus\{0\} && \text{integer processing time of job $j\in J$} \\ +d_j & && \text{due date of job $j\in J$} \\ +w_j & && \text{weight (priority) of job $j\in J$} \\ +p_{\max} &= \max_{j\in J} p_j && \text{maximum processing time} \\ +T &= \left\lceil \tfrac{\sum_{j\in J} p_j - p_{\max}}{m} \right\rceil + p_{\max} + && \text{planning horizon (safe upper bound, no optimum lost)} \\ +\widetilde{c}_{jt} & && \text{cost of job $j$ starting at the beginning of period $t$} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +y_{jt} \in \{0,1\} \quad && \text{$=1$ if job $j$ starts at the beginning of period $t$ (so $j$ ends in period $t+p_j-1$);} \\ + && j\in J,\; t\in\{1,\dots,T-p_j+1\}. +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad \sum_{j\in J}\ \sum_{t=1}^{T-p_j+1} \widetilde{c}_{jt}\, y_{jt} +\tag{1a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{t=1}^{T-p_j+1} y_{jt} &= 1 +&& \forall\, j\in J \tag{1b}\\[2pt] +\sum_{j\in J}\ \sum_{s=\max\{1,\,t-p_j+1\}}^{t} y_{js} &\le m +&& \forall\, t\in\{1,\dots,T\} \tag{1c}\\[2pt] +y_{jt} &\in \{0,1\} +&& \forall\, j\in J,\; t\in\{1,\dots,T\} \tag{1d} +\end{align}$$ + +Constraints (1b) ensure every job starts exactly once; Constraints (1c) impose that at most $m$ jobs are in process in any period (machine capacity). diff --git a/tasks/kowalczyk2024/problem_description.txt b/tasks/kowalczyk2024/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b404a7c40070bbd1819abd6d7ec2ea20627d009 --- /dev/null +++ b/tasks/kowalczyk2024/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A facility has a set of jobs and a set of identical parallel machines. Each job has a positive integer processing time, a due date, and a positive weight representing its priority. The planner must assign every job to exactly one machine and determine the order in which jobs are processed on each machine. Jobs are processed non-preemptively: once a job starts on a machine, it runs to completion without interruption, and each machine processes at most one job at a time. + +There is no idle time between consecutive jobs on any machine, so each machine processes its assigned jobs back-to-back starting from time zero. The start time of a job on its assigned machine equals the sum of the processing times of all jobs that precede it on that machine, and its completion time equals its start time plus its own processing time. + +The tardiness of a job is the amount by which its completion time exceeds its due date, or zero if it finishes on or before its due date. The weighted tardiness of a job is its weight multiplied by its tardiness. + +The input data for each instance specifies the number of jobs, the number of machines, and for each job its integer processing time, its due date, and its weight. + +The objective is to minimize the total weighted tardiness, i.e. the sum of the weighted tardiness values across all jobs. diff --git a/tasks/kowalczyk2024/solution_logger.py b/tasks/kowalczyk2024/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/kowalczyk2024/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/kowalczyk2024/solution_schema.json b/tasks/kowalczyk2024/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..da1cb3ac55bb284e962a4a64eb09d4d48c07a8a1 --- /dev/null +++ b/tasks/kowalczyk2024/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total weighted tardiness across all jobs.", + "schedule": " Start time assigned to each job on its machine." +} diff --git a/tasks/kress2019/feasibility_check.py b/tasks/kress2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..666493b9f409f5c2ff816ddda95c3619adeae605 --- /dev/null +++ b/tasks/kress2019/feasibility_check.py @@ -0,0 +1,1049 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the PCSP-SL (Preemptive Crane Scheduling Problem with +Seaside and Landside containers) from Kress, Dornseifer & Jaehn (2019). + +Checks constraints from the mathematical formulation (Appendix A): + Constraint 1: Initial crane positions (A.4) + Constraint 2: Crane movement speed — at most 1 slot per time unit (A.5) + Constraint 3: Non-crossing — seaside crane always left of landside crane (A.6) + Constraint 4: Cranes within block bounds (A.7) + Constraint 5: All seaside containers reach target slots (A.20, A.21) + Constraint 6: Landside containers delivered within time windows (A.30) + Constraint 7: Makespan consistency — C >= finish time of last seaside container + Constraint 26: Objective consistency — reported objective_value equals the + makespan recomputed from the seaside-container completion times + +For solutions that only contain an objective_value (e.g., from the efficient DP), +only basic checks are performed (non-null, positive). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('crane_l_positions', 'crane_w_positions', 'landside_events', 'objective_value', 'seaside_events') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('landside_events', 'seaside_events') +_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 check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + S = instance["S"] + n = instance["n"] + m = instance["m"] + p = instance["p"] + sigma_w = instance["sigma_w"] + sigma_l = instance["sigma_l"] + + seaside = instance["seaside_containers"] + s_target = {sc["id"]: sc["target_slot"] for sc in seaside} + + landside = instance["landside_containers"] + land_info = {} + for lc in landside: + land_info[lc["id"]] = { + "source": lc["source_slot"], + "r": lc["earliest_finish_time"], + "d": lc["deadline"] + } + + violations = [] + violation_magnitudes = [] + violated_constraint_set = set() + + obj = solution.get("objective_value") + status = solution.get("status") + status_name = solution.get("status_name", "") + if obj is None: + # No solution was found by the solver -- return null (not false) + return { + "feasible": None, + "violated_constraints": [], + "violations": [f"No solution to check: objective_value is null (status={status}, status_name={status_name})"], + "violation_magnitudes": [], + } + + # If solution only has objective_value (no detailed schedule), basic checks only + has_schedule = "crane_w_positions" in solution and "crane_l_positions" in solution + if not has_schedule: + if obj <= 0: + violated_constraint_set.add(7) + violations.append( + f"Constraint 7 (makespan): objective_value={obj} must be positive" + ) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(obj), + "rhs": 0.0, + "raw_excess": float(abs(obj)), + "normalizer": eps, + "ratio": float(abs(obj) / eps) + }) + + + # ===================================================================== + # List-based domain checks for kress2019 + # Binary l^I_t, l^J_{t,i,s}: each container lifted by each crane at most once. + for event_type, events in [("seaside_events", solution.get("seaside_events", [])), + ("landside_events", solution.get("landside_events", []))]: + seen_containers = set() + for ev in events: + cid = ev.get("container_id") + if cid in seen_containers: + violated_constraint_set.add(9) + violations.append( + f"Constraint 9 (binary domain): container {cid} appears twice in {event_type}" + ) + violation_magnitudes.append({ + "constraint": 9, "lhs": 2.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + seen_containers.add(cid) + for tkey in ("seaside_drop_time", "lift_time", "drop_time"): + if tkey in ev: + try: + tv = float(ev[tkey]) + except (TypeError, ValueError): + continue + if abs(tv - round(tv)) > 1e-5: + violated_constraint_set.add(9) + violations.append( + f"Constraint 9 (integer domain): {tkey}={tv} for container {cid} not integer" + ) + violation_magnitudes.append({ + "constraint": 9, "lhs": tv, "rhs": round(tv), + "raw_excess": abs(tv - round(tv)), + "normalizer": max(abs(round(tv)), 1e-5), + "ratio": abs(tv - round(tv)) / max(abs(round(tv)), 1e-5), + }) + + # The bundled profile has one landside job, which is also the mandatory + # next-deadline group. Require its complete lift/drop witness rather than + # silently skipping every constraint when nested times are absent. + landside_by_id = { + event.get("container_id"): event + for event in solution.get("landside_events", []) + if isinstance(event, dict) + } + for container_id, info in land_info.items(): + event = landside_by_id.get(container_id) + missing = [] if event is not None else ["event"] + if event is not None: + missing = [ + field for field in ("source_slot", "lift_time", "drop_time") + if field not in event + ] + if missing: + violated_constraint_set.add(6) + violations.append( + f"Landside container {container_id} lacks complete processing " + f"witness fields: {missing}" + ) + violation_magnitudes.append({ + "constraint": 6, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + elif event["source_slot"] != info["source"]: + violated_constraint_set.add(6) + violations.append( + f"Landside container {container_id} source_slot=" + f"{event['source_slot']} does not match {info['source']}" + ) + violation_magnitudes.append({ + "constraint": 6, "lhs": float(event["source_slot"]), + "rhs": float(info["source"]), "raw_excess": 1.0, + "normalizer": max(abs(float(info["source"])), eps), + "ratio": 1.0 / max(abs(float(info["source"])), eps), + }) + + _domain_check_vars_binary = [] + _domain_check_vars_integer = [] + + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # ===================================================================== + # Constraint 8: Binary domain — variables must be 0 or 1 + for var_name, var_dict in _domain_check_vars_binary: + if isinstance(var_dict, dict): + for key, val in var_dict.items(): + try: + v = float(val) + except (TypeError, ValueError): + continue + if abs(v - round(v)) > tol or round(v) not in (0, 1): + viol = min(abs(v - 0), abs(v - 1)) + if viol > tol: + violated_constraint_set.add(8) + violations.append( + f"Constraint 8 (binary domain): {var_name}[{key}] = {v} not in {0, 1}") + violation_magnitudes.append({ + "constraint": 8, + "lhs": v, + "rhs": 1.0, + "raw_excess": float(viol), + "normalizer": 1.0, + "ratio": float(viol), + }) + + # Constraint 9: Integer domain — variables must be integral + for var_name, var_dict in _domain_check_vars_integer: + if isinstance(var_dict, dict): + for key, val in var_dict.items(): + try: + v = float(val) + except (TypeError, ValueError): + continue + frac = abs(v - round(v)) + if frac > tol: + violated_constraint_set.add(9) + violations.append( + f"Constraint 9 (integer domain): {var_name}[{key}] = {v} is not integer") + violation_magnitudes.append({ + "constraint": 9, + "lhs": v, + "rhs": round(v), + "raw_excess": float(frac), + "normalizer": max(abs(round(v)), eps), + "ratio": float(frac / max(abs(round(v)), eps)), + }) + + + if not has_schedule: + return _build_result(violated_constraint_set, violations, violation_magnitudes) + + # Detailed schedule available — thorough checks + C = solution.get("makespan", obj) + + # Parse crane positions (keys may be string) + x_w = {} + x_l = {} + for k, v in solution["crane_w_positions"].items(): + x_w[int(k)] = float(v) + for k, v in solution["crane_l_positions"].items(): + x_l[int(k)] = float(v) + + T_max = max(max(x_w.keys()), max(x_l.keys())) + + # ========================================================================= + # Constraint 1 (A.4): Initial crane positions + # ========================================================================= + if abs(x_w[0] - sigma_w) > tol: + violation_amount = abs(x_w[0] - sigma_w) + normalizer = max(abs(sigma_w), eps) + violated_constraint_set.add(1) + violations.append( + f"Constraint 1 (initial position): seaside crane x_w[0]={x_w[0]}, " + f"expected sigma_w={sigma_w}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(x_w[0]), + "rhs": float(sigma_w), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + if abs(x_l[0] - sigma_l) > tol: + violation_amount = abs(x_l[0] - sigma_l) + normalizer = max(abs(sigma_l), eps) + violated_constraint_set.add(1) + violations.append( + f"Constraint 1 (initial position): landside crane x_l[0]={x_l[0]}, " + f"expected sigma_l={sigma_l}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(x_l[0]), + "rhs": float(sigma_l), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint 2 (A.5): Crane movement speed + # ========================================================================= + for t in range(1, T_max + 1): + if t in x_w and (t - 1) in x_w: + move = abs(x_w[t] - x_w[t - 1]) + if move > 1 + tol: + violated_constraint_set.add(2) + violations.append( + f"Constraint 2 (movement): seaside crane moves {move:.4f} " + f"slots at t={t} (max 1)" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(move), + "rhs": 1.0, + "raw_excess": float(move - 1), + "normalizer": 1.0, + "ratio": float(move - 1) + }) + if t in x_l and (t - 1) in x_l: + move = abs(x_l[t] - x_l[t - 1]) + if move > 1 + tol: + violated_constraint_set.add(2) + violations.append( + f"Constraint 2 (movement): landside crane moves {move:.4f} " + f"slots at t={t} (max 1)" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(move), + "rhs": 1.0, + "raw_excess": float(move - 1), + "normalizer": 1.0, + "ratio": float(move - 1) + }) + + # ========================================================================= + # Constraint 3 (A.6): Non-crossing + # ========================================================================= + for t in range(0, T_max + 1): + if t in x_w and t in x_l: + if x_w[t] > x_l[t] - 1 + tol: + gap = x_w[t] - (x_l[t] - 1) + violated_constraint_set.add(3) + violations.append( + f"Constraint 3 (non-crossing): at t={t}, x_w={x_w[t]:.4f}, " + f"x_l={x_l[t]:.4f}, need x_w <= x_l - 1" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(x_w[t]), + "rhs": float(x_l[t] - 1), + "raw_excess": float(gap), + "normalizer": max(abs(x_l[t] - 1), eps), + "ratio": float(gap / max(abs(x_l[t] - 1), eps)) + }) + + # ========================================================================= + # Constraint 4 (A.7): Cranes within bounds + # ========================================================================= + for t in range(0, T_max + 1): + if t in x_w: + if x_w[t] < -tol or x_w[t] > S + 1 + tol: + violated_constraint_set.add(4) + violations.append( + f"Constraint 4 (bounds): x_w[{t}]={x_w[t]:.4f} out of [0, {S+1}]" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(x_w[t]), + "rhs": float(S + 1), + "raw_excess": float(max(x_w[t] - (S + 1), -x_w[t])), + "normalizer": float(S + 1), + "ratio": float(max(x_w[t] - (S + 1), -x_w[t]) / (S + 1)) + }) + if t in x_l: + if x_l[t] < -tol or x_l[t] > S + 1 + tol: + violated_constraint_set.add(4) + violations.append( + f"Constraint 4 (bounds): x_l[{t}]={x_l[t]:.4f} out of [0, {S+1}]" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(x_l[t]), + "rhs": float(S + 1), + "raw_excess": float(max(x_l[t] - (S + 1), -x_l[t])), + "normalizer": float(S + 1), + "ratio": float(max(x_l[t] - (S + 1), -x_l[t]) / (S + 1)) + }) + + # ========================================================================= + # Constraint 5: All seaside containers reach target (from events) + # ========================================================================= + if "seaside_events" in solution: + for event in solution["seaside_events"]: + cid = event["container_id"] + target = s_target.get(cid, None) + if target is None: + continue + has_direct_drop = "seaside_drop_slot" in event and event["seaside_drop_slot"] == target + has_landside_drop = "landside_drop_time" in event + has_handover = "landside_lift_slot" in event + if not has_direct_drop and not (has_handover or has_landside_drop): + violated_constraint_set.add(5) + violations.append( + f"Constraint 5 (seaside target): container {cid} does not " + f"reach target slot {target}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0 + }) + + # ========================================================================= + # Constraint A.8: Seaside container drop ordering (i < j => t_drop_i <= t_drop_j) + # ========================================================================= + if "seaside_events" in solution: + _sd_time = {} + for event in solution["seaside_events"]: + if "seaside_drop_time" in event: + _sd_time[event["container_id"]] = event["seaside_drop_time"] + _ids = sorted(_sd_time.keys()) + for _a in range(len(_ids)): + for _b in range(_a + 1, len(_ids)): + i, j = _ids[_a], _ids[_b] + if i < j and _sd_time[i] > _sd_time[j] + tol: + excess = _sd_time[i] - _sd_time[j] + violated_constraint_set.add(10) + violations.append( + f"Constraint A.8 (seaside drop order): container {i} seaside_drop_time={_sd_time[i]} > container {j} seaside_drop_time={_sd_time[j]}" + ) + violation_magnitudes.append({ + "constraint": 10, "lhs": float(_sd_time[i]), "rhs": float(_sd_time[j]), + "raw_excess": float(excess), + "normalizer": max(abs(_sd_time[j]), eps), + "ratio": float(excess / max(abs(_sd_time[j]), eps)), + }) + + # ========================================================================= + # Constraint A.10: Seaside crane at drop slot during [t, t+p] + # ========================================================================= + if "seaside_events" in solution: + for event in solution["seaside_events"]: + if "seaside_drop_time" in event and "seaside_drop_slot" in event: + t_d = int(round(event["seaside_drop_time"])) + s_d = event["seaside_drop_slot"] + for tp in range(t_d, min(t_d + p + 1, T_max + 1)): + if tp in x_w and abs(x_w[tp] - s_d) > tol: + excess = abs(x_w[tp] - s_d) + violated_constraint_set.add(11) + violations.append( + f"Constraint A.10 (seaside pos during drop): container {event['container_id']} drops at slot {s_d} starting t={t_d}, but x_w[{tp}]={x_w[tp]}" + ) + violation_magnitudes.append({ + "constraint": 11, "lhs": float(x_w[tp]), "rhs": float(s_d), + "raw_excess": float(excess), + "normalizer": max(abs(s_d), eps), + "ratio": float(excess / max(abs(s_d), eps)), + }) + + # ========================================================================= + # Constraint A.11: Landside crane at lift slot during landside lift of + # seaside container, held for [t, t+p] + # ========================================================================= + if "seaside_events" in solution: + for event in solution["seaside_events"]: + if "landside_lift_time" in event and "landside_lift_slot" in event: + t_l = int(round(event["landside_lift_time"])) + s_l = event["landside_lift_slot"] + for tp in range(t_l, min(t_l + p + 1, T_max + 1)): + if tp in x_l and abs(x_l[tp] - s_l) > tol: + excess = abs(x_l[tp] - s_l) + violated_constraint_set.add(12) + violations.append( + f"Constraint A.11 (landside pos during seaside-lift): container {event['container_id']} landside lifts at slot {s_l} starting t={t_l}, but x_l[{tp}]={x_l[tp]}" + ) + violation_magnitudes.append({ + "constraint": 12, "lhs": float(x_l[tp]), "rhs": float(s_l), + "raw_excess": float(excess), + "normalizer": max(abs(s_l), eps), + "ratio": float(excess / max(abs(s_l), eps)), + }) + + # ========================================================================= + # Constraint A.12: Landside crane at target slot during landside drop of + # seaside container, held for [t, t+p] + # ========================================================================= + if "seaside_events" in solution: + for event in solution["seaside_events"]: + if "landside_drop_time" in event: + t_d = int(round(event["landside_drop_time"])) + s_t = s_target.get(event["container_id"]) + if s_t is None: + continue + for tp in range(t_d, min(t_d + p + 1, T_max + 1)): + if tp in x_l and abs(x_l[tp] - s_t) > tol: + excess = abs(x_l[tp] - s_t) + violated_constraint_set.add(13) + violations.append( + f"Constraint A.12 (landside pos during seaside-drop): container {event['container_id']} dropped at target {s_t} starting t={t_d}, but x_l[{tp}]={x_l[tp]}" + ) + violation_magnitudes.append({ + "constraint": 13, "lhs": float(x_l[tp]), "rhs": float(s_t), + "raw_excess": float(excess), + "normalizer": max(abs(s_t), eps), + "ratio": float(excess / max(abs(s_t), eps)), + }) + + # ========================================================================= + # Constraint A.13: Landside crane at source slot during landside lift of + # landside container, held for [t, t+p] + # ========================================================================= + if "landside_events" in solution and m > 0: + for event in solution["landside_events"]: + if "lift_time" in event: + t_l = int(round(event["lift_time"])) + info = land_info.get(event["container_id"]) + if info is None: + continue + a_j = info["source"] + for tp in range(t_l, min(t_l + p + 1, T_max + 1)): + if tp in x_l and abs(x_l[tp] - a_j) > tol: + excess = abs(x_l[tp] - a_j) + violated_constraint_set.add(14) + violations.append( + f"Constraint A.13 (landside pos during landside-lift): container {event['container_id']} lifted at source {a_j} starting t={t_l}, but x_l[{tp}]={x_l[tp]}" + ) + violation_magnitudes.append({ + "constraint": 14, "lhs": float(x_l[tp]), "rhs": float(a_j), + "raw_excess": float(excess), + "normalizer": max(abs(a_j), eps), + "ratio": float(excess / max(abs(a_j), eps)), + }) + + # ========================================================================= + # Constraint A.14: Landside crane at S+1 during landside drop of + # landside container, held for [t, t+p] + # ========================================================================= + if "landside_events" in solution and m > 0: + for event in solution["landside_events"]: + if "drop_time" in event: + t_d = int(round(event["drop_time"])) + for tp in range(t_d, min(t_d + p + 1, T_max + 1)): + if tp in x_l and x_l[tp] < (S + 1) - tol: + excess = (S + 1) - x_l[tp] + violated_constraint_set.add(15) + violations.append( + f"Constraint A.14 (landside at S+1 during landside-drop): container {event['container_id']} dropping at t={t_d}, but x_l[{tp}]={x_l[tp]} < S+1={S+1}" + ) + violation_magnitudes.append({ + "constraint": 15, "lhs": float(x_l[tp]), "rhs": float(S + 1), + "raw_excess": float(excess), + "normalizer": float(S + 1), + "ratio": float(excess / (S + 1)), + }) + + # ========================================================================= + # Constraint A.15: Landside crane cannot start a lift during [t, t+p-1] + # while it is dropping a seaside container (landside drop occupies the crane). + # ========================================================================= + if "seaside_events" in solution: + _busy = [] + for event in solution["seaside_events"]: + if "landside_drop_time" in event: + t_d = int(round(event["landside_drop_time"])) + _busy.append((t_d, t_d + p - 1, event["container_id"])) + _landside_lift_starts = [] + for ev in solution.get("seaside_events", []): + if "landside_lift_time" in ev: + _landside_lift_starts.append((int(round(ev["landside_lift_time"])), f"seaside-ctnr {ev['container_id']}")) + for ev in solution.get("landside_events", []): + if "lift_time" in ev: + _landside_lift_starts.append((int(round(ev["lift_time"])), f"landside-ctnr {ev['container_id']}")) + for (lb, ub, drop_cid) in _busy: + for (t_lift, src) in _landside_lift_starts: + if lb <= t_lift <= ub: + violated_constraint_set.add(16) + violations.append( + f"Constraint A.15 (landside busy during drop): landside lift {src} starts at t={t_lift} while landside crane is dropping seaside container {drop_cid} in [{lb},{ub}]" + ) + violation_magnitudes.append({ + "constraint": 16, "lhs": 1.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + + # ========================================================================= + # Constraint A.17: Landside crane cumulative (lifts - drops) in [0, 1] + # ========================================================================= + _events17 = [] + for event in solution.get("seaside_events", []): + if "landside_lift_time" in event: + _events17.append((int(round(event["landside_lift_time"])), +1)) + if "landside_drop_time" in event: + _events17.append((int(round(event["landside_drop_time"])), -1)) + for event in solution.get("landside_events", []): + if "lift_time" in event: + _events17.append((int(round(event["lift_time"])), +1)) + if "drop_time" in event: + _events17.append((int(round(event["drop_time"])), -1)) + _events17.sort() + _cumul = 0 + for (t_ev, delta) in _events17: + _cumul += delta + if _cumul < 0 or _cumul > 1: + excess = float(max(_cumul - 1, -_cumul)) + violated_constraint_set.add(17) + violations.append( + f"Constraint A.17 (landside transit): cumul={_cumul} at t={t_ev} outside [0,1]" + ) + violation_magnitudes.append({ + "constraint": 17, "lhs": float(_cumul), + "rhs": 1.0 if _cumul > 1 else 0.0, + "raw_excess": excess, "normalizer": 1.0, "ratio": excess, + }) + break + + # ========================================================================= + # Constraint A.18: Landside crane (seaside containers only) cumul(lift - drop) in [0,1] + # ========================================================================= + _events18 = [] + for event in solution.get("seaside_events", []): + if "landside_lift_time" in event: + _events18.append((int(round(event["landside_lift_time"])), +1)) + if "landside_drop_time" in event: + _events18.append((int(round(event["landside_drop_time"])), -1)) + _events18.sort() + _cumul = 0 + for (t_ev, delta) in _events18: + _cumul += delta + if _cumul < 0 or _cumul > 1: + excess = float(max(_cumul - 1, -_cumul)) + violated_constraint_set.add(18) + violations.append( + f"Constraint A.18 (landside seaside-ctnr balance): cumul={_cumul} at t={t_ev} outside [0,1]" + ) + violation_magnitudes.append({ + "constraint": 18, "lhs": float(_cumul), + "rhs": 1.0 if _cumul > 1 else 0.0, + "raw_excess": excess, "normalizer": 1.0, "ratio": excess, + }) + break + + # ========================================================================= + # Constraint A.19: Landside crane (landside containers only) cumul(lift - drop) in [0,1] + # ========================================================================= + if m > 0: + _events19 = [] + for event in solution.get("landside_events", []): + if "lift_time" in event: + _events19.append((int(round(event["lift_time"])), +1)) + if "drop_time" in event: + _events19.append((int(round(event["drop_time"])), -1)) + _events19.sort() + _cumul = 0 + for (t_ev, delta) in _events19: + _cumul += delta + if _cumul < 0 or _cumul > 1: + excess = float(max(_cumul - 1, -_cumul)) + violated_constraint_set.add(19) + violations.append( + f"Constraint A.19 (landside landside-ctnr balance): cumul={_cumul} at t={t_ev} outside [0,1]" + ) + violation_magnitudes.append({ + "constraint": 19, "lhs": float(_cumul), + "rhs": 1.0 if _cumul > 1 else 0.0, + "raw_excess": excess, "normalizer": 1.0, "ratio": excess, + }) + break + + # ========================================================================= + # Constraint A.22: Handover — landside lift slot == seaside drop slot + # ========================================================================= + if "seaside_events" in solution: + for event in solution["seaside_events"]: + if "landside_lift_slot" in event and "seaside_drop_slot" in event: + if event["landside_lift_slot"] != event["seaside_drop_slot"]: + excess = abs(event["landside_lift_slot"] - event["seaside_drop_slot"]) + violated_constraint_set.add(22) + violations.append( + f"Constraint A.22 (handover slot): container {event['container_id']} seaside_drop_slot={event['seaside_drop_slot']} != landside_lift_slot={event['landside_lift_slot']}" + ) + violation_magnitudes.append({ + "constraint": 22, + "lhs": float(event["landside_lift_slot"]), + "rhs": float(event["seaside_drop_slot"]), + "raw_excess": float(excess), + "normalizer": max(abs(event["seaside_drop_slot"]), eps), + "ratio": float(excess / max(abs(event["seaside_drop_slot"]), eps)), + }) + + # ========================================================================= + # Constraint A.23: Handover — landside lift time >= seaside drop time + # ========================================================================= + if "seaside_events" in solution: + for event in solution["seaside_events"]: + if "landside_lift_time" in event and "seaside_drop_time" in event: + if event["landside_lift_time"] < event["seaside_drop_time"] - tol: + excess = event["seaside_drop_time"] - event["landside_lift_time"] + violated_constraint_set.add(23) + violations.append( + f"Constraint A.23 (handover time): container {event['container_id']} landside_lift_time={event['landside_lift_time']} < seaside_drop_time={event['seaside_drop_time']}" + ) + violation_magnitudes.append({ + "constraint": 23, + "lhs": float(event["landside_lift_time"]), + "rhs": float(event["seaside_drop_time"]), + "raw_excess": float(excess), + "normalizer": max(abs(event["seaside_drop_time"]), eps), + "ratio": float(excess / max(abs(event["seaside_drop_time"]), eps)), + }) + + # ========================================================================= + # Constraint A.24: landside drop >= landside lift (seaside containers) + # ========================================================================= + if "seaside_events" in solution: + for event in solution["seaside_events"]: + if "landside_drop_time" in event and "landside_lift_time" in event: + if event["landside_drop_time"] < event["landside_lift_time"] - tol: + excess = event["landside_lift_time"] - event["landside_drop_time"] + violated_constraint_set.add(24) + violations.append( + f"Constraint A.24 (landside drop>=lift seaside): container {event['container_id']} landside_drop_time={event['landside_drop_time']} < landside_lift_time={event['landside_lift_time']}" + ) + violation_magnitudes.append({ + "constraint": 24, + "lhs": float(event["landside_drop_time"]), + "rhs": float(event["landside_lift_time"]), + "raw_excess": float(excess), + "normalizer": max(abs(event["landside_lift_time"]), eps), + "ratio": float(excess / max(abs(event["landside_lift_time"]), eps)), + }) + + # ========================================================================= + # Constraint A.25: landside drop >= landside lift (landside containers) + # ========================================================================= + if "landside_events" in solution and m > 0: + for event in solution["landside_events"]: + if "drop_time" in event and "lift_time" in event: + if event["drop_time"] < event["lift_time"] - tol: + excess = event["lift_time"] - event["drop_time"] + violated_constraint_set.add(25) + violations.append( + f"Constraint A.25 (landside drop>=lift landside): container {event['container_id']} drop_time={event['drop_time']} < lift_time={event['lift_time']}" + ) + violation_magnitudes.append({ + "constraint": 25, + "lhs": float(event["drop_time"]), + "rhs": float(event["lift_time"]), + "raw_excess": float(excess), + "normalizer": max(abs(event["lift_time"]), eps), + "ratio": float(excess / max(abs(event["lift_time"]), eps)), + }) + + # ========================================================================= + # Constraint 6: Landside containers within time windows (from events) + # ========================================================================= + if "landside_events" in solution and m > 0: + for event in solution["landside_events"]: + cid = event["container_id"] + info = land_info.get(cid) + if info is None: + continue + if "drop_time" in event: + drop_finish = event["drop_time"] + p + if drop_finish < info["r"] - tol: + violated_constraint_set.add(6) + violations.append( + f"Constraint 6 (time window): landside container {cid} " + f"dropped too early: finish={drop_finish}, r={info['r']}" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(drop_finish), + "rhs": float(info["r"]), + "raw_excess": float(info["r"] - drop_finish), + "normalizer": max(float(info["r"]), eps), + "ratio": float((info["r"] - drop_finish) / max(info["r"], eps)) + }) + if drop_finish > info["d"] + tol: + violated_constraint_set.add(6) + violations.append( + f"Constraint 6 (time window): landside container {cid} " + f"dropped too late: finish={drop_finish}, d={info['d']}" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(drop_finish), + "rhs": float(info["d"]), + "raw_excess": float(drop_finish - info["d"]), + "normalizer": max(float(info["d"]), eps), + "ratio": float((drop_finish - info["d"]) / max(info["d"], eps)) + }) + + # ========================================================================= + # Constraint 7: Makespan consistency + # ========================================================================= + if C is not None and C <= 0: + violated_constraint_set.add(7) + violations.append(f"Constraint 7 (makespan): C={C} must be positive") + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(C), + "rhs": 0.0, + "raw_excess": float(abs(C)), + "normalizer": eps, + "ratio": float(abs(C) / eps) + }) + + # ========================================================================= + # Constraint 26: Objective consistency — the reported objective_value must + # equal the makespan recomputed from the seaside-container completion times. + # + # The objective (A.1) is min C, where C is the makespan: the earliest time + # by which every seaside container has been placed at its target slot. Per + # (A.2)/(A.3), C >= t_drop + p for the final drop of each seaside container, + # and at the optimum C equals the latest such finish time. Every seaside + # container's placement-at-target finish time is fully determined by the + # seaside_events carried in the solution (cooperative -> landside_drop_time, + # direct -> seaside_drop_time), so the makespan can be recomputed exactly + # (full recompute) and compared to the reported objective_value. This + # rejects fabricated objective values (e.g. 0 or sys.float_info.max) that + # leave the schedule itself untouched. + # ========================================================================= + seaside_events_obj = solution.get("seaside_events") + if seaside_events_obj: + try: + reported_obj = float(obj) + except (TypeError, ValueError): + reported_obj = None + completion_times = [] + for event in seaside_events_obj: + comp = None + # Cooperative handling: the landside crane places the container at + # its target slot; placement finishes p units after the drop start. + if "landside_drop_time" in event: + try: + comp = float(event["landside_drop_time"]) + p + except (TypeError, ValueError): + comp = None + # Direct handling: the seaside crane drops the container itself. + elif "seaside_drop_time" in event: + try: + comp = float(event["seaside_drop_time"]) + p + except (TypeError, ValueError): + comp = None + if comp is not None: + completion_times.append(comp) + if reported_obj is not None and completion_times: + true_obj = max(completion_times) + abs_diff = abs(reported_obj - true_obj) + # Makespan is an integer time count: a 0.5 absolute floor fires on + # any integer mismatch, with a tiny relative term for float noise. + tol_obj = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > tol_obj: + violated_constraint_set.add(26) + violations.append( + f"Constraint 26 (objective consistency): reported " + f"objective_value={reported_obj} differs from makespan " + f"recomputed from seaside_events={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol_obj:.6g})" + ) + violation_magnitudes.append({ + "constraint": 26, + "lhs": float(reported_obj), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": max(abs(true_obj), eps), + "ratio": float(abs_diff / max(abs(true_obj), eps)), + }) + + return _build_result(violated_constraint_set, violations, violation_magnitudes) + + +def _build_result(violated_constraint_set, violations, violation_magnitudes): + violated_list = sorted(violated_constraint_set) + + # ===================================================================== + # ===================================================================== + # Constraint 8: Binary domain — variables must be 0 or 1 + _domain_check_vars_binary = [] + _domain_check_vars_integer = [] + feasible = len(violated_list) == 0 + return { + "feasible": feasible, + "violated_constraints": violated_list, + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for PCSP-SL solutions (Kress et al. 2019)" + ) + 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) + + if result["feasible"] is None: + print("NO SOLUTION: Nothing to check.") + for v in result["violations"]: + print(f" - {v}") + elif result["feasible"]: + print(f"FEASIBLE: Solution satisfies all constraints.") + else: + print(f"INFEASIBLE: 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/kress2019/gurobi_code.py b/tasks/kress2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..2e88b9e35fc6a192ba1e7cb7f158353ef60d95c6 --- /dev/null +++ b/tasks/kress2019/gurobi_code.py @@ -0,0 +1,789 @@ +#!/usr/bin/env python3 +""" +MIP formulation for the PCSP-SL (Preemptive Crane Scheduling Problem with +Seaside and Landside containers) from Appendix A of: + + Kress, Dornseifer & Jaehn (2019) + "An Exact Solution Approach for Scheduling Cooperative Gantry Cranes" + European Journal of Operational Research, 273(1), 82-101. + +Solver: Gurobi (gurobipy) + +Usage: + python gurobi_code.py --instance_path instance_1.json \ + --solution_path gurobi_solution_1.json \ + --time_limit 3600 +""" + +import argparse +import json +import time +from collections import Counter + +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 +def load_instance(path: str) -> dict: + """Load a PCSP-SL instance from a JSON file.""" + with open(path, "r") as f: + data = json.load(f) + return data + + +def compute_T(S: int, n: int, m: int, p: int) -> int: + """ + Compute a conservative upper bound T on the time horizon. + + T must be large enough so that an optimal schedule fits within [0, T]. + We use: + T = 2*p*n + (S+1)*n + 2*p*m + (S+1)*m + S + 1 + which accounts for every container being lifted, moved the maximum + distance, and dropped, plus initial repositioning. + """ + return 2 * p * n + (S + 1) * n + 2 * p * m + (S + 1) * m + S + 1 + + +def compute_lambda(landside_containers: list, m: int) -> dict: + """ + Compute lambda_j for each landside container l_j. + + lambda_j = number of landside jobs with the same deadline as l_j. + lambda_{m+1} = 0 (by convention, used in constraint A.27). + + Landside containers are assumed to be 1-indexed (id = 1..m). + """ + if m == 0: + return {} + + deadlines = [lc["deadline"] for lc in landside_containers] + deadline_counts = Counter(deadlines) + + lam = {} + for lc in landside_containers: + j = lc["id"] + lam[j] = deadline_counts[lc["deadline"]] + + # lambda_{m+1} = 0 + lam[m + 1] = 0 + return lam + + +def solve_pcsp_sl(instance: dict, time_limit: int) -> dict: + """ + Build and solve the MIP formulation from Appendix A of Kress et al. (2019). + + Returns a dictionary with at least the 'objective_value' field. + """ + # ========================================================================= + # Extract instance data + # ========================================================================= + S = instance["S"] + n = instance["n"] + m = instance["m"] + p = instance["p"] + sigma_w = instance["sigma_w"] + sigma_l = instance["sigma_l"] + + # Seaside containers (1-indexed): target slots s_i + seaside = instance["seaside_containers"] # list of dicts with 'id', 'target_slot' + s = {} # s[i] = target slot for seaside container w_i + for sc in seaside: + s[sc["id"]] = sc["target_slot"] + + # Landside containers (1-indexed): source slots a_j, earliest finish time r_j, deadline d_j + landside = instance["landside_containers"] # list of dicts + a = {} # a[j] = source slot for landside container l_j + r = {} # r[j] = earliest finish time + d = {} # d[j] = deadline + for lc in landside: + j = lc["id"] + a[j] = lc["source_slot"] + r[j] = lc["earliest_finish_time"] + d[j] = lc["deadline"] + + # Compute lambda values + lam = compute_lambda(landside, m) + + # Compute time horizon upper bound + T = compute_T(S, n, m, p) + + # Index sets + I_set = list(range(1, n + 1)) # seaside containers {w_1, ..., w_n} + J_set = list(range(1, m + 1)) # landside containers {l_1, ..., l_m} + T_set = list(range(0, T + 1)) # time instants {0, ..., T} + S_slots = list(range(1, S + 1)) # intermediate storage slots {1, ..., S} + + # Big-M constant for constraint (A.23) + bigM = T * T # sufficiently large + + print(f"Instance: S={S}, n={n}, m={m}, p={p}, T={T}") + print(f" sigma_w={sigma_w}, sigma_l={sigma_l}") + print(f" Seaside targets: {s}") + if m > 0: + print(f" Landside sources: {a}, r: {r}, d: {d}") + print(f" Lambda: {lam}") + + # ========================================================================= + # Create Gurobi model + # ========================================================================= + model = gp.Model("PCSP_SL") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ========================================================================= + # Decision Variables (A.31 - A.38) + # ========================================================================= + + # x_{c,t}: position of crane c at time t (continuous, non-negative) (A.35) + x_w = {} # seaside crane positions + x_l = {} # landside crane positions + for t in T_set: + x_w[t] = model.addVar(lb=0.0, ub=S + 1, vtype=GRB.CONTINUOUS, + name=f"x_w_{t}") + x_l[t] = model.addVar(lb=0.0, ub=S + 1, vtype=GRB.CONTINUOUS, + name=f"x_l_{t}") + + # C: makespan (continuous, non-negative) (A.36) + C = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, name="C") + + # l^I_t: seaside crane starts lifting any w_i at time t (A.31) + lI = {} + for t in T_set: + lI[t] = model.addVar(vtype=GRB.BINARY, name=f"lI_{t}") + + # l^J_{t,i,s}: landside crane starts lifting w_i at time t in slot s (A.32) + lJ_tis = {} + for t in T_set: + for i in I_set: + for ss in S_slots: + lJ_tis[t, i, ss] = model.addVar(vtype=GRB.BINARY, + name=f"lJ_{t}_{i}_{ss}") + + # d^I_{t,i,s}: seaside crane starts dropping w_i at time t in slot s (A.32) + dI_tis = {} + for t in T_set: + for i in I_set: + for ss in S_slots: + dI_tis[t, i, ss] = model.addVar(vtype=GRB.BINARY, + name=f"dI_{t}_{i}_{ss}") + + # l^J_{t,j}: landside crane starts lifting l_j at time t (A.33) + lJ_tj = {} + for t in T_set: + for j in J_set: + lJ_tj[t, j] = model.addVar(vtype=GRB.BINARY, + name=f"lJj_{t}_{j}") + + # d^J_{t,j}: landside crane starts dropping l_j at time t (A.33) + dJ_tj = {} + for t in T_set: + for j in J_set: + dJ_tj[t, j] = model.addVar(vtype=GRB.BINARY, + name=f"dJj_{t}_{j}") + + # d^I_{t,i}: landside crane starts dropping w_i at time t (A.34) + dI_ti = {} + for t in T_set: + for i in I_set: + dI_ti[t, i] = model.addVar(vtype=GRB.BINARY, + name=f"dIi_{t}_{i}") + + # u_j, v_j, q_j: auxiliary binary variables for landside scheduling (A.37) + u = {} + v = {} + q = {} + for j in J_set: + u[j] = model.addVar(vtype=GRB.BINARY, name=f"u_{j}") + v[j] = model.addVar(vtype=GRB.BINARY, name=f"v_{j}") + q[j] = model.addVar(vtype=GRB.BINARY, name=f"q_{j}") + + # (A.38) v_j = 0 for j in {m+1, ..., m + lambda_m} + # These are extra v variables that must be fixed to 0. + # lambda_m is the number of landside containers with the same deadline + # as l_m (the last landside container). + v_extra = {} + if m > 0: + lambda_m = lam[m] + for j in range(m + 1, m + lambda_m + 1): + v_extra[j] = model.addVar(vtype=GRB.BINARY, name=f"v_{j}") + model.addConstr(v_extra[j] == 0, name=f"A38_v_{j}_eq_0") + + model.update() + + # ========================================================================= + # Objective Function (A.1): min C + # ========================================================================= + model.setObjective(C, GRB.MINIMIZE) + + # ========================================================================= + # Constraints + # ========================================================================= + + # ---- (A.2) Makespan: last seaside container dropped by seaside crane ---- + # t * d^I_{t,n,s_n} + p <= C, for all t in {1,...,T} + # Note: s_n is the target slot of the last seaside container w_n. + # d^I_{t,n,s_n} is only defined for s_n in {1,...,S}. + # If s_n = S+1, then w_n goes directly to landside I/O and the seaside + # crane drops it there; but d^I_{t,i,s} is only for s in {1,...,S}. + # For s_n = S+1, the container is dropped at the target by the landside + # crane (via d^I_{t,n} for the landside drop), so A.2 may not directly + # apply via dI_tis. However, constraint A.21 ensures that either + # d^I_{t,i,s_i} or d^I_{t,i} is used. When s_i = S+1, d^I_{t,i,s_i} + # is not in {1,...,S}, so d^I_{t,i} must be used (landside drops it). + # In that case, A.3 covers the makespan. + # + # We add the constraint for s_n in {1,...,S} only: + s_n = s[n] + if s_n <= S: + for t in range(1, T + 1): + model.addConstr( + t * dI_tis[t, n, s_n] + p <= C, + name=f"A2_t{t}" + ) + + # ---- (A.3) Makespan: last seaside container dropped by landside crane ---- + # t * sum_{w_i in I} d^I_{t,i} + p <= C, for all t in {1,...,T} + for t in range(1, T + 1): + model.addConstr( + t * gp.quicksum(dI_ti[t, i] for i in I_set) + p <= C, + name=f"A3_t{t}" + ) + + # ---- (A.4) Initial crane positions ---- + # x_{w,0} = sigma_w, x_{l,0} = sigma_l + model.addConstr(x_w[0] == sigma_w, name="A4_w") + model.addConstr(x_l[0] == sigma_l, name="A4_l") + + # ---- (A.5) Crane movement: at most 1 slot per time unit ---- + # x_{c,t-1} - 1 <= x_{c,t} <= x_{c,t-1} + 1 + # for c in {w,l}, t in {1,...,T} + for t in range(1, T + 1): + model.addConstr(x_w[t] >= x_w[t - 1] - 1, name=f"A5_w_lb_t{t}") + model.addConstr(x_w[t] <= x_w[t - 1] + 1, name=f"A5_w_ub_t{t}") + model.addConstr(x_l[t] >= x_l[t - 1] - 1, name=f"A5_l_lb_t{t}") + model.addConstr(x_l[t] <= x_l[t - 1] + 1, name=f"A5_l_ub_t{t}") + + # ---- (A.6) Non-crossing: seaside crane always left of landside crane ---- + # x_{w,t} <= x_{l,t} - 1, for all t in {0,...,T} + for t in T_set: + model.addConstr(x_w[t] <= x_l[t] - 1, name=f"A6_t{t}") + + # ---- (A.7) Cranes stay within block ---- + # x_{c,t} <= S+1, for c in {w,l}, t in {1,...,T} + # (Already enforced by variable upper bounds, but add explicitly for clarity) + for t in range(1, T + 1): + model.addConstr(x_w[t] <= S + 1, name=f"A7_w_t{t}") + model.addConstr(x_l[t] <= S + 1, name=f"A7_l_t{t}") + + # ---- (A.8) Seaside container drop ordering ---- + # sum_t sum_s t*d^I_{t,i,s} <= sum_t sum_s t*d^I_{t,j,s} + # for all w_i, w_j in I with i < j + for i in I_set: + for j in I_set: + if i < j: + lhs = gp.quicksum( + t * dI_tis[t, i, ss] + for t in T_set for ss in S_slots + ) + rhs = gp.quicksum( + t * dI_tis[t, j, ss] + for t in T_set for ss in S_slots + ) + model.addConstr(lhs <= rhs, name=f"A8_i{i}_j{j}") + + # ---- (A.9) Seaside crane at slot 0 during lifting ---- + # x_{w,t'} <= (1 - l^I_t) * S + # for t in {0,...,T-p}, t' in {t,...,t+p} + for t in range(0, T - p + 1): + for tp in range(t, t + p + 1): + model.addConstr( + x_w[tp] <= (1 - lI[t]) * S, + name=f"A9_t{t}_tp{tp}" + ) + + # ---- (A.10) Seaside crane position during dropping by seaside crane ---- + # (1 - sum_i sum_s d^I_{t,i,s}) * S + sum_i sum_s s*d^I_{t,i,s} >= x_{w,t'} + # x_{w,t'} >= sum_i sum_s s*d^I_{t,i,s} + # for t in {0,...,T-p}, t' in {t,...,t+p} + for t in range(0, T - p + 1): + sum_dI = gp.quicksum(dI_tis[t, i, ss] for i in I_set for ss in S_slots) + sum_s_dI = gp.quicksum( + ss * dI_tis[t, i, ss] for i in I_set for ss in S_slots + ) + for tp in range(t, t + p + 1): + # Upper bound on x_w[tp] + model.addConstr( + (1 - sum_dI) * S + sum_s_dI >= x_w[tp], + name=f"A10_ub_t{t}_tp{tp}" + ) + # Lower bound on x_w[tp] + model.addConstr( + x_w[tp] >= sum_s_dI, + name=f"A10_lb_t{t}_tp{tp}" + ) + + # ---- (A.11) Landside crane position during lifting of seaside container ---- + # (1 - sum_i sum_s l^J_{t,i,s}) * (S+1) + sum_i sum_s s*l^J_{t,i,s} >= x_{l,t'} + # x_{l,t'} >= sum_i sum_s s*l^J_{t,i,s} + # for t in {0,...,T-p}, t' in {t,...,t+p} + for t in range(0, T - p + 1): + sum_lJ = gp.quicksum( + lJ_tis[t, i, ss] for i in I_set for ss in S_slots + ) + sum_s_lJ = gp.quicksum( + ss * lJ_tis[t, i, ss] for i in I_set for ss in S_slots + ) + for tp in range(t, t + p + 1): + model.addConstr( + (1 - sum_lJ) * (S + 1) + sum_s_lJ >= x_l[tp], + name=f"A11_ub_t{t}_tp{tp}" + ) + model.addConstr( + x_l[tp] >= sum_s_lJ, + name=f"A11_lb_t{t}_tp{tp}" + ) + + # ---- (A.12) Landside crane position during dropping of seaside container ---- + # (1 - sum_i d^I_{t,i}) * (S+1) + sum_i s_i*d^I_{t,i} >= x_{l,t'} + # x_{l,t'} >= sum_i s_i*d^I_{t,i} + # for t in {0,...,T-p}, t' in {t,...,t+p} + for t in range(0, T - p + 1): + sum_dIi = gp.quicksum(dI_ti[t, i] for i in I_set) + sum_si_dIi = gp.quicksum(s[i] * dI_ti[t, i] for i in I_set) + for tp in range(t, t + p + 1): + model.addConstr( + (1 - sum_dIi) * (S + 1) + sum_si_dIi >= x_l[tp], + name=f"A12_ub_t{t}_tp{tp}" + ) + model.addConstr( + x_l[tp] >= sum_si_dIi, + name=f"A12_lb_t{t}_tp{tp}" + ) + + # ---- (A.13) Landside crane position during lifting of landside container ---- + # (1 - sum_j l^J_{t,j}) * (S+1) + sum_j a_j*l^J_{t,j} >= x_{l,t'} + # x_{l,t'} >= sum_j a_j*l^J_{t,j} + # for t in {0,...,T-p}, t' in {t,...,t+p} + if m > 0: + for t in range(0, T - p + 1): + sum_lJj = gp.quicksum(lJ_tj[t, j] for j in J_set) + sum_aj_lJj = gp.quicksum(a[j] * lJ_tj[t, j] for j in J_set) + for tp in range(t, t + p + 1): + model.addConstr( + (1 - sum_lJj) * (S + 1) + sum_aj_lJj >= x_l[tp], + name=f"A13_ub_t{t}_tp{tp}" + ) + model.addConstr( + x_l[tp] >= sum_aj_lJj, + name=f"A13_lb_t{t}_tp{tp}" + ) + + # ---- (A.14) Landside crane at slot S+1 during dropping of landside container ---- + # x_{l,t'} >= sum_j (S+1)*d^J_{t,j} + # for t in {0,...,T-p}, t' in {t,...,t+p} + if m > 0: + for t in range(0, T - p + 1): + sum_dJj = gp.quicksum((S + 1) * dJ_tj[t, j] for j in J_set) + for tp in range(t, t + p + 1): + model.addConstr( + x_l[tp] >= sum_dJj, + name=f"A14_t{t}_tp{tp}" + ) + + # ---- (A.15) Landside crane does not simultaneously lift and drop ---- + # sum_i sum_s l^J_{t',i,s} + sum_j l^J_{t',j} <= 1 - sum_i d^I_{t,i} + # for t in {0,...,T-p}, t' in {t,...,t+p-1} + # + # Note: The original paper writes d^I_{t,s} which appears to be d^I_{t,i}. + # This constraint ensures the landside crane cannot start lifting while it + # is in the process of dropping a seaside container. + for t in range(0, T - p + 1): + sum_dIi_t = gp.quicksum(dI_ti[t, i] for i in I_set) + for tp in range(t, t + p): # t' in {t, ..., t+p-1} + sum_lift_tp = gp.quicksum( + lJ_tis[tp, i, ss] for i in I_set for ss in S_slots + ) + if m > 0: + sum_lift_tp += gp.quicksum(lJ_tj[tp, j] for j in J_set) + model.addConstr( + sum_lift_tp <= 1 - sum_dIi_t, + name=f"A15_t{t}_tp{tp}" + ) + + # ---- (A.16) Seaside crane: at most one container in transit at any time ---- + # 0 <= sum_{t'=0}^{t} (l^I_{t'} - sum_i sum_s d^I_{t',i,s}) <= 1 + # for all t in {0,...,T} + for t in T_set: + cumul = gp.quicksum( + lI[tp] - gp.quicksum( + dI_tis[tp, i, ss] for i in I_set for ss in S_slots + ) + for tp in range(0, t + 1) + ) + model.addConstr(cumul >= 0, name=f"A16_lb_t{t}") + model.addConstr(cumul <= 1, name=f"A16_ub_t{t}") + + # ---- (A.17) Landside crane: at most one container in transit at any time ---- + # 0 <= sum_{t'=0}^{t} (sum_i sum_s l^J_{t',i,s} + sum_j l^J_{t',j} + # - sum_i d^I_{t',i} - sum_j d^J_{t',j}) <= 1 + # for all t in {0,...,T} + for t in T_set: + cumul = gp.quicksum( + gp.quicksum(lJ_tis[tp, i, ss] for i in I_set for ss in S_slots) + + gp.quicksum(lJ_tj[tp, j] for j in J_set) + - gp.quicksum(dI_ti[tp, i] for i in I_set) + - gp.quicksum(dJ_tj[tp, j] for j in J_set) + for tp in range(0, t + 1) + ) + model.addConstr(cumul >= 0, name=f"A17_lb_t{t}") + model.addConstr(cumul <= 1, name=f"A17_ub_t{t}") + + # ---- (A.18) Landside crane: seaside container lift-drop balance ---- + # 0 <= sum_{t'=0}^{t} sum_i (sum_s l^J_{t',i,s} - d^I_{t',i}) <= 1 + # for all t in {0,...,T} + for t in T_set: + cumul = gp.quicksum( + gp.quicksum(lJ_tis[tp, i, ss] for ss in S_slots) - dI_ti[tp, i] + for tp in range(0, t + 1) for i in I_set + ) + model.addConstr(cumul >= 0, name=f"A18_lb_t{t}") + model.addConstr(cumul <= 1, name=f"A18_ub_t{t}") + + # ---- (A.19) Landside crane: landside container lift-drop balance ---- + # 0 <= sum_{t'=0}^{t} sum_j (l^J_{t',j} - d^J_{t',j}) <= 1 + # for all t in {0,...,T} + if m > 0: + for t in T_set: + cumul = gp.quicksum( + lJ_tj[tp, j] - dJ_tj[tp, j] + for tp in range(0, t + 1) for j in J_set + ) + model.addConstr(cumul >= 0, name=f"A19_lb_t{t}") + model.addConstr(cumul <= 1, name=f"A19_ub_t{t}") + + # ---- (A.20) Each seaside container reaches target: either landside picks ---- + # it up or seaside drops it at s_i directly. + # sum_t (sum_s l^J_{t,i,s} + d^I_{t,i,s_i}) = 1, for all w_i in I + # + # Note: d^I_{t,i,s_i} is only defined for s_i in {1,...,S}. + # If s_i = S+1, the container must be handed over (landside picks up), + # so the d^I_{t,i,s_i} term effectively does not exist for s_i = S+1. + for i in I_set: + expr = gp.quicksum( + gp.quicksum(lJ_tis[t, i, ss] for ss in S_slots) + for t in T_set + ) + if s[i] <= S: + expr += gp.quicksum(dI_tis[t, i, s[i]] for t in T_set) + model.addConstr(expr == 1, name=f"A20_i{i}") + + # ---- (A.21) Each seaside container: landside drop or seaside direct drop ---- + # sum_t (d^I_{t,i} + d^I_{t,i,s_i}) = 1, for all w_i in I + # + # d^I_{t,i} is the landside crane's drop of w_i. d^I_{t,i,s_i} is the + # seaside crane's direct drop at the target slot. + # Again, d^I_{t,i,s_i} only applies when s_i in {1,...,S}. + for i in I_set: + expr = gp.quicksum(dI_ti[t, i] for t in T_set) + if s[i] <= S: + expr += gp.quicksum(dI_tis[t, i, s[i]] for t in T_set) + model.addConstr(expr == 1, name=f"A21_i{i}") + + # ---- (A.22) Handover: landside can only pick up where seaside dropped ---- + # sum_t l^J_{t,i,s} <= sum_t d^I_{t,i,s} + # for all w_i in I, s in {1,...,S} + for i in I_set: + for ss in S_slots: + model.addConstr( + gp.quicksum(lJ_tis[t, i, ss] for t in T_set) + <= gp.quicksum(dI_tis[t, i, ss] for t in T_set), + name=f"A22_i{i}_s{ss}" + ) + + # ---- (A.23) Handover: landside picks up after seaside drops ---- + # (1 - sum_t l^J_{t,i,s}) * bigM + sum_t t*l^J_{t,i,s} + # >= sum_t t*d^I_{t,i,s} + # for all w_i in I, s in {1,...,S} + for i in I_set: + for ss in S_slots: + sum_lJ_active = gp.quicksum(lJ_tis[t, i, ss] for t in T_set) + sum_t_lJ = gp.quicksum(t * lJ_tis[t, i, ss] for t in T_set) + sum_t_dI = gp.quicksum(t * dI_tis[t, i, ss] for t in T_set) + model.addConstr( + (1 - sum_lJ_active) * bigM + sum_t_lJ >= sum_t_dI, + name=f"A23_i{i}_s{ss}" + ) + + # ---- (A.24) Landside drop after landside lift for seaside containers ---- + # sum_t t*d^I_{t,i} >= sum_t sum_s t*l^J_{t,i,s} + # for all w_i in I + for i in I_set: + lhs = gp.quicksum(t * dI_ti[t, i] for t in T_set) + rhs = gp.quicksum( + t * lJ_tis[t, i, ss] for t in T_set for ss in S_slots + ) + model.addConstr(lhs >= rhs, name=f"A24_i{i}") + + # ---- (A.25) Landside drop after landside lift for landside containers ---- + # sum_t t*d^J_{t,j} >= sum_t t*l^J_{t,j} + # for all l_j in J + for j in J_set: + lhs = gp.quicksum(t * dJ_tj[t, j] for t in T_set) + rhs = gp.quicksum(t * lJ_tj[t, j] for t in T_set) + model.addConstr(lhs >= rhs, name=f"A25_j{j}") + + # ---- (A.26)-(A.30) Landside container time window enforcement ---- + if m > 0: + # Merge v and v_extra into a single lookup + v_all = {} + for j in J_set: + v_all[j] = v[j] + for j in v_extra: + v_all[j] = v_extra[j] + + for j in J_set: + # (A.26) (T+1)*u_j >= C - d_j + 0.5 + model.addConstr( + (T + 1) * u[j] >= C - d[j] + 0.5, + name=f"A26_j{j}" + ) + + # (A.27) u_j <= sum_{k=j+1}^{j+lambda_{j+1}} v_k + # lambda_{j+1}: for j < m, this is lam[j+1]; for j = m, lam[m+1] = 0 + if j < m: + lam_jp1 = lam[j + 1] + else: + lam_jp1 = lam[m + 1] # = 0 + + if lam_jp1 > 0: + sum_v = gp.quicksum( + v_all[k] for k in range(j + 1, j + lam_jp1 + 1) + if k in v_all + ) + model.addConstr(u[j] <= sum_v, name=f"A27_j{j}") + else: + # lambda_{j+1} = 0 => u_j <= 0 + model.addConstr(u[j] <= 0, name=f"A27_j{j}") + + # (A.28) q_j >= 0.5*(u_j + v_j) + model.addConstr( + q[j] >= 0.5 * (u[j] + v[j]), + name=f"A28_j{j}" + ) + + # (A.29) sum_t d^J_{t,j} >= q_j + model.addConstr( + gp.quicksum(dJ_tj[t, j] for t in T_set) >= q[j], + name=f"A29_j{j}" + ) + + # (A.30) q_j * r_j <= sum_t t*d^J_{t,j} + p <= d_j + sum_t_dJ = gp.quicksum(t * dJ_tj[t, j] for t in T_set) + model.addConstr( + q[j] * r[j] <= sum_t_dJ + p, + name=f"A30_lb_j{j}" + ) + model.addConstr( + sum_t_dJ + p <= d[j], + name=f"A30_ub_j{j}" + ) + + # ---- Additional: total number of lifts by seaside crane equals n ---- + # (Implied by A.16 + A.20 + A.21, but can help solver) + model.addConstr( + gp.quicksum(lI[t] for t in T_set) == n, + name="total_seaside_lifts" + ) + + # Every bundled instance has exactly one landside job. It is necessarily + # the next-deadline group and must therefore be processed under the stated + # release contract, even when its deadline lies after the seaside makespan. + for j in J_set: + # A released landside job is mandatory, so its time-window selector + # must also be active. Requiring lift/drop alone left q_j free at zero + # and allowed a solver incumbent to finish one job before r_j. + model.addConstr(q[j] == 1, name=f"released_required_q_{j}") + model.addConstr( + gp.quicksum(lJ_tj[t, j] for t in T_set) == 1, + name=f"released_required_landside_lift_{j}", + ) + model.addConstr( + gp.quicksum(dJ_tj[t, j] for t in T_set) == 1, + name=f"released_required_landside_drop_{j}", + ) + + # ========================================================================= + # Solve + # ========================================================================= + print(f"\nModel has {model.NumVars} variables and {model.NumConstrs} constraints.") + print(f"Solving with time limit = {time_limit} seconds...\n") + + solve_start = time.time() + model.optimize() + solve_time = time.time() - solve_start + + # ========================================================================= + # Extract solution + # ========================================================================= + result = {} + + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + result["makespan"] = obj_val + result["solve_time"] = solve_time + result["status"] = model.Status + result["status_name"] = { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + }.get(model.Status, f"OTHER({model.Status})") + + result["optimal"] = model.Status == GRB.OPTIMAL + result["gap"] = model.MIPGap + result["best_bound"] = model.ObjBound + + # Extract crane positions for the solution + crane_schedule_w = {} + crane_schedule_l = {} + for t in T_set: + crane_schedule_w[t] = x_w[t].X + crane_schedule_l[t] = x_l[t].X + result["crane_w_positions"] = crane_schedule_w + result["crane_l_positions"] = crane_schedule_l + + # Extract seaside container events + seaside_events = [] + for i in I_set: + event = {"container_id": i, "target_slot": s[i]} + # Find when seaside crane lifts (the lift time for container i is + # determined by the cumulative count: the i-th lift start) + for t in T_set: + for ss in S_slots: + if dI_tis[t, i, ss].X > 0.5: + event["seaside_drop_time"] = t + event["seaside_drop_slot"] = ss + if dI_ti[t, i].X > 0.5: + event["landside_drop_time"] = t + for ss in S_slots: + if lJ_tis[t, i, ss].X > 0.5: + event["landside_lift_time"] = t + event["landside_lift_slot"] = ss + seaside_events.append(event) + result["seaside_events"] = seaside_events + + # Extract landside container events + if m > 0: + landside_events = [] + for j in J_set: + event = {"container_id": j, "source_slot": a[j]} + for t in T_set: + if lJ_tj[t, j].X > 0.5: + event["lift_time"] = t + if dJ_tj[t, j].X > 0.5: + event["drop_time"] = t + landside_events.append(event) + result["landside_events"] = landside_events + + print(f"\nSolution found: C (makespan) = {obj_val}") + print(f" Solve time: {solve_time:.2f}s") + if model.Status == GRB.OPTIMAL: + print(" Status: OPTIMAL") + else: + print(f" Status: {result['status_name']} (gap = {result.get('gap', 'N/A')})") + + else: + result["objective_value"] = None + result["makespan"] = None + result["solve_time"] = solve_time + result["status"] = model.Status + result["status_name"] = "NO_SOLUTION" + result["optimal"] = False + result["gap"] = None + result["best_bound"] = model.ObjBound + if model.Status == GRB.INFEASIBLE: + # Preserve a compact IIS certificate in the audit artifact. This + # makes contradictions in the released formulation diagnosable + # instead of returning only a schema-less null solution. + model.computeIIS() + result["iis_constraints"] = [ + constraint.ConstrName + for constraint in model.getConstrs() + if constraint.IISConstr + ] + print(f"\nNo feasible solution found. Status = {model.Status}") + print(f" Solve time: {solve_time:.2f}s") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve PCSP-SL using the MIP formulation from " + "Kress, Dornseifer & Jaehn (2019), Appendix A." + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the JSON instance file." + ) + parser.add_argument( + "--solution_path", + type=str, + default=None, + help="Path for the output solution JSON. " + "Default: gurobi_solution_{instance_index}.json" + ) + 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 instance + instance = load_instance(args.instance_path) + + # Determine output path + if args.solution_path is None: + idx = instance.get("instance_index", 0) + args.solution_path = f"gurobi_solution_{idx}.json" + + # Solve + result = solve_pcsp_sl(instance, args.time_limit) + + # Convert any non-serializable keys (int dict keys) to strings for JSON + serializable_result = {} + for key, val in result.items(): + if isinstance(val, dict): + serializable_result[key] = {str(k): v for k, v in val.items()} + else: + serializable_result[key] = val + + # Write solution + with open(args.solution_path, "w") as f: + serializable_result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(serializable_result, f, indent=2) + + print(f"\nSolution written to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/kress2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/kress2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kress2019/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/kress2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/kress2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kress2019/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/kress2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/kress2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kress2019/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/kress2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/kress2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kress2019/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/kress2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/kress2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kress2019/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/kress2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/kress2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kress2019/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/kress2019/gurobi_solution/large_solution_1.json b/tasks/kress2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..09cb1f1e07b1eb981e878a6f56332a2b21cf04c4 --- /dev/null +++ b/tasks/kress2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0750bef0e3aa4fc0c058eb502b2164659e8b390528f53953dc42547d4c606878 +size 5513 diff --git a/tasks/kress2019/gurobi_solution/large_solution_2.json b/tasks/kress2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1a9e51613e2f5d1a471e153c823c889bd84ac704 --- /dev/null +++ b/tasks/kress2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6489760fa007ea589225a08728b963e6fa2606ea712c2832350fe04e3a33855a +size 9935 diff --git a/tasks/kress2019/gurobi_solution/large_solution_3.json b/tasks/kress2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..71a723822c64823765db0a13978b7ee886bd9a6c --- /dev/null +++ b/tasks/kress2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6ebf483e4f045007106b7401930c12c5770d5a249dae9db36ac0e52de09ed74 +size 7868 diff --git a/tasks/kress2019/gurobi_solution/large_solution_4.json b/tasks/kress2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..cf9207ada430d1a2d0d3ba2dde2aff9f18f5be4f --- /dev/null +++ b/tasks/kress2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de37ce0b789b985d0b550823e2a6559e59e53488c75e91aa55da82872aaa3c9f +size 4661 diff --git a/tasks/kress2019/gurobi_solution/large_solution_5.json b/tasks/kress2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c070cc2fe3138abcb86060090a8e705ee7473cd6 --- /dev/null +++ b/tasks/kress2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a2d463cdcf74c080a6c1dc75d2d9af8256f1d2e10ee01bed14f441ccc7fa79d +size 9777 diff --git a/tasks/kress2019/gurobi_solution/tiny_solution.json b/tasks/kress2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..dac81139d1a4b79dbfb31da66a1c01a88e36a683 --- /dev/null +++ b/tasks/kress2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55b6fe967f88e53a78878dcaec771e28c5f1d164319e78e34bf441382aea7019 +size 2862 diff --git a/tasks/kress2019/gurobi_solution_log/large_log_1.jsonl b/tasks/kress2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2b3415f87adf595c57c4c9bf63c1500f8e25a2af --- /dev/null +++ b/tasks/kress2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ce10b475324750ed178e47ef77397f846783b826efa8a48a155801c6d2aa34e +size 1228 diff --git a/tasks/kress2019/gurobi_solution_log/large_log_2.jsonl b/tasks/kress2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b8d52481e344db6d8c4acf222bf00bb15996c717 --- /dev/null +++ b/tasks/kress2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d89ddde98947e2109857b965bf939581a1441b040509bccd532cba90ad0ed49 +size 158 diff --git a/tasks/kress2019/gurobi_solution_log/large_log_3.jsonl b/tasks/kress2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d849b4c4f6e40a008394fa0de55694d1e4eecb93 --- /dev/null +++ b/tasks/kress2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:176c9e5f81afd4cf4bfa3be6f1209ad1f76f5c6fb2491ee7c2d4110cad224ff6 +size 175 diff --git a/tasks/kress2019/gurobi_solution_log/large_log_4.jsonl b/tasks/kress2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c69575db46e125facbf6b96dc39a671c7475e02 --- /dev/null +++ b/tasks/kress2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b40fe8d2761e55c84b2aa6ba3e94a92955387db7606cf9b345712eca469d01c4 +size 796 diff --git a/tasks/kress2019/gurobi_solution_log/large_log_5.jsonl b/tasks/kress2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..06c3034c527141a600d569785dd541f86b608446 --- /dev/null +++ b/tasks/kress2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:969349e98ded0abf54a846fb05619412d29e920a6dca532abc9ef59642143f97 +size 350 diff --git a/tasks/kress2019/gurobi_solution_log/tiny_log.jsonl b/tasks/kress2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b0a04604c427f7efa8708ec63809177054c7c546 --- /dev/null +++ b/tasks/kress2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5871d21f7ea11f0e8ce69c3bb39155de589c3fac133f81be5cc888ce13fe8398 +size 56 diff --git a/tasks/kress2019/instance/large_instance_1.json b/tasks/kress2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0c3be2b096d3fc8ff506463b4073f2423ddec3b4 --- /dev/null +++ b/tasks/kress2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1cf38dfe10fd24ea0a1c46b55bf7824c8552c784ad56c318ca1bd28aa9e17f0 +size 444 diff --git a/tasks/kress2019/instance/large_instance_2.json b/tasks/kress2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c6f04586091063658bdc429f92df1801bd539262 --- /dev/null +++ b/tasks/kress2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab8604572c0b986d2dfe3c84dd873d804cea58c59288f745cecdc007a7256c97 +size 501 diff --git a/tasks/kress2019/instance/large_instance_3.json b/tasks/kress2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..788585d172bea53658cb909376332bf6c764c49b --- /dev/null +++ b/tasks/kress2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:913ebea0fbb2b8fa86daabbb45c304940a0a078f7babea3e8737d1d8eb374820 +size 506 diff --git a/tasks/kress2019/instance/large_instance_4.json b/tasks/kress2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..3d5ddfc595a9647c4d88f768d0a4ece3397eb1c0 --- /dev/null +++ b/tasks/kress2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d99583bc59c08ddbf56c43ec5cf108af0a64513b01e8708963dc253dba5393d8 +size 549 diff --git a/tasks/kress2019/instance/large_instance_5.json b/tasks/kress2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7bf68e48b7e8c2928117e39408549c38f6a2e5d5 --- /dev/null +++ b/tasks/kress2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd7a1c24c7574b772e1a2b8b5115c7c5d83d8325260e058a8dc71f258b2e4f81 +size 514 diff --git a/tasks/kress2019/instance/tiny_instance.json b/tasks/kress2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..f8d65c71ca4dc4be990f97632ea9acbbe060b677 --- /dev/null +++ b/tasks/kress2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d17846983e9a09822de0b60187b4395ecb785860a2665c85c531ff14a8b11e5 +size 607 diff --git a/tasks/kress2019/instance_schema.json b/tasks/kress2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1b801cc279d0bd328066fa2f176e59a070f34778 --- /dev/null +++ b/tasks/kress2019/instance_schema.json @@ -0,0 +1,22 @@ +{ + "S": " Number of interior storage slots in the block, with slot zero as the seaside handover point and slot S+1 as the landside handover point.", + "n": " Number of seaside containers arriving at the seaside handover point.", + "m": " Number of landside containers already stored in the block that must be delivered to the landside handover point.", + "p": " Number of consecutive time units required to complete each lift or drop operation for both cranes.", + "sigma_w": " Initial slot position of the seaside crane at time zero.", + "sigma_l": " Initial slot position of the landside crane at time zero.", + "seaside_containers": [ + { + "id": " Sequence number of this seaside container, defining its required pickup order at the seaside handover point.", + "target_slot": " Storage slot where this seaside container must ultimately be placed." + } + ], + "landside_containers": [ + { + "id": " Identifier of this landside container, ordered by non-decreasing deadline.", + "source_slot": " Interior storage slot where this landside container is initially located.", + "earliest_finish_time": " Earliest time at which this landside container may be dropped at the landside handover point.", + "deadline": " Latest time by which this landside container must be dropped at the landside handover point." + } + ] +} \ No newline at end of file diff --git a/tasks/kress2019/mathematical_formulation.md b/tasks/kress2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..94140195d20625bf19e01a77ddf7fec6b5633f80 --- /dev/null +++ b/tasks/kress2019/mathematical_formulation.md @@ -0,0 +1,193 @@ +# Original Formulation: Preemptive Crane Scheduling Problem with Seaside and Landside jobs (PCSP-SL) + +*Source: An Exact Solution Approach for Scheduling Cooperative Gantry Cranes, Dominik Kress, Jan Dornseifer, Florian Jaehn, European Journal of Operational Research, 2019 (Appendix A).* + +## Sets and Indices + +- Slots $s \in \{0, 1, \ldots, S+1\}$: slot $0$ is the seaside handover point (I/O), slots $1,\ldots,S$ are the storage positions, slot $S+1$ is the landside handover point (I/O). + +- Cranes $c \in \{w, l\}$: $w$ is the seaside crane, $l$ is the landside crane. + +- Seaside containers $I = \{w_1, w_2, \ldots, w_n\}$, ordered by pick-up sequence ($w_i$ is picked up before $w_j$ for $i < j$); all originate at slot $0$. + +- Landside containers $J = \{l_1, l_2, \ldots, l_m\}$, ordered in non-decreasing order of deadlines $d_j$. + +- Time instants $t \in \{0, 1, \ldots, T\}$. + +## Parameters + +- $S \in \mathbb{N}$: number of storage slots in the block. + +- $n \in \mathbb{N}$, $n \geq 1$: number of seaside containers ($|I| = n$). + +- $m \in \mathbb{N}$: number of landside containers ($|J| = m$). + +- $p \in \mathbb{N}$: number of time units required to lift (pick up) or drop a container. + +- $T \in \mathbb{N}$: upper bound on the number of time slots needed to characterize an optimal solution. + +- $\sigma_w = x_{w,0} \in \{0, \ldots, S\}$: initial position of the seaside crane. + +- $\sigma_l = x_{l,0} \in \{1, \ldots, S+1\}$: initial position of the landside crane, with $\sigma_w < \sigma_l$. + +- $s_i \in \{1, \ldots, S+1\}$: target slot of seaside container $w_i \in I$. + +- $a_j \in \{1, \ldots, S\}$: source slot of landside container $l_j \in J$. + +- $r_j \in \mathbb{N}$: earliest finish time of landside container $l_j \in J$. + +- $d_j \in \mathbb{N}$: deadline of landside container $l_j \in J$. + +- $\lambda_j$: number of landside jobs with the same deadline as $l_j$; $\lambda_{m+1} = 0$. + +## Decision Variables + +- $x_{c,t} \in \mathbb{R}_0^+$: position of crane $c \in \{w,l\}$ at time instant $t$. + +- $C \in \mathbb{R}_0^+$: makespan (seaside makespan, to be minimized). + +- $l^I_t \in \{0,1\}$: $1$ if crane $c=w$ starts lifting any container $w_i \in I$ at time $t$. + +- $l^J_{t,i,s} \in \{0,1\}$: $1$ if crane $c=l$ starts lifting container $w_i$ at time $t$ in slot $s$. + +- $l^J_{t,j} \in \{0,1\}$: $1$ if crane $c=l$ starts lifting container $l_j$ at time $t$. + +- $d^I_{t,i,s} \in \{0,1\}$: $1$ if crane $c=w$ starts dropping container $w_i$ at time $t$ in slot $s$. + +- $d^I_{t,i} \in \{0,1\}$: $1$ if crane $c=l$ starts dropping container $w_i$ at time $t$. + +- $d^J_{t,j} \in \{0,1\}$: $1$ if crane $c=l$ starts dropping container $l_j$ at time $t$. + +- $u_j \in \{0,1\}$: $1$ if landside container $l_j$ must be processed (its deadline $d_j \leq C$). + +- $v_j \in \{0,1\}$: assures an additional landside container with smallest deadline larger than $C$ is processed (if it exists). + +- $q_j \in \{0,1\}$: auxiliary modelling variable. + +## Objective + +$$\begin{align} +\min \quad & C \tag{A.1} +\end{align}$$ + +## Constraints + +$$\begin{align} +& t \cdot d^I_{t,n,s_n} + p \leq C + && \forall t \in \{1, \ldots, T\} \tag{A.2}\\[2pt] +& t \cdot \sum_{w_i \in I} d^I_{t,i} + p \leq C + && \forall t \in \{1, \ldots, T\} \tag{A.3}\\[2pt] +& x_{c,0} = \sigma_c + && \forall c \in \{w, l\} \tag{A.4}\\[2pt] +& x_{c,t-1} - 1 \leq x_{c,t} \leq x_{c,t-1} + 1 + && \forall c \in \{w, l\},\ t \in \{0, \ldots, T\} \tag{A.5}\\[2pt] +& x_{w,t} \leq x_{l,t} - 1 + && \forall t \in \{0, \ldots, T\} \tag{A.6}\\[2pt] +& x_{c,t} \leq S + 1 + && \forall c \in \{w, l\},\ t \in \{1, \ldots, T\} \tag{A.7}\\[2pt] +& \sum_{t=0}^{T} \sum_{s=1}^{S} t \cdot d^I_{t,i,s} + \leq \sum_{t=0}^{T} \sum_{s=1}^{S} t \cdot d^I_{t,j,s} + && \forall w_i, w_j \in I,\ i < j \tag{A.8}\\[2pt] +& x_{w,t'} \leq (1 - l^I_t) \cdot S + && \forall t \in \{0, \ldots, T-p\},\ t' \in \{t, \ldots, t+p\} \tag{A.9} +\end{align}$$ + +Position of the seaside crane while dropping a seaside container: $$\begin{align} +& \Bigl(1 - \sum_{w_i \in I} \sum_{s=1}^{S} d^I_{t,i,s}\Bigr) \cdot S + + \sum_{w_i \in I} \sum_{s=1}^{S} s \cdot d^I_{t,i,s} + \;\geq\; x_{w,t'} \;\geq\; + \sum_{w_i \in I} \sum_{s=1}^{S} s \cdot d^I_{t,i,s} \notag\\ +& \hspace{6cm} \forall t \in \{0, \ldots, T-p\},\ t' \in \{t, \ldots, t+p\} \tag{A.10} +\end{align}$$ + +Position of the landside crane while lifting a seaside container: $$\begin{align} +& \Bigl(1 - \sum_{w_i \in I} \sum_{s=1}^{S} l^J_{t,i,s}\Bigr) \cdot (S+1) + + \sum_{w_i \in I} \sum_{s=1}^{S} s \cdot l^J_{t,i,s} + \;\geq\; x_{l,t'} \;\geq\; + \sum_{w_i \in I} \sum_{s=1}^{S} s \cdot l^J_{t,i,s} \notag\\ +& \hspace{6cm} \forall t \in \{0, \ldots, T-p\},\ t' \in \{t, \ldots, t+p\} \tag{A.11} +\end{align}$$ + +Position of the landside crane while dropping a seaside container: $$\begin{align} +& \Bigl(1 - \sum_{w_i \in I} d^I_{t,i}\Bigr) \cdot (S+1) + + \sum_{w_i \in I} s_i \cdot d^I_{t,i} + \;\geq\; x_{l,t'} \;\geq\; + \sum_{w_i \in I} s_i \cdot d^I_{t,i} \notag\\ +& \hspace{6cm} \forall t \in \{0, \ldots, T-p\},\ t' \in \{t, \ldots, t+p\} \tag{A.12} +\end{align}$$ + +Position of the landside crane while lifting a landside container: $$\begin{align} +& \Bigl(1 - \sum_{l_j \in J} l^J_{t,j}\Bigr) \cdot (S+1) + + \sum_{l_j \in J} a_j \cdot l^J_{t,j} + \;\geq\; x_{l,t'} \;\geq\; + \sum_{l_j \in J} a_j \cdot l^J_{t,j} \notag\\ +& \hspace{6cm} \forall t \in \{0, \ldots, T-p\},\ t' \in \{t, \ldots, t+p\} \tag{A.13} +\end{align}$$ + +$$\begin{align} +& x_{l,t'} \geq \sum_{l_j \in J} (S+1) \cdot d^J_{t,j} + && \forall t \in \{0, \ldots, T-p\},\ t' \in \{t, \ldots, t+p\} \tag{A.14} +\end{align}$$ + +Landside crane does not simultaneously lift and drop in the same slot (the paper writes $d^I_{t,s}$, i.e. $d^I_{t,i}$): $$\begin{align} +& \sum_{w_i \in I} \sum_{s=1}^{S} l^J_{t',i,s} + \sum_{l_j \in J} l^J_{t',j} + \leq 1 - \sum_{w_i \in I} d^I_{t,i} \notag\\ +& \hspace{6cm} \forall t \in \{0, \ldots, T-p\},\ t' \in \{t, \ldots, t+p-1\} \tag{A.15} +\end{align}$$ + +$$\begin{align} +& 0 \leq \sum_{t'=0}^{t} \Bigl( l^I_{t'} - \sum_{w_i \in I} \sum_{s=1}^{S} d^I_{t',i,s} \Bigr) \leq 1 + && \forall t \in \{0, \ldots, T\} \tag{A.16}\\[2pt] +& 0 \leq \sum_{t'=0}^{t} \Bigl( \sum_{w_i \in I} \sum_{s=1}^{S} l^J_{t',i,s} + + \sum_{l_j \in J} l^J_{t',j} + - \sum_{w_i \in I} d^I_{t',i} - \sum_{l_j \in J} d^J_{t',j} \Bigr) \leq 1 + && \forall t \in \{0, \ldots, T\} \tag{A.17}\\[2pt] +& 0 \leq \sum_{t'=0}^{t} \sum_{w_i \in I} \Bigl( \sum_{s=1}^{S} l^J_{t',i,s} - d^I_{t',i} \Bigr) \leq 1 + && \forall t \in \{0, \ldots, T\} \tag{A.18}\\[2pt] +& 0 \leq \sum_{t'=0}^{t} \sum_{l_j \in J} \bigl( l^J_{t',j} - d^J_{t',j} \bigr) \leq 1 + && \forall t \in \{0, \ldots, T\} \tag{A.19}\\[2pt] +& \sum_{t=0}^{T} \Bigl( \sum_{s=1}^{S} l^J_{t,i,s} + d^I_{t,i,s_i} \Bigr) = 1 + && \forall w_i \in I \tag{A.20}\\[2pt] +& \sum_{t=0}^{T} \bigl( d^I_{t,i} + d^I_{t,i,s_i} \bigr) = 1 + && \forall w_i \in I \tag{A.21}\\[2pt] +& \sum_{t=0}^{T} l^J_{t,i,s} \leq \sum_{t=0}^{T} d^I_{t,i,s} + && \forall w_i \in I,\ s \in \{1, \ldots, S\} \tag{A.22} +\end{align}$$ + +Handover ordering (the constant $T d$ acts as a big-$M$ term, written literally as in the paper): $$\begin{align} +& \Bigl(1 - \sum_{t=0}^{T} l^J_{t,i,s}\Bigr) \cdot T d + \sum_{t=0}^{T} t \cdot l^J_{t,i,s} + \geq \sum_{t=0}^{T} t \cdot d^I_{t,i,s} + && \forall w_i \in I,\ s \in \{1, \ldots, S\} \tag{A.23}\\[2pt] +& \sum_{t=0}^{T} t \cdot d^I_{t,i} \geq \sum_{t=0}^{T} \sum_{s=1}^{S} t \cdot l^J_{t,i,s} + && \forall w_i \in I \tag{A.24}\\[2pt] +& \sum_{t=0}^{T} t \cdot d^J_{t,j} \geq \sum_{t=0}^{T} t \cdot l^J_{t,j} + && \forall l_j \in J \tag{A.25}\\[2pt] +& (T+1) \cdot u_j \geq C - d_j + 0.5 + && \forall l_j \in J \tag{A.26}\\[2pt] +& u_j \leq \sum_{i=j+1}^{j + \lambda_{j+1}} v_i + && \forall l_j \in J \tag{A.27}\\[2pt] +& q_j \geq 0.5 \cdot (u_j + v_j) + && \forall l_j \in J \tag{A.28}\\[2pt] +& \sum_{t=0}^{T} d^J_{t,j} \geq q_j + && \forall l_j \in J \tag{A.29}\\[2pt] +& q_j \cdot r_j \leq \sum_{t=0}^{T} t \cdot d^J_{t,j} + p \leq d_j + && \forall l_j \in J \tag{A.30} +\end{align}$$ + +Variable domains: $$\begin{align} +& l^I_t \in \{0,1\} + && \forall t \in \{0, \ldots, T\} \tag{A.31}\\[2pt] +& l^J_{t,i,s},\, d^I_{t,i,s} \in \{0,1\} + && \forall t \in \{0, \ldots, T\},\ s \in \{1, \ldots, S\},\ w_i \in I \tag{A.32}\\[2pt] +& l^J_{t,j},\, d^J_{t,j} \in \{0,1\} + && \forall t \in \{0, \ldots, T\},\ l_j \in J \tag{A.33}\\[2pt] +& d^I_{t,i} \in \{0,1\} + && \forall t \in \{0, \ldots, T\},\ w_i \in I \tag{A.34}\\[2pt] +& x_{c,t} \in \mathbb{R}_0^+ + && \forall c \in \{w, l\},\ t \in \{0, \ldots, T\} \tag{A.35}\\[2pt] +& C \in \mathbb{R}_0^+ \tag{A.36}\\[2pt] +& u_j,\, v_j,\, q_j \in \{0,1\} + && \forall l_j \in J \tag{A.37}\\[2pt] +& v_j = 0 + && \forall j \in \{m+1, \ldots, m + \lambda_m\} \tag{A.38} +\end{align}$$ diff --git a/tasks/kress2019/problem_description.txt b/tasks/kress2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..e3ccf002eefaad0c6bc5931b7ae7890cf077eb07 --- /dev/null +++ b/tasks/kress2019/problem_description.txt @@ -0,0 +1,15 @@ +# Problem Description + +A container terminal operates a single storage block served by two identical rail-mounted gantry cranes that share the same pair of rails. The block is modeled as a one-dimensional line of positions called slots, numbered from zero through a value equal to the number of storage slots plus one. Slot zero is the seaside handover point where inbound containers arrive, and the last slot is the landside handover point where outbound containers must be delivered. The slots in between are storage positions. One crane, called the seaside crane, is responsible for handling containers that arrive from the seaside, while the other, called the landside crane, handles both seaside containers that require cooperative processing and landside containers that must leave through the landside handover point. Time is discretized into unit-length intervals, and in each interval a crane performs exactly one operation: move one slot to the left, move one slot to the right, lift part of a container pickup, drop part of a container placement, or wait in place. Lifting and dropping each take a fixed number of consecutive time units, the same for both cranes, during which the crane remains stationary at the relevant slot. + +The input specifies the number of storage slots, the number of seaside containers, the number of landside containers, and the number of time units required for each lift or drop operation. Each crane has a given initial slot position, and the seaside crane must always be strictly to the left of the landside crane. There are n seaside containers arriving at slot zero in a fixed pickup sequence: container one must be picked up before container two, and so on. Each seaside container has a designated target storage slot, which may be any slot from one through the last slot. There are m landside containers, each already stored at a known source slot among the interior storage positions. Each landside container has an earliest finish time, representing the earliest time at which it may be dropped at the landside handover point, and a deadline, representing the latest time by which it must be dropped there. The landside containers are ordered by non-decreasing deadline. + +The scheduler must determine the position and operation of each crane at every time step from time zero up to an upper bound on the time horizon. The seaside crane picks up seaside containers at slot zero in their prescribed order and moves each one toward its target slot or toward an intermediate handover slot. Either the seaside crane delivers a seaside container all the way to its target slot, or the seaside crane drops the container at an intermediate storage slot and the landside crane later picks it up from that same slot and delivers it to the target slot. Each seaside container is handled at most once by each crane, meaning the seaside crane performs exactly one lift and one drop per container, and if the landside crane is involved it also performs exactly one lift and one drop for that container. Landside containers are handled exclusively by the landside crane, which picks each one up from its source slot and drops it at the landside handover point. + +The two cranes travel on the same rails and can never occupy the same slot at the same time; the seaside crane must remain at least one slot to the left of the landside crane at every time instant. Both cranes must stay within the bounds of the block. Each crane can carry at most one container at a time, so lifts and drops alternate for each crane. Whenever a crane is lifting a container, it must remain at the origin slot of that container for the full duration of the lift, and whenever it is dropping a container, it must remain at the destination slot for the full duration of the drop. The landside crane cannot begin lifting a new container while it is still in the middle of dropping another one. + +If the landside crane picks up a seaside container from an intermediate slot, that slot must be the same slot where the seaside crane previously dropped it, and the landside crane's lift may only begin after the seaside crane's drop has started at that slot. The landside crane can only begin dropping a seaside container at its target slot after it has finished lifting that container from its intermediate slot, and similarly can only begin dropping a landside container at the landside handover point after lifting it from its source slot. The seaside crane must drop its containers respecting the original pickup sequence: earlier containers in the sequence must be dropped no later than later containers. + +Regarding which landside containers must be served: every landside container whose deadline is no later than the final makespan must be processed. In addition, to avoid infeasibility just beyond the end of the planning horizon, if there are landside containers not yet due by the makespan, at least one landside container from the group sharing the next-earliest deadline after the makespan must also be processed. Whenever a landside container is processed, it must be dropped at the landside handover point at a time that lies within the window between its earliest finish time and its deadline. + +The goal is to minimize the makespan of seaside container processing, defined as the earliest time by which all seaside containers have been dropped at their target slots. diff --git a/tasks/kress2019/solution_logger.py b/tasks/kress2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/kress2019/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/kress2019/solution_schema.json b/tasks/kress2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..619e7a682e13fea370eba50a27672952e476b795 --- /dev/null +++ b/tasks/kress2019/solution_schema.json @@ -0,0 +1,24 @@ +{ + "objective_value": " Makespan of seaside container processing, equal to the earliest time by which all seaside containers have been placed at their target slots.", + "crane_w_positions": " Slot position of the seaside crane at each time step from zero through the time horizon.", + "crane_l_positions": " Slot position of the landside crane at each time step from zero through the time horizon.", + "seaside_events": [ + { + "container_id": " Identifier of the seaside container this event describes.", + "target_slot": " Storage slot where this seaside container must ultimately be placed.", + "seaside_drop_time": " Time at which the seaside crane begins dropping this container at an intermediate or target slot.", + "seaside_drop_slot": " Slot where the seaside crane drops this container.", + "landside_lift_time": " Time at which the landside crane begins lifting this container from the intermediate slot, present only when cooperative handling is used.", + "landside_lift_slot": " Intermediate slot from which the landside crane picks up this container, present only when cooperative handling is used.", + "landside_drop_time": " Time at which the landside crane begins dropping this container at its target slot, present only when cooperative handling is used." + } + ], + "landside_events": [ + { + "container_id": " Identifier of the landside container this event describes.", + "source_slot": " Interior storage slot where this landside container was initially located.", + "lift_time": " Time at which the landside crane begins lifting this container from its source slot.", + "drop_time": " Time at which the landside crane begins dropping this container at the landside handover point." + } + ] +} \ No newline at end of file diff --git a/tasks/kreter2018/feasibility_check.py b/tasks/kreter2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f6902c2ca0be4ba62ea6b048a4e99731c646ca9c --- /dev/null +++ b/tasks/kreter2018/feasibility_check.py @@ -0,0 +1,473 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for RACP solutions based on Kreter et al. (2018): +"Mixed-Integer Linear Programming and Constraint Programming Formulations + for Solving Resource Availability Cost Problems" + +Checks hard constraints from the abstract RACP formulation (Section 2.1): + Constraint (1): objective_value == sum_{k in R} c_k * R_k (objective) + Constraint (2): S_j - S_i >= p_i for in A (precedence) + Constraint (3): r_k(S,t) <= R_k for k in R, t in T (resource capacity) + Constraint (4): S_i in {0,1,...,d_bar} for i in V (domain) + Constraint (5): R_k >= 0 for k in R (non-negativity) + +For RACP/max, constraint (6) replaces (2): S_j - S_i >= delta_{ij}. + +This is the obj-recompute ("Tier C") variant of feasibility_check.py: it adds +Constraint (1), an objective-consistency check that recomputes the total +resource provision cost from the solution's resource_amounts and the +instance's resource_costs, and rejects solutions whose reported +objective_value disagrees. All other constraint logic is byte-for-byte +identical to feasibility_check.py. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'resource_amounts', 'start_times') +_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_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + activities = instance['activities'] + precedence_relations = instance['precedence_relations'] + n_resources = instance['num_resource_types'] + problem_type = instance.get('problem_type', 'RACP') + + if 'max_project_duration' in instance: + d_bar = instance['max_project_duration'] + else: + d_bar = int(instance.get('deadline_factor', 1.0) * + instance.get('earliest_project_completion', 0)) + + durations = {a['id']: a['duration'] for a in activities} + requirements = {a['id']: a['resource_requirements'] for a in activities} + act_ids = [a['id'] for a in activities] + + # Parse solution + start_times = {int(k): v for k, v in solution['start_times'].items()} + resource_amounts = {int(k): v for k, v in solution['resource_amounts'].items()} + + # Domain check on solution dict keys: every start_times key must be a + # valid activity id; every resource_amounts key must be a valid + # resource-type index in [0, n_resources). + _domain_violations = [] + _act_id_set = set(act_ids) + for sid in start_times.keys(): + if sid not in _act_id_set: + _domain_violations.append( + f"start_times key {sid!r} is not a valid activity id" + ) + for rk in resource_amounts.keys(): + if not (0 <= rk < n_resources): + _domain_violations.append( + f"resource_amounts key {rk!r} is not a valid resource index " + f"in [0, {n_resources})" + ) + + # Build arc weights + arc_weights = {} + if problem_type == 'RACP/max' and 'arc_weights' in instance: + for idx, (i, j) in enumerate(precedence_relations): + arc_weights[(i, j)] = instance['arc_weights'][idx] + else: + for (i, j) in precedence_relations: + arc_weights[(i, j)] = durations[i] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + for _msg in _domain_violations: + violated_constraints.add(0) + violations.append(f"Domain: {_msg}") + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + + # Determine which constraint index to use for precedence + # For RACP: constraint (2); for RACP/max: constraint (6) + if problem_type == 'RACP/max': + prec_constraint_idx = 6 + else: + prec_constraint_idx = 2 + + # ========================================================================= + # Constraint (2) or (6): Precedence / Temporal constraints + # S_j - S_i >= p_i (RACP) or S_j - S_i >= delta_{ij} (RACP/max) + # This is a >= constraint: violation_amount = max(0, RHS - LHS) + # ========================================================================= + for (i, j) in precedence_relations: + delta_ij = arc_weights[(i, j)] + lhs = start_times[j] - start_times[i] + rhs = delta_ij + violation_amount = max(0, rhs - lhs) + if violation_amount > tol: + violated_constraints.add(prec_constraint_idx) + violations.append( + f"Precedence violated: S_{j} - S_{i} = {lhs} < {rhs} " + f"(arc <{i},{j}>, required lag {delta_ij})" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": prec_constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint (3): Resource capacity + # r_k(S,t) <= R_k for each k in R, t in {0,...,d_bar-1} + # r_k(S,t) = sum_{i active at t} r_{ik} + # Active set: A(S,t) = {i in V^r | S_i <= t < S_i + p_i} + # This is a <= constraint: violation_amount = max(0, LHS - RHS) + # ========================================================================= + for k in range(n_resources): + R_k = resource_amounts[k] + for t in range(d_bar): + usage = 0 + for a in activities: + i = a['id'] + p_i = durations[i] + if p_i > 0 and start_times[i] <= t < start_times[i] + p_i: + usage += requirements[i][k] + lhs = usage + rhs = R_k + violation_amount = max(0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(3) + violations.append( + f"Resource capacity violated: resource {k} at time {t}, " + f"usage {lhs} > capacity {rhs}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint (4): Domain constraint + # S_i in {0, 1, ..., d_bar} for all i in V + # Check: 0 <= S_i <= d_bar and S_i is integer + # Treat as two-sided: violation if S_i < 0 or S_i > d_bar or not integer + # ========================================================================= + for i in act_ids: + s_i = start_times[i] + # Check integrality + if abs(s_i - round(s_i)) > tol: + violated_constraints.add(4) + violation_amount = abs(s_i - round(s_i)) + violations.append( + f"Domain violated: S_{i} = {s_i} is not integer" + ) + normalizer = max(abs(d_bar), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(s_i), + "rhs": float(round(s_i)), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + # Check lower bound: S_i >= 0 (i.e., 0 <= S_i, or S_i >= 0) + if s_i < -tol: + violated_constraints.add(4) + violation_amount = abs(s_i) + violations.append( + f"Domain violated: S_{i} = {s_i} < 0" + ) + normalizer = max(abs(0), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(s_i), + "rhs": 0.0, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + # Check upper bound: S_i <= d_bar + if s_i > d_bar + tol: + violated_constraints.add(4) + violation_amount = s_i - d_bar + violations.append( + f"Domain violated: S_{i} = {s_i} > d_bar = {d_bar}" + ) + normalizer = max(abs(d_bar), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(s_i), + "rhs": float(d_bar), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint (5): Non-negativity of resource amounts + # R_k >= 0 for all k in R + # This is a >= constraint: violation_amount = max(0, 0 - R_k) = max(0, -R_k) + # ========================================================================= + for k in range(n_resources): + R_k = resource_amounts[k] + violation_amount = max(0, -R_k) + if violation_amount > tol: + violated_constraints.add(5) + violations.append( + f"Non-negativity violated: R_{k} = {R_k} < 0" + ) + normalizer = eps # RHS = 0, so normalizer = max(|0|, eps) = eps + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(R_k), + "rhs": 0.0, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint (1): Objective consistency (Tier C obj-recompute defense) + # Formulation (1): Minimize sum_{k in R} c_k * R_k + # The reported objective_value must equal the total resource provision + # cost recomputed from the solution's resource_amounts (R_k) and the + # instance's resource_costs (c_k). Both are fully present, so this is an + # exact full recompute. Rejects fabricated objective_value reports (e.g. + # obj=0 or obj=sys.float_info.max) that would otherwise pass the + # constraint-only check above. + # Comparison tolerance: tol_obj = max(1e-3, 1e-3 * |true_obj|) (0.1% rel). + # ========================================================================= + resource_costs = instance.get('resource_costs') + reported_obj = solution.get('objective_value') + if resource_costs is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + true_obj = None + if reported is not None: + try: + true_obj = float(sum( + float(resource_costs[k]) * float(resource_amounts[k]) + for k in range(n_resources) + )) + except (KeyError, IndexError, TypeError, ValueError): + true_obj = None + if reported is not None and true_obj is not None: + abs_diff = abs(reported - true_obj) + tol_obj = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + violated_constraints.add(1) + violations.append( + f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_k(c_k*R_k)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol_obj:.6g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(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 RACP solutions (Kreter 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 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) + + if result['feasible']: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. 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/kreter2018/gurobi_code.py b/tasks/kreter2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..dcedb62df98298c5d24a3322f0b1781a6f5630ac --- /dev/null +++ b/tasks/kreter2018/gurobi_code.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Start-based MILP model for RACP +from Kreter et al. (2018), Section 4.1.1. + +_GUROBI_CODE_START_TIME = time.time() +"Mixed-Integer Linear Programming and Constraint Programming Formulations + for Solving Resource Availability Cost Problems" +European Journal of Operational Research. + +Start-based formulation for RACP: + Minimize sum_{k in R} c_k * R_k + subject to: + (7) sum_{t in W_i} x_{it} = 1 for all i in V + (8) sum_{tau=ES_i}^{min(LS_i, t-p_i)} x_{i,tau} + - sum_{tau=ES_j}^{t} x_{j,tau} >= 0 for in A, t in W_j + (9) sum_{i in V^r} r_{ik} * + sum_{tau=max(ES_i, t-p_i+1)}^{min(LS_i, t)} x_{i,tau} + <= R_k for k in R, t in T + (10) x_{it} in {0,1} for i in V, t in W_i + (11) R_k >= 0 for k in R + +For RACP/max, constraint (8) uses delta_{ij} instead of p_i. +""" + +import argparse +import json +import sys +import time +from collections import deque +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_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 not installed. Please install Gurobi.", file=sys.stderr) + sys.exit(1) + + +def load_instance(path): + """Load a problem instance from a JSON file.""" + with open(path, 'r') as f: + return json.load(f) + + +def compute_es_ls(activities, arcs, arc_weights, d_bar): + """ + Compute earliest start times (ES) and latest start times (LS) + using forward/backward passes on the project network. + + For RACP: arcs are precedence constraints with weight delta_{ij} = p_i. + For RACP/max: arcs have general weights delta_{ij}. + + Uses topological sort (Kahn's algorithm) for DAG processing. + For networks with negative arc weights (max time lags creating cycles + in the constraint graph), falls back to Bellman-Ford. + """ + n_act = len(activities) + act_ids = [a['id'] for a in activities] + + # Build adjacency lists + successors = {i: [] for i in act_ids} + predecessors = {i: [] for i in act_ids} + for (i, j) in arcs: + successors[i].append(j) + predecessors[j].append(i) + + # Topological sort (Kahn's algorithm) + in_degree = {i: len(predecessors[i]) for i in act_ids} + queue = deque([i for i in act_ids if in_degree[i] == 0]) + topo_order = [] + while queue: + node = queue.popleft() + topo_order.append(node) + for succ in successors[node]: + in_degree[succ] -= 1 + if in_degree[succ] == 0: + queue.append(succ) + + if len(topo_order) != n_act: + # Network has cycles (possible with max time lags) - use Bellman-Ford + # **NOT SPECIFIED IN PAPER** for RACP instances, which are always acyclic. + # Inferred assumption: Fall back to Bellman-Ford for general temporal constraints. + ES = bellman_ford_es(act_ids, arcs, arc_weights) + else: + # Forward pass: compute ES (longest path from source) + ES = {i: 0 for i in act_ids} + for i in topo_order: + for j in successors[i]: + weight = arc_weights.get((i, j), 0) + ES[j] = max(ES[j], ES[i] + weight) + + # Backward pass: compute LS + # LS[i] = d_bar - longest_path_from_i_to_sink + # Equivalently: LS[i] = min over successors j of (LS[j] - delta_{ij}) + LS = {i: d_bar for i in act_ids} + if len(topo_order) == n_act: + for i in reversed(topo_order): + for j in successors[i]: + weight = arc_weights.get((i, j), 0) + LS[i] = min(LS[i], LS[j] - weight) + else: + LS = bellman_ford_ls(act_ids, arcs, arc_weights, d_bar) + + return ES, LS + + +def bellman_ford_es(act_ids, arcs, arc_weights): + """Bellman-Ford algorithm to compute earliest start times (longest paths from source).""" + ES = {i: 0 for i in act_ids} + n = len(act_ids) + for _ in range(n - 1): + updated = False + for (i, j) in arcs: + w = arc_weights.get((i, j), 0) + if ES[i] + w > ES[j]: + ES[j] = ES[i] + w + updated = True + if not updated: + break + return ES + + +def bellman_ford_ls(act_ids, arcs, arc_weights, d_bar): + """Bellman-Ford algorithm to compute latest start times (backward pass).""" + LS = {i: d_bar for i in act_ids} + n = len(act_ids) + for _ in range(n - 1): + updated = False + for (i, j) in arcs: + w = arc_weights.get((i, j), 0) + if LS[j] - w < LS[i]: + LS[i] = LS[j] - w + updated = True + if not updated: + break + return LS + + +def compute_peak_resource_usage(activities, schedule, n_resources, d_bar): + """ + Compute the peak resource usage for each resource type given a schedule. + Returns a list of peak usages [peak_k for k in range(n_resources)]. + """ + durations = {a['id']: a['duration'] for a in activities} + requirements = {a['id']: a['resource_requirements'] for a in activities} + + peak = [0] * n_resources + for t in range(d_bar): + usage = [0] * n_resources + for a in activities: + i = a['id'] + p_i = durations[i] + if p_i > 0 and schedule[i] <= t < schedule[i] + p_i: + for k in range(n_resources): + usage[k] += requirements[i][k] + for k in range(n_resources): + peak[k] = max(peak[k], usage[k]) + return peak + + +def compute_schedule_cost(peak_usage, resource_costs): + """Compute the total cost of providing resources given peak usage.""" + return sum(resource_costs[k] * peak_usage[k] for k in range(len(resource_costs))) + + +def solve_racp(instance, time_limit): + """ + Solve the RACP (or RACP/max) using the start-based MILP formulation. + Returns a dictionary with the solution. + """ + start_time = time.time() + + activities = instance['activities'] + precedence_relations = instance['precedence_relations'] + resource_costs = instance['resource_costs'] + n_resources = instance['num_resource_types'] + problem_type = instance.get('problem_type', 'RACP') + + # Compute d_bar (maximum project duration) + if 'max_project_duration' in instance: + d_bar = instance['max_project_duration'] + else: + d_bar = int(instance.get('deadline_factor', 1.0) * + instance.get('earliest_project_completion', 0)) + + n_act = len(activities) + durations = {a['id']: a['duration'] for a in activities} + requirements = {a['id']: a['resource_requirements'] for a in activities} + act_ids = [a['id'] for a in activities] + + # Build arc weights + # For RACP: delta_{ij} = p_i (processing time of predecessor) + # For RACP/max: delta_{ij} may differ and could be provided in instance + arc_weights = {} + if problem_type == 'RACP': + for (i, j) in precedence_relations: + arc_weights[(i, j)] = durations[i] + elif problem_type == 'RACP/max': + # Check if arc weights are provided in the instance + if 'arc_weights' in instance: + for idx, (i, j) in enumerate(precedence_relations): + arc_weights[(i, j)] = instance['arc_weights'][idx] + else: + # **NOT SPECIFIED IN PAPER** for this instance format. + # Inferred assumption: treat as RACP (delta_{ij} = p_i). + for (i, j) in precedence_relations: + arc_weights[(i, j)] = durations[i] + else: + # Default to RACP behavior + for (i, j) in precedence_relations: + arc_weights[(i, j)] = durations[i] + + # Preprocessing: compute ES and LS using Bellman-Ford (cf. Ahuja et al., 1993) + ES, LS = compute_es_ls(activities, precedence_relations, arc_weights, d_bar) + + # Sanity check + for i in act_ids: + if ES[i] > LS[i]: + return { + 'objective_value': None, + 'status': 'infeasible', + 'message': f'Activity {i} has ES={ES[i]} > LS={LS[i]}' + } + + # Compute upper bound on objective value from ES-schedule and LS-schedule + # (Section 6: "The upper bound on the objective value is calculated as the + # minimum of the objective values of the ES-schedule and LS-schedule.") + es_schedule = {i: ES[i] for i in act_ids} + ls_schedule = {i: LS[i] for i in act_ids} + es_peak = compute_peak_resource_usage(activities, es_schedule, n_resources, d_bar) + ls_peak = compute_peak_resource_usage(activities, ls_schedule, n_resources, d_bar) + cost_es = compute_schedule_cost(es_peak, resource_costs) + cost_ls = compute_schedule_cost(ls_peak, resource_costs) + obj_ub = min(cost_es, cost_ls) + + if cost_es <= cost_ls: + better_schedule = es_schedule + better_peak = es_peak + else: + better_schedule = ls_schedule + better_peak = ls_peak + + # Time periods: T = {0, 1, ..., d_bar} + T = range(d_bar + 1) + + # Upper bounds on R_k: sum of all resource requirements (safe bound) + R_ub = [0] * n_resources + for k in range(n_resources): + R_ub[k] = sum(requirements[i][k] for i in act_ids) + + # ========================================================================= + # Build Gurobi Model + # ========================================================================= + model = gp.Model("RACP_start_based") + model.setParam("Threads", 1) + + # Solver settings + remaining_time = max(1, time_limit - int(time.time() - start_time)) + model.setParam("TimeLimit", remaining_time) + model.setParam("OutputFlag", 1) + + # ----- Decision Variables ----- + + # x[i,t] = 1 if activity i starts at time t, 0 otherwise (Eq. 10) + x = {} + for i in act_ids: + for t in range(ES[i], LS[i] + 1): + x[i, t] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{t}") + + # R[k] = amount of resource k provided (Eq. 11) + R = {} + for k in range(n_resources): + R[k] = model.addVar(lb=0.0, ub=R_ub[k], vtype=GRB.CONTINUOUS, name=f"R_{k}") + + model.update() + + # ----- Objective Function (Eq. 1/7-11 header) ----- + # Minimize sum_{k in R} c_k * R_k + model.setObjective( + gp.quicksum(resource_costs[k] * R[k] for k in range(n_resources)), + GRB.MINIMIZE + ) + + # ----- Constraint (7): Assignment ----- + # Each activity starts at exactly one time in its feasible window + for i in act_ids: + model.addConstr( + gp.quicksum(x[i, t] for t in range(ES[i], LS[i] + 1)) == 1, + name=f"assign_{i}" + ) + + # ----- Constraint (8): Disaggregated Precedence/Temporal Constraints ----- + # For RACP: uses p_i; for RACP/max: uses delta_{ij} + # For in A, t in W_j: + # sum_{tau=ES_i}^{min(LS_i, t - delta_{ij})} x_{i,tau} + # - sum_{tau=ES_j}^{t} x_{j,tau} >= 0 + for (i, j) in precedence_relations: + delta_ij = arc_weights[(i, j)] + for t in range(ES[j], LS[j] + 1): + lhs_ub = min(LS[i], t - delta_ij) + if lhs_ub >= ES[i]: + lhs = gp.quicksum(x[i, tau] for tau in range(ES[i], lhs_ub + 1)) + else: + lhs = 0 + rhs = gp.quicksum(x[j, tau] for tau in range(ES[j], t + 1)) + model.addConstr(lhs - rhs >= 0, name=f"prec_{i}_{j}_{t}") + + # ----- Constraint (9): Resource Constraints ----- + # For each k in R, t in T: + # sum_{i in V^r} r_{ik} * sum_{tau=max(ES_i, t-p_i+1)}^{min(LS_i, t)} x_{i,tau} <= R_k + for k in range(n_resources): + for t in T: + terms = [] + for i in act_ids: + r_ik = requirements[i][k] + p_i = durations[i] + if r_ik == 0 or p_i == 0: + continue + tau_lo = max(ES[i], t - p_i + 1) + tau_hi = min(LS[i], t) + if tau_lo <= tau_hi: + terms.append( + r_ik * gp.quicksum( + x[i, tau] for tau in range(tau_lo, tau_hi + 1) + ) + ) + if terms: + model.addConstr( + gp.quicksum(terms) <= R[k], + name=f"res_{k}_{t}" + ) + + # ----- Warm Start (MIP Start) ----- + # Provide the better of ES/LS schedule as initial solution + for i in act_ids: + for t in range(ES[i], LS[i] + 1): + x[i, t].Start = 1.0 if t == better_schedule[i] else 0.0 + for k in range(n_resources): + R[k].Start = better_peak[k] + + # ========================================================================= + # Optimize + # ========================================================================= + model.optimize() + + # ========================================================================= + # Extract Solution + # ========================================================================= + result = {} + if model.SolCount > 0: + result['objective_value'] = model.ObjVal + + # Extract start times + start_times = {} + for i in act_ids: + for t in range(ES[i], LS[i] + 1): + if x[i, t].X > 0.5: + start_times[i] = t + break + result['start_times'] = start_times + + # Extract resource amounts + resource_amounts = {} + for k in range(n_resources): + resource_amounts[k] = R[k].X + result['resource_amounts'] = resource_amounts + + if model.Status == GRB.OPTIMAL: + result['status'] = 'optimal' + else: + result['status'] = 'feasible' + else: + result['objective_value'] = None + result['status'] = 'no_solution_found' + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="RACP Start-based MILP solver using Gurobi " + "(Kreter et al., 2018, Section 4.1)" + ) + 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, required=True, + help="Path where the final solution JSON file will be written") + 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) + + instance = load_instance(args.instance_path) + result = solve_racp(instance, 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) + + if result['objective_value'] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/kreter2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/kreter2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kreter2018/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/kreter2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/kreter2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kreter2018/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/kreter2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/kreter2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kreter2018/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/kreter2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/kreter2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kreter2018/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/kreter2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/kreter2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kreter2018/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/kreter2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/kreter2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/kreter2018/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/kreter2018/gurobi_solution/large_solution_1.json b/tasks/kreter2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..fc00f96d54dc9798fc66248dfbac6623f512f27b --- /dev/null +++ b/tasks/kreter2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be1a59dea803ac1f4706e322decfc095f906783e359cc371abb7060307e43440 +size 7748 diff --git a/tasks/kreter2018/gurobi_solution/large_solution_2.json b/tasks/kreter2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..dd54ba5e462a91306874c8bf041c0b1232b716d8 --- /dev/null +++ b/tasks/kreter2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e2908eb4c298e49e2966daed936311d7163c5d60e4eb91e0342dccd456a7836 +size 8109 diff --git a/tasks/kreter2018/gurobi_solution/large_solution_3.json b/tasks/kreter2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..912e076727be75bfbf47b147a5f7c8f7c58d0786 --- /dev/null +++ b/tasks/kreter2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76fa2589509bbc26bf64dc6247b5f2526865fbaa1fa58f736a8beda36feccf84 +size 8108 diff --git a/tasks/kreter2018/gurobi_solution/large_solution_4.json b/tasks/kreter2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f52a320c685774aebed76e7a27806e43c043713c --- /dev/null +++ b/tasks/kreter2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d0f64f64822483fd693982d6d0540728b6e98867b0bf4fc2a9f51a53c8abdff +size 7738 diff --git a/tasks/kreter2018/gurobi_solution/large_solution_5.json b/tasks/kreter2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..52b348c876f7991de194f564c1f4c01846909ae4 --- /dev/null +++ b/tasks/kreter2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd560dba00a6013854e2bc758ad80b60543baea31af23eeee919783b10919d0c +size 8109 diff --git a/tasks/kreter2018/gurobi_solution/tiny_solution.json b/tasks/kreter2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..7e4c0849c20497a598d4d7d456a8934a1ec47ad2 --- /dev/null +++ b/tasks/kreter2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c532878daec5f7719a615769e58cded2b52b9cd960a28f1a68b46414efa7bb65 +size 304 diff --git a/tasks/kreter2018/gurobi_solution_log/large_log_1.jsonl b/tasks/kreter2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..05cfb8acd2e0fe190360ad04b940c57a3832f0dc --- /dev/null +++ b/tasks/kreter2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1adda5a09a0fb3d2d5655a021c6d74cfeb7ce2899b93b41446306bd2f9e29e7a +size 43 diff --git a/tasks/kreter2018/gurobi_solution_log/large_log_2.jsonl b/tasks/kreter2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0f1279d604bceb2373aac1bd5390d721091d7e39 --- /dev/null +++ b/tasks/kreter2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51e35f2b09f499708cc22750b6246729aef12340f07e5c14ca4231a1c59b6976 +size 44 diff --git a/tasks/kreter2018/gurobi_solution_log/large_log_3.jsonl b/tasks/kreter2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..95d7baa70dc17d1d69dcd918452d1d30cdadc171 --- /dev/null +++ b/tasks/kreter2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3036390d34b2beba567003bc29ee18eef8927c3e1c41e01714dd0e1c6db1afe +size 43 diff --git a/tasks/kreter2018/gurobi_solution_log/large_log_4.jsonl b/tasks/kreter2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2bac9f97935caa0f239698ddb4206e8bb97f41ba --- /dev/null +++ b/tasks/kreter2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55ccce1866fb72ad2163f1728a0a15a27b685b43f189969526456d0fec5402ef +size 43 diff --git a/tasks/kreter2018/gurobi_solution_log/large_log_5.jsonl b/tasks/kreter2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..94248fbb60e6f319ee1fbffa54eae65b48981a16 --- /dev/null +++ b/tasks/kreter2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:037c29d8d282b14514ca18d7aa49abcdef6b48b089bc3c70809c1be32e6599a8 +size 44 diff --git a/tasks/kreter2018/gurobi_solution_log/tiny_log.jsonl b/tasks/kreter2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14a221ea59b57d23f007dea0f185101148f369dd --- /dev/null +++ b/tasks/kreter2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b00b89e71b9a7bd642304de62b88c2146d7ad4052730c3e9ddac4426937d12f8 +size 41 diff --git a/tasks/kreter2018/instance/large_instance_1.json b/tasks/kreter2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..02f74fe736fce38aaedf235eed1965c2894ecc37 --- /dev/null +++ b/tasks/kreter2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9e71210703b7ce96edacf9f6c33893d3d9d4a5bae029e0b73029ee8dd39cee6 +size 103725 diff --git a/tasks/kreter2018/instance/large_instance_2.json b/tasks/kreter2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f78a25b1a6a83eb2200550c00022fd0e04d254fa --- /dev/null +++ b/tasks/kreter2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6f1e25c4ff38f71d00b712006a7e96ee85f4bd6e97ff2b7c15ac4e62b03e76d +size 103957 diff --git a/tasks/kreter2018/instance/large_instance_3.json b/tasks/kreter2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9f3171bd955db835cc2f71c5442f5ca89967b279 --- /dev/null +++ b/tasks/kreter2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:964cda0d923b81b2121e641419866a8956ddb6354108d6b7101a4b31e7a49897 +size 103292 diff --git a/tasks/kreter2018/instance/large_instance_4.json b/tasks/kreter2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..b1cb98fad9dcba308372785dbe5b81f40303c830 --- /dev/null +++ b/tasks/kreter2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4324caf5b3ee8b56f7521ed4c1d5aef0f27e59f29c83d1316f03602fd48a99c9 +size 103091 diff --git a/tasks/kreter2018/instance/large_instance_5.json b/tasks/kreter2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..020f74af6d23f42e6503b92f60a1f937ce8fbf78 --- /dev/null +++ b/tasks/kreter2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d233110e0a9d3e738b98f9e6db5790571038d91a51db925e920cf207a594da24 +size 103635 diff --git a/tasks/kreter2018/instance/tiny_instance.json b/tasks/kreter2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..268df11bed7c52a99f201812c0e58f5ad1f9c010 --- /dev/null +++ b/tasks/kreter2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a92300c6e14b8863ee7f9bac610d9fd09a3cd43e5aed18abd46ed41bae3305df +size 2302 diff --git a/tasks/kreter2018/instance_schema.json b/tasks/kreter2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f647694129deb806a1f2befbdd8c16da26dcc1f2 --- /dev/null +++ b/tasks/kreter2018/instance_schema.json @@ -0,0 +1,15 @@ +{ + "num_real_activities": " Number of real (non-fictitious) activities in the project.", + "num_total_activities": " Total number of activities including the fictitious project start and project end activities.", + "num_resource_types": " Number of renewable resource types available for the project.", + "max_project_duration": " Absolute deadline by which the project must be completed.", + "activities": [ + { + "id": " Unique identifier for the activity.", + "duration": " Number of time periods required to complete the activity without interruption.", + "resource_requirements": " Amount of each resource type consumed per period while the activity is in progress." + } + ], + "precedence_relations": " Each pair [i, j] indicates that activity j cannot start until activity i has finished.", + "resource_costs": " Per-unit cost of providing each resource type for the entire project duration." +} diff --git a/tasks/kreter2018/mathematical_formulation.md b/tasks/kreter2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d4bbe962d70993631ac4f51201f2f6c9d38cdf80 --- /dev/null +++ b/tasks/kreter2018/mathematical_formulation.md @@ -0,0 +1,53 @@ +# Original Formulation: Resource Availability Cost Problem (RACP) + +*Source: Mixed-Integer Linear Programming and Constraint Programming Formulations for Solving Resource Availability Cost Problems, Stefan Kreter, Andreas Schutt, Peter J. Stuckey, Jürgen Zimmermann, 2018 (European Journal of Operational Research).* + +## Sets and Indices + +$$\begin{align*} + & V := \{0, 1, \ldots, n, n+1\} && \text{set of activities } (n \geq 1) \\ + & V^f \subset V && \text{fictitious activities } (p_i = 0,\ r_{ik} = 0\ \forall k);\ 0, n+1 \in V^f \\ + & V^r := V \setminus V^f && \text{real activities (positive processing time)} \\ + & \mathcal{R} && \text{set of renewable resource types} \\ + & A && \text{arc set; } \langle i,j \rangle \in A \text{ is a precedence relation} \\ + & N = (V, A) && \text{activity-on-node project network} +\end{align*}$$ + +## Parameters + +$$\begin{align*} + & n && \text{number of non-dummy activities} \\ + & p_i \in \mathbb{N}_0 && \text{processing time of activity } i \in V \\ + & r_{ik} \in \mathbb{N}_0 && \text{per-period requirement of activity } i \text{ on resource } k \\ + & c_k && \text{cost for providing one unit of resource } k \in \mathcal{R} \\ + & \bar{d} && \text{prescribed upper bound on the project duration (must not be exceeded)} +\end{align*}$$ + +Derived quantities used in the formulation: $$\begin{align*} + & C_i := S_i + p_i && \text{completion time of activity } i \in V \text{ (non-interruptible)} \\ + & \mathcal{A}(S,t) := \{ i \in V^r \mid S_i \leq t < C_i \} && \text{active set at time } t \in [0,\bar{d}] \text{ for schedule } S \\ + & r_k(S,t) := \sum_{i \in \mathcal{A}(S,t)} r_{ik} && \text{utilization of resource } k \text{ at time } t +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} + & S_i \in \mathbb{N}_0 && \text{start time of activity } i \in V,\quad \text{with } S_0 := 0 \text{ and } S_{n+1} \leq \bar{d} \\ + & R_k \geq 0 && \text{amount of resource } k \in \mathcal{R} \text{ to be provided (continuous)} +\end{align*}$$ + +## Objective + +$$\begin{align} + \text{Minimize} \quad & \sum_{k \in \mathcal{R}} c_k R_k \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} + \text{subject to} \quad + & S_j - S_i \geq p_i & \langle i,j \rangle \in A \tag{2} \\ + & r_k(S,t) \leq R_k & k \in \mathcal{R},\ t \in [0,\bar{d}] \tag{3} \\ + & S_i \in \{0,1,\ldots,\bar{d}\} & i \in V \tag{4} \\ + & R_k \geq 0 & k \in \mathcal{R} \tag{5} +\end{align}$$ diff --git a/tasks/kreter2018/problem_description.txt b/tasks/kreter2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa1d723b04771ebf818a1c03fdd0c482d2d455b5 --- /dev/null +++ b/tasks/kreter2018/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A project consists of a set of activities, including two fictitious activities representing the project start and the project end. The fictitious activities have zero processing time and require no resources. Each real (non-fictitious) activity has a known integer processing time and a known integer per-period requirement for each renewable resource type. Once started, an activity runs without interruption for its full processing time. The project uses one or more types of renewable resources, and for each resource type a per-unit cost of provision is given. The amount of each resource provided is fixed for the entire project duration: every unit of a resource that is made available remains available in every period from the project start to the project end. + +The activities are linked by precedence relations. Each precedence relation specifies that a particular successor activity may not start until the predecessor activity has completed, meaning the start time of the successor must be at least as large as the start time of the predecessor plus the predecessor's processing time. The project start activity must begin at time zero, and the project end activity must start no later than a prescribed project deadline. This deadline is given as input and represents an absolute upper bound on the project duration that must not be exceeded. + +For each activity, the planner must choose an integer start time. The earliest and latest allowable start times for each activity can be derived from the precedence network and the deadline; an activity may only be scheduled within this allowable window. In each time period, the total demand placed on a resource type equals the sum of the per-period requirements of all real activities that are in progress during that period (an activity is in progress during a period if its start time is at or before that period and its completion time is strictly after that period). The total demand on each resource type in every period must not exceed the amount of that resource provided. + +The goal is to determine start times for all activities and provision levels for all resource types so as to minimize the total resource provision cost, which is the sum over all resource types of the per-unit cost multiplied by the amount provided for that resource type, while respecting all precedence relations, the project deadline, and the requirement that resource usage never exceeds provision in any period. diff --git a/tasks/kreter2018/solution_logger.py b/tasks/kreter2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/kreter2018/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/kreter2018/solution_schema.json b/tasks/kreter2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9ea668371e879a0984b0b2c190fb5a4865945761 --- /dev/null +++ b/tasks/kreter2018/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total resource provision cost of the schedule, summing the per-unit cost times the amount provided across all resource types.", + "start_times": " Chosen integer start time for each activity in the project.", + "resource_amounts": " Amount of each renewable resource type provided for the entire project duration." +} diff --git a/tasks/lai2021/feasibility_check.py b/tasks/lai2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..4843e748a915d62ec1bcc4cc46299cac8b728a30 --- /dev/null +++ b/tasks/lai2021/feasibility_check.py @@ -0,0 +1,391 @@ +""" +Feasibility checker for the Maximally Diverse Grouping Problem (MDGP). + +Checks hard constraints from the mathematical formulation: + Constraint (1): sum_{g=1}^{m} X_{ig} = 1, for all i (each vertex assigned to exactly one group) + Constraint (2): L_g <= sum_{i=1}^{N} X_{ig} <= U_g, for all g (group capacity bounds) + Constraint (3): X_{ig} in {0, 1} (binary domain) + Constraint (4): objective consistency -- the reported objective_value must equal the + objective recomputed from the assignment, i.e. + sum_{g} 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 + + + +def main(): + parser = argparse.ArgumentParser(description="Feasibility checker for MDGP") + 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 + + N = instance['N'] + m = instance['m'] + capacities = instance['group_capacities'] + L = [cap['L_g'] for cap in capacities] + U = [cap['U_g'] for cap in capacities] + + assignment = solution.get('assignment', {}) + + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint (1): sum_{g=1}^{m} X_{ig} = 1 for all i = 1..N + # Each vertex must be assigned to exactly one group. + # ========================================================================= + # Count how many groups each vertex is assigned to + vertex_group_count = {} + for v_str, g in assignment.items(): + v = int(v_str) + vertex_group_count[v] = vertex_group_count.get(v, 0) + 1 + + # Check unassigned vertices + for i in range(N): + count = vertex_group_count.get(i, 0) + if abs(count - 1) > tol: + violated_constraints.add(1) + rhs = 1.0 + lhs = float(count) + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + if count == 0: + violations.append(f"Vertex {i} is not assigned to any group") + else: + violations.append(f"Vertex {i} is assigned to {count} groups instead of 1") + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # ========================================================================= + # Constraint (2): L_g <= sum_{i=1}^{N} X_{ig} <= U_g for all g = 1..m + # Group capacity bounds. + # ========================================================================= + # Count group sizes from assignment + group_sizes = [0] * m + for v_str, g in assignment.items(): + g_int = int(g) + if 0 <= g_int < m: + group_sizes[g_int] += 1 + + for g in range(m): + size = group_sizes[g] + # Check lower bound: L_g <= size => size >= L_g + lb_violation = L[g] - size + if lb_violation > tol: + violated_constraints.add(2) + lhs = float(size) + rhs = float(L[g]) + normalizer = max(abs(rhs), eps) + violations.append( + f"Group {g} has {size} members, below lower bound {L[g]}") + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": lb_violation, + "normalizer": normalizer, + "ratio": lb_violation / normalizer + }) + + # Check upper bound: size <= U_g + ub_violation = size - U[g] + if ub_violation > tol: + violated_constraints.add(2) + lhs = float(size) + rhs = float(U[g]) + normalizer = max(abs(rhs), eps) + violations.append( + f"Group {g} has {size} members, above upper bound {U[g]}") + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": ub_violation, + "normalizer": normalizer, + "ratio": ub_violation / normalizer + }) + + # ========================================================================= + # Constraint (3): X_{ig} in {0, 1} (binary domain) + # In the solution representation, assignment maps vertex -> group (integer). + # Check that all group indices are valid integers in {0, ..., m-1}. + # ========================================================================= + for v_str, g in assignment.items(): + v = int(v_str) + g_val = g if isinstance(g, int) else int(g) + if g_val < 0 or g_val >= m: + violated_constraints.add(3) + lhs = float(g_val) + rhs_lo = 0.0 + rhs_hi = float(m - 1) + if g_val < 0: + violation_amount = abs(g_val) + rhs = rhs_lo + else: + violation_amount = g_val - (m - 1) + rhs = rhs_hi + normalizer = max(abs(rhs), eps) + violations.append( + f"Vertex {v} assigned to invalid group {g_val} (valid range: 0..{m-1})") + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": normalizer, + "ratio": float(violation_amount) / normalizer + }) + + # ========================================================================= + # Constraint (4): Objective consistency (Tier C anti-score-gaming check). + # The MDGP objective is fully determined by the assignment: + # obj = sum_{g} sum_{i j: + i, j = j, i + return i * (N - 1) - i * (i - 1) // 2 + (j - i - 1) + + # Group membership from the (canonical) assignment dict. + members_by_group = {} + for v_str, g in assignment.items(): + v = int(v_str) + # Only in-range vertices contribute a valid pairwise distance. + if 0 <= v < N: + members_by_group.setdefault(int(g), []).append(v) + + true_obj = 0.0 + for g, mem in members_by_group.items(): + mem = sorted(mem) + for a in range(len(mem)): + for b in range(a + 1, len(mem)): + true_obj += float(dist_upper[_flat_idx(mem[a], mem[b])]) + + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(4) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed within-group distance sum=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})") + violation_magnitudes.append({ + "constraint": 4, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer + }) + except Exception: + # Fail open: never crash where the original would not, and never + # remove or alter constraint (1)-(3) verdicts. A malformed + # solution that breaks the recompute is already caught above. + pass + + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if feasible: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {sorted(violated_constraints)}") + 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/lai2021/gurobi_code.py b/tasks/lai2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..fef559a3efc415710f582afc42f5b1c83ffa9389 --- /dev/null +++ b/tasks/lai2021/gurobi_code.py @@ -0,0 +1,185 @@ +""" +Gurobi implementation of the Maximally Diverse Grouping Problem (MDGP). + +Based on: Lai, Hao, Fu & Yue (2021), "Neighborhood decomposition based variable +neighborhood search and tabu search for maximally diverse grouping", +European Journal of Operational Research. + +The model is a Quadratic Binary Programming (QBP) formulation: + Maximize sum_{g=1}^{m} sum_{i 0: + obj.add(X[i, g] * X[j, g], D[i][j]) + + model.setObjective(obj, GRB.MAXIMIZE) + + # Constraint (2): each vertex assigned to exactly one group + for i in range(N): + model.addConstr(gp.quicksum(X[i, g] for g in range(m)) == 1, + name=f"assign_{i}") + + # Constraint (3): group capacity bounds + for g in range(m): + model.addConstr(gp.quicksum(X[i, g] for i in range(N)) >= L[g], + name=f"cap_lb_{g}") + model.addConstr(gp.quicksum(X[i, g] for i in range(N)) <= U[g], + name=f"cap_ub_{g}") + + model.optimize() + + # Extract solution + objective_value = None + assignment = {} + + if model.SolCount > 0: + objective_value = model.ObjVal + for i in range(N): + for g in range(m): + if X[i, g].X > 0.5: + assignment[i] = g + break + else: + # No feasible solution found + objective_value = None + + return objective_value, assignment, model.Status + + +def main(): + parser = argparse.ArgumentParser(description="Gurobi solver for MDGP") + 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) + + N, m, L, U, D = load_instance(args.instance_path) + objective_value, assignment, status = solve_mdgp(N, m, L, U, D, args.time_limit) + + # Build solution output + solution = { + "objective_value": objective_value, + "solver_status": status, + "N": N, + "m": m, + } + + if assignment: + # Group assignments: vertex -> group (0-indexed) + solution["assignment"] = {str(i): g for i, g in assignment.items()} + # Groups: group -> list of vertices + groups = {} + for i, g in assignment.items(): + groups.setdefault(g, []).append(i) + solution["groups"] = {str(g): sorted(verts) for g, verts in groups.items()} + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Objective value: {objective_value}") + print(f"Solution written to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/lai2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/lai2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lai2021/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/lai2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/lai2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lai2021/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/lai2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/lai2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lai2021/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/lai2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/lai2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lai2021/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/lai2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/lai2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lai2021/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/lai2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/lai2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lai2021/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/lai2021/gurobi_solution/large_solution_1.json b/tasks/lai2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c30f626ad88e642789b489c1ee86f80acf4ead73 --- /dev/null +++ b/tasks/lai2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b04d1e30fbd2fc74a5e6e7ab34d02f42367af73835b29c918a924d4e94e09db0 +size 11131 diff --git a/tasks/lai2021/gurobi_solution/large_solution_2.json b/tasks/lai2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..34b943dde1f314ef3472b2ed0eebbc4bddee40ea --- /dev/null +++ b/tasks/lai2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6873331f9de00ea03fe11bc727a409d1e29559abf31547ec25835e25847cf4a9 +size 11110 diff --git a/tasks/lai2021/gurobi_solution/large_solution_3.json b/tasks/lai2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..348d6f7b90334e4e5f5b1c64197dec7d54e51933 --- /dev/null +++ b/tasks/lai2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72cbadc685677bcfdfce2bacb7d093a4bd6c35c4acb0f695d6f2eef756180452 +size 11115 diff --git a/tasks/lai2021/gurobi_solution/large_solution_4.json b/tasks/lai2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9b5c11d3f9a0ae375a6b58dcd377cadc7c28e392 --- /dev/null +++ b/tasks/lai2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ad107742d8448e7d5b9f4f27b5dc473ebf2920d72339ae1382f157207e9949b +size 11110 diff --git a/tasks/lai2021/gurobi_solution/large_solution_5.json b/tasks/lai2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9120244a7496d25779c519d971d04200c0bb4f0f --- /dev/null +++ b/tasks/lai2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:151f008f9a28997ef0dffb741d40da5bc08ec138250d875c1d56387ece7ad787 +size 11121 diff --git a/tasks/lai2021/gurobi_solution/tiny_solution.json b/tasks/lai2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..27c369b815a8f7c568614890d215dc3fe00d2d22 --- /dev/null +++ b/tasks/lai2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:759d1e7c3fd5d9284ab325147032d5ea6372bb10942c3ef0d50a092ef57b5021 +size 515 diff --git a/tasks/lai2021/gurobi_solution_log/large_log_1.jsonl b/tasks/lai2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6b4b2da9dd61cad40095456f87f301a86fc3ba93 --- /dev/null +++ b/tasks/lai2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa467c3d8e49fe5d8c1be72b4d7a8b495e7dba7d2127f875e9b556001fa9cb7d +size 46 diff --git a/tasks/lai2021/gurobi_solution_log/large_log_2.jsonl b/tasks/lai2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac69e8d19b9f68c8a9d0c916fa1fd92f6480dc96 --- /dev/null +++ b/tasks/lai2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21c60e75e7df1579299aea43b57b5b157e208b5b2697502568b8b253fb0bc344 +size 46 diff --git a/tasks/lai2021/gurobi_solution_log/large_log_3.jsonl b/tasks/lai2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..810088c7edfd0392b956c8881f2cbb9cc4988222 --- /dev/null +++ b/tasks/lai2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40e01aa8fc4d25271b0aa39a91da66f6451177e7f369cad2935cc6ab66054451 +size 48 diff --git a/tasks/lai2021/gurobi_solution_log/large_log_4.jsonl b/tasks/lai2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d3e6f0829fd1db341faba6b8459965a5232d7b9d --- /dev/null +++ b/tasks/lai2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75dcbfd98334a73d8a8a3ac8b25f14895e4fa3ab5b91242be82c2de7b5e88608 +size 45 diff --git a/tasks/lai2021/gurobi_solution_log/large_log_5.jsonl b/tasks/lai2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e402e3a2afe21fb21043edb08d254379125512b3 --- /dev/null +++ b/tasks/lai2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ad442217f50896dcb22ce20b558d7531ddde642d88d969125e8285a866bdf53 +size 55 diff --git a/tasks/lai2021/gurobi_solution_log/tiny_log.jsonl b/tasks/lai2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..668f78029c5777493c99ef55f7a120e86cf81a89 --- /dev/null +++ b/tasks/lai2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af85ee606471cd06342f21fe1459f889623191630e99adfc6ceb759e90bd5be8 +size 48 diff --git a/tasks/lai2021/instance/large_instance_1.json b/tasks/lai2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c6796d9449dc5f07b3f27c71fdf798b8b201b2e9 --- /dev/null +++ b/tasks/lai2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a5a754bef625529f3f5ff07361e6c251c014cd17e54bd5bb14342fbd3520e07 +size 391864 diff --git a/tasks/lai2021/instance/large_instance_2.json b/tasks/lai2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6012978c624aa60bd550c71ccd8b7e95f0ada9a0 --- /dev/null +++ b/tasks/lai2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10a66b36cd3b80b2e32eec69cac6a0c8a7e81b5b8bb7b1f3f64c5599faef1989 +size 391798 diff --git a/tasks/lai2021/instance/large_instance_3.json b/tasks/lai2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ee3a9afe420fd8d0451ddbb09648a8b49ddb0a7a --- /dev/null +++ b/tasks/lai2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1fdfab51c0e55c3b1c685f7c4cf7f1f9abb06a245b762dd1bdbf1c1514502fd +size 862490 diff --git a/tasks/lai2021/instance/large_instance_4.json b/tasks/lai2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..143126afb688b1805363c4bface48dda7e13e2d2 --- /dev/null +++ b/tasks/lai2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50c9ef58a05f433bf13563bfeb272384b7717dfc1ab42f63064c6e01aaf5bffb +size 313620 diff --git a/tasks/lai2021/instance/large_instance_5.json b/tasks/lai2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c7bbea32bbe6a5545bdc79802fdec66391f31c01 --- /dev/null +++ b/tasks/lai2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00303f6f2af5991ecfa89de2c7b416341bc14d6c9afae8afe26773e1cd163fdb +size 858838 diff --git a/tasks/lai2021/instance/tiny_instance.json b/tasks/lai2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..e6943e050ebcdeafc5deadf945680e003b6a0e10 --- /dev/null +++ b/tasks/lai2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84dfa2d07c941e53ba484ba532da447d4c352204d85307cddbe8cf72a79918ea +size 1510 diff --git a/tasks/lai2021/instance_schema.json b/tasks/lai2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2d2d06681ce7d9a8f27a55fb24852448c04f3c01 --- /dev/null +++ b/tasks/lai2021/instance_schema.json @@ -0,0 +1,14 @@ +{ + "N": " Total number of elements to be partitioned into groups.", + "m": " Number of groups into which the elements must be partitioned.", + "group_capacities": " Capacity bounds for each group, where each entry contains:", + "group_capacities[*]": { + "L_g": " Minimum number of elements that must be assigned to this group.", + "U_g": " Maximum number of elements that may be assigned to this group." + }, + "distance_type": " Whether pairwise distances are real-valued ('real') or integer-valued ('int').", + "distance_range": " The lower and upper bounds of the range from which pairwise distances are drawn.", + "distances_upper_triangular": " Pairwise distances between all distinct element pairs, stored as the upper triangle of the symmetric distance matrix in row-major order: d(0,1), d(0,2), ..., d(0,N-1), d(1,2), ..., d(N-2,N-1).", + "distance_format": " Description of how the upper-triangular distance entries are ordered.", + "num_distance_entries": " Total number of pairwise distance values stored, equal to N*(N-1)/2." +} diff --git a/tasks/lai2021/mathematical_formulation.md b/tasks/lai2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3bcb0962b03d66698b4102056cf5d2933e0d54d9 --- /dev/null +++ b/tasks/lai2021/mathematical_formulation.md @@ -0,0 +1,36 @@ +# Original Formulation: Maximally Diverse Grouping Problem (MDGP) + +*Source: Neighborhood Decomposition Based Variable Neighborhood Search and Tabu Search for Maximally Diverse Grouping, Xiangjing Lai, Jin-Kao Hao, Zhang-Hua Fu, and Dong Yue, 2021 (quadratic binary program of Gallego, Laguna, Martı́, and Duarte, 2013; Rodrı́guez, Lozano, Garcı́a-Martı́nez, and González-Barrera, 2013).* + +## Sets and Parameters + +- $V$: set of $N$ elements to be partitioned. + +- $m$: number of groups (positive integer), indexed by $g$. + +- $D = [d_{ij}]_{N \times N}$: symmetric distance (dissimilarity) matrix between elements. + +- $L_g$, $U_g$ with $1 \le g \le m$, $L_g \le U_g$: lower and upper capacity limits of group $g$. + +## Decision Variables + +- $X_{ig} \in \{0,1\}$, $\forall i \in \{1,\dots,N\},\; \forall g \in \{1,\dots,m\}$: 1 if element (vertex) $i$ is assigned to group $g$, 0 otherwise. + +## Objective (Quadratic Binary Program) + +$$\begin{align} +\max \quad & \sum_{g=1}^{m} \sum_{i=1}^{N-1} \sum_{j=i+1}^{N} d_{ij}\, X_{ig}\, X_{jg} \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{g=1}^{m} X_{ig} &= 1, + & \forall i \in \{1,\dots,N\}, \tag{2}\\ +L_g \le \sum_{i=1}^{N} X_{ig} &\le U_g, + & \forall g \in \{1,\dots,m\}, \tag{3}\\ +X_{ig} &\in \{0,1\}, + & \forall i \in \{1,\dots,N\},\; \forall g \in \{1,\dots,m\}. \tag{4} +\end{align}$$ + +The objective (1) is the quadratic sum of the pairwise distances within each group, which must be maximized. Constraints (2) guarantee that every vertex is placed in exactly one group. Constraints (3) ensure that the size of group $g$ lies within the interval $[L_g, U_g]$. Constraints (4) are the binary restrictions on the assignment variables. **The products $X_{ig}\,X_{jg}$ in (1) make the formulation a genuine 0–1 quadratic program, left in its original nonlinear form here.** diff --git a/tasks/lai2021/problem_description.txt b/tasks/lai2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..65608749601cb431c53f89067f27f69263e513e0 --- /dev/null +++ b/tasks/lai2021/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +A collection of N elements is given, together with a symmetric distance measure between every pair of distinct elements, yielding N times (N minus one) divided by two pairwise distances, all of which are nonnegative. The elements must be partitioned into exactly m groups. Each of the m groups has a specified lower capacity limit and an upper capacity limit on the number of elements it may contain. Every element must be placed in exactly one group, and the number of elements assigned to any group must fall between that group's lower and upper capacity limits, inclusive. The goal is to assign all elements to groups so as to maximize the total diversity, defined as the sum, over all groups, of the pairwise distances between every pair of elements that belong to the same group. Equivalently, for each group, every pair of co-assigned elements contributes their pairwise distance to the objective, and the objective is the grand total of all such within-group pairwise distances across all groups. + +The input data consists of the total number of elements N, the number of groups m, a lower capacity limit and an upper capacity limit for each of the m groups, and the pairwise distance between every pair of distinct elements stored as the upper triangle of a symmetric distance matrix in row-major order. diff --git a/tasks/lai2021/solution_logger.py b/tasks/lai2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/lai2021/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/lai2021/solution_schema.json b/tasks/lai2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b2e6b98214fb435f98fdd20d4e676f573e6d2b66 --- /dev/null +++ b/tasks/lai2021/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total diversity score, computed as the sum of pairwise distances between all pairs of elements assigned to the same group, across all groups.", + "assignment": " Group to which each element is assigned, where keys are zero-indexed element identifiers and values are zero-indexed group identifiers.", + "groups": " List of elements assigned to each group, where keys are zero-indexed group identifiers and values are sorted lists of zero-indexed element identifiers." +} diff --git a/tasks/laporte2003/feasibility_check.py b/tasks/laporte2003/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a9267a0b8768e06025939703e3aafec5cf446df9 --- /dev/null +++ b/tasks/laporte2003/feasibility_check.py @@ -0,0 +1,605 @@ +""" +Feasibility checker for the Undirected Traveling Purchaser Problem (TPP). + +Based on: Laporte, Riera-Ledesma, and Salazar-González (2003) +"A Branch-and-Cut Algorithm for the Undirected Traveling Purchaser Problem" +Operations Research 51(6):940–951 + +Checks hard constraints (2)–(9) from the mathematical formulation, plus an +objective-consistency check (constraint index 10). + +Constraint (10) — Objective consistency (Tier C defense): + Recompute the objective value (1) directly from the solution variables + w = sum_{e in E} c_e x_e + sum_{p_k in K} sum_{v_i in M_k} b_ki z_ki + and reject the solution as infeasible when the reported + `objective_value` disagrees with the recomputed value. The TPP solution + carries every variable the objective depends on — the traversed edges + `tour_edges` (x_e) and the `purchases` (z_ki) — so this is an exact + full recompute, not a lower bound. This blocks LLM score-gaming + exploits that fabricate `objective_value` while keeping the + routes/purchases technically feasible. +""" + +import argparse +import json +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'purchases', 'tour', 'tour_edges', 'visited_markets') +_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: + 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(instance_path): + """Load a TPP instance from JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + + n_vertices = data["num_vertices"] + n_products = data["num_products"] + depot = data["depot"] + supply_type = data["supply_type"] + + V = list(range(n_vertices)) + M = [v for v in V if v != depot] + + # travel_costs: key "i,j" (i cost + travel_costs = {} + for key, cost in data["travel_costs"].items(): + i, j = map(int, key.split(",")) + travel_costs[(min(i, j), max(i, j))] = cost + + # product_demands: list indexed by product index + demands = data["product_demands"] + + # product_markets: key str(product) -> list of market indices + product_markets = {} + for k_str, markets in data["product_markets"].items(): + product_markets[int(k_str)] = markets + + # purchase_costs: key "market,product" -> cost + # Store as purchase_costs[product][market] = cost + purchase_costs = {} + for key, cost in data["purchase_costs"].items(): + parts = key.split(",") + market = int(parts[0]) + product = int(parts[1]) + if product not in purchase_costs: + purchase_costs[product] = {} + purchase_costs[product][market] = cost + + # supplies: key "product,market" -> quantity + # Store as supplies[product][market] = quantity + supplies = {} + if supply_type == "unlimited": + for k in range(n_products): + supplies[k] = {} + for i in product_markets.get(k, []): + supplies[k][i] = demands[k] + else: + for key, val in data.get("supplies", {}).items(): + parts = key.split(",") + product = int(parts[0]) + market = int(parts[1]) + if product not in supplies: + supplies[product] = {} + supplies[product][market] = val + + return { + "n_vertices": n_vertices, + "n_markets": data["num_markets"], + "n_products": n_products, + "depot": depot, + "supply_type": supply_type, + "V": V, + "M": M, + "travel_costs": travel_costs, + "demands": demands, + "product_markets": product_markets, + "purchase_costs": purchase_costs, + "supplies": supplies, + } + + +def load_solution(solution_path): + """Load a TPP solution from JSON file.""" + with open(solution_path, 'r') as f: + return json.load(f) + + +def compute_mandatory_sets(inst): + """Compute M* (mandatory markets) and K* (products without market choice).""" + depot = inst["depot"] + n_products = inst["n_products"] + demands = inst["demands"] + product_markets = inst["product_markets"] + supplies = inst["supplies"] + + # M* = {v_0} union {v_i in M : exists p_k such that sum_{j in M_k \ {i}} q_kj < d_k} + M_star = {depot} + for i in inst["M"]: + for k in range(n_products): + if i in product_markets.get(k, []): + total_without_i = sum( + supplies.get(k, {}).get(j, 0) + for j in product_markets.get(k, []) if j != i + ) + if total_without_i < demands[k]: + M_star.add(i) + break + + # K* = {p_k : sum_{i in M_k} q_ki = d_k} + K_star = set() + for k in range(n_products): + total = sum(supplies.get(k, {}).get(i, 0) for i in product_markets.get(k, [])) + if total == demands[k]: + K_star.add(k) + + return M_star, K_star + + +def check_feasibility(inst, sol): + """ + Check all hard constraints (2)-(9) of the TPP formulation, plus the + objective-consistency constraint (10). + + Returns a dict with feasibility result. + """ + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_constraints_set = set() + + depot = inst["depot"] + n_vertices = inst["n_vertices"] + n_products = inst["n_products"] + V = inst["V"] + M = inst["M"] + demands = inst["demands"] + product_markets = inst["product_markets"] + supplies = inst["supplies"] + travel_costs = inst["travel_costs"] + purchase_costs = inst["purchase_costs"] + + M_star, K_star = compute_mandatory_sets(inst) + + # --- Extract solution variables --- + + # y_i: whether market i is visited (1 if visited, 0 otherwise) + visited_markets = set(sol.get("visited_markets", [])) + y = {} + y[depot] = 1 # depot always visited + for i in M: + y[i] = 1 if i in visited_markets else 0 + + # x_e: edge variables from tour_edges + tour_edges = sol.get("tour_edges", []) + x = defaultdict(int) + for edge in tour_edges: + e = (min(edge[0], edge[1]), max(edge[0], edge[1])) + x[e] = 1 + + # z_ki: purchase quantities + # sol["purchases"] is {str(product): {str(market): quantity}} + z = {} + for k in range(n_products): + z[k] = {} + for k_str, market_dict in sol.get("purchases", {}).items(): + k = int(k_str) + for m_str, qty in market_dict.items(): + m = int(m_str) + z[k][m] = float(qty) + + def add_violation(constraint_idx, message, lhs, rhs): + """Record a constraint violation.""" + if constraint_idx == 2: + # = constraint: violation = |lhs - rhs| + violation_amount = abs(lhs - rhs) + elif constraint_idx == 3: + # >= constraint: violation = max(0, rhs - lhs) + violation_amount = max(0.0, rhs - lhs) + elif constraint_idx == 4: + # = constraint: violation = |lhs - rhs| + violation_amount = abs(lhs - rhs) + elif constraint_idx == 5: + # <= constraint: violation = max(0, lhs - rhs) + violation_amount = max(0.0, lhs - rhs) + elif constraint_idx == 6: + # binary: violation = deviation from {0,1} + violation_amount = abs(lhs - rhs) + elif constraint_idx == 7: + # binary: violation = deviation from {0,1} + violation_amount = abs(lhs - rhs) + elif constraint_idx == 8: + # = 1 constraint: violation = |lhs - 1| + violation_amount = abs(lhs - rhs) + elif constraint_idx == 9: + # >= 0 constraint: violation = max(0, -lhs) + violation_amount = max(0.0, rhs - lhs) + else: + violation_amount = abs(lhs - rhs) + + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(constraint_idx) + violations.append(message) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ========================================================================= + # Constraint (2): Degree constraints + # sum_{e in delta({v_i})} x_e = 2 * y_i for all v_i in V + # ========================================================================= + for v in V: + degree = 0 + for e, val in x.items(): + if val > tol and (e[0] == v or e[1] == v): + degree += val + lhs = degree + rhs = 2.0 * y.get(v, 0) + if abs(lhs - rhs) > tol: + add_violation(2, + f"Degree constraint violated at vertex {v}: " + f"degree={lhs}, 2*y_{v}={rhs}", + lhs, rhs) + + # ========================================================================= + # Constraint (3): Connectivity constraints + # sum_{e in delta(S)} x_e >= 2 * y_i for all S subset M, v_i in S + # + # Instead of enumerating all subsets, we check connectivity of the tour + # restricted to visited vertices + depot. If the subgraph induced by + # visited vertices (with edges from x) is connected, then all connectivity + # constraints are satisfied. + # ========================================================================= + visited_with_depot = visited_markets | {depot} + if len(visited_with_depot) > 1: + # Build adjacency for visited vertices + adj = defaultdict(set) + for e, val in x.items(): + if val > tol and e[0] in visited_with_depot and e[1] in visited_with_depot: + adj[e[0]].add(e[1]) + adj[e[1]].add(e[0]) + + # BFS from depot + reachable = set() + queue = [depot] + reachable.add(depot) + while queue: + node = queue.pop(0) + for neighbor in adj[node]: + if neighbor not in reachable: + reachable.add(neighbor) + queue.append(neighbor) + + # Check if all visited markets are reachable from depot + unreachable = visited_with_depot - reachable + if unreachable: + # For each unreachable vertex, the connectivity constraint is violated + # S = unreachable set, delta(S) has no edges, but y_i=1 for i in S + # So sum x_e in delta(S) = 0 < 2 * y_i = 2 + for v in unreachable: + lhs = 0.0 + rhs = 2.0 * y.get(v, 0) + if rhs > tol: + add_violation(3, + f"Connectivity violated: vertex {v} not reachable " + f"from depot in tour subgraph", + lhs, rhs) + + # ========================================================================= + # Constraint (4): Product demand satisfaction + # sum_{v_i in M_k} z_ki = d_k for all p_k in K + # ========================================================================= + for k in range(n_products): + total_purchased = sum(z.get(k, {}).values()) + lhs = total_purchased + rhs = float(demands[k]) + if abs(lhs - rhs) > tol: + add_violation(4, + f"Demand not satisfied for product {k}: " + f"purchased={lhs}, demand={rhs}", + lhs, rhs) + + # ========================================================================= + # Constraint (5): Purchase only at visited markets with supply limits + # z_ki <= q_ki * y_i for all p_k in K, v_i in M_k + # ========================================================================= + for k in range(n_products): + for m, qty in z.get(k, {}).items(): + if qty > tol: + q_ki = supplies.get(k, {}).get(m, 0) + y_i = y.get(m, 0) + lhs = float(qty) + rhs = float(q_ki * y_i) + if lhs - rhs > tol: + if y_i == 0: + msg = (f"Product {k} purchased at unvisited market {m}: " + f"z={lhs}, q*y={rhs}") + else: + msg = (f"Product {k} purchase exceeds supply at market {m}: " + f"z={lhs}, q*y={rhs}") + add_violation(5, msg, lhs, rhs) + + # ========================================================================= + # Constraint (6): Binary edge variables + # x_e in {0, 1} for all e in E + # ========================================================================= + for e, val in x.items(): + if abs(val - 0) > tol and abs(val - 1) > tol: + nearest = 0.0 if val < 0.5 else 1.0 + add_violation(6, + f"Edge {e} has non-binary value x={val}", + float(val), nearest) + + # ========================================================================= + # Constraint (7): Binary vertex selection for non-mandatory markets + # y_i in {0, 1} for all v_i in M \ M* + # ========================================================================= + for i in M: + if i not in M_star: + yi = y.get(i, 0) + if abs(yi - 0) > tol and abs(yi - 1) > tol: + nearest = 0.0 if yi < 0.5 else 1.0 + add_violation(7, + f"Market {i} (non-mandatory) has non-binary y={yi}", + float(yi), nearest) + + # ========================================================================= + # Constraint (8): Mandatory market visits + # y_i = 1 for all v_i in M* + # ========================================================================= + for i in M_star: + yi = y.get(i, 0) + lhs = float(yi) + rhs = 1.0 + if abs(lhs - rhs) > tol: + add_violation(8, + f"Mandatory market {i} not visited: y={yi}", + lhs, rhs) + + # ========================================================================= + # Constraint (9): Non-negativity of purchase quantities + # z_ki >= 0 for all p_k in K, v_i in M_k + # ========================================================================= + for k in range(n_products): + for m in product_markets.get(k, []): + z_ki = z.get(k, {}).get(m, 0.0) + lhs = float(z_ki) + rhs = 0.0 + if lhs < -tol: + add_violation(9, + f"Negative purchase: z_{k},{m} = {lhs}", + lhs, rhs) + + # ========================================================================= + # Constraint (10): Objective consistency [Tier C defense] + # reported objective_value must equal the objective (1) recomputed + # from the solution variables: + # w = sum_{e in E} c_e x_e + sum_{p_k in K} sum_{v_i in M_k} b_ki z_ki + # Travel costs are read with the same key convention as load_instance + # (travel_costs[(min,max)]); purchase costs with purchase_costs[k][m]. + # The TPP solution carries every objective-determining variable + # (tour_edges -> x_e, purchases -> z_ki), so this is an exact full + # recompute. Rejecting on mismatch blocks fabricated objective values. + # ========================================================================= + 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: + true_route = sum( + travel_costs.get(e, 0) + for e, val in x.items() if val > tol + ) + true_purchase = sum( + purchase_costs.get(k, {}).get(m, 0) * zq + for k in z + for m, zq in z[k].items() + ) + true_obj = float(true_route + true_purchase) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + add_violation(10, + f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_e(c_e*x_e)+sum_ki(b_ki*z_ki)={true_obj} " + f"(routing={true_route}, purchase={true_purchase}, " + f"|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported, true_obj) + + # Build result + feasible = len(violated_constraints_set) == 0 + violated_constraints = sorted(violated_constraints_set) + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the Undirected Traveling Purchaser Problem (TPP)." + ) + parser.add_argument("--instance_path", required=True, + help="Path to the JSON file containing the data instance.") + parser.add_argument("--solution_path", required=True, + help="Path to the JSON file containing the candidate solution.") + parser.add_argument("--result_path", required=True, + help="Path to write the JSON file containing the feasibility result.") + args = parser.parse_args() + + inst = load_instance(args.instance_path) + sol = load_solution(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(inst, sol) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE.") + 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/laporte2003/gurobi_code.py b/tasks/laporte2003/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c54aab22676d05acd11be6d15f26d25fece56862 --- /dev/null +++ b/tasks/laporte2003/gurobi_code.py @@ -0,0 +1,477 @@ +""" +Gurobi MIP implementation for the Undirected Traveling Purchaser Problem (TPP). + +Based on: Laporte, Riera-Ledesma, and Salazar-Gonzalez (2003) +"A Branch-and-Cut Algorithm for the Undirected Traveling Purchaser Problem" +Operations Research 51(6):940-951 + +Implements the ILP formulation (1)-(9) with: + - Lazy connectivity constraints (3) via callback + - Valid inequalities (10), (14) added upfront for strengthening +""" + +import argparse +import json +import time +import sys +from itertools import combinations + +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 + + +def load_instance(instance_path): + """Load a TPP instance from JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + + n_vertices = data["num_vertices"] + n_markets = data["num_markets"] + n_products = data["num_products"] + depot = data["depot"] + supply_type = data["supply_type"] + + # Build vertex set V = {0, 1, ..., n_vertices-1} + V = list(range(n_vertices)) + # Markets M = V \ {depot} + M = [v for v in V if v != depot] + + # Travel costs: symmetric, stored as "i,j" with i < j + travel_costs = {} + for key, cost in data["travel_costs"].items(): + i, j = map(int, key.split(",")) + travel_costs[(min(i, j), max(i, j))] = cost + + # Edge set E = {(i,j) : i < j, i,j in V} + E = [(i, j) for i in V for j in V if i < j] + + # Edge costs + c = {e: travel_costs.get(e, 0) for e in E} + + # Product demands + demands = data["product_demands"] # list of length n_products + + # Product markets: product k -> list of markets where it can be purchased + product_markets = {} + for k_str, markets in data["product_markets"].items(): + product_markets[int(k_str)] = markets + + # Purchase costs: b[k][i] = cost of product k at market i + purchase_costs = {} + for key, cost in data["purchase_costs"].items(): + parts = key.split(",") + market = int(parts[0]) + product = int(parts[1]) + if product not in purchase_costs: + purchase_costs[product] = {} + purchase_costs[product][market] = cost + + # Supplies: q[k][i] = supply of product k at market i + supplies = {} + if supply_type == "unlimited": + # Unlimited supply: q_{ki} = d_k for all k, i in M_k + for k in range(n_products): + supplies[k] = {} + for i in product_markets[k]: + supplies[k][i] = demands[k] + else: + for key, val in data["supplies"].items(): + parts = key.split(",") + product = int(parts[0]) + market = int(parts[1]) + if product not in supplies: + supplies[product] = {} + supplies[product][market] = val + + return { + "n_vertices": n_vertices, + "n_markets": n_markets, + "n_products": n_products, + "depot": depot, + "supply_type": supply_type, + "V": V, + "M": M, + "E": E, + "c": c, + "demands": demands, + "product_markets": product_markets, + "purchase_costs": purchase_costs, + "supplies": supplies, + } + + +def compute_mandatory_sets(inst): + """ + Compute M* (mandatory markets) and K* (products without market choice). + M* = {v_0} union {v_i in M : exists p_k in K such that sum_{v_j in M_k \\ {v_i}} q_{kj} < d_k} + K* = {p_k in K : sum_{v_i in M_k} q_{ki} = d_k} + """ + depot = inst["depot"] + n_products = inst["n_products"] + demands = inst["demands"] + product_markets = inst["product_markets"] + supplies = inst["supplies"] + + M_star = {depot} + for i in inst["M"]: + for k in range(n_products): + if i in product_markets[k]: + total_without_i = sum( + supplies[k].get(j, 0) + for j in product_markets[k] + if j != i + ) + if total_without_i < demands[k]: + M_star.add(i) + break + + K_star = set() + for k in range(n_products): + total = sum(supplies[k].get(i, 0) for i in product_markets[k]) + if total == demands[k]: + K_star.add(k) + + return M_star, K_star + + +def find_connected_components(vertices, edges_used): + """Find connected components given a set of vertices and edges.""" + adj = {v: [] for v in vertices} + for (i, j) in edges_used: + if i in adj and j in adj: + adj[i].append(j) + adj[j].append(i) + + visited = set() + components = [] + for v in vertices: + if v not in visited: + comp = [] + stack = [v] + while stack: + u = stack.pop() + if u in visited: + continue + visited.add(u) + comp.append(u) + for w in adj[u]: + if w not in visited: + stack.append(w) + components.append(set(comp)) + return components + + +def solve_tpp(inst, time_limit): + """Solve the TPP using Gurobi with branch-and-cut.""" + V = inst["V"] + M = inst["M"] + E = inst["E"] + c = inst["c"] + n_products = inst["n_products"] + demands = inst["demands"] + product_markets = inst["product_markets"] + purchase_costs = inst["purchase_costs"] + supplies = inst["supplies"] + depot = inst["depot"] + + M_star, K_star = compute_mandatory_sets(inst) + + # Create Gurobi model + model = gp.Model("TPP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("LazyConstraints", 1) + + # Decision variables + # x[e] = 1 if edge e is in the solution + x = {} + for e in E: + x[e] = model.addVar(vtype=GRB.BINARY, name=f"x_{e[0]}_{e[1]}") + + # y[i] = 1 if market i is visited + y = {} + for i in V: + if i in M_star: + y[i] = model.addVar(vtype=GRB.BINARY, lb=1.0, ub=1.0, name=f"y_{i}") + elif i == depot: + y[i] = model.addVar(vtype=GRB.BINARY, lb=1.0, ub=1.0, name=f"y_{i}") + else: + y[i] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}") + + # z[k][i] = amount of product k purchased at market i + z = {} + for k in range(n_products): + z[k] = {} + for i in product_markets[k]: + if k in K_star: + # Fixed: z_{ki} = q_{ki} + z[k][i] = model.addVar( + vtype=GRB.CONTINUOUS, + lb=supplies[k][i], + ub=supplies[k][i], + name=f"z_{k}_{i}", + ) + else: + z[k][i] = model.addVar( + vtype=GRB.CONTINUOUS, + lb=0.0, + ub=supplies[k].get(i, 0), + name=f"z_{k}_{i}", + ) + + model.update() + + # Objective (1): min sum c_e * x_e + sum b_{ki} * z_{ki} + obj = gp.LinExpr() + for e in E: + obj += c[e] * x[e] + for k in range(n_products): + for i in product_markets[k]: + b_ki = purchase_costs.get(k, {}).get(i, 0) + obj += b_ki * z[k][i] + model.setObjective(obj, GRB.MINIMIZE) + + # Helper: edges incident to vertex i -> delta({v_i}) + def delta_vertex(i): + return [e for e in E if i in e] + + # Helper: edges in delta(S) for a subset S + def delta_set(S): + S_set = set(S) + return [e for e in E if (e[0] in S_set) != (e[1] in S_set)] + + # Constraint (2): degree constraints + for i in V: + inc_edges = delta_vertex(i) + model.addConstr( + gp.quicksum(x[e] for e in inc_edges) == 2 * y[i], + name=f"degree_{i}", + ) + + # Constraint (4): demand satisfaction + for k in range(n_products): + model.addConstr( + gp.quicksum(z[k][i] for i in product_markets[k]) == demands[k], + name=f"demand_{k}", + ) + + # Constraint (5): products can only be purchased at visited markets + for k in range(n_products): + for i in product_markets[k]: + q_ki = supplies[k].get(i, 0) + model.addConstr(z[k][i] <= q_ki * y[i], name=f"supply_{k}_{i}") + + # Valid inequality (10): x_{v0,vj} <= y_j + for j in M: + e = (min(depot, j), max(depot, j)) + if e in x: + model.addConstr(x[e] <= y[j], name=f"trivial_{j}") + + # Valid inequality (14) with S = M_k for each product k + # sum_{e in delta(S)} x_e >= 2 for S = M_k + # Condition: sum_{v_i in M_k \ S} q_{ki} < d_k, which with S = M_k gives + # sum over empty set = 0 < d_k, so the condition always holds. + # This ensures the tour must enter/leave the set of markets selling product k. + for k in range(n_products): + Mk = set(product_markets[k]) + S = Mk + if S: + delta_S = delta_set(S) + if delta_S: + model.addConstr( + gp.quicksum(x[e] for e in delta_S) >= 2, + name=f"cover_{k}", + ) + + # Callback for lazy connectivity constraints (3) + def subtour_callback(model, where): + if where == GRB.Callback.MIPSOL: + x_vals = model.cbGetSolution(x) + y_vals = model.cbGetSolution(y) + + # Find edges used in the solution + edges_used = [e for e in E if x_vals[e] > 0.5] + # Find visited vertices + visited = [v for v in V if y_vals[v] > 0.5] + + if len(visited) < 2: + return + + # Find connected components among visited vertices + components = find_connected_components(visited, edges_used) + + # If all visited vertices are connected (single component with depot), OK + if len(components) == 1 and depot in components[0]: + return + + # For each component not containing the depot, add subtour elimination + for comp in components: + if depot not in comp: + # Constraint (3): sum_{e in delta(S)} x_e >= 2 y_i for all v_i in S + S = comp + delta_S = delta_set(S) + for i in S: + if i in y: + model.cbLazy( + gp.quicksum(x[e] for e in delta_S) >= 2 * y[i] + ) + + # Solve + model.optimize(subtour_callback) + + # Extract solution + result = {"objective_value": None, "status": None} + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + # Extract visited markets + visited_markets = [i for i in M if y[i].X > 0.5] + result["visited_markets"] = visited_markets + + # Extract tour edges + tour_edges = [(e[0], e[1]) for e in E if x[e].X > 0.5] + result["tour_edges"] = tour_edges + + # Extract purchase assignments + purchases = {} + for k in range(n_products): + purchases[k] = {} + for i in product_markets[k]: + val = z[k][i].X + if val > 1e-6: + purchases[k][i] = val + result["purchases"] = { + str(k): {str(i): v for i, v in mk.items()} + for k, mk in purchases.items() + } + + # Compute routing cost and purchase cost breakdown + routing_cost = sum(c[e] * x[e].X for e in E) + purchase_cost = sum( + purchase_costs.get(k, {}).get(i, 0) * z[k][i].X + for k in range(n_products) + for i in product_markets[k] + ) + result["routing_cost"] = routing_cost + result["purchase_cost"] = purchase_cost + + # Extract tour order + if tour_edges: + adj = {} + for (i, j) in tour_edges: + adj.setdefault(i, []).append(j) + adj.setdefault(j, []).append(i) + tour = [depot] + prev = -1 + cur = depot + while True: + neighbors = adj.get(cur, []) + next_v = None + for n in neighbors: + if n != prev: + next_v = n + break + if next_v is None or next_v == depot: + break + tour.append(next_v) + prev = cur + cur = next_v + result["tour"] = tour + else: + result["status"] = "infeasible" + result["objective_value"] = None + + result["solve_time"] = model.Runtime + result["mip_gap"] = model.MIPGap if model.SolCount > 0 else None + result["num_nodes"] = int(model.NodeCount) + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi MIP solver for the Undirected Traveling Purchaser Problem" + ) + parser.add_argument( + "--instance_path", type=str, required=True, help="Path to the JSON instance file" + ) + parser.add_argument( + "--solution_path", + type=str, + default="gurobi_solution_1.json", + help="Path for the output solution JSON file", + ) + 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) + + print(f"Loading instance from: {args.instance_path}") + inst = load_instance(args.instance_path) + print( + f"Instance: {inst['n_vertices']} vertices, {inst['n_markets']} markets, " + f"{inst['n_products']} products, supply_type={inst['supply_type']}" + ) + + M_star, K_star = compute_mandatory_sets(inst) + print(f"Mandatory markets |M*| = {len(M_star)}, Fixed products |K*| = {len(K_star)}") + + print(f"Solving with time limit = {args.time_limit} seconds...") + result = solve_tpp(inst, args.time_limit) + + print(f"\n--- Results ---") + print(f"Status: {result['status']}") + print(f"Objective value: {result['objective_value']}") + if result["objective_value"] is not None: + print(f"Routing cost: {result.get('routing_cost', 'N/A')}") + print(f"Purchase cost: {result.get('purchase_cost', 'N/A')}") + print(f"Visited markets: {result.get('visited_markets', [])}") + print(f"Tour: {result.get('tour', [])}") + print(f"Solve time: {result['solve_time']:.2f}s") + print(f"MIP gap: {result.get('mip_gap', 'N/A')}") + print(f"Nodes explored: {result.get('num_nodes', 'N/A')}") + + # Save solution + output = { + "objective_value": result["objective_value"], + "status": result["status"], + "solve_time": result["solve_time"], + "mip_gap": result.get("mip_gap"), + "num_nodes": result.get("num_nodes"), + "visited_markets": result.get("visited_markets", []), + "tour": result.get("tour", []), + "tour_edges": result.get("tour_edges", []), + "purchases": result.get("purchases", {}), + "routing_cost": result.get("routing_cost"), + "purchase_cost": result.get("purchase_cost"), + } + + with open(args.solution_path, "w") as f: + output["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(output, f, indent=2) + + print(f"\nSolution saved to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/laporte2003/gurobi_feasi_result/large_feasi_result_1.json b/tasks/laporte2003/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/laporte2003/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/laporte2003/gurobi_feasi_result/large_feasi_result_2.json b/tasks/laporte2003/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/laporte2003/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/laporte2003/gurobi_feasi_result/large_feasi_result_3.json b/tasks/laporte2003/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/laporte2003/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/laporte2003/gurobi_feasi_result/large_feasi_result_4.json b/tasks/laporte2003/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/laporte2003/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/laporte2003/gurobi_feasi_result/large_feasi_result_5.json b/tasks/laporte2003/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/laporte2003/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/laporte2003/gurobi_feasi_result/tiny_feasi_result.json b/tasks/laporte2003/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/laporte2003/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/laporte2003/gurobi_solution/large_solution_1.json b/tasks/laporte2003/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e5c2079a623088796ff60ec2e27a7ef4fc47d929 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30282bfd889d1dea1e93c67f181ac23fa05fae9f9a89e3ad003d21fa983aeaa6 +size 14950 diff --git a/tasks/laporte2003/gurobi_solution/large_solution_2.json b/tasks/laporte2003/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f4259e3fc2de62b0f770cf81ec52719996498c99 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36c241ffee9f1da4e7035d4c3bbb3d29caae14552442dbfb5c76c808427fcfe7 +size 58897 diff --git a/tasks/laporte2003/gurobi_solution/large_solution_3.json b/tasks/laporte2003/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ea0fee702bc2ee780a4895e37afaf6b4cd3b54c2 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38f447792e1398d34a3c4f2e9dee4f8cc43642d661f62614d3b3009fbe3cd4a7 +size 7643 diff --git a/tasks/laporte2003/gurobi_solution/large_solution_4.json b/tasks/laporte2003/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f8b97afb7f6aae79a7825fb9f1c7bde7ee58ea86 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd42b180185bab8de121817f78a871ad6bdab2a9e7f01874e077d902b27f3b64 +size 4339 diff --git a/tasks/laporte2003/gurobi_solution/large_solution_5.json b/tasks/laporte2003/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a9314eecd3eaf2466d83a0176f0ea0932518d5fe --- /dev/null +++ b/tasks/laporte2003/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c820ff0dea9dc528e1bbe0eff902c509c5edba2e59de251f63fdb1528992a30 +size 4364 diff --git a/tasks/laporte2003/gurobi_solution/tiny_solution.json b/tasks/laporte2003/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..376af5ca030d2a9fa6c94b546870fd1174f50f7d --- /dev/null +++ b/tasks/laporte2003/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d848b11437348f2ca3e418c27e1ee5e20d301b65d15ffaa455c0758140573bc7 +size 2565 diff --git a/tasks/laporte2003/gurobi_solution_log/large_log_1.jsonl b/tasks/laporte2003/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..589c1ac7f8b187da7b1276017c3f8bc40b49048a --- /dev/null +++ b/tasks/laporte2003/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25d10c2c9b420da08684b1d7a327a0b3115f1ff8e2982ee11a884f4ab7ba03e2 +size 230 diff --git a/tasks/laporte2003/gurobi_solution_log/large_log_2.jsonl b/tasks/laporte2003/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b8a9e8135ae5d96fda2eea8c24ec8701f4e8763e --- /dev/null +++ b/tasks/laporte2003/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f2fdd345a250318d8ba6aff621f2ed1fad277b8769263f6d9fb3959d2217491 +size 180 diff --git a/tasks/laporte2003/gurobi_solution_log/large_log_3.jsonl b/tasks/laporte2003/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2576926138aab470d56856896cbf9abd1a1730a1 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a30d33a348d3a1ca551e8d1eadff0b13d1d0fd3316d9739304017ea09f8efda +size 176 diff --git a/tasks/laporte2003/gurobi_solution_log/large_log_4.jsonl b/tasks/laporte2003/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57084a0e863fe4100a1e0dbd784c12bc9c4d5e34 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebc0ffb4c7ce679625b3639586939e16e253622eb5a5412ca7e8bf2ff2d56ca1 +size 174 diff --git a/tasks/laporte2003/gurobi_solution_log/large_log_5.jsonl b/tasks/laporte2003/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f960d4a59bbef08655322afe96486b4aec153ee3 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:058c4d3c3b4880062d455b63fdc13782cbf5ca96f217b54f7388bfab242df31f +size 347 diff --git a/tasks/laporte2003/gurobi_solution_log/tiny_log.jsonl b/tasks/laporte2003/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..26eb47befae1ae9995d0c4b99e8607bdf2e51165 --- /dev/null +++ b/tasks/laporte2003/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d78facfc6ae0333720b7f05b6dfac5b1c39e30276cc3380746232b4573673c3 +size 83 diff --git a/tasks/laporte2003/instance/large_instance_1.json b/tasks/laporte2003/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..76b6c1c761b40f6c09702bc2dfc192490610fb8d --- /dev/null +++ b/tasks/laporte2003/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e8280cd8f23c8fdbdb022fc293f031b5bbbd7a232ec3e76cfea6f8ae8dff02f +size 314992 diff --git a/tasks/laporte2003/instance/large_instance_2.json b/tasks/laporte2003/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..be80e1e4b09e72d9441b3b3b4e1bd652dcd10b30 --- /dev/null +++ b/tasks/laporte2003/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:369125e4c9d6c5f2c37b75e8fc2a30d08e9b383f1a474403c56783e7789e8cbe +size 342214 diff --git a/tasks/laporte2003/instance/large_instance_3.json b/tasks/laporte2003/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..734fbd95239bb8eac8b886a83da82359d8c65746 --- /dev/null +++ b/tasks/laporte2003/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b478583b6cd4c01dc2418d2730908900a94a700cbea83d54c71b8ad66c5fe7c +size 301856 diff --git a/tasks/laporte2003/instance/large_instance_4.json b/tasks/laporte2003/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..04fc89c0b5274b9d9ee7ba18c43b167a8c1b8951 --- /dev/null +++ b/tasks/laporte2003/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbee36c338f16552c9bbfa91950431b6bb5591d0a8da6422e5ae05b67fa4de5d +size 321474 diff --git a/tasks/laporte2003/instance/large_instance_5.json b/tasks/laporte2003/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a4e3bacb0e71e1021d3674a31f22cade5dae7340 --- /dev/null +++ b/tasks/laporte2003/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9fcb229c19545269e4e29ca19ad9e2aaa53b7eae410774b24e1fbae7620b113 +size 290814 diff --git a/tasks/laporte2003/instance/tiny_instance.json b/tasks/laporte2003/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a42a3849ba26e6fdae5a6a16c73adc9e16460109 --- /dev/null +++ b/tasks/laporte2003/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7250727fdaefbf595a037cf70e75fca3ff063346dff6291bd28d617ac32d8dde +size 87887 diff --git a/tasks/laporte2003/instance_schema.json b/tasks/laporte2003/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..aad518b863d9a47eb4a7900c9a1e174cbbd3a38c --- /dev/null +++ b/tasks/laporte2003/instance_schema.json @@ -0,0 +1,13 @@ +{ + "num_vertices": " Total number of vertices including the depot and all markets.", + "num_markets": " Number of markets the purchaser may visit (excludes the depot).", + "num_products": " Number of distinct products that must be purchased.", + "depot": " Index of the depot vertex where the purchaser's round trip starts and ends.", + "coordinates": " X-Y coordinates of each vertex used to derive Euclidean travel costs, or null when travel costs are generated randomly.", + "tau": " Upper bound of the range from which random symmetric travel costs are drawn, or null for Euclidean instances.", + "travel_costs": " Symmetric travel cost for the edge connecting each pair of vertices.", + "product_demands": " Number of units of each product that must be purchased in total.", + "product_markets": " List of market indices where each product is available for purchase.", + "purchase_costs": " Per-unit cost of buying a product at a specific market.", + "supplies": " Maximum number of units of a product available for purchase at a specific market." +} diff --git a/tasks/laporte2003/mathematical_formulation.md b/tasks/laporte2003/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..17a29498f067e44666cdb3b60b2591cb6300959b --- /dev/null +++ b/tasks/laporte2003/mathematical_formulation.md @@ -0,0 +1,69 @@ +# Original Formulation: Undirected Traveling Purchaser Problem + +*Source*: Laporte, Riera-Ledesma, Salazar-González (2003), “A Branch-and-Cut Algorithm for the Undirected Traveling Purchaser Problem,” *Operations Research* 51(6):940–951. Equations (1)–(9) in the paper. + +## Sets and Indices + +- $v_0$: depot vertex. + +- $M = \{v_1, \ldots, v_n\}$: set of markets ($n \ge 4$). + +- $V = \{v_0\} \cup M$: vertex set. + +- $E = \{[v_i,v_j] : v_i,v_j \in V,\ 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/laporte2003/solution_schema.json b/tasks/laporte2003/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0efdd5c4816b2e84f8fd3643bedef96f4733b00a --- /dev/null +++ b/tasks/laporte2003/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Total cost of the purchasing tour, combining travel costs along traversed edges and purchase costs at visited markets.", + "visited_markets": " Markets (excluding the depot) that the purchaser visits during the tour.", + "tour": " Ordered sequence of vertices starting at the depot that describes the traversal order of the closed tour.", + "tour_edges": " Undirected edges traversed by the tour, each given as a pair of endpoint vertices.", + "purchases": " dict, key: '{market}'> Quantity of each product bought at each market along the tour." +} diff --git a/tasks/lee1996/feasibility_check.py b/tasks/lee1996/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..2f5f4bd5da136c7353844833b9a85a2cc626bc89 --- /dev/null +++ b/tasks/lee1996/feasibility_check.py @@ -0,0 +1,580 @@ +""" +Feasibility checker for the Steiner Tree-Star (STS) Problem. + +Checks a candidate solution against all hard constraints from the mathematical +formulation in Lee, Chiu, Ryan (1996). + +Constraints (numbered by formulation order): + (1) sum_j x_{ij} = 1, for each i in M [assignment] + (2) x_{ij} <= u_j, for all i in M, j in N [link to active] + (3) y_{jk} <= u_j, for j < k, j,k in N [edge requires active j] + (4) y_{jk} <= u_k, for j < k, j,k in N [edge requires active k] + (5) sum y_{jk} = sum u_j - 1 [spanning tree count] + (6) subtour elimination (anti-cycle) [no cycles in Steiner tree] + (7) x_{ij} >= 0, for all i,j [non-negativity of x] + (8) y_{jk} >= 0, for j < k, j,k in N [non-negativity of y] + (9) u_j in {0,1}, for j in N [binary domain] + (10) objective consistency: reported objective_value must equal the + objective recomputed from the solution variables + sum_{i,j} c_{ij} x_{ij} + sum_{j 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 check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violated_constraints = set() + violation_magnitudes = [] + + m = instance["target_nodes"]["count"] + n = instance["steiner_nodes"]["count"] + c = instance["cost_matrices"]["assignment_costs"]["matrix"] + d = instance["cost_matrices"]["interconnection_costs"]["matrix"] + b = instance["steiner_nodes"]["node_weights"] + + # ----- Reconstruct decision variables from the solution ----- + # u_j: 1 if Steiner node j is active, 0 otherwise + active_set = set(solution["active_steiner_nodes"]) + u = [1.0 if j in active_set else 0.0 for j in range(n)] + + # x_{ij}: 1 if target i assigned to Steiner j, 0 otherwise + assignments = solution["assignments"] + x = [[0.0] * n for _ in range(m)] + for i_str, j_val in assignments.items(): + i = int(i_str) + j = int(j_val) + if 0 <= i < m and 0 <= j < n: + x[i][j] = 1.0 + + # y_{jk}: 1 if edge (j,k) in Steiner tree, 0 otherwise (j < k) + edges = solution.get("steiner_tree_edges", []) + y = {} + for edge in edges: + j, k = int(edge[0]), int(edge[1]) + jj, kk = min(j, k), max(j, k) + y[(jj, kk)] = 1.0 + + def record_violation(constraint_idx, lhs_val, rhs_val, message): + if constraint_idx == 5 or constraint_idx == 1: + # Equality: violation = |LHS - RHS| + violation_amount = abs(lhs_val - rhs_val) + elif constraint_idx in (3, 4, 2): + # <= : violation = max(LHS - RHS, 0) + violation_amount = max(lhs_val - rhs_val, 0.0) + elif constraint_idx in (7, 8): + # >= : violation = max(RHS - LHS, 0) + violation_amount = max(rhs_val - lhs_val, 0.0) + elif constraint_idx == 6: + # <= : violation = max(LHS - RHS, 0) + violation_amount = max(lhs_val - rhs_val, 0.0) + elif constraint_idx == 9: + # = (binary domain): violation = distance from {0,1} + violation_amount = abs(lhs_val - rhs_val) + elif constraint_idx == 10: + # = (objective consistency): violation = |reported - recomputed| + violation_amount = abs(lhs_val - rhs_val) + else: + violation_amount = abs(lhs_val - rhs_val) + + if violation_amount > tol: + violated_constraints.add(constraint_idx) + violations.append(message) + normalizer = max(abs(rhs_val), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs_val), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ===== Constraint (1): sum_j x_{ij} = 1 for each i in M ===== + for i in range(m): + lhs = sum(x[i][j] for j in range(n)) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation(1, lhs, rhs, + f"Constraint (1): Target {i} assigned to " + f"{lhs:.6f} Steiner nodes (should be exactly 1)") + + # ===== Constraint (2): x_{ij} <= u_j for all i, j ===== + for i in range(m): + for j in range(n): + lhs = x[i][j] + rhs = u[j] + if lhs - rhs > tol: + record_violation(2, lhs, rhs, + f"Constraint (2): Target {i} assigned to " + f"inactive Steiner node {j} " + f"(x[{i}][{j}]={lhs:.6f}, u[{j}]={rhs:.6f})") + + # ===== Constraint (3): y_{jk} <= u_j for j < k ===== + for (jj, kk), y_val in y.items(): + lhs = y_val + rhs = u[jj] + if lhs - rhs > tol: + record_violation(3, lhs, rhs, + f"Constraint (3): Steiner edge ({jj},{kk}) " + f"present but Steiner node {jj} inactive " + f"(y={lhs:.6f}, u[{jj}]={rhs:.6f})") + + # ===== Constraint (4): y_{jk} <= u_k for j < k ===== + for (jj, kk), y_val in y.items(): + lhs = y_val + rhs = u[kk] + if lhs - rhs > tol: + record_violation(4, lhs, rhs, + f"Constraint (4): Steiner edge ({jj},{kk}) " + f"present but Steiner node {kk} inactive " + f"(y={lhs:.6f}, u[{kk}]={rhs:.6f})") + + # ===== Constraint (5): sum y_{jk} = sum u_j - 1 ===== + lhs_5 = sum(y.values()) + rhs_5 = sum(u) - 1.0 + violation_5 = abs(lhs_5 - rhs_5) + if violation_5 > tol: + record_violation(5, lhs_5, rhs_5, + f"Constraint (5): Number of Steiner tree edges " + f"({lhs_5:.6f}) != number of active Steiner nodes " + f"minus 1 ({rhs_5:.6f})") + + # ===== Constraint (6): Anti-cycle (subtour elimination) ===== + # The active Steiner nodes connected by the y edges must form a tree + # (connected and acyclic). We check: + # (a) connectivity among active Steiner nodes + # (b) no cycles (guaranteed if #edges = #active_nodes - 1 AND connected, + # but we also explicitly check subsets) + num_active = int(sum(u)) + num_edges = int(round(lhs_5)) + + if num_active >= 2: + # Build adjacency for active Steiner nodes from y edges + adj = defaultdict(set) + for (jj, kk), y_val in y.items(): + if y_val > 0.5: + adj[jj].add(kk) + adj[kk].add(jj) + + # Check connectivity via BFS among active nodes + active_list = [j for j in range(n) if u[j] > 0.5] + if active_list: + visited = set() + queue = deque([active_list[0]]) + visited.add(active_list[0]) + while queue: + node = queue.popleft() + for nb in adj[node]: + if nb not in visited and u[nb] > 0.5: + visited.add(nb) + queue.append(nb) + + # Check all active nodes are connected + unreached = [j for j in active_list if j not in visited] + if unreached: + # Find connected components for the violation + # Identify the subsets H that violate subtour elimination + # For each disconnected component, the edges within it + # exceed |component| - 1 relative to the full tree constraint + # Report as a subtour/connectivity violation. + all_visited = set() + components = [] + for start in active_list: + if start in all_visited: + continue + comp = set() + q = deque([start]) + comp.add(start) + while q: + nd = q.popleft() + for nb in adj[nd]: + if nb not in comp and u[nb] > 0.5: + comp.add(nb) + q.append(nb) + components.append(comp) + all_visited |= comp + + if len(components) > 1: + # For each component H (size >= 2), check: + # sum_{j 0.5 and jj in comp and kk in comp: + edges_in_comp += 1 + # For a connected component, edges_in_comp should be + # <= |comp| - 1. But since the overall tree is + # disconnected, the constraint (6) is violated for + # a subset H that spans components. + # Report the disconnected tree as violating (6). + # Report once overall + comp_sizes = [len(c) for c in components] + # Use the full active set as H and pick ell from the + # smaller component. The violation: + # sum y in H = num_edges, sum u in H\{ell} = num_active-1 + # The subtour violation for a proper subset: + for comp in components: + if len(comp) >= 2: + comp_list = sorted(comp) + edges_in_comp = 0.0 + for (jj, kk), y_val in y.items(): + if y_val > 0.5 and jj in comp and kk in comp: + edges_in_comp += y_val + ell = comp_list[0] + rhs_6 = sum(u[j] for j in comp_list if j != ell) + lhs_6 = edges_in_comp + # This component is a tree internally, but the + # disconnection means another component also has + # edges = |comp2| - 1, and total edges > + # total_active - 1 is caught by constraint (5). + # However, constraint (6) is about subsets. + # If components are disconnected, pick subset H + # as one component plus one node from another. + # Simplest: report disconnected active Steiner graph + # Use the largest component as H + largest_comp = max(components, key=len) + other_nodes = active_set - largest_comp + if other_nodes: + # Pick H = largest_comp union {one node from other} + extra_node = min(other_nodes) + H = sorted(largest_comp | {extra_node}) + ell = extra_node + edges_in_H = 0.0 + for (jj, kk), y_val in y.items(): + if y_val > 0.5 and jj in set(H) and kk in set(H): + edges_in_H += y_val + rhs_6 = sum(u[j] for j in H if j != ell) + lhs_6 = edges_in_H + if lhs_6 - rhs_6 > tol: + record_violation(6, lhs_6, rhs_6, + f"Constraint (6): Steiner tree is " + f"disconnected ({len(components)} " + f"components among active nodes). " + f"Subtour elimination violated for " + f"H={H}, ell={ell}") + + # Also check for cycles explicitly. + # If edges among active nodes > |active| - 1, there's a cycle. + edges_among_active = 0 + for (jj, kk), y_val in y.items(): + if y_val > 0.5 and u[jj] > 0.5 and u[kk] > 0.5: + edges_among_active += 1 + if edges_among_active > num_active - 1: + # There is a cycle. Find a cycle subset H. + # Use DFS to find a cycle + visited_dfs = set() + parent_dfs = {} + cycle_H = None + for start in active_list: + if start in visited_dfs: + continue + stack = [(start, -1)] + while stack: + nd, par = stack.pop() + if nd in visited_dfs: + # Found a cycle + # Trace back to find H + cycle_H = {nd} + cur = par + while cur != nd and cur != -1: + cycle_H.add(cur) + cur = parent_dfs.get(cur, -1) + if cur == nd: + cycle_H.add(nd) + break + visited_dfs.add(nd) + parent_dfs[nd] = par + for nb in adj[nd]: + if nb != par and u[nb] > 0.5: + stack.append((nb, nd)) + if cycle_H and len(cycle_H) >= 3: + break + + if cycle_H and len(cycle_H) >= 3: + H = sorted(cycle_H) + ell = H[0] + edges_in_H = 0.0 + H_set = set(H) + for (jj, kk), y_val in y.items(): + if y_val > 0.5 and jj in H_set and kk in H_set: + edges_in_H += y_val + rhs_6 = sum(u[j] for j in H if j != ell) + lhs_6 = edges_in_H + if lhs_6 - rhs_6 > tol: + record_violation(6, lhs_6, rhs_6, + f"Constraint (6): Cycle detected among " + f"Steiner nodes. Subtour elimination " + f"violated for H={H}, ell={ell}") + + # ===== Constraint (7): x_{ij} >= 0 ===== + for i in range(m): + for j in range(n): + lhs = x[i][j] + rhs = 0.0 + if rhs - lhs > tol: + record_violation(7, lhs, rhs, + f"Constraint (7): x[{i}][{j}]={lhs:.6f} < 0") + + # ===== Constraint (8): y_{jk} >= 0 ===== + for (jj, kk), y_val in y.items(): + lhs = y_val + rhs = 0.0 + if rhs - lhs > tol: + record_violation(8, lhs, rhs, + f"Constraint (8): y[{jj}][{kk}]={lhs:.6f} < 0") + + # ===== Constraint (9): u_j in {0, 1} ===== + for j in range(n): + u_val = u[j] + # Check that u_val is 0 or 1 + dist_to_binary = min(abs(u_val - 0.0), abs(u_val - 1.0)) + if dist_to_binary > tol: + closest = 0.0 if abs(u_val) < abs(u_val - 1.0) else 1.0 + record_violation(9, u_val, closest, + f"Constraint (9): u[{j}]={u_val:.6f} is not " + f"binary (closest binary value: {closest:.0f})") + + # ===== Constraint (10): Objective consistency (Tier C) ===== + # Recompute the total network cost from the solution variables and reject + # any solution whose reported objective_value disagrees. Every variable + # the objective depends on (u_j, x_{ij}, y_{jk}) is present in the + # solution, so a full recompute is exact. + # obj = sum_{i,j} c_{ij} x_{ij} + sum_{j obj_tol: + record_violation(10, reported, true_obj, + f"Constraint (10): Objective consistency " + f"violated: reported objective_value=" + f"{reported} differs from recomputed total " + f"cost (assignment {assignment_cost:.6f} + " + f"edges {edge_cost:.6f} + activation " + f"{activation_cost:.6f} = {true_obj:.6f}); " + f"|diff|={abs_diff:.6g}, tol={obj_tol:.6g}") + + 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 the Steiner Tree-Star (STS) Problem." + ) + 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 candidate 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) + + if result["feasible"]: + print(f"FEASIBLE: No constraint violations found.") + else: + print(f"INFEASIBLE: {len(result['violated_constraints'])} " + f"constraint(s) violated: {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/lee1996/gurobi_code.py b/tasks/lee1996/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..788b9ac7a4856abc88c3f7a64197e5c85d6c9765 --- /dev/null +++ b/tasks/lee1996/gurobi_code.py @@ -0,0 +1,483 @@ +""" +Gurobi implementation of the Steiner Tree-Star (STS) Problem. + +Based on: + Lee, Chiu, Ryan (1996) "A Branch and Cut Algorithm for a Steiner + Tree-Star Problem", INFORMS Journal on Computing, 8(3):194-201. + +The STS problem connects m target nodes through n Steiner nodes by: + - Assigning each target node to exactly one active Steiner node + - Connecting active Steiner nodes via a spanning tree + - Minimizing: assignment costs + Steiner edge costs + Steiner node fixed costs + +Variables: + x[i,j] in [0,1] : 1 if target i connects to Steiner j + u[j] in {0,1} : 1 if Steiner j is active + y[j,k] >= 0 : 1 if edge (j,k) is in Steiner spanning tree (j < k) + +Only u[j] is declared binary; integrality of x and y follows from the +polyhedral structure (Proposition 1 in the paper). +""" + +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 + + +# --------------------------------------------------------------------------- +# Callback: Lazy subtour elimination constraints (anti-cycle) +# --------------------------------------------------------------------------- + +def subtour_callback(model, where): + """ + Lazy constraint callback for subtour elimination among Steiner nodes. + + When a candidate integer solution is found (MIPSOL), we: + 1. Identify the set of active Steiner nodes S (u_j >= 0.5). + 2. Build the subgraph of S using edges with y_{jk} >= 0.5. + 3. Find connected components of that subgraph. + 4. If there are multiple components (the tree is disconnected), + add a subtour elimination (anti-cycle) constraint for each + component C: + sum_{j 0.5] + else: + # For fractional solutions, use a lower threshold + active = [j for j in range(n) if u_val[j] > 0.01] + + if len(active) <= 1: + return # No subtour possible with 0 or 1 active nodes + + # Build adjacency list for active nodes using edges with positive flow + threshold = 0.5 if is_integer else 0.01 + adj = defaultdict(set) + active_set = set(active) + for j in active: + for k in active: + if j < k and (j, k) in y_val and y_val[j, k] > threshold: + adj[j].add(k) + adj[k].add(j) + + # Find connected components via BFS + visited = set() + components = [] + for start in active: + if start in visited: + continue + component = [] + queue = [start] + visited.add(start) + while queue: + node = queue.pop(0) + component.append(node) + for neighbor in adj[node]: + if neighbor not in visited and neighbor in active_set: + visited.add(neighbor) + queue.append(neighbor) + components.append(component) + + # If all active nodes are in one component, no subtour violation + if len(components) <= 1: + # Even with one component, check if there are cycles within it + # For integer solutions: if edges in component > |component| - 1, there's a cycle + if is_integer and len(components) == 1: + comp = components[0] + comp_set = set(comp) + edge_count = sum( + 1 for j in comp for k in comp if j < k and y_val.get((j, k), 0) > 0.5 + ) + if edge_count > len(comp) - 1: + # There is a cycle; add the anti-cycle constraint + expr = gp.quicksum( + y_vars[j, k] + for j in comp for k in comp if j < k + ) + model.cbLazy(expr <= len(comp) - 1) + return + + # Add a subtour elimination constraint for each component + for comp in components: + if len(comp) < 2: + continue + comp_set = set(comp) + + if is_integer: + # For integer solutions, add SEC: sum y_{jk} for j,k in C <= |C| - 1 + expr = gp.quicksum( + y_vars[j, k] + for j in comp for k in comp if j < k + ) + model.cbLazy(expr <= len(comp) - 1) + else: + # For fractional solutions, add the same constraint form + # Also check if the constraint is actually violated + lhs_val = sum( + y_val.get((min(j, k), max(j, k)), 0) + for idx_j, j in enumerate(comp) + for k in comp[idx_j + 1:] + ) + rhs_val = sum(u_val[j] for j in comp) - 1 + + if lhs_val > rhs_val + 1e-6: + # Pick any ell in comp for the general form: + # sum_{j= 0, 1 if edge (j,k) in Steiner tree + y = {} + for j in range(n): + for k in range(j + 1, n): + y[j, k] = model.addVar( + lb=0.0, ub=1.0, obj=d[j][k], + vtype=GRB.CONTINUOUS, name=f"y_{j}_{k}" + ) + + model.update() + + # ----------------------------------------------------------------------- + # Constraints + # ----------------------------------------------------------------------- + + # (1) Each target node assigned to exactly one Steiner node + for i in range(m): + model.addConstr( + gp.quicksum(x[i, j] for j in range(n)) == 1, + name=f"assign_{i}" + ) + + # (2) Target can only connect to active Steiner node + for i in range(m): + for j in range(n): + model.addConstr(x[i, j] <= u[j], name=f"link_{i}_{j}") + + # (3) Edge requires endpoint j to be active + for j in range(n): + for k in range(j + 1, n): + model.addConstr(y[j, k] <= u[j], name=f"edge_j_{j}_{k}") + + # (4) Edge requires endpoint k to be active + for j in range(n): + for k in range(j + 1, n): + model.addConstr(y[j, k] <= u[k], name=f"edge_k_{j}_{k}") + + # (5) Spanning tree: number of edges = number of active nodes - 1 + model.addConstr( + gp.quicksum(y[j, k] for j in range(n) for k in range(j + 1, n)) + == gp.quicksum(u[j] for j in range(n)) - 1, + name="spanning_tree" + ) + + # ----------------------------------------------------------------------- + # Valid inequalities (11) and (12) added at root + # ----------------------------------------------------------------------- + + # (11) Degree inequality type 1: + # sum_{ell < j} y_{ell,j} + sum_{j < k} y_{j,k} >= u_j + for j in range(n): + lhs = gp.quicksum(y[ell, j] for ell in range(j)) + lhs += gp.quicksum(y[j, k] for k in range(j + 1, n)) + model.addConstr(lhs >= u[j], name=f"degree1_{j}") + + # (12) Degree inequality type 2: + # sum_i x_{ij} + sum_{ell < j} y_{ell,j} + sum_{j < k} y_{j,k} >= 3*u_j + for j in range(n): + lhs = gp.quicksum(x[i, j] for i in range(m)) + lhs += gp.quicksum(y[ell, j] for ell in range(j)) + lhs += gp.quicksum(y[j, k] for k in range(j + 1, n)) + model.addConstr(lhs >= 3 * u[j], name=f"degree2_{j}") + + # ----------------------------------------------------------------------- + # Model parameters + # ----------------------------------------------------------------------- + model.ModelSense = GRB.MINIMIZE + model.Params.LazyConstraints = 1 + + if time_limit is not None: + model.Params.TimeLimit = time_limit + + # Store data on the model for callback access + model._n = n + model._m = m + model._u = u + model._y = y + model._x = x + + return model, x, u, y + + +# --------------------------------------------------------------------------- +# Solution extraction +# --------------------------------------------------------------------------- + +def extract_solution(model, x, u, y, m, n): + """ + Extract the solution from a solved Gurobi model. + + Returns a dictionary suitable for JSON serialization. + """ + sol = {} + + status = model.Status + sol["solver_status"] = status + sol["status_name"] = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.INTERRUPTED: "INTERRUPTED", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + }.get(status, f"OTHER({status})") + + if model.SolCount == 0: + sol["objective_value"] = None + sol["best_bound"] = model.ObjBound if hasattr(model, "ObjBound") else None + sol["solution_count"] = 0 + return sol + + sol["objective_value"] = model.ObjVal + sol["best_bound"] = model.ObjBound + sol["mip_gap"] = model.MIPGap + sol["solution_count"] = model.SolCount + sol["runtime_seconds"] = model.Runtime + sol["node_count"] = int(model.NodeCount) + + # Active Steiner nodes + active_steiners = [] + for j in range(n): + if u[j].X > 0.5: + active_steiners.append(j) + sol["active_steiner_nodes"] = active_steiners + + # Target-to-Steiner assignments + assignments = {} + for i in range(m): + for j in range(n): + if x[i, j].X > 0.5: + assignments[str(i)] = j + break + sol["assignments"] = assignments + + # Steiner tree edges + edges = [] + for j in range(n): + for k in range(j + 1, n): + if y[j, k].X > 0.5: + edges.append([j, k]) + sol["steiner_tree_edges"] = edges + + # Cost breakdown + assignment_cost = sum( + x[i, j].X * x[i, j].Obj for i in range(m) for j in range(n) + ) + tree_cost = sum( + y[j, k].X * y[j, k].Obj for j in range(n) for k in range(j + 1, n) + ) + node_cost = sum(u[j].X * u[j].Obj for j in range(n)) + + sol["cost_breakdown"] = { + "assignment_cost": round(assignment_cost, 6), + "steiner_tree_cost": round(tree_cost, 6), + "steiner_node_cost": round(node_cost, 6), + "total": round(assignment_cost + tree_cost + node_cost, 6), + } + + return sol + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Solve the Steiner Tree-Star (STS) Problem using Gurobi." + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON instance file." + ) + parser.add_argument( + "--solution_path", type=str, default="gurobi_solution_1.json", + help="Path for the output solution JSON file (default: gurobi_solution_1.json)." + ) + parser.add_argument( + "--time_limit", type=int, default=None, + 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) + + # Load instance + with open(args.instance_path, "r") as f: + instance_data = json.load(f) + + m = instance_data["target_nodes"]["count"] + n = instance_data["steiner_nodes"]["count"] + + print(f"Instance: {args.instance_path}") + print(f" Target nodes (m): {m}") + print(f" Steiner nodes (n): {n}") + if args.time_limit is not None: + print(f" Time limit: {args.time_limit}s") + + # Build model + model, x, u, y = build_model(instance_data, time_limit=args.time_limit) + + # Solve with callback + wall_start = time.time() + model.optimize(subtour_callback) + wall_end = time.time() + + print(f"\nSolver finished in {wall_end - wall_start:.2f}s wall-clock time.") + print(f" Status: {model.Status}") + if model.SolCount > 0: + print(f" Objective: {model.ObjVal:.6f}") + print(f" Best bound: {model.ObjBound:.6f}") + print(f" Gap: {model.MIPGap:.6%}") + else: + print(" No feasible solution found.") + + # Extract and save solution + solution = extract_solution(model, x, u, y, m, n) + solution["instance_path"] = args.instance_path + solution["wall_clock_seconds"] = round(wall_end - wall_start, 3) + + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"\nSolution written to: {args.solution_path}") + + return 0 if model.SolCount > 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/lee1996/gurobi_feasi_result/large_feasi_result_1.json b/tasks/lee1996/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lee1996/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/lee1996/gurobi_feasi_result/large_feasi_result_2.json b/tasks/lee1996/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lee1996/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/lee1996/gurobi_feasi_result/large_feasi_result_3.json b/tasks/lee1996/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lee1996/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/lee1996/gurobi_feasi_result/large_feasi_result_4.json b/tasks/lee1996/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lee1996/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/lee1996/gurobi_feasi_result/large_feasi_result_5.json b/tasks/lee1996/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lee1996/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/lee1996/gurobi_feasi_result/tiny_feasi_result.json b/tasks/lee1996/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lee1996/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/lee1996/gurobi_solution/large_solution_1.json b/tasks/lee1996/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..118f28130161b24cb4eddfcb4c5d464a380431d0 --- /dev/null +++ b/tasks/lee1996/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a57de781eb5bbd96f4c6a9eebc3f88b1461934748d495e994564445e38bdc21d +size 3442 diff --git a/tasks/lee1996/gurobi_solution/large_solution_2.json b/tasks/lee1996/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..da6e933b0899fff22333574758b9173b53bf7359 --- /dev/null +++ b/tasks/lee1996/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c437cabe4b5c33ed8f7f1196ac9217587c48139775fa16ef1b83e6e0f2ebd3c7 +size 3336 diff --git a/tasks/lee1996/gurobi_solution/large_solution_3.json b/tasks/lee1996/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..33065ea2f53916b44899d7c05e7f2acd5189e6c6 --- /dev/null +++ b/tasks/lee1996/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64d30af0fcc041398d568ff71d8e8dbe73155241f2ec63d9272c55462dde15bc +size 3392 diff --git a/tasks/lee1996/gurobi_solution/large_solution_4.json b/tasks/lee1996/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..cf32ccb84f5c9ab8ff1b694f3e85f27387fa189d --- /dev/null +++ b/tasks/lee1996/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4afd4559a22f0831373cbe04e81d2aee9d1e1f9cbdb1a22ef2fdf21c63692a3f +size 3242 diff --git a/tasks/lee1996/gurobi_solution/large_solution_5.json b/tasks/lee1996/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d7ccc5123db892ef6ac077fa21df521cf4fe2bee --- /dev/null +++ b/tasks/lee1996/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20a8b2057fd9612af440ff9d5730ef88471cb8a0f62b18889f9f3525b26131cf +size 3363 diff --git a/tasks/lee1996/gurobi_solution/tiny_solution.json b/tasks/lee1996/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..11ba307cd84eb867a5a5e792a28d481873f46814 --- /dev/null +++ b/tasks/lee1996/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71992d5dcf1c37873242ac67a15f71f3192d8b67a4d58809468d33ed2c9fdd1c +size 1627 diff --git a/tasks/lee1996/gurobi_solution_log/large_log_1.jsonl b/tasks/lee1996/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b7f2ccc159bb00722c844ef3cbbf53c5b64fd67d --- /dev/null +++ b/tasks/lee1996/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87dc524100a0b233310201f50ba1697ebe56a988bbec9d23bd937e27ab193618 +size 291 diff --git a/tasks/lee1996/gurobi_solution_log/large_log_2.jsonl b/tasks/lee1996/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4afb92ab0da0bdcd5a26cb536f84a5ec78db878a --- /dev/null +++ b/tasks/lee1996/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:303d8d8c9a0587347d336d8c934c3588ce9d18b61d3ca3644dd91e50da4c0d2c +size 208 diff --git a/tasks/lee1996/gurobi_solution_log/large_log_3.jsonl b/tasks/lee1996/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f310530b5d071159f2173a002bc6d1772a872713 --- /dev/null +++ b/tasks/lee1996/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9097ff84ed11d5bb2e4b5dfd6db10dd0fd908f1d2d4327b60cd3fc8b38c4a43 +size 620 diff --git a/tasks/lee1996/gurobi_solution_log/large_log_4.jsonl b/tasks/lee1996/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f0253aeff619f118e361c611b69f9e99f88b2c0 --- /dev/null +++ b/tasks/lee1996/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fe3bb72376c842d5d1fa5ed9412f84b1d6a6c72a64eba7bdb4d0ca49dcbdf1d +size 208 diff --git a/tasks/lee1996/gurobi_solution_log/large_log_5.jsonl b/tasks/lee1996/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..001b973ccd63b3bda71901b5e1b3a9c201b220c9 --- /dev/null +++ b/tasks/lee1996/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f27e311773f6f5f1413d7d4eeb3e8b87a631069d9fd01c149ca6f533a40efbb2 +size 363 diff --git a/tasks/lee1996/gurobi_solution_log/tiny_log.jsonl b/tasks/lee1996/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92f6188e10c28588a36e2a8941147591323c5546 --- /dev/null +++ b/tasks/lee1996/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcd2cc2745faed505642b54877911aeaa30d148deb3934d1060169d20bee08ef +size 98 diff --git a/tasks/lee1996/instance/large_instance_1.json b/tasks/lee1996/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..8fa2d92d6daa2f930d1d30839dab4a9d42ed0252 --- /dev/null +++ b/tasks/lee1996/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58059ad74e08f5674c289e802849d901e4f61962e15a1dc58fc1f03a0e5a9d8f +size 351475 diff --git a/tasks/lee1996/instance/large_instance_2.json b/tasks/lee1996/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8b20e807cbbe7cea36824953679a38c6434ab4d9 --- /dev/null +++ b/tasks/lee1996/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:468f8429f69f6b30bbc9757e85c93ad24c5d0f958fcb1083e16a45048d711e27 +size 349287 diff --git a/tasks/lee1996/instance/large_instance_3.json b/tasks/lee1996/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1c801af466e7ad85439986126545bc5efdc65165 --- /dev/null +++ b/tasks/lee1996/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d245622afa3c8d10a5f6655750c712eb58e04c086f4d8b0f8274f7d91d0793a +size 351623 diff --git a/tasks/lee1996/instance/large_instance_4.json b/tasks/lee1996/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2305a610a81fb9d66f0b30bac04727eeb9675e4f --- /dev/null +++ b/tasks/lee1996/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae76ee75f30579657a2d71929b1ff6d88a7653d806e5c160ba0524171b81c2e9 +size 350654 diff --git a/tasks/lee1996/instance/large_instance_5.json b/tasks/lee1996/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9472df05307c9a3dbfe43048060967a119e91b6f --- /dev/null +++ b/tasks/lee1996/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da68413f1d76a830a1a73044b401a08261ed3028ea63ac3f30c8ca94589d4e33 +size 351428 diff --git a/tasks/lee1996/instance/tiny_instance.json b/tasks/lee1996/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..3910cf00fc6a126aadfa58c3ebcb99c151dc5980 --- /dev/null +++ b/tasks/lee1996/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb499f9d18c7ba20f690733f6f0c82afb834877c6e2b7ebed11dc66f01cec225 +size 58374 diff --git a/tasks/lee1996/instance_schema.json b/tasks/lee1996/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fa31ccbd5c80278cdbc31f693a7560cacb9ccd2c --- /dev/null +++ b/tasks/lee1996/instance_schema.json @@ -0,0 +1,23 @@ +{ + "parameters": { + "m": " Number of target nodes that must be connected to the network.", + "n": " Number of potential hub sites (Steiner nodes) available for activation." + }, + "target_nodes": { + "count": " Number of target nodes that must be connected to the network.", + "coordinates": " Two-dimensional position of each target node on the Euclidean plane." + }, + "steiner_nodes": { + "count": " Number of potential hub sites (Steiner nodes) available for activation.", + "coordinates": " Two-dimensional position of each Steiner node on the Euclidean plane.", + "node_weights": " Fixed activation cost incurred when each Steiner node is selected for use in the network." + }, + "cost_matrices": { + "assignment_costs": { + "matrix": " Euclidean distance from each target node to each Steiner node, representing the cost of assigning a target node to a Steiner node." + }, + "interconnection_costs": { + "matrix": " Euclidean distance between each pair of Steiner nodes, representing the cost of connecting two active Steiner nodes in the spanning tree." + } + } +} \ No newline at end of file diff --git a/tasks/lee1996/mathematical_formulation.md b/tasks/lee1996/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..c049e13dbede43951472b7a47a8c06e2c7c26e4e --- /dev/null +++ b/tasks/lee1996/mathematical_formulation.md @@ -0,0 +1,58 @@ +# Original Formulation: Steiner Tree-Star Problem (STS) + +*Source*: Lee, Chiu, Ryan (1996), “A Branch and Cut Algorithm for a Steiner Tree-Star Problem,” *INFORMS Journal on Computing* 8(3):194–201. Equations (1)–(9) in the paper. + +## Sets and Indices + +- $M = \{1,\ldots,m\}$: set of target nodes; index $i \in M$. + +- $N = \{1,\ldots,n\}$: set of Steiner nodes; indices $j,k \in N$ (with $jj}} d_{jk}\, y_{jk} + + \sum_{j \in N} b_j\, u_j. + \tag{OBJ} +\end{equation}$$ + +## Constraints + +$$\begin{align} + \sum_{j \in N} x_{ij} &\;=\; 1, + && \forall\, i \in M, \tag{1}\\[2pt] + x_{ij} &\;\le\; u_j, + && \forall\, i \in M,\; j \in N, \tag{2}\\[2pt] + y_{jk} &\;\le\; u_j, + && \forall\, j,k \in N,\; jj}} y_{jk} + &\;=\; \sum_{j \in N} u_j \;-\; 1, \tag{5}\\[2pt] + \sum_{j \in H} \sum_{\substack{k \in H\\k>j}} y_{jk} + &\;\le\; \sum_{j \in H\setminus\{\ell\}} u_j, + && \forall\, \ell \in H,\; H \subset N,\; |H| \ge 3, \tag{6}\\[2pt] + x_{ij} &\;\ge\; 0, + && \forall\, i \in M,\; j \in N, \tag{7}\\[2pt] + y_{jk} &\;\ge\; 0, + && \forall\, j,k \in N,\; j= 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/lee1996/solution_schema.json b/tasks/lee1996/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3bea02d299f18d0e66dc67e471dfdb0df305bb58 --- /dev/null +++ b/tasks/lee1996/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Total network cost, comprising target-to-Steiner assignment costs, spanning tree edge costs, and Steiner node activation costs.", + "active_steiner_nodes": " Indices of the Steiner nodes selected for activation in the network.", + "assignments": " Index of the active Steiner node to which each target node is connected.", + "steiner_tree_edges": " Pairs of active Steiner node indices connected by an edge in the spanning tree." +} diff --git a/tasks/legrain2020/feasibility_check.py b/tasks/legrain2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..99c7da52d17393aae694fe93d5e8692dad309620 --- /dev/null +++ b/tasks/legrain2020/feasibility_check.py @@ -0,0 +1,703 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Nurse Scheduling Problem (INRC-II static) +Based on Legrain, Omer, Rosat (2020) - Formulation (1) + +Hard constraints checked (numbered top-to-bottom in formulation): + Constraint 1 (1b): Flow at source - each nurse has exactly one roster + Constraint 2 (1c): Flow conservation - single assignment per day (H1) + + forbidden shift successions (H3) + Constraint 4 (1e): Skill linking - nurse only performs skills they have (H4) + Constraint 5 (1f): Minimum demand - staffing >= D_{p,sigma} (H2) + Constraint 7 (1h): Integrality of x, y + Constraint 8 (1i): Non-negativity of w, z + Constraint 9 (Tier C): Objective consistency - reported objective_value + must lie within [LB, UB] derived from the schedule + and instance parameters. + +Soft constraints skipped: + Constraint 3 (1d): S6/S7 total assignments / weekends + Constraint 6 (1g): S1 optimal coverage +""" + +import argparse +import json +import math +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'schedule') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('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 _compute_obj_bounds(instance, solution): + """Return (lower_bound, upper_bound) on the total objective implied by the + schedule + instance. The LB is the *exact* minimum obj attainable given the + schedule (every continuous slack at its lower bound, every binary indicator + at its forced value); the UB is a generous instance-derived ceiling that + safely covers any feasible incumbent including LP-suboptimal MIP heuristic + solutions, while remaining finite enough to reject sys.float_info.max-style + exploits.""" + num_nurses = instance["num_nurses"] + num_days = instance["num_days"] + num_weeks = instance["num_weeks"] + nurses = instance["nurses"] + skills_list = instance["skills"] + shifts_data = instance["shifts"] + shift_names = [s["name"] for s in shifts_data] + CS_minus = {s["name"]: s["CS_minus"] for s in shifts_data} + CS_plus = {s["name"]: s["CS_plus"] for s in shifts_data} + demand = instance["demand"] + pw = instance["penalty_weights"] + c_S1 = pw["c_S1"]; c_S2a = pw["c_S2a"]; c_S2b = pw["c_S2b"] + c_S3 = pw["c_S3"]; c_S4 = pw["c_S4"]; c_S5 = pw["c_S5"] + c_S6 = pw["c_S6"]; c_S7 = pw["c_S7"] + + valid_shifts = set(shift_names) + valid_skills = set(skills_list) + + work = [[0] * num_days for _ in range(num_nurses)] + x = {} + skill_used = {} + schedule_by_nurse = { + entry["nurse_id"]: entry["assignments"] + for entry in solution.get("schedule", []) or [] + } + for nid, assignments in schedule_by_nurse.items(): + if not isinstance(nid, int) or nid < 0 or nid >= num_nurses: + continue + seen_days = set() + for a in assignments: + d = a.get("day") + sn = a.get("shift") + sk = a.get("skill") + if d is None or sn is None: + continue + if not (isinstance(d, int) and 0 <= d < num_days): + continue + if sn not in valid_shifts: + continue + if d in seen_days: + continue + seen_days.add(d) + work[nid][d] = 1 + x[(nid, d, sn)] = 1 + if sk in valid_skills: + skill_used[(nid, d, sn)] = sk + + weekends = [] + for m in range(num_weeks): + sat = 7 * m + 5 + sun = 7 * m + 6 + if sat < num_days and sun < num_days: + weekends.append((m, sat, sun)) + + # ----- LB components (tight minimum given the schedule) ----- + actual_y = defaultdict(int) + for (nid, d, sn), sk in skill_used.items(): + actual_y[(d, sn, sk)] += 1 + + s1_total = 0 + for d in range(num_days): + for sn in shift_names: + for sk in skills_list: + D_opt = demand[d][sn][sk]["optimal"] + actual = actual_y.get((d, sn, sk), 0) + s1_total += max(0, D_opt - actual) + + s2a_over = 0 + s2a_under = 0 + for nurse in nurses: + i = nurse["id"] + if not isinstance(i, int) or i < 0 or i >= num_nurses: + continue + cdp = nurse["contract"]["CD_plus"] + cdm = nurse["contract"]["CD_minus"] + for k in range(num_days - cdp): + window_sum = sum(work[i][k + j] for j in range(cdp + 1)) + s2a_over += max(0, window_sum - cdp) + for k in range(num_days): + sw = work[i][0] if k == 0 else max(0, work[i][k] - work[i][k - 1]) + if sw == 0: + continue + for j in range(1, cdm): + if k + j < num_days: + s2a_under += max(0, sw - work[i][k + j]) + + s2b_over = 0 + s2b_under = 0 + for nurse in nurses: + i = nurse["id"] + if not isinstance(i, int) or i < 0 or i >= num_nurses: + continue + for sn in shift_names: + csp = CS_plus[sn] + csm = CS_minus[sn] + x_arr = [x.get((i, k, sn), 0) for k in range(num_days)] + for k in range(num_days - csp): + window_sum = sum(x_arr[k + j] for j in range(csp + 1)) + s2b_over += max(0, window_sum - csp) + for k in range(num_days): + ss = x_arr[0] if k == 0 else max(0, x_arr[k] - x_arr[k - 1]) + if ss == 0: + continue + for j in range(1, csm): + if k + j < num_days: + s2b_under += max(0, ss - x_arr[k + j]) + + s3_over = 0 + s3_under = 0 + for nurse in nurses: + i = nurse["id"] + if not isinstance(i, int) or i < 0 or i >= num_nurses: + continue + crp = nurse["contract"]["CR_plus"] + crm = nurse["contract"]["CR_minus"] + for k in range(num_days - crp): + window_work = sum(work[i][k + j] for j in range(crp + 1)) + s3_over += max(0, 1 - window_work) + for k in range(num_days): + sr = (1 - work[i][0]) if k == 0 else max(0, work[i][k - 1] - work[i][k]) + if sr == 0: + continue + for j in range(1, crm): + if k + j < num_days: + s3_under += max(0, sr - (1 - work[i][k + j])) + + s4_count = 0 + for nurse in nurses: + i = nurse["id"] + if not isinstance(i, int) or i < 0 or i >= num_nurses: + continue + for p in nurse.get("preferences", []) or []: + if x.get((i, p.get("day"), p.get("shift")), 0) == 1: + s4_count += 1 + + s5_total = 0 + for nurse in nurses: + i = nurse["id"] + if not isinstance(i, int) or i < 0 or i >= num_nurses: + continue + for _, sat, sun in weekends: + s5_total += abs(work[i][sat] - work[i][sun]) + + s6_total = 0 + for nurse in nurses: + i = nurse["id"] + if not isinstance(i, int) or i < 0 or i >= num_nurses: + continue + Lm = nurse["contract"]["L_minus"] + Lp = nurse["contract"]["L_plus"] + total_work = sum(work[i]) + s6_total += max(0, Lm - total_work) + max(0, total_work - Lp) + + s7_total = 0 + for nurse in nurses: + i = nurse["id"] + if not isinstance(i, int) or i < 0 or i >= num_nurses: + continue + WEp = nurse["contract"]["WE_plus"] + we_worked_count = 0 + for _, sat, sun in weekends: + if work[i][sat] == 1 or work[i][sun] == 1: + we_worked_count += 1 + s7_total += max(0, we_worked_count - WEp) + + lb = ( + c_S1 * s1_total + + c_S2a * (s2a_over + s2a_under) + + c_S2b * (s2b_over + s2b_under) + + c_S3 * (s3_over + s3_under) + + c_S4 * s4_count + + c_S5 * s5_total + + c_S6 * s6_total + + c_S7 * s7_total + ) + + # ----- UB: instance-derived ceiling that any feasible obj must respect. + # Each violation variable in the model is non-negative with positive obj + # coefficient; we bound each by the largest value it could conceivably + # take in any feasible solution (LP-suboptimal incumbents included). + s1_max_total = 0 + for d in range(num_days): + for sn in shift_names: + for sk in skills_list: + s1_max_total += demand[d][sn][sk]["optimal"] + ub_S1 = c_S1 * s1_max_total + + ub_S2a_over = c_S2a * num_nurses * num_days + ub_S2a_under = c_S2a * sum( + num_days * max(0, nurse["contract"]["CD_minus"] - 1) + for nurse in nurses + if isinstance(nurse.get("id"), int) + ) + ub_S2b_over = c_S2b * num_nurses * num_days * len(shift_names) + ub_S2b_under = c_S2b * num_nurses * num_days * sum( + max(0, CS_minus[sn] - 1) for sn in shift_names + ) + ub_S3_over = c_S3 * num_nurses * num_days + ub_S3_under = c_S3 * sum( + num_days * max(0, nurse["contract"]["CR_minus"] - 1) + for nurse in nurses + if isinstance(nurse.get("id"), int) + ) + ub_S4 = c_S4 * sum( + len(nurse.get("preferences", []) or []) for nurse in nurses + ) + ub_S5 = c_S5 * num_nurses * len(weekends) + ub_S6 = c_S6 * num_nurses * num_days + ub_S7 = c_S7 * num_nurses * len(weekends) + + ub = ( + ub_S1 + + ub_S2a_over + ub_S2a_under + + ub_S2b_over + ub_S2b_under + + ub_S3_over + ub_S3_under + + ub_S4 + ub_S5 + ub_S6 + ub_S7 + ) + # Safety margin (10x) -- generous enough that real Gurobi heuristic + # incumbents never exceed it while still rejecting sys.float_info.max. + ub = max(ub * 10, lb * 10 + 1e6) + return float(lb), float(ub) + + +def main(): + parser = argparse.ArgumentParser(description="Feasibility checker for NSP (INRC-II)") + parser.add_argument("--instance_path", required=True, help="Path to instance JSON") + parser.add_argument("--solution_path", required=True, help="Path to solution JSON") + parser.add_argument("--result_path", required=True, help="Path to write result JSON") + 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 + + # Handle degenerate solutions (solver found no solution / infeasible) + sol_status = solution.get("status") + sol_schedule = solution.get("schedule", []) + if sol_status in (3, "3", "INFEASIBLE", "NO_SOLUTION_FOUND") or \ + (solution.get("objective_value") is None and len(sol_schedule) == 0): + status_desc = solution.get("status_description", solution.get("status", "unknown")) + result = { + "feasible": False, + "violated_constraints": [1], + "violations": [ + f"No solution provided (solver status={status_desc}). " + f"Empty schedule cannot satisfy constraint 1b (every nurse must have a roster)." + ], + "violation_magnitudes": [{ + "constraint": 1, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }], + } + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + print(f"Solution is INFEASIBLE (no solution from solver, status={status_desc}).") + return + + tol = 1e-5 + eps = 1e-5 + + num_nurses = instance["num_nurses"] + num_days = instance["num_days"] + nurses = instance["nurses"] + demand = instance["demand"] # list of dicts indexed by day + forbidden = instance["forbidden_shift_successions"] + skills_list = instance["skills"] + + # Build nurse lookup + nurse_by_id = {n["id"]: n for n in nurses} + nurse_skills = {n["id"]: set(n["skills"]) for n in nurses} + + schedule = solution["schedule"] + schedule_by_nurse = {entry["nurse_id"]: entry["assignments"] for entry in schedule} + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs, rhs, operator="eq"): + violated_constraints.add(constraint_idx) + violations.append(msg) + if operator == "eq": + violation_amount = abs(lhs - rhs) + elif operator == "geq": + # LHS >= RHS required, violation = max(0, RHS - LHS) + violation_amount = max(0.0, rhs - lhs) + elif operator == "leq": + # LHS <= RHS required, violation = max(0, LHS - RHS) + violation_amount = max(0.0, lhs - rhs) + else: + violation_amount = abs(lhs - rhs) + + if violation_amount > tol: + 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), + }) + + # ========================================================================= + # Constraint 1 (1b): Flow at source - each nurse has exactly one roster + # sum_{j in A+_{i,o_i}} x_{ij} = 1, for all i + # In practice: each nurse in the instance must appear in the solution. + # ========================================================================= + for nurse in nurses: + nid = nurse["id"] + if nid not in schedule_by_nurse: + # LHS = 0 (no roster), RHS = 1 + record_violation(1, + f"Nurse {nid} ({nurse['name']}) has no roster in the solution", + 0.0, 1.0, "eq") + + # ========================================================================= + # Constraint 2 (1c): Flow conservation at intermediate nodes + # Enforces H1 (single assignment per day) and H3 (forbidden successions) + # ========================================================================= + for nurse in nurses: + nid = nurse["id"] + assignments = schedule_by_nurse.get(nid, []) + + # H1: At most one shift per day + day_counts = defaultdict(int) + for a in assignments: + day_counts[a["day"]] += 1 + for day, count in day_counts.items(): + if count > 1: + # LHS = count (shifts on that day), RHS = 1 + record_violation(2, + f"Nurse {nid} has {count} assignments on day {day} (H1: single assignment per day)", + float(count), 1.0, "leq") + + # H3: Forbidden shift successions + sorted_assignments = sorted(assignments, key=lambda a: a["day"]) + for i in range(len(sorted_assignments) - 1): + a1 = sorted_assignments[i] + a2 = sorted_assignments[i + 1] + if a2["day"] == a1["day"] + 1: + for fs in forbidden: + if a1["shift"] == fs[0] and a2["shift"] == fs[1]: + # Forbidden succession: LHS = 1 (occurs), RHS = 0 (must not occur) + record_violation(2, + f"Nurse {nid} has forbidden succession {fs[0]}->{fs[1]} on days {a1['day']}->{a2['day']} (H3)", + 1.0, 0.0, "leq") + + # ========================================================================= + # Constraint 4 (1e): Skill assignment linking (H4) + # Nurse can only perform skills they have. + # ========================================================================= + for nurse in nurses: + nid = nurse["id"] + assignments = schedule_by_nurse.get(nid, []) + nurse_sk = nurse_skills[nid] + for a in assignments: + skill = a["skill"] + if skill not in nurse_sk: + # LHS = 1 (assignment with invalid skill), RHS = 0 + record_violation(4, + f"Nurse {nid} assigned skill '{skill}' on day {a['day']} shift {a['shift']}, " + f"but only has skills {sorted(nurse_sk)} (H4)", + 1.0, 0.0, "leq") + + # ========================================================================= + # Constraint 5 (1f): Minimum demand (H2) + # sum_{i in N_sigma} y_{ip,sigma} >= D_{p,sigma}, for all p, sigma + # ========================================================================= + # Count assignments per (day, shift, skill) + staffing = defaultdict(int) + for entry in schedule: + for a in entry["assignments"]: + staffing[(a["day"], a["shift"], a["skill"])] += 1 + + for day_idx in range(num_days): + day_demand = demand[day_idx] + for shift_name, skill_demands in day_demand.items(): + for skill_name, dem in skill_demands.items(): + min_dem = dem["minimum"] + actual = staffing.get((day_idx, shift_name, skill_name), 0) + if actual < min_dem - tol: + # LHS = actual, RHS = min_dem, constraint is LHS >= RHS + record_violation(5, + f"Day {day_idx} shift {shift_name} skill {skill_name}: " + f"staffing {actual} < minimum demand {min_dem} (H2)", + float(actual), float(min_dem), "geq") + + # ========================================================================= + # Constraint 7 (1h): Integrality of x, y + # x_{ij}, y_{ip,sigma} in {0,1} + # Trivially satisfied by the solution format (discrete assignments). + # We verify that assignment values are valid (known shifts and skills). + # ========================================================================= + valid_shifts = {s["name"] for s in instance["shifts"]} + valid_skills = set(instance["skills"]) + for entry in schedule: + nid = entry["nurse_id"] + for a in entry["assignments"]: + if a["shift"] not in valid_shifts: + record_violation(7, + f"Nurse {nid} day {a['day']}: unknown shift '{a['shift']}'", + 1.0, 0.0, "leq") + if a["skill"] not in valid_skills: + record_violation(7, + f"Nurse {nid} day {a['day']}: unknown skill '{a['skill']}'", + 1.0, 0.0, "leq") + if not (0 <= a["day"] < num_days): + record_violation(7, + f"Nurse {nid}: day {a['day']} out of range [0, {num_days - 1}]", + float(a["day"]), float(num_days - 1), "leq") + + # ========================================================================= + # Constraint 8 (1i): Non-negativity of w, z + # w, z >= 0. These are slack/surplus variables implicitly >= 0 by definition + # when computed from a valid schedule. Trivially satisfied. + # ========================================================================= + # No explicit check needed; w and z are derived from the schedule and + # are always non-negative by construction. + + # ========================================================================= + # Constraint 9 (Tier C): Objective consistency + # Recompute the canonical minimum penalty implied by the schedule. Legacy + # Gurobi references also serialize a penalty_breakdown because a + # time-limited incumbent can retain nonminimal continuous slack values; + # in that case bind objective_value to the serialized component sum instead + # of accepting the former, extremely broad instance-level upper bound. + # ========================================================================= + 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: + lb, _ = _compute_obj_bounds(instance, solution) + obj_tol = max(1e-3, 1e-3 * abs(lb)) + if reported < lb - obj_tol: + record_violation( + 9, + f"Objective consistency violated: reported objective_value=" + f"{reported} is below the schedule-derived lower bound " + f"LB={lb} (shortfall={lb - reported:.6g}, tol={obj_tol:.3g}).", + reported, lb, "geq", + ) + elif abs(reported - lb) > obj_tol: + breakdown = solution.get("penalty_breakdown") + component_names = ( + "S1_optimal_coverage", + "S2a_consecutive_days", + "S2b_consecutive_shifts", + "S3_consecutive_rest", + "S4_preferences", + "S5_complete_weekend", + "S6_total_assignments", + "S7_working_weekends", + ) + breakdown_total = None + if isinstance(breakdown, dict) and all( + name in breakdown for name in component_names): + try: + values = [float(breakdown[name]) + for name in component_names] + if all(math.isfinite(value) and value >= 0.0 + for value in values): + breakdown_total = sum(values) + except (TypeError, ValueError): + breakdown_total = None + + legacy_tol = max(1e-3, 1e-8 * max(abs(reported), 1.0)) + if (breakdown_total is None + or abs(reported - breakdown_total) > legacy_tol): + record_violation( + 9, + f"Objective consistency violated: reported " + f"objective_value={reported} is above the canonical " + f"schedule cost LB={lb}, but does not equal a complete " + f"legacy penalty_breakdown (sum={breakdown_total}, " + f"tol={legacy_tol:.3g}).", + reported, + breakdown_total if breakdown_total is not None else lb, + "eq", + ) + + # Build result + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if feasible: + print("Solution is FEASIBLE (all hard constraints satisfied).") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {sorted(violated_constraints)}") + 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/legrain2020/gurobi_code.py b/tasks/legrain2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..f353a0a49d98d65d78f1ef1fdf288e40388b4d30 --- /dev/null +++ b/tasks/legrain2020/gurobi_code.py @@ -0,0 +1,688 @@ +""" +Gurobi implementation of a compact MIP for the Nurse Scheduling Problem from: +Legrain, Omer, Rosat (2020), +"A rotation-based branch-and-price approach for the nurse scheduling problem", +Computers & Operations Research, 122, 104944. + +The paper uses an INRC-II formulation with rotation-based branch-and-price. +Since rotation enumeration is specific to the B&P approach, this file implements +an equivalent compact MIP formulation that captures the same constraints (H1-H4) +and soft-constraint penalties (S1-S7) using standard decision variables. +""" + +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(path): + """Load an INRC-II nurse scheduling instance from JSON.""" + with open(path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(instance_path, solution_path, time_limit): + data = load_instance(instance_path) + + num_nurses = data["num_nurses"] + num_days = data["num_days"] + num_weeks = data["num_weeks"] + skills = data["skills"] + shifts_data = data["shifts"] + shift_names = [s["name"] for s in shifts_data] + num_shifts = len(shift_names) + num_skills = len(skills) + + # Index mappings + shift_idx = {name: idx for idx, name in enumerate(shift_names)} + skill_idx = {name: idx for idx, name in enumerate(skills)} + + # Shift parameters + CS_minus = {s: shifts_data[shift_idx[s]]["CS_minus"] for s in shift_names} + CS_plus = {s: shifts_data[shift_idx[s]]["CS_plus"] for s in shift_names} + + # Forbidden successions as index pairs + forbidden = [] + for pair in data["forbidden_shift_successions"]: + forbidden.append((shift_idx[pair[0]], shift_idx[pair[1]])) + + # Penalty weights + pw = data["penalty_weights"] + c_S1 = pw["c_S1"] + c_S2a = pw["c_S2a"] + c_S2b = pw["c_S2b"] + c_S3 = pw["c_S3"] + c_S4 = pw["c_S4"] + c_S5 = pw["c_S5"] + c_S6 = pw["c_S6"] + c_S7 = pw["c_S7"] + + # Nurse data + nurses = data["nurses"] + nurse_skills = {} # nurse_id -> set of skill indices + for nurse in nurses: + i = nurse["id"] + nurse_skills[i] = set(skill_idx[sk] for sk in nurse["skills"]) + + # Nurses that can perform each skill + nurses_with_skill = {sigma: [] for sigma in range(num_skills)} + for i in range(num_nurses): + for sigma in nurse_skills[i]: + nurses_with_skill[sigma].append(i) + + # Nurse contracts + L_minus = {} + L_plus = {} + CD_minus = {} + CD_plus = {} + CR_minus = {} + CR_plus = {} + WE_plus = {} + for nurse in nurses: + i = nurse["id"] + c = nurse["contract"] + L_minus[i] = c["L_minus"] + L_plus[i] = c["L_plus"] + CD_minus[i] = c["CD_minus"] + CD_plus[i] = c["CD_plus"] + CR_minus[i] = c["CR_minus"] + CR_plus[i] = c["CR_plus"] + WE_plus[i] = c["WE_plus"] + + # Nurse preferences (undesired assignments) + prefs = {} # (nurse_id, day, shift_idx) -> True + for nurse in nurses: + i = nurse["id"] + for p in nurse["preferences"]: + prefs[(i, p["day"], shift_idx[p["shift"]])] = True + + # Demand data: demand[day][shift_name][skill_name] -> {minimum, optimal} + demand_data = data["demand"] + D_min = {} # (day, shift_idx, skill_idx) -> minimum demand + D_opt = {} # (day, shift_idx, skill_idx) -> optimal demand + for k in range(num_days): + for s_name in shift_names: + s = shift_idx[s_name] + for sk_name in skills: + sigma = skill_idx[sk_name] + d_entry = demand_data[k][s_name][sk_name] + D_min[(k, s, sigma)] = d_entry["minimum"] + D_opt[(k, s, sigma)] = d_entry["optimal"] + + # Weekend days: assuming week starts Monday (day 0 = Monday of week 1) + # Saturday = day 5, 12, 19, 26; Sunday = day 6, 13, 20, 27 + weekends = [] + for m in range(num_weeks): + sat = 7 * m + 5 + sun = 7 * m + 6 + if sat < num_days and sun < num_days: + weekends.append((m, sat, sun)) + + # ------------------------------------------------------------------------- + # Build Gurobi model + # ------------------------------------------------------------------------- + model = gp.Model("NSP_Legrain2020") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + model.setParam("MIPFocus", 1) # focus on finding feasible solutions quickly + + # ----- Decision variables ----- + + # x[i,k,s]: nurse i works shift s on day k + x = {} + for i in range(num_nurses): + for k in range(num_days): + for s in range(num_shifts): + x[i, k, s] = model.addVar(vtype=GRB.BINARY, + name=f"x_{i}_{k}_{s}") + + # work[i,k]: nurse i works on day k (any shift) + work = {} + for i in range(num_nurses): + for k in range(num_days): + work[i, k] = model.addVar(vtype=GRB.BINARY, + name=f"work_{i}_{k}") + + # y[i,k,s,sigma]: nurse i performs skill sigma on shift s, day k + y = {} + for i in range(num_nurses): + for k in range(num_days): + for s in range(num_shifts): + for sigma in nurse_skills[i]: + y[i, k, s, sigma] = model.addVar( + vtype=GRB.BINARY, + name=f"y_{i}_{k}_{s}_{sigma}") + + # z[k,s,sigma]: optimal demand violation + z = {} + for k in range(num_days): + for s in range(num_shifts): + for sigma in range(num_skills): + z[k, s, sigma] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"z_{k}_{s}_{sigma}") + + # S6: total assignment violations + w_under = {} + w_over = {} + for i in range(num_nurses): + w_under[i] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"w_under_{i}") + w_over[i] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"w_over_{i}") + + # S7: weekend violation + w_we = {} + for i in range(num_nurses): + w_we[i] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"w_we_{i}") + + # Weekend worked indicator: we_worked[i,m] = 1 if nurse works at least + # one day of weekend m + we_worked = {} + for i in range(num_nurses): + for m, sat, sun in weekends: + we_worked[i, m] = model.addVar(vtype=GRB.BINARY, + name=f"we_worked_{i}_{m}") + + # S5: complete weekend violation + we_viol = {} + for i in range(num_nurses): + for m, sat, sun in weekends: + we_viol[i, m] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"we_viol_{i}_{m}") + + # S2a: consecutive worked days upper-bound violation + cd_over = {} + for i in range(num_nurses): + cdp = CD_plus[i] + for k in range(num_days - cdp): + cd_over[i, k] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"cd_over_{i}_{k}") + + # S2a: consecutive worked days lower-bound violation + # start_work[i,k] indicates start of a work streak at day k + start_work = {} + for i in range(num_nurses): + for k in range(num_days): + start_work[i, k] = model.addVar(vtype=GRB.BINARY, + name=f"start_work_{i}_{k}") + + cd_under = {} + for i in range(num_nurses): + cdm = CD_minus[i] + for k in range(num_days): + for j in range(1, cdm): + if k + j < num_days: + cd_under[i, k, j] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, + name=f"cd_under_{i}_{k}_{j}") + + # S2b: consecutive same-shift upper-bound violation + cs_over = {} + for i in range(num_nurses): + for s in range(num_shifts): + csp = CS_plus[shift_names[s]] + for k in range(num_days - csp): + cs_over[i, k, s] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, + name=f"cs_over_{i}_{k}_{s}") + + # S2b: consecutive same-shift lower-bound violation + # start_shift[i,k,s] indicates start of a consecutive-same-shift streak + start_shift = {} + for i in range(num_nurses): + for k in range(num_days): + for s in range(num_shifts): + start_shift[i, k, s] = model.addVar( + vtype=GRB.BINARY, + name=f"start_shift_{i}_{k}_{s}") + + cs_under = {} + for i in range(num_nurses): + for s in range(num_shifts): + csm = CS_minus[shift_names[s]] + for k in range(num_days): + for j in range(1, csm): + if k + j < num_days: + cs_under[i, k, s, j] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, + name=f"cs_under_{i}_{k}_{s}_{j}") + + # S3: consecutive days off violations + # rest[i,k] = 1 - work[i,k] + # Upper bound: no rest streak longer than CR_plus + cr_over = {} + for i in range(num_nurses): + crp = CR_plus[i] + for k in range(num_days - crp): + cr_over[i, k] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"cr_over_{i}_{k}") + + # Lower bound on consecutive rest + start_rest = {} + for i in range(num_nurses): + for k in range(num_days): + start_rest[i, k] = model.addVar(vtype=GRB.BINARY, + name=f"start_rest_{i}_{k}") + + cr_under = {} + for i in range(num_nurses): + crm = CR_minus[i] + for k in range(num_days): + for j in range(1, crm): + if k + j < num_days: + cr_under[i, k, j] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, + name=f"cr_under_{i}_{k}_{j}") + + model.update() + + # ----- Constraints ----- + + # Link work[i,k] = sum_s x[i,k,s] + for i in range(num_nurses): + for k in range(num_days): + model.addConstr( + work[i, k] == gp.quicksum(x[i, k, s] for s in range(num_shifts)), + name=f"link_work_{i}_{k}") + + # H1: At most one shift per day (work is binary, so sum <= 1) + for i in range(num_nurses): + for k in range(num_days): + model.addConstr( + gp.quicksum(x[i, k, s] for s in range(num_shifts)) <= 1, + name=f"H1_{i}_{k}") + + # H3: Forbidden shift successions + for i in range(num_nurses): + for k in range(num_days - 1): + for s1, s2 in forbidden: + model.addConstr( + x[i, k, s1] + x[i, k + 1, s2] <= 1, + name=f"H3_{i}_{k}_{s1}_{s2}") + + # H4: Skill linking - nurse can only use skills they have + # sum_{sigma in Sigma_i} y[i,k,s,sigma] = x[i,k,s] + for i in range(num_nurses): + for k in range(num_days): + for s in range(num_shifts): + model.addConstr( + gp.quicksum(y[i, k, s, sigma] + for sigma in nurse_skills[i]) == x[i, k, s], + name=f"H4_{i}_{k}_{s}") + + # H2: Minimum demand + for k in range(num_days): + for s in range(num_shifts): + for sigma in range(num_skills): + if D_min[(k, s, sigma)] > 0: + model.addConstr( + gp.quicksum(y[i, k, s, sigma] + for i in nurses_with_skill[sigma]) >= + D_min[(k, s, sigma)], + name=f"H2_{k}_{s}_{sigma}") + + # S1: Optimal coverage + for k in range(num_days): + for s in range(num_shifts): + for sigma in range(num_skills): + model.addConstr( + gp.quicksum(y[i, k, s, sigma] + for i in nurses_with_skill[sigma]) + + z[k, s, sigma] >= D_opt[(k, s, sigma)], + name=f"S1_{k}_{s}_{sigma}") + + # S6: Total assignments bounds + for i in range(num_nurses): + total_work = gp.quicksum(work[i, k] for k in range(num_days)) + model.addConstr(w_under[i] >= L_minus[i] - total_work, + name=f"S6_under_{i}") + model.addConstr(w_over[i] >= total_work - L_plus[i], + name=f"S6_over_{i}") + + # S7: Total working weekends + for i in range(num_nurses): + for m, sat, sun in weekends: + model.addConstr(we_worked[i, m] >= work[i, sat], + name=f"we_worked_sat_{i}_{m}") + model.addConstr(we_worked[i, m] >= work[i, sun], + name=f"we_worked_sun_{i}_{m}") + model.addConstr(we_worked[i, m] <= work[i, sat] + work[i, sun], + name=f"we_worked_ub_{i}_{m}") + model.addConstr( + w_we[i] >= gp.quicksum(we_worked[i, m] + for m, _, _ in weekends) - WE_plus[i], + name=f"S7_{i}") + + # S5: Complete weekend + for i in range(num_nurses): + for m, sat, sun in weekends: + model.addConstr(we_viol[i, m] >= work[i, sat] - work[i, sun], + name=f"S5a_{i}_{m}") + model.addConstr(we_viol[i, m] >= work[i, sun] - work[i, sat], + name=f"S5b_{i}_{m}") + + # S2a: Consecutive worked days - upper bound + for i in range(num_nurses): + cdp = CD_plus[i] + for k in range(num_days - cdp): + model.addConstr( + cd_over[i, k] >= gp.quicksum( + work[i, k + j] for j in range(cdp + 1)) - cdp, + name=f"S2a_over_{i}_{k}") + + # S2a: Consecutive worked days - lower bound + # start_work[i,k] >= work[i,k] - work[i,k-1] + for i in range(num_nurses): + cdm = CD_minus[i] + model.addConstr(start_work[i, 0] >= work[i, 0], + name=f"start_work_{i}_0") + for k in range(1, num_days): + model.addConstr( + start_work[i, k] >= work[i, k] - work[i, k - 1], + name=f"start_work_{i}_{k}") + # If a work streak starts at k, then days k+1..k+cdm-1 should be worked + for k in range(num_days): + for j in range(1, cdm): + if k + j < num_days: + model.addConstr( + cd_under[i, k, j] >= + start_work[i, k] - work[i, k + j], + name=f"S2a_under_{i}_{k}_{j}") + + # S2b: Consecutive same-shift - upper bound + for i in range(num_nurses): + for s in range(num_shifts): + csp = CS_plus[shift_names[s]] + for k in range(num_days - csp): + model.addConstr( + cs_over[i, k, s] >= gp.quicksum( + x[i, k + j, s] for j in range(csp + 1)) - csp, + name=f"S2b_over_{i}_{k}_{s}") + + # S2b: Consecutive same-shift - lower bound + # start_shift[i,k,s] >= x[i,k,s] - x[i,k-1,s] + for i in range(num_nurses): + for s in range(num_shifts): + csm = CS_minus[shift_names[s]] + model.addConstr(start_shift[i, 0, s] >= x[i, 0, s], + name=f"start_shift_{i}_0_{s}") + for k in range(1, num_days): + model.addConstr( + start_shift[i, k, s] >= x[i, k, s] - x[i, k - 1, s], + name=f"start_shift_{i}_{k}_{s}") + for k in range(num_days): + for j in range(1, csm): + if k + j < num_days: + model.addConstr( + cs_under[i, k, s, j] >= + start_shift[i, k, s] - x[i, k + j, s], + name=f"S2b_under_{i}_{k}_{s}_{j}") + + # S3: Consecutive days off - upper bound + for i in range(num_nurses): + crp = CR_plus[i] + for k in range(num_days - crp): + # sum of rest days in window of crp+1: (crp+1) - sum(work) + # violation if rest > crp, i.e., sum(work) < 1 + model.addConstr( + cr_over[i, k] >= 1 - gp.quicksum( + work[i, k + j] for j in range(crp + 1)), + name=f"S3_over_{i}_{k}") + + # S3: Consecutive days off - lower bound + # start_rest[i,k] >= (1-work[i,k]) - (1-work[i,k-1]) = work[i,k-1] - work[i,k] + for i in range(num_nurses): + crm = CR_minus[i] + # Day 0: rest starts if not working + model.addConstr(start_rest[i, 0] >= 1 - work[i, 0], + name=f"start_rest_{i}_0") + for k in range(1, num_days): + model.addConstr( + start_rest[i, k] >= work[i, k - 1] - work[i, k], + name=f"start_rest_{i}_{k}") + # If rest streak starts at k, days k+1..k+crm-1 should also be rest + for k in range(num_days): + for j in range(1, crm): + if k + j < num_days: + model.addConstr( + cr_under[i, k, j] >= + start_rest[i, k] - (1 - work[i, k + j]), + name=f"S3_under_{i}_{k}_{j}") + + # ----- Objective ----- + obj = gp.LinExpr() + + # S1: Optimal coverage penalty + obj += c_S1 * gp.quicksum(z[k, s, sigma] + for k in range(num_days) + for s in range(num_shifts) + for sigma in range(num_skills)) + + # S2a: Consecutive worked days violations + obj += c_S2a * gp.quicksum(cd_over[i, k] + for i in range(num_nurses) + for k in range(num_days - CD_plus[i])) + obj += c_S2a * gp.quicksum(cd_under[i, k, j] + for i in range(num_nurses) + for k in range(num_days) + for j in range(1, CD_minus[i]) + if k + j < num_days) + + # S2b: Consecutive same-shift violations + obj += c_S2b * gp.quicksum(cs_over[i, k, s] + for i in range(num_nurses) + for s in range(num_shifts) + for k in range(num_days - + CS_plus[shift_names[s]])) + obj += c_S2b * gp.quicksum(cs_under[i, k, s, j] + for i in range(num_nurses) + for s in range(num_shifts) + for k in range(num_days) + for j in range(1, CS_minus[shift_names[s]]) + if k + j < num_days) + + # S3: Consecutive days off violations + obj += c_S3 * gp.quicksum(cr_over[i, k] + for i in range(num_nurses) + for k in range(num_days - CR_plus[i])) + obj += c_S3 * gp.quicksum(cr_under[i, k, j] + for i in range(num_nurses) + for k in range(num_days) + for j in range(1, CR_minus[i]) + if k + j < num_days) + + # S4: Preferences penalty + obj += c_S4 * gp.quicksum(x[i, k, s] + for (i, k, s) in prefs) + + # S5: Complete weekend penalty + obj += c_S5 * gp.quicksum(we_viol[i, m] + for i in range(num_nurses) + for m, _, _ in weekends) + + # S6: Total assignments penalty + obj += c_S6 * gp.quicksum(w_under[i] + w_over[i] + for i in range(num_nurses)) + + # S7: Working weekends penalty + obj += c_S7 * gp.quicksum(w_we[i] for i in range(num_nurses)) + + model.setObjective(obj, GRB.MINIMIZE) + + # ------------------------------------------------------------------------- + # Solve + # ------------------------------------------------------------------------- + model.optimize() + + # ------------------------------------------------------------------------- + # Extract solution + # ------------------------------------------------------------------------- + result = {} + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + result["status"] = model.Status + result["status_description"] = { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + }.get(model.Status, f"STATUS_{model.Status}") + + # Extract schedule: for each nurse, list of (day, shift, skill) + schedule = [] + for i in range(num_nurses): + nurse_schedule = { + "nurse_id": i, + "nurse_name": nurses[i]["name"], + "assignments": [] + } + for k in range(num_days): + for s in range(num_shifts): + if x[i, k, s].X > 0.5: + assigned_skill = None + for sigma in nurse_skills[i]: + if (i, k, s, sigma) in y and y[i, k, s, sigma].X > 0.5: + assigned_skill = skills[sigma] + break + nurse_schedule["assignments"].append({ + "day": k, + "shift": shift_names[s], + "skill": assigned_skill + }) + schedule.append(nurse_schedule) + + result["schedule"] = schedule + + # Compute penalty breakdown + penalty_breakdown = {} + val_S1 = c_S1 * sum(z[k, s, sigma].X + for k in range(num_days) + for s in range(num_shifts) + for sigma in range(num_skills)) + penalty_breakdown["S1_optimal_coverage"] = round(val_S1, 2) + + val_S2a_over = c_S2a * sum( + cd_over[i, k].X + for i in range(num_nurses) + for k in range(num_days - CD_plus[i])) + val_S2a_under = c_S2a * sum( + cd_under[i, k, j].X + for i in range(num_nurses) + for k in range(num_days) + for j in range(1, CD_minus[i]) + if k + j < num_days) + penalty_breakdown["S2a_consecutive_days"] = round( + val_S2a_over + val_S2a_under, 2) + + val_S2b_over = c_S2b * sum( + cs_over[i, k, s].X + for i in range(num_nurses) + for s in range(num_shifts) + for k in range(num_days - CS_plus[shift_names[s]])) + val_S2b_under = c_S2b * sum( + cs_under[i, k, s, j].X + for i in range(num_nurses) + for s in range(num_shifts) + for k in range(num_days) + for j in range(1, CS_minus[shift_names[s]]) + if k + j < num_days) + penalty_breakdown["S2b_consecutive_shifts"] = round( + val_S2b_over + val_S2b_under, 2) + + val_S3_over = c_S3 * sum( + cr_over[i, k].X + for i in range(num_nurses) + for k in range(num_days - CR_plus[i])) + val_S3_under = c_S3 * sum( + cr_under[i, k, j].X + for i in range(num_nurses) + for k in range(num_days) + for j in range(1, CR_minus[i]) + if k + j < num_days) + penalty_breakdown["S3_consecutive_rest"] = round( + val_S3_over + val_S3_under, 2) + + val_S4 = c_S4 * sum(x[i, k, s].X for (i, k, s) in prefs) + penalty_breakdown["S4_preferences"] = round(val_S4, 2) + + val_S5 = c_S5 * sum(we_viol[i, m].X + for i in range(num_nurses) + for m, _, _ in weekends) + penalty_breakdown["S5_complete_weekend"] = round(val_S5, 2) + + val_S6 = c_S6 * sum(w_under[i].X + w_over[i].X + for i in range(num_nurses)) + penalty_breakdown["S6_total_assignments"] = round(val_S6, 2) + + val_S7 = c_S7 * sum(w_we[i].X for i in range(num_nurses)) + penalty_breakdown["S7_working_weekends"] = round(val_S7, 2) + + result["penalty_breakdown"] = penalty_breakdown + + else: + result["objective_value"] = None + result["status"] = model.Status + result["status_description"] = "NO_SOLUTION_FOUND" + result["schedule"] = [] + + # Add solver info + result["solver"] = "Gurobi" + result["time_limit"] = time_limit + if hasattr(model, "Runtime"): + result["runtime_seconds"] = round(model.Runtime, 2) + if hasattr(model, "MIPGap") and model.SolCount > 0: + result["mip_gap"] = round(model.MIPGap, 6) + if model.SolCount > 0 and hasattr(model, "ObjBound"): + result["best_bound"] = round(model.ObjBound, 2) + + # 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}") + print(f"Objective value: {result['objective_value']}") + if result.get("penalty_breakdown"): + print("Penalty breakdown:") + for key, val in result["penalty_breakdown"].items(): + print(f" {key}: {val}") + return result + + +def main(): + parser = argparse.ArgumentParser( + description="NSP Gurobi solver (Legrain et al. 2020 INRC-II formulation)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, + default="gurobi_solution_1.json", + 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) + + build_and_solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/legrain2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/legrain2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2020/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/legrain2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/legrain2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2020/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/legrain2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/legrain2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2020/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/legrain2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/legrain2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2020/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/legrain2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/legrain2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2020/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/legrain2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/legrain2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2020/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/legrain2020/gurobi_solution/large_solution_1.json b/tasks/legrain2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f9e7d6aa038935965a1fe8b0d13d1da777f56a9a --- /dev/null +++ b/tasks/legrain2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:612427446a46813b3a28b9464019db85348dbcef52d08a0c0d4fa09ba49e7d33 +size 531749 diff --git a/tasks/legrain2020/gurobi_solution/large_solution_2.json b/tasks/legrain2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..772ea558b10e39bc92dd2c452c3153459561b5b6 --- /dev/null +++ b/tasks/legrain2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f0710e90325988de52e62654ab8d17dc9c8c49f57ce74df8fced27dd6f252e7 +size 499724 diff --git a/tasks/legrain2020/gurobi_solution/large_solution_3.json b/tasks/legrain2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7f163a3235e72db4d1df6d1c4d498628728d1c7a --- /dev/null +++ b/tasks/legrain2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:597978b0cc85724a7751935063c245390879f664c22beff1badbec8fce701d7f +size 409181 diff --git a/tasks/legrain2020/gurobi_solution/large_solution_4.json b/tasks/legrain2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d40b035b4f25e6db088a7a3dfda45804b567d4b3 --- /dev/null +++ b/tasks/legrain2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:711d1e04e8cbbda82212c6bb722b550340e6faea015956ba4da36df941f88613 +size 552045 diff --git a/tasks/legrain2020/gurobi_solution/large_solution_5.json b/tasks/legrain2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..54825ee46863ce397c825d0b8aab537158ecfcbc --- /dev/null +++ b/tasks/legrain2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d3f3eb3304770cf767a794fb727342f35c6f5b46676c6c5ae631fa40ce9e821 +size 518188 diff --git a/tasks/legrain2020/gurobi_solution/tiny_solution.json b/tasks/legrain2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..a141bb4f563eb42421436c4dcde6ff80b516d8fe --- /dev/null +++ b/tasks/legrain2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8200e9a467c43d3e24a1e6dd685ac291a4815196cf92ad43db115700da93f35 +size 58036 diff --git a/tasks/legrain2020/gurobi_solution_log/large_log_1.jsonl b/tasks/legrain2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..971c83c349bc8bc466139f0778eede93596a02c1 --- /dev/null +++ b/tasks/legrain2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9292c95d8630365ac232335cc5f814a507a915f6a041444dd0cfc33a4bef4a7b +size 97 diff --git a/tasks/legrain2020/gurobi_solution_log/large_log_2.jsonl b/tasks/legrain2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9d249f7dfff5340253d85b3a35fe0d797690d9b --- /dev/null +++ b/tasks/legrain2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d93b4b5acb397df9bc0ea8b688f5df6ff6a8b7404c56f676f58b235badad5651 +size 4885 diff --git a/tasks/legrain2020/gurobi_solution_log/large_log_3.jsonl b/tasks/legrain2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a89f9500bf4eb166b6793088924ecf2140d23100 --- /dev/null +++ b/tasks/legrain2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0d033291b48d68c88215e8e98e62189a9bab6bea49d5f322e1198711d4cfd50 +size 2933 diff --git a/tasks/legrain2020/gurobi_solution_log/large_log_4.jsonl b/tasks/legrain2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e38c9485f3dbfc1432bcd518180c7db818b16101 --- /dev/null +++ b/tasks/legrain2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96ac0476da176972277835185f5ae18427ee905bfb7ed7ca35865c776bce7180 +size 1503 diff --git a/tasks/legrain2020/gurobi_solution_log/large_log_5.jsonl b/tasks/legrain2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..97f70409412050a1e2d845694a8cf2f67ab93c09 --- /dev/null +++ b/tasks/legrain2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d0f0936a18468ab04cb68f0a674ed3fccc1b7b1115334ec2becfa8c2dd9f747 +size 6888 diff --git a/tasks/legrain2020/gurobi_solution_log/tiny_log.jsonl b/tasks/legrain2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a69444aeec881f78cf202f9e89a95fa6f020ed7b --- /dev/null +++ b/tasks/legrain2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8814c5ab550f6a6eeef8e745c94a370413eef0817bd438e1aa6458fc108f4c56 +size 128 diff --git a/tasks/legrain2020/instance/large_instance_1.json b/tasks/legrain2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3cc9e5c51ba90684f3c08eb2a148c2bf3a0ffe83 --- /dev/null +++ b/tasks/legrain2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:407121bf26e6961581f20a50d1512ea787628fd347ccddcfe2da48babdc4f086 +size 291532 diff --git a/tasks/legrain2020/instance/large_instance_2.json b/tasks/legrain2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6b53a263fbd56e4f351cd94ebbabd71a673d9878 --- /dev/null +++ b/tasks/legrain2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43e506c7ad6eeff66c887ba1747cd0e94d02c82ddc93309bcb0e7ccd26ad6122 +size 305020 diff --git a/tasks/legrain2020/instance/large_instance_3.json b/tasks/legrain2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..2c9ac48fa6c6fcd6770c8dfbbc6ef3522d7c3523 --- /dev/null +++ b/tasks/legrain2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b099eb804279a31dda91d591e6e3821e2a982162bd235dc7ad40ec4f447ae2e2 +size 113511 diff --git a/tasks/legrain2020/instance/large_instance_4.json b/tasks/legrain2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..98d57167510b44445136a91fa9e921907648af63 --- /dev/null +++ b/tasks/legrain2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a2d762be5f3cfb037ed4c0ef2ef53873604bf72236ca969af0e86d120d7863d +size 289840 diff --git a/tasks/legrain2020/instance/large_instance_5.json b/tasks/legrain2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e0645403019dec219560d605a294ad33d6ce2f3d --- /dev/null +++ b/tasks/legrain2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c06d86694b7c355f5c2584bd92252202a822667a3ec8d3df7881ed922c33fcc +size 299051 diff --git a/tasks/legrain2020/instance/tiny_instance.json b/tasks/legrain2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..760d2aa176e2d0a339849b77d626dae17c8f6a88 --- /dev/null +++ b/tasks/legrain2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2414d803bc07aaee3364ce9ab465ff6f79ede17fc2dfb30f4aa7dea848a296f +size 43838 diff --git a/tasks/legrain2020/instance_schema.json b/tasks/legrain2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8e0d05fdbd3d7069049fd98d3d37ac7e117a92d1 --- /dev/null +++ b/tasks/legrain2020/instance_schema.json @@ -0,0 +1,58 @@ +{ + "num_nurses": " Total number of nurses available for scheduling.", + "num_weeks": " Number of weeks in the planning horizon.", + "num_days": " Total number of days in the planning horizon (seven times the number of weeks).", + "num_shifts": " Number of distinct shift types per day.", + "num_skills": " Number of distinct nursing skills.", + "skills": " Names of the nursing skills that can be performed.", + "shifts": [ + { + "name": " Name of the shift.", + "CS_minus": " Minimum number of consecutive days a nurse should work this same shift once started.", + "CS_plus": " Maximum number of consecutive days a nurse should work this same shift." + } + ], + "forbidden_shift_successions": " Pairs of shifts where a nurse working the first shift on one day may not work the second shift on the following day.", + "penalty_weights": { + "c_S1": " Per-nurse penalty for each unit of shortfall below optimal staffing coverage.", + "c_S2a": " Per-day penalty for each day a consecutive-worked-days stretch deviates from its bounds.", + "c_S2b": " Per-day penalty for each day a consecutive-same-shift stretch deviates from its bounds.", + "c_S3": " Per-day penalty for each day a consecutive-days-off stretch deviates from its bounds.", + "c_S4": " Penalty incurred each time a nurse is assigned to one of their preferred-off day-shift pairs.", + "c_S5": " Penalty incurred when a nurse works only one of the two days of a weekend.", + "c_S6": " Per-day penalty for each day a nurse's total worked days deviates from the allowed range.", + "c_S7": " Per-weekend penalty for each weekend a nurse works beyond the allowed maximum." + }, + "nurses": [ + { + "id": " Unique identifier for the nurse.", + "name": " Display name of the nurse.", + "skills": " Skills this nurse is qualified to perform.", + "contract": { + "L_minus": " Minimum total number of days the nurse should work over the planning horizon.", + "L_plus": " Maximum total number of days the nurse should work over the planning horizon.", + "CD_minus": " Minimum number of consecutive worked days in any uninterrupted work stretch.", + "CD_plus": " Maximum number of consecutive worked days in any uninterrupted work stretch.", + "CR_minus": " Minimum number of consecutive days off in any rest period.", + "CR_plus": " Maximum number of consecutive days off in any rest period.", + "WE_plus": " Maximum number of weekends the nurse should work over the planning horizon." + }, + "preferences": [ + { + "day": " Day index (0-based) of the preferred-off assignment.", + "shift": " Shift name of the preferred-off assignment." + } + ] + } + ], + "demand": [ + { + "{shift_name}": { + "{skill_name}": { + "minimum": " Minimum number of nurses with this skill required on this shift and day (hard constraint).", + "optimal": " Desired number of nurses with this skill on this shift and day (shortfalls are penalized)." + } + } + } + ] +} diff --git a/tasks/legrain2020/mathematical_formulation.md b/tasks/legrain2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..23084557109543c1ba25ab8df968b7b982f0e58e --- /dev/null +++ b/tasks/legrain2020/mathematical_formulation.md @@ -0,0 +1,89 @@ +# Original Formulation: Nurse Scheduling Problem (NSP) + +*Source: A rotation-based branch-and-price approach for the nurse scheduling problem, Antoine Legrain, Jérémy Omer, Samuel Rosat, Mathematical Programming Computation, 12(3), 417–450, 2020.* + +This is Formulation (1) of Section 3.3 (“Integer Programming formulation”): the rotation-based IP that the paper writes first as the definition of the NSP it studies. The problem is described narratively in Section 2; the only explicit mathematical formulation is (1), and its notation ($x,\mathbf{w},y,z$ and the rostering-graph flow constraints) is carried into the branch-and-price algorithm of Section 4. The decision variable $x_{ij}$ is indexed over the (exponential) set of feasible rotations/arcs $\Omega_i$; this exponential cardinality is preserved (the paper generates rotations by column generation, but that is an algorithmic detail of Section 4, not part of the problem definition). + +## Sets and Indices + +- $\mathcal{N}$ : set of nurses, indexed by $i \in \{1,\dots,|\mathcal{N}|\}$. + +- $K = 7M$ : number of days in the planning horizon ($M$ weeks), indexed by $k \in \{1,\dots,K\}$. + +- $\mathcal{S}$ : set of shifts, indexed by $s$. + +- $\Sigma$ : set of skills, indexed by $\sigma$. + +- $p = (k,s)$ : an *assignment* (worked shift $s$ on day $k$); ranges over $\{1,\dots,K\}\times\mathcal{S}$. + +- $\Omega_i$ : set of feasible rotations for nurse $i$ (exponential cardinality). + +- $\mathcal{V}_i$ : set of vertices in the rostering graph of nurse $i$; $o_i$ source node, $d_i$ sink node. + +- $\mathcal{A}^+_{iv}$, $\mathcal{A}^-_{iv}$ : arcs entering / leaving vertex $v$ in the rostering graph of nurse $i$ (each arc $j$ corresponds to a rotation or a resting period). + +- $\mathcal{N}_\sigma$ : set of nurses that can perform skill $\sigma$; $\Sigma_i$ : set of skills nurse $i$ can perform. + +## Parameters + +- $D_{p\sigma}$ : minimum demand in nurses performing skill $\sigma$ on assignment $p$. + +- $O_{p\sigma}$ : optimal demand in nurses performing skill $\sigma$ on assignment $p$. + +- $\mathbf{c}$ : vector of the cost of each arc in the rotation graph of each nurse (encodes penalties for **S2,S3,S4,S5**). + +- $\mathbf{c}_w = (c_{S6}, c_{S6}, c_{S7})$ : vector of unit costs for violations of **S6**–**S7**. + +- $c_{S1}$ : unit penalty for insufficient staffing for optimal coverage (**S1**). + +- $\mathbf{a}_j$ : Boolean vector indicating which assignment $p$ is in rotation $j$ (component $a_{jp}$). + +- $\mathbf{b}_j$ : vector containing the number of assignments and worked weekends in rotation $j$ of nurse $i$. + +- $\mathbf{B}_i = (L^-_i, L^+_i, WE^+_i)$ : vector of the bounds associated with **S6**–**S7** (min/max total worked days and max worked weekends for nurse $i$). + +## Decision Variables + +- $x_{ij} \in \{0,1\}$ : $=1$ iff the rotation (or resting period) associated with arc $j$ is part of the roster of nurse $i$. + +- $\mathbf{w}_i \in \mathbb{N}^3$ : vector of the violations of the soft constraints **S6**–**S7** in the roster of nurse $i$. + +- $y_{ip\sigma} \in \{0,1\}$ : $=1$ iff nurse $i$ performs skill $\sigma$ on assignment $p$. + +- $z_{p\sigma} \in \mathbb{N}$ : violation of the optimal demand constraint for assignment $p$ and skill $\sigma$. + +## Objective + +$$\begin{align} +\min \quad + & \underbrace{\mathbf{c}^{T}\mathbf{x}}_{\textbf{S2,S3,S4,S5}} + + \underbrace{\sum_{i} \mathbf{c}_{w}^{T}\mathbf{w}_i}_{\textbf{S6,S7}} + + \underbrace{c_{S1}\sum_{l,\sigma} z_{l\sigma}}_{\textbf{S1}} + \tag{1a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\textbf{[H1]}\quad + & \sum_{j \in \mathcal{A}^+_{io_i}} x_{ij} = 1, + && \forall i && [\alpha_{io_i}] \tag{1b}\\[2pt] +\textbf{[H1,H3]}\quad + & \sum_{j \in \mathcal{A}^+_{iv}} x_{ij} - \sum_{j \in \mathcal{A}^-_{iv}} x_{ij} = 0, + && \forall i,\ \forall v \in \mathcal{V}_i \setminus \{o_i,d_i\} && [\alpha_{iv}] \tag{1c}\\[2pt] +\textbf{[S6,S7]}\quad + & \sum_{j \in \Omega_i} \mathbf{b}_j\, x_{ij} + \mathbf{w}_i \le \mathbf{B}_i, + && \forall i && [\boldsymbol{\beta}_i] \tag{1d}\\[2pt] +\textbf{[H4]}\quad + & \sum_{j \in \Omega_i}\sum_{p} a_{jp}\, x_{ij} - \sum_{\sigma \in \Sigma_i} y_{ip\sigma} = 0, + && \forall i,\ p && [\delta_{ip}] \tag{1e}\\[2pt] +\textbf{[H2]}\quad + & \sum_{i \in \mathcal{N}_\sigma} y_{ip\sigma} \ge D_{p\sigma}, + && \forall p,\ \sigma && \tag{1f}\\[2pt] +\textbf{[S1]}\quad + & \sum_{i \in \mathcal{N}_\sigma} y_{ip\sigma} + z_{p\sigma} \ge O_{p\sigma}, + && \forall p,\ \sigma && \tag{1g}\\[2pt] + & x_{ij},\, y_{ip\sigma} \in \{0,1\}, + && \forall i,\ j,\ p,\ \sigma && \tag{1h}\\[2pt] + & \mathbf{w},\, \mathbf{z} \ge 0. && && \tag{1i} +\end{align}$$ diff --git a/tasks/legrain2020/problem_description.txt b/tasks/legrain2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..59a9898321dfc15174f07c80a041fa99a2ee2b05 --- /dev/null +++ b/tasks/legrain2020/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A hospital must build a complete schedule for a set of nurses over a planning horizon spanning a given number of whole weeks, where the total number of days equals seven times the number of weeks. Each day is divided into a set of named shifts, and every nurse possesses one or more skills from a known set of skills. An assignment is a particular shift on a particular day. For every combination of assignment and skill, the input specifies both a minimum demand and an optimal demand in nurses who perform that skill on that assignment. Each nurse has a personalized contract that specifies a minimum and maximum total number of worked days over the entire horizon, a minimum and maximum number of consecutive worked days, a minimum and maximum number of consecutive days off, and a maximum number of worked weekends over the horizon. Each nurse also has a set of preferred-off assignments, representing specific day-shift pairs that the nurse wishes not to work. For each shift, the input gives a minimum and maximum number of consecutive assignments to that same shift. A set of forbidden shift successions is given as pairs of shifts such that a nurse who works the first shift on some day may not work the second shift on the immediately following day. Finally, the input provides a unit penalty weight for each of the following categories: insufficient staffing for optimal coverage, consecutive worked-days violations, consecutive same-shift violations, consecutive days-off violations, preference violations, incomplete-weekend violations, total-assignment violations, and total worked-weekend violations. + +The scheduler must decide, for each nurse and each day, whether the nurse works or rests, and if the nurse works, which shift and which skill the nurse performs. A nurse may work at most one shift per day and may only cover demand for a skill that the nurse actually possesses. The number of nurses performing a given skill on a given assignment must be at least the minimum demand for that skill and assignment; this is a hard requirement that cannot be violated. If the number of nurses performing a given skill on a given assignment falls short of the optimal demand, each missing nurse is penalized at the insufficient-staffing unit weight. A nurse may not work a shift on one day followed by a forbidden successor shift on the next day; this too is inviolable. + +The remaining scheduling rules may be violated at a cost. For each nurse, the number of consecutive worked days within any uninterrupted work stretch should lie between the nurse's minimum and maximum consecutive worked-days bounds; each day of deviation is penalized at the consecutive worked-days unit weight. Similarly, the number of consecutive assignments to the same shift within any uninterrupted stretch of that shift should lie between that shift's minimum and maximum consecutive same-shift bounds; each assignment of deviation is penalized at the consecutive same-shift unit weight. The number of consecutive days off within any rest period should lie between the nurse's minimum and maximum consecutive days-off bounds; each day of deviation is penalized at the consecutive days-off unit weight. Each time a nurse is assigned to a day-shift pair that appears in the nurse's preferred-off set, the preference unit weight is incurred. Weekends should be worked completely or not at all: if a nurse works exactly one of Saturday and Sunday in any given week, the incomplete-weekend unit weight is incurred for that weekend. The total number of worked days over the entire horizon for each nurse should lie between the nurse's minimum and maximum total assignment bounds; each day of deviation in either direction is penalized at the total-assignment unit weight. The number of weekends in which the nurse works at least one day should not exceed the nurse's maximum worked-weekends limit; each weekend in excess is penalized at the worked-weekend unit weight. + +The goal is to minimize the total penalty, which is the sum of all insufficient-staffing penalties across all assignments and skills, all consecutive worked-days and consecutive same-shift penalties across all nurses, all consecutive days-off penalties across all nurses, all preference penalties across all nurses, all incomplete-weekend penalties across all nurses, all total-assignment deviation penalties across all nurses, and all excess worked-weekend penalties across all nurses. diff --git a/tasks/legrain2020/solution_logger.py b/tasks/legrain2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/legrain2020/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/legrain2020/solution_schema.json b/tasks/legrain2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..33b5d9c6b5fd9bbe5e60d76cc53195231b32242f --- /dev/null +++ b/tasks/legrain2020/solution_schema.json @@ -0,0 +1,16 @@ +{ + "objective_value": " Total weighted penalty summed across all soft-constraint violations.", + "schedule": [ + { + "nurse_id": " Identifier of the nurse this schedule belongs to.", + "nurse_name": " Display name of the nurse this schedule belongs to.", + "assignments": [ + { + "day": " Day index (0-based) on which the nurse works.", + "shift": " Name of the shift the nurse works on this day.", + "skill": " Skill the nurse performs on this assignment." + } + ] + } + ] +} diff --git a/tasks/legrain2024/feasibility_check.py b/tasks/legrain2024/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a70ace251b81a80371d55a8e18477fcc998a2fbf --- /dev/null +++ b/tasks/legrain2024/feasibility_check.py @@ -0,0 +1,855 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Nurse Scheduling Problem (Legrain & Omer 2024). + +Checks all hard constraints from the mathematical formulation (1b)-(1f) and +subproblem constraints (3-9) that are marked as hard in the instance. + +Constraints numbered top-to-bottom from the formulation: + 1 (1b) Assignment: each nurse exactly one shift per day + 2 (1c) Skill-assignment linking + 3 (1d) Demand coverage (with z slack, always satisfiable) + 4 (1e) Integrality (trivially satisfied for discrete schedules) + 5 (1f) Non-negativity of z (trivially satisfied) + 6 Total shift types / total working days + 7 Total worked weekends + 8 Consecutive shift types (working days, days off, same shift) + 9 Consecutive worked weekends + 10 Identical weekend + 11 Forbidden pattern + 12 Preferences + 13 Objective consistency (exactly recomputed from the schedule after + optimally completing the omitted nurse-to-skill assignments) +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'schedule', 'skill_assignments') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('schedule', 'skill_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 + + +def _minimum_unmet_demand(workers, skill_sets, skill_demand): + """Return the exact minimum uncovered demand for one day/shift. + + The model assigns every scheduled nurse to exactly one skill they possess. + Because every uncovered unit has the same penalty, the recourse problem is + a maximum-cardinality bipartite matching between nurses and unit-demand + skill slots. Nurses left unmatched to a demand slot may be assigned to any + other possessed skill and do not change the objective. + """ + demand_slots = [] + for skill, raw_demand in skill_demand.items(): + value = float(raw_demand) + rounded = round(value) + if not math.isfinite(value) or value < 0 or abs(value - rounded) > 1e-8: + raise ValueError( + f"demand for skill {skill!r} must be a non-negative integer" + ) + demand_slots.extend([skill] * int(rounded)) + + owner = [None] * len(demand_slots) + + def augment(nurse_id, seen): + for slot, skill in enumerate(demand_slots): + if seen[slot] or skill not in skill_sets[nurse_id]: + continue + seen[slot] = True + if owner[slot] is None or augment(owner[slot], seen): + owner[slot] = nurse_id + return True + return False + + covered = 0 + for nurse_id in workers: + if augment(nurse_id, [False] * len(demand_slots)): + covered += 1 + return float(len(demand_slots) - covered) + + + +def check_feasibility(inst, sol): + tol = 1e-5 + eps = 1e-5 + + meta = inst["instance_metadata"] + num_days = meta["num_days"] + shifts = inst["shifts"] + skills = inst.get("skills", []) + nurses = inst["nurses"] + weekends = inst["weekends"] + hard_con = inst["constraints"]["hard_constraints"] + soft_con = inst["constraints"].get("soft_constraints", {}) or {} + demand = inst.get("demand", {}) or {} + demand_penalty = inst.get("unsatisfied_demand_penalty", 0) + + schedule = sol["schedule"] + skill_assignments = sol["skill_assignments"] + all_shifts = shifts + ["None"] + + nurse_ids = [n["id"] for n in nurses] + nurse_skills = {n["id"]: set(n["skills"]) for n in nurses} + + def weekend_days(weekend): + return [ + weekend[key] + for key in ("friday", "saturday", "sunday") + if key in weekend + ] + + violations = [] # list of (constraint_idx, message) + magnitudes = [] # list of magnitude dicts + + def record(idx, msg, lhs, rhs, ctype="eq"): + """Record a violation if it exceeds tolerance.""" + if ctype == "eq": + va = abs(lhs - rhs) + elif ctype == "leq": + va = max(0.0, lhs - rhs) + elif ctype == "geq": + va = max(0.0, rhs - lhs) + else: + va = 0.0 + if va > tol: + normalizer = max(abs(rhs), eps) + violations.append((idx, msg)) + magnitudes.append({ + "constraint": idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(va), + "normalizer": float(normalizer), + "ratio": float(va / normalizer), + }) + + def is_work(s): + return s != "None" + + def get_shifts(nurse_id): + """Return list of shifts for days 1..num_days (0-indexed list).""" + return [schedule.get(nurse_id, {}).get(f"day_{d}", "None") + for d in range(1, num_days + 1)] + + # ================================================================== + # Constraint 1 (1b): Each nurse exactly one shift per day + # ================================================================== + for nid in nurse_ids: + if nid not in schedule: + record(1, f"Nurse {nid} missing from schedule", 0, 1, "eq") + continue + for d in range(1, num_days + 1): + dk = f"day_{d}" + if dk not in schedule[nid]: + record(1, f"Nurse {nid} missing assignment on day {d}", 0, 1, "eq") + else: + s = schedule[nid][dk] + if s not in all_shifts: + record(1, f"Nurse {nid} day {d}: invalid shift '{s}'", 0, 1, "eq") + + # ================================================================== + # Constraint 2 (1c): exact skill-assignment witness and hard/soft + # possession rule. Every worked assignment has exactly one reported skill; + # a day off reports "None". + # ================================================================== + hard_skill = bool(hard_con.get("skill_requirement", False)) + for nid in nurse_ids: + nurse_skill_days = skill_assignments.get(nid, {}) + if not isinstance(nurse_skill_days, dict): + record(2, f"Nurse {nid} has no skill-assignment mapping", 0, 1, "eq") + continue + for d in range(1, num_days + 1): + day_key = f"day_{d}" + shift = schedule.get(nid, {}).get(day_key, "None") + if day_key not in nurse_skill_days: + record(2, f"Nurse {nid} missing skill assignment on day {d}", 0, 1, "eq") + continue + assigned_skill = nurse_skill_days[day_key] + if not is_work(shift): + if assigned_skill != "None": + record(2, + f"Nurse {nid} is off on day {d} but reports skill {assigned_skill}", + 1, 0, "eq") + elif assigned_skill not in skills: + record(2, + f"Nurse {nid} works {shift} on day {d} but skill {assigned_skill!r} is invalid", + 0, 1, "eq") + elif hard_skill and assigned_skill not in nurse_skills[nid]: + record(2, + f"Nurse {nid} lacks assigned skill {assigned_skill} on day {d}", + 0, 1, "geq") + + # ================================================================== + # Constraint 3 (1d): exact hard demand equality where requested. In soft + # variants, nonnegative z absorbs the shortfall and is recomputed below. + # ================================================================== + if hard_con.get("demand_equality", False): + for d in range(1, num_days + 1): + day_key = f"day_{d}" + for shift in shifts: + for skill in skills: + required = float( + demand.get(day_key, {}).get(shift, {}).get(skill, 0) + ) + assigned = sum( + 1 + for nid in nurse_ids + if schedule.get(nid, {}).get(day_key) == shift + and skill_assignments.get(nid, {}).get(day_key) == skill + ) + if abs(assigned - required) > tol: + record(3, + f"Hard demand equality day={d}, shift={shift}, skill={skill}: assigned={assigned}, required={required}", + assigned, required, "eq") + + # ================================================================== + # Constraint 4 (1e): Integrality — trivially satisfied for discrete + # ================================================================== + + # ================================================================== + # Constraint 5 (1f): Non-negativity of z — trivially satisfied + # ================================================================== + + # ================================================================== + # Constraint 6: Total shift types / total working days + # Hard only if present in hard_constraints. + # ================================================================== + tw = hard_con.get("total_working_days") + if tw: + tw_min = tw.get("min", 0) + tw_max = tw.get("max", num_days) + for nid in nurse_ids: + total = sum(1 for s in get_shifts(nid) if is_work(s)) + if total > tw_max: + record(6, + f"Nurse {nid} works {total} days, max allowed {tw_max}", + total, tw_max, "leq") + if total < tw_min: + record(6, + f"Nurse {nid} works {total} days, min required {tw_min}", + total, tw_min, "geq") + + # ================================================================== + # Constraint 7: Total worked weekends + # ================================================================== + tww = hard_con.get("total_worked_weekends") + if tww: + tww_max = tww.get("max", len(weekends)) + for nid in nurse_ids: + wk_count = 0 + for wk in weekends: + if any( + is_work(schedule.get(nid, {}).get(f"day_{day}", "None")) + for day in weekend_days(wk) + ): + wk_count += 1 + if wk_count > tww_max: + record(7, + f"Nurse {nid} works {wk_count} weekends, max {tww_max}", + wk_count, tww_max, "leq") + + # ================================================================== + # Constraint 8: Consecutive shift types + # Covers consecutive_working_days, consecutive_days_off, + # and consecutive_same_shift (all sub-cases of paper constraint 5). + # ================================================================== + cw = hard_con.get("consecutive_working_days") + if cw: + cw_min = cw.get("min", 0) + cw_max = cw.get("max", num_days) + for nid in nurse_ids: + sched = get_shifts(nid) + streak = 0 + for d in range(num_days): + if is_work(sched[d]): + streak += 1 + if streak > cw_max: + record(8, + f"Nurse {nid}: {streak} consecutive working days at day {d+1}, max {cw_max}", + streak, cw_max, "leq") + else: + if streak > 0 and streak < cw_min: + # Don't penalise boundary streaks (starting at day 1) + start_day = d - streak # 0-indexed start + if start_day > 0: + record(8, + f"Nurse {nid}: {streak} consecutive working days ending day {d}, min {cw_min}", + streak, cw_min, "geq") + streak = 0 + # Final streak: don't penalise if ends at last day (boundary) + + co = hard_con.get("consecutive_days_off") + if co: + co_min = co.get("min", 0) + co_max = co.get("max", num_days) + for nid in nurse_ids: + sched = get_shifts(nid) + streak = 0 + for d in range(num_days): + if not is_work(sched[d]): + streak += 1 + if streak > co_max: + record(8, + f"Nurse {nid}: {streak} consecutive days off at day {d+1}, max {co_max}", + streak, co_max, "leq") + else: + if streak > 0 and streak < co_min: + start_day = d - streak + if start_day > 0: + record(8, + f"Nurse {nid}: {streak} consecutive days off ending day {d}, min {co_min}", + streak, co_min, "geq") + streak = 0 + + cs = hard_con.get("consecutive_same_shift") + if cs: + cs_max = cs.get("max", num_days) + for nid in nurse_ids: + sched = get_shifts(nid) + for s in shifts: + streak = 0 + for d in range(num_days): + if sched[d] == s: + streak += 1 + if streak > cs_max: + record(8, + f"Nurse {nid}: {streak} consecutive '{s}' shifts at day {d+1}, max {cs_max}", + streak, cs_max, "leq") + else: + streak = 0 + + # ================================================================== + # Constraint 9: Consecutive worked weekends + # ================================================================== + cwk = hard_con.get("consecutive_worked_weekends") + if cwk: + cwk_max = cwk.get("max", len(weekends)) + for nid in nurse_ids: + streak = 0 + for wk in weekends: + if any( + is_work(schedule.get(nid, {}).get(f"day_{day}", "None")) + for day in weekend_days(wk) + ): + streak += 1 + if streak > cwk_max: + record(9, + f"Nurse {nid}: {streak} consecutive worked weekends at week {wk['week']}, max {cwk_max}", + streak, cwk_max, "leq") + else: + streak = 0 + + # ================================================================== + # Constraint 10: Identical weekend + # ================================================================== + iw = hard_con.get("identical_weekend") + if iw and iw.get("enabled", False): + for nid in nurse_ids: + for wk in weekends: + constituent_shifts = [ + schedule.get(nid, {}).get(f"day_{day}", "None") + for day in weekend_days(wk) + ] + if len(set(constituent_shifts)) > 1: + record(10, + f"Nurse {nid} week {wk['week']}: weekend shifts {constituent_shifts} must be identical", + 1, 0, "leq") + + # ================================================================== + # Constraint 11: Forbidden patterns + # ================================================================== + fps = hard_con.get("forbidden_patterns", []) + for fp in fps: + pattern = fp["pattern"] + pat_len = len(pattern) + desc = fp.get("description", "forbidden pattern") + for nid in nurse_ids: + for d in range(1, num_days - pat_len + 2): + match = True + for offset, (day_type, shift_name) in enumerate(pattern): + dd = d + offset + actual = schedule.get(nid, {}).get(f"day_{dd}", "None") + if actual != shift_name: + match = False + break + if match: + day_range = f"days {d}-{d + pat_len - 1}" + record(11, + f"Nurse {nid}: {desc} at {day_range}", + pat_len, pat_len - 1, "leq") + + # ================================================================== + # Constraint 12: Preferences (only if marked as hard) + # ================================================================== + if "preferences" in hard_con or hard_con.get("hard_preferences", False): + for nurse in nurses: + nid = nurse["id"] + for pref in nurse.get("preferences", []): + day = pref["day"] + ptype = pref["type"] + shift_pref = pref.get("shift", "None") + dk = f"day_{day}" + actual = schedule.get(nid, {}).get(dk, "None") + + violated = False + if ptype == "day_off" and actual != "None": + violated = True + msg = f"Nurse {nid} day {day}: prefers day off, assigned {actual}" + elif ptype == "day_on" and actual == "None": + violated = True + msg = f"Nurse {nid} day {day}: prefers working, assigned off" + elif ptype == "shift_on" and actual != shift_pref: + violated = True + msg = f"Nurse {nid} day {day}: prefers {shift_pref}, assigned {actual}" + elif ptype == "shift_off" and actual == shift_pref: + violated = True + msg = f"Nurse {nid} day {day}: prefers not {shift_pref}, assigned {actual}" + + if violated: + record(12, msg, 1, 0, "leq") + + # ================================================================== + # Constraint 13: Objective consistency from the concrete schedule and + # nurse-to-skill witness. + # ================================================================== + 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: + schedule_pen = 0.0 + + # --- SC1: total_working_days (soft) --- + s_tw = soft_con.get("total_working_days") + if isinstance(s_tw, dict): + tw_min_s = s_tw.get("min", 0) + tw_max_s = s_tw.get("max", num_days) + pen_under = s_tw.get("penalty_under", 0) + pen_over = s_tw.get("penalty_over", 0) + for nid in nurse_ids: + total = sum(1 for s in get_shifts(nid) if is_work(s)) + schedule_pen += pen_over * max(0, total - tw_max_s) + schedule_pen += pen_under * max(0, tw_min_s - total) + + # --- SC2: total_worked_weekends (soft) --- + s_tww = soft_con.get("total_worked_weekends") + if isinstance(s_tww, dict): + tww_max_s = s_tww.get("max", len(weekends)) + pen_wk = s_tww.get("penalty", 0) + for nid in nurse_ids: + wk_count = 0 + for wk in weekends: + if any( + is_work(schedule.get(nid, {}).get(f"day_{day}", "None")) + for day in weekend_days(wk) + ): + wk_count += 1 + schedule_pen += pen_wk * max(0, wk_count - tww_max_s) + + # --- SC3: consecutive_working_days (soft) --- + s_cwd = soft_con.get("consecutive_working_days") + if isinstance(s_cwd, dict): + cwd_max_s = s_cwd.get("max") + cwd_min_s = s_cwd.get("min") + pen_cwd_over = s_cwd.get("penalty_over", 0) + pen_cwd_under = s_cwd.get("penalty_under", 0) + for nid in nurse_ids: + sched = get_shifts(nid) + if cwd_max_s is not None: + window = cwd_max_s + 1 + for d_start in range(1, num_days + 1): + if d_start + window - 1 > num_days: + break + sum_work = sum(1 for k in range(window) + if is_work(sched[d_start - 1 + k])) + schedule_pen += pen_cwd_over * max(0, sum_work - cwd_max_s) + if cwd_min_s is not None and cwd_min_s > 1: + for g in range(1, cwd_min_s): + for d_start in range(1, num_days + 1): + end_day = d_start + g - 1 + if end_day > num_days: + break + if d_start == 1 or end_day + 1 > num_days: + continue + if (not is_work(sched[d_start - 2]) and + all(is_work(sched[d_start - 1 + k]) for k in range(g)) and + not is_work(sched[end_day])): + schedule_pen += pen_cwd_under + + # --- SC4: consecutive_days_off (soft) --- + s_cdo = soft_con.get("consecutive_days_off") + if isinstance(s_cdo, dict): + cdo_max_s = s_cdo.get("max") + cdo_min_s = s_cdo.get("min") + pen_cdo_over = s_cdo.get("penalty_over", 0) + pen_cdo_under = s_cdo.get("penalty_under", 0) + for nid in nurse_ids: + sched = get_shifts(nid) + if cdo_max_s is not None: + window = cdo_max_s + 1 + for d_start in range(1, num_days + 1): + if d_start + window - 1 > num_days: + break + sum_off = sum(1 for k in range(window) + if not is_work(sched[d_start - 1 + k])) + schedule_pen += pen_cdo_over * max(0, sum_off - cdo_max_s) + if cdo_min_s is not None and cdo_min_s > 1: + for g in range(1, cdo_min_s): + for d_start in range(1, num_days + 1): + end_day = d_start + g - 1 + if end_day > num_days: + break + if d_start == 1 or end_day + 1 > num_days: + continue + if (is_work(sched[d_start - 2]) and + all(not is_work(sched[d_start - 1 + k]) for k in range(g)) and + is_work(sched[end_day])): + schedule_pen += pen_cdo_under + + # --- SC5: consecutive_same_shift (soft) --- + s_css = soft_con.get("consecutive_same_shift") + if isinstance(s_css, dict): + css_max_s = s_css.get("max") + pen_css = s_css.get("penalty", 0) + if css_max_s is not None: + window = css_max_s + 1 + for nid in nurse_ids: + sched = get_shifts(nid) + for s in shifts: + for d_start in range(1, num_days + 1): + if d_start + window - 1 > num_days: + break + sum_s = sum(1 for k in range(window) + if sched[d_start - 1 + k] == s) + schedule_pen += pen_css * max(0, sum_s - css_max_s) + + # --- SC6: consecutive_worked_weekends (soft) --- + s_cww = soft_con.get("consecutive_worked_weekends") + if isinstance(s_cww, dict): + cww_max_s = s_cww.get("max") + pen_cww = s_cww.get("penalty", 0) + if cww_max_s is not None: + num_wks = len(weekends) + window = cww_max_s + 1 + for nid in nurse_ids: + wk_worked_flag = [] + for wk in weekends: + wk_worked_flag.append( + 1 if any( + is_work(schedule.get(nid, {}).get(f"day_{day}", "None")) + for day in weekend_days(wk) + ) else 0) + for start in range(num_wks): + if start + window > num_wks: + break + sum_w = sum(wk_worked_flag[start + k] for k in range(window)) + schedule_pen += pen_cww * max(0, sum_w - cww_max_s) + + # --- SC7: identical_weekend (soft) --- + s_iw = soft_con.get("identical_weekend") + if isinstance(s_iw, dict) and s_iw.get("enabled", False): + pen_iw = s_iw.get("penalty", 0) + for nid in nurse_ids: + for wk in weekends: + constituent_shifts = [ + schedule.get(nid, {}).get(f"day_{day}", "None") + for day in weekend_days(wk) + ] + if len(set(constituent_shifts)) > 1: + schedule_pen += pen_iw + + # --- Soft forbidden patterns --- + for fp in soft_con.get("forbidden_patterns", []) or []: + pattern = fp.get("pattern", []) + pat_len = len(pattern) + penalty = float(fp.get("penalty", 0) or 0) + if not pattern: + continue + for nid in nurse_ids: + for d_start in range(1, num_days - pat_len + 2): + if all( + schedule.get(nid, {}).get(f"day_{d_start + offset}", "None") + == shift_name + for offset, (_day_type, shift_name) in enumerate(pattern) + ): + schedule_pen += penalty + + # --- SC8: preferences (gurobi always applies these, regardless of + # whether the instance lists them in hard/soft; each pref carries + # its own penalty field). + for nurse in nurses: + nid = nurse["id"] + for pref in nurse.get("preferences", []): + day = pref["day"] + if day < 1 or day > num_days: + continue + ptype = pref["type"] + shift_pref = pref.get("shift", "None") + penalty = pref.get("penalty", 0) + actual = schedule.get(nid, {}).get(f"day_{day}", "None") + if ptype == "day_off": + if actual != "None": + schedule_pen += penalty + elif ptype == "day_on": + if actual == "None": + schedule_pen += penalty + elif ptype == "shift_on": + if shift_pref in all_shifts and actual != shift_pref: + schedule_pen += penalty + elif ptype == "shift_off": + if shift_pref in all_shifts and actual == shift_pref: + schedule_pen += penalty + + # --- Soft skill-possession mismatches --- + if not hard_skill: + mismatch_penalty = float( + soft_con.get("skill_requirement_penalty", 0) or 0 + ) + for nid in nurse_ids: + for d in range(1, num_days + 1): + day_key = f"day_{d}" + if is_work(schedule.get(nid, {}).get(day_key, "None")): + assigned_skill = skill_assignments.get(nid, {}).get(day_key) + if assigned_skill in skills and assigned_skill not in nurse_skills[nid]: + schedule_pen += mismatch_penalty + + # --- Exact unsatisfied demand from the submitted skill witness --- + unmet_demand = 0.0 + pen_z = float(demand_penalty or 0) + for d in range(1, num_days + 1): + day_key = f"day_{d}" + day_dem = demand.get(day_key, {}) + if not day_dem: + continue + for s in shifts: + s_dem = day_dem.get(s, {}) + if not s_dem: + continue + for skill, required in s_dem.items(): + assigned = sum( + 1 + for nid in nurse_ids + if schedule.get(nid, {}).get(day_key, "None") == s + and skill_assignments.get(nid, {}).get(day_key) == skill + ) + unmet_demand += max(0.0, float(required) - assigned) + + demand_cost = pen_z * unmet_demand + expected_obj = schedule_pen + demand_cost + objective_tol = max(1e-5, 1e-7 * max(1.0, abs(expected_obj))) + + if abs(reported - expected_obj) > objective_tol: + record(13, + (f"Objective consistency: reported objective_value=" + f"{reported} does not equal the exactly recomputed value " + f"(schedule_penalty={schedule_pen:.6g} + " + f"demand_penalty={demand_cost:.6g} = {expected_obj:.6g}); " + f"difference={abs(reported - expected_obj):.3g}, " + f"tol={objective_tol:.3g}"), + reported, expected_obj, "eq") + + # ================================================================== + # Build result + # ================================================================== + violated_indices = sorted(set(c for c, _ in violations)) + # Aggregate messages per constraint, keeping order + seen_msgs = [] + for c in violated_indices: + for ci, m in violations: + if ci == c and m not in seen_msgs: + seen_msgs.append(m) + + feasible = len(violated_indices) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": seen_msgs, + "violation_magnitudes": magnitudes if not feasible else [], + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Nurse Scheduling (Legrain & Omer 2024)") + 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") + args = parser.parse_args() + + with open(args.instance_path) as f: + inst = json.load(f) + with open(args.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(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(inst, sol) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility: {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/legrain2024/gurobi_code.py b/tasks/legrain2024/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..7968019f9464c6d4561cabb996d33e5f0c8eb575 --- /dev/null +++ b/tasks/legrain2024/gurobi_code.py @@ -0,0 +1,775 @@ +""" +Nurse Scheduling Problem (NSP) — Compact ILP formulation solved with Gurobi. + +This implements a compact reformulation equivalent to the extended formulation +(1a)-(1f) from Legrain & Omer (2024). The paper uses an exponential number of +roster variables in a set-partitioning style formulation, solved via column +generation. Since enumerating all rosters is impractical for direct ILP +submission, we instead use a compact formulation with direct shift-assignment +variables that models the same constraints and objective. + +Variables: + w[i,d,s] binary — 1 if nurse i works shift s on day d + (s includes "None" for day off) + y[i,d,s,sigma] binary — 1 if nurse i performs skill sigma on day d, shift s + (only for work shifts s != "None"; only created for + skills the nurse possesses) + z[d,s,sigma] >= 0 — unsatisfied demand for skill sigma on day d, shift s + +ASSUMPTION (boundary handling for min-consecutive constraints): Streaks of +working days (or days off) that start at day 1 or end at the last day of the +horizon are *not* penalized for being shorter than the minimum. This is because +those streaks may be part of a longer streak that extends beyond the planning +horizon. +""" + +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: str) -> dict: + with open(path, "r") as f: + return json.load(f) + + +def build_model(inst: dict) -> tuple: + """Build the Gurobi model and return (model, metadata needed for solution extraction).""" + + meta = inst["instance_metadata"] + num_nurses = meta["num_nurses"] + num_days = meta["num_days"] + shifts = inst["shifts"] # work shifts only (e.g. ["Early", "Night"]) + skills = inst["skills"] + nurses = inst["nurses"] + weekends = inst["weekends"] + demand = inst["demand"] + demand_penalty = inst["unsatisfied_demand_penalty"] + hard = inst["constraints"]["hard_constraints"] + soft = inst["constraints"]["soft_constraints"] + + all_shifts = shifts + ["None"] # include "None" as day-off shift + days = list(range(1, num_days + 1)) + + # Build nurse skill sets + nurse_skills = {} + for nurse in nurses: + nurse_skills[nurse["id"]] = set(nurse["skills"]) + + nurse_ids = [n["id"] for n in nurses] + + model = gp.Model("NSP_Legrain2024") + model.setParam("Threads", 1) + + # ----------------------------------------------------------------------- + # Decision variables + # ----------------------------------------------------------------------- + + # w[i,d,s]: nurse i works shift s on day d + w = {} + for i in nurse_ids: + for d in days: + for s in all_shifts: + w[i, d, s] = model.addVar(vtype=GRB.BINARY, name=f"w_{i}_{d}_{s}") + + # y[i,d,s,sigma]: nurse i uses skill sigma on day d, shift s. When skill + # possession is hard, unavailable skills are omitted. The INRC-I release + # variant makes possession soft, so all skills must remain selectable and + # a mismatch is charged in the objective. + y = {} + hard_skill_requirement = bool(hard.get("skill_requirement", False)) + for i in nurse_ids: + for d in days: + for s in shifts: + for sigma in skills: + if not hard_skill_requirement or sigma in nurse_skills[i]: + y[i, d, s, sigma] = model.addVar( + vtype=GRB.BINARY, name=f"y_{i}_{d}_{s}_{sigma}" + ) + + # z[d,s,sigma]: unsatisfied demand + z = {} + for d in days: + for s in shifts: + for sigma in skills: + z[d, s, sigma] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, name=f"z_{d}_{s}_{sigma}" + ) + + model.update() + + # ----------------------------------------------------------------------- + # Hard constraints + # ----------------------------------------------------------------------- + + # (HC1) Single assignment per day: each nurse works exactly one shift + # (including "None") per day. + for i in nurse_ids: + for d in days: + model.addConstr( + gp.quicksum(w[i, d, s] for s in all_shifts) == 1, + name=f"single_assign_{i}_{d}", + ) + + # (HC2) Forbidden patterns + for fp in hard.get("forbidden_patterns", []): + pattern = fp["pattern"] + # Pattern is a list of [day_type, shift] pairs for consecutive days. + # e.g. [["AnyDay","Night"],["AnyDay","Early"]] means Night on day d + # followed by Early on day d+1 is forbidden. + pat_len = len(pattern) + if pat_len < 2: + continue # single-day patterns don't constrain consecutive days + + for i in nurse_ids: + for d in days: + # Check if the window d..d+pat_len-1 fits in the horizon + if d + pat_len - 1 > num_days: + continue + # Build the constraint: sum of matching w variables <= pat_len - 1 + terms = [] + valid = True + for offset, (day_type, shift_name) in enumerate(pattern): + dd = d + offset + if shift_name not in all_shifts: + valid = False + break + terms.append(w[i, dd, shift_name]) + if valid and terms: + model.addConstr( + gp.quicksum(terms) <= pat_len - 1, + name=f"forbidden_{fp['description'][:20]}_{i}_{d}", + ) + + # ----------------------------------------------------------------------- + # Linking constraints + # ----------------------------------------------------------------------- + + # (LC1) For work shifts: w[i,d,s] = sum_sigma y[i,d,s,sigma] + for i in nurse_ids: + for d in days: + for s in shifts: + skill_vars = [ + y[i, d, s, sigma] + for sigma in skills + if (i, d, s, sigma) in y + ] + if skill_vars: + model.addConstr( + w[i, d, s] == gp.quicksum(skill_vars), + name=f"link_wy_{i}_{d}_{s}", + ) + else: + # Nurse has no skills for this shift — cannot work it + model.addConstr( + w[i, d, s] == 0, + name=f"no_skill_{i}_{d}_{s}", + ) + + # (LC2) Demand coverage. Most variants allow penalized shortfall z. The + # INRC-I-style instance explicitly requests exact hard demand. + hard_demand_equality = bool(hard.get("demand_equality", False)) + for d in days: + day_key = f"day_{d}" + if day_key not in demand: + continue + for s in shifts: + if s not in demand[day_key]: + continue + for sigma in skills: + if sigma not in demand[day_key][s]: + continue + b = demand[day_key][s][sigma] + assigned = [ + y[i, d, s, sigma] + for i in nurse_ids + if (i, d, s, sigma) in y + ] + if hard_demand_equality: + model.addConstr( + gp.quicksum(assigned) == b, + name=f"hard_demand_equal_{d}_{s}_{sigma}", + ) + model.addConstr( + z[d, s, sigma] == 0, + name=f"hard_demand_no_slack_{d}_{s}_{sigma}", + ) + else: + model.addConstr( + gp.quicksum(assigned) + z[d, s, sigma] >= b, + name=f"demand_{d}_{s}_{sigma}", + ) + + # ----------------------------------------------------------------------- + # Helper: work[i,d] = 1 - w[i,d,"None"] (continuous, derived) + # We'll use expressions inline rather than extra variables. + # ----------------------------------------------------------------------- + + def work_expr(i, d): + """Expression equal to 1 if nurse i works on day d, 0 otherwise.""" + return 1 - w[i, d, "None"] + + # ----------------------------------------------------------------------- + # Soft constraints — penalty variables and objective terms + # ----------------------------------------------------------------------- + obj_terms = [] + + # Soft skill possession: every mismatch is visible in y and charged once. + if not hard_skill_requirement: + mismatch_penalty = float(soft.get("skill_requirement_penalty", 0) or 0) + for (i, d, s, sigma), variable in y.items(): + if sigma not in nurse_skills[i]: + obj_terms.append(mismatch_penalty * variable) + + # Soft forbidden patterns (the hard versions were added above). + for fp_index, fp in enumerate(soft.get("forbidden_patterns", []) or []): + pattern = fp.get("pattern", []) + pat_len = len(pattern) + if not pattern: + continue + penalty = float(fp.get("penalty", 0) or 0) + for i in nurse_ids: + for d in days: + if d + pat_len - 1 > num_days: + continue + terms = [] + valid = True + for offset, (_day_type, shift_name) in enumerate(pattern): + if shift_name not in all_shifts: + valid = False + break + terms.append(w[i, d + offset, shift_name]) + if valid: + violation = model.addVar( + vtype=GRB.BINARY, + name=f"soft_forbidden_{fp_index}_{i}_{d}", + ) + model.addConstr( + violation >= gp.quicksum(terms) - (pat_len - 1), + name=f"soft_forbidden_link_{fp_index}_{i}_{d}", + ) + obj_terms.append(penalty * violation) + + # --- (SC1) Total working days [min, max] per nurse --- + tw = soft.get("total_working_days") + if tw: + tw_min = tw["min"] + tw_max = tw["max"] + pen_under = tw["penalty_under"] + pen_over = tw["penalty_over"] + for i in nurse_ids: + over = model.addVar(lb=0, name=f"over_total_{i}") + under = model.addVar(lb=0, name=f"under_total_{i}") + total_work = gp.quicksum(work_expr(i, d) for d in days) + model.addConstr(over >= total_work - tw_max, name=f"total_over_{i}") + model.addConstr(under >= tw_min - total_work, name=f"total_under_{i}") + obj_terms.append(pen_over * over) + obj_terms.append(pen_under * under) + + # --- (SC2) Total worked weekends [max] per nurse --- + # Always build wk_worked indicators so downstream HARD constraints + # (consecutive_worked_weekends) can reference them even when total_worked + # _weekends is in hard_constraints rather than soft_constraints. + tww = soft.get("total_worked_weekends") + wk_worked = {} # wk_worked[i,wk_idx] binary + h_tww_present = isinstance(hard.get("consecutive_worked_weekends"), dict) or \ + isinstance(hard.get("total_worked_weekends"), dict) + if tww or h_tww_present: + for i in nurse_ids: + for wk in weekends: + wk_idx = wk["week"] + weekend_days = [ + wk[key] for key in ("friday", "saturday", "sunday") + if key in wk + ] + wk_var = model.addVar(vtype=GRB.BINARY, name=f"wk_worked_{i}_{wk_idx}") + wk_worked[i, wk_idx] = wk_var + for weekend_day in weekend_days: + for s in shifts: + model.addConstr( + wk_var >= w[i, weekend_day, s], + name=f"wk_link_{weekend_day}_{i}_{wk_idx}_{s}", + ) + model.addConstr( + wk_var + <= gp.quicksum( + w[i, weekend_day, s] + for weekend_day in weekend_days for s in shifts + ), + name=f"wk_upper_{i}_{wk_idx}", + ) + + if tww: + max_wk = tww["max"] + pen_wk = tww["penalty"] + for i in nurse_ids: + over_wk = model.addVar(lb=0, name=f"over_weekends_{i}") + model.addConstr( + over_wk + >= gp.quicksum( + wk_worked[i, wk["week"]] for wk in weekends + ) + - max_wk, + name=f"total_wk_over_{i}", + ) + obj_terms.append(pen_wk * over_wk) + + # --- (SC3) Consecutive working days [min, max] --- + cwd = soft.get("consecutive_working_days") + if cwd: + cwd_min = cwd["min"] + cwd_max = cwd["max"] + pen_cwd_under = cwd["penalty_under"] + pen_cwd_over = cwd["penalty_over"] + + for i in nurse_ids: + # Max consecutive working days: in any window of (cwd_max+1) days, + # at most cwd_max are working days. + window = cwd_max + 1 + for d in days: + if d + window - 1 > num_days: + break + slack = model.addVar(lb=0, name=f"consec_work_over_{i}_{d}") + model.addConstr( + gp.quicksum(work_expr(i, d + k) for k in range(window)) + <= cwd_max + slack, + name=f"max_consec_work_{i}_{d}", + ) + obj_terms.append(pen_cwd_over * slack) + + # Min consecutive working days: penalize short streaks. + # A streak of length g (1 <= g < cwd_min) starting at day d is + # detected when day d-1 is off (or d==1), days d..d+g-1 are working, + # and day d+g is off (or d+g > num_days). + # + # ASSUMPTION: We do NOT penalize boundary streaks (starting at day 1 + # or ending at the last day) since they may extend beyond the horizon. + for g in range(1, cwd_min): + for d in days: + end_day = d + g - 1 + if end_day > num_days: + break + + # We need day d-1 to be off and day d+g to be off + # (boundary: d==1 or d+g > num_days means boundary streak, + # skip per assumption) + if d == 1 or end_day + 1 > num_days: + continue + + # Violation if: off on d-1 AND work on d..end_day AND off on d+g + # That is: w[i,d-1,None]=1, work(i,d')=1 for d'=d..end_day, w[i,end_day+1,None]=1 + # + # Linearize: viol >= w[i,d-1,None] + sum_{d'=d}^{end_day} work(i,d') + w[i,end_day+1,None] - (g+1) + # If all conditions hold, RHS = 1 + g + 1 - (g+1) = 1, so viol >= 1 + # Otherwise RHS <= 0 + viol = model.addVar(lb=0, name=f"short_work_{i}_{d}_{g}") + model.addConstr( + viol + >= w[i, d - 1, "None"] + + gp.quicksum(work_expr(i, d + k) for k in range(g)) + + w[i, end_day + 1, "None"] + - (g + 1), + name=f"min_consec_work_{i}_{d}_{g}", + ) + obj_terms.append(pen_cwd_under * viol) + + # --- (SC4) Consecutive days off [min, max] --- + cdo = soft.get("consecutive_days_off") + if cdo: + cdo_min = cdo["min"] + cdo_max = cdo["max"] + pen_cdo_under = cdo["penalty_under"] + pen_cdo_over = cdo["penalty_over"] + + for i in nurse_ids: + # Max consecutive days off: in any window of (cdo_max+1) days, + # at most cdo_max are off. + window = cdo_max + 1 + for d in days: + if d + window - 1 > num_days: + break + slack = model.addVar(lb=0, name=f"consec_off_over_{i}_{d}") + model.addConstr( + gp.quicksum(w[i, d + k, "None"] for k in range(window)) + <= cdo_max + slack, + name=f"max_consec_off_{i}_{d}", + ) + obj_terms.append(pen_cdo_over * slack) + + # Min consecutive days off: penalize short rest streaks. + # ASSUMPTION: boundary streaks not penalized (same as working days). + for g in range(1, cdo_min): + for d in days: + end_day = d + g - 1 + if end_day > num_days: + break + if d == 1 or end_day + 1 > num_days: + continue + + # Violation if: work on d-1, off on d..end_day, work on d+g + viol = model.addVar(lb=0, name=f"short_off_{i}_{d}_{g}") + model.addConstr( + viol + >= work_expr(i, d - 1) + + gp.quicksum(w[i, d + k, "None"] for k in range(g)) + + work_expr(i, end_day + 1) + - (g + 1), + name=f"min_consec_off_{i}_{d}_{g}", + ) + obj_terms.append(pen_cdo_under * viol) + + # --- (SC5) Consecutive same shift [max] --- + css = soft.get("consecutive_same_shift") + if css: + css_max = css["max"] + pen_css = css["penalty"] + window = css_max + 1 + for i in nurse_ids: + for s in shifts: + for d in days: + if d + window - 1 > num_days: + break + slack = model.addVar(lb=0, name=f"consec_shift_{i}_{s}_{d}") + model.addConstr( + gp.quicksum(w[i, d + k, s] for k in range(window)) + <= css_max + slack, + name=f"max_consec_shift_{i}_{s}_{d}", + ) + obj_terms.append(pen_css * slack) + + # --- (SC6) Consecutive worked weekends [max] --- + cww = soft.get("consecutive_worked_weekends") + if cww and wk_worked: + cww_max = cww["max"] + pen_cww = cww["penalty"] + num_weekends = len(weekends) + wk_indices = [wk["week"] for wk in weekends] + + window = cww_max + 1 + for i in nurse_ids: + for start in range(len(wk_indices)): + if start + window > num_weekends: + break + slack = model.addVar( + lb=0, + name=f"consec_wk_{i}_{wk_indices[start]}", + ) + model.addConstr( + gp.quicksum( + wk_worked[i, wk_indices[start + k]] for k in range(window) + ) + <= cww_max + slack, + name=f"max_consec_wk_{i}_{wk_indices[start]}", + ) + obj_terms.append(pen_cww * slack) + + # --- (SC7) Identical weekend --- + iw = soft.get("identical_weekend") + if iw and iw.get("enabled", False): + pen_iw = iw["penalty"] + for i in nurse_ids: + for wk in weekends: + wk_idx = wk["week"] + weekend_days = [ + wk[key] for key in ("friday", "saturday", "sunday") + if key in wk + ] + if len(weekend_days) < 2: + continue + base_day = weekend_days[0] + viol = model.addVar( + vtype=GRB.BINARY, name=f"ident_wk_viol_{i}_{wk_idx}" + ) + # If any constituent day differs from the first weekend day, + # charge the weekend once. + for other_day in weekend_days[1:]: + for s in all_shifts: + model.addConstr( + viol >= w[i, base_day, s] - w[i, other_day, s], + name=f"ident_wk_a_{i}_{wk_idx}_{other_day}_{s}", + ) + model.addConstr( + viol >= w[i, other_day, s] - w[i, base_day, s], + name=f"ident_wk_b_{i}_{wk_idx}_{other_day}_{s}", + ) + obj_terms.append(pen_iw * viol) + + # --- (SC8) Nurse preferences --- + for nurse in nurses: + i = nurse["id"] + for pref in nurse.get("preferences", []): + day = pref["day"] + ptype = pref["type"] + shift_pref = pref["shift"] + penalty = pref["penalty"] + + if day < 1 or day > num_days: + continue + + if ptype == "day_off": + # Nurse prefers day off: penalize if not off + viol = model.addVar(lb=0, name=f"pref_off_{i}_{day}") + model.addConstr( + viol >= 1 - w[i, day, "None"], + name=f"pref_off_c_{i}_{day}", + ) + obj_terms.append(penalty * viol) + elif ptype == "day_on": + # Nurse prefers to work: penalize if off + viol = model.addVar(lb=0, name=f"pref_on_{i}_{day}") + model.addConstr( + viol >= w[i, day, "None"], + name=f"pref_on_c_{i}_{day}", + ) + obj_terms.append(penalty * viol) + elif ptype == "shift_on": + # Nurse prefers a specific shift: penalize if not assigned that shift + if shift_pref in all_shifts: + viol = model.addVar(lb=0, name=f"pref_shift_{i}_{day}_{shift_pref}") + model.addConstr( + viol >= 1 - w[i, day, shift_pref], + name=f"pref_shift_c_{i}_{day}_{shift_pref}", + ) + obj_terms.append(penalty * viol) + elif ptype == "shift_off": + # Nurse prefers not to work a specific shift + if shift_pref in all_shifts: + viol = model.addVar(lb=0, name=f"pref_noshift_{i}_{day}_{shift_pref}") + model.addConstr( + viol >= w[i, day, shift_pref], + name=f"pref_noshift_c_{i}_{day}_{shift_pref}", + ) + obj_terms.append(penalty * viol) + + # --- Unsatisfied demand penalty (c_z, math_model §PARAMETERS) --- + for key in z: + obj_terms.append(demand_penalty * z[key]) + + # ----------------------------------------------------------------------- + # Hard versions of the same constraints (when instance puts a constraint + # in `hard_constraints` instead of `soft_constraints`, e.g. large_31). + # These have no slack — strict feasibility. + # ----------------------------------------------------------------------- + + # Hard: total_working_days + h_tw = hard.get("total_working_days") if isinstance(hard.get("total_working_days"), dict) else None + if h_tw: + for i in nurse_ids: + total_work = gp.quicksum(work_expr(i, d) for d in days) + if "max" in h_tw: + model.addConstr(total_work <= h_tw["max"], name=f"hard_total_max_{i}") + if "min" in h_tw: + model.addConstr(total_work >= h_tw["min"], name=f"hard_total_min_{i}") + + # Hard: consecutive_working_days (max + min) + h_cwd = hard.get("consecutive_working_days") if isinstance(hard.get("consecutive_working_days"), dict) else None + if h_cwd: + cmax = h_cwd.get("max") + cmin = h_cwd.get("min") + for i in nurse_ids: + if cmax is not None: + window = cmax + 1 + for d in days: + if d + window - 1 > num_days: + break + model.addConstr( + gp.quicksum(work_expr(i, d + k) for k in range(window)) <= cmax, + name=f"hard_max_consec_work_{i}_{d}", + ) + if cmin is not None: + # Hard min: a working streak shorter than cmin is forbidden. + # Forbid pattern off-(work for g)-off where 1 <= g < cmin. + for g in range(1, cmin): + for d in days: + end_day = d + g - 1 + if end_day > num_days or d == 1 or end_day + 1 > num_days: + continue + # Disallow: w[i,d-1,None] + work(d..end_day) + w[i,end_day+1,None] >= g+2 + # i.e. forbid the case where this exactly equals g+2. + # Linear: sum <= g+1 ensures NOT all three conditions fully meet. + model.addConstr( + w[i, d - 1, "None"] + + gp.quicksum(work_expr(i, d + k) for k in range(g)) + + w[i, end_day + 1, "None"] + <= g + 1, + name=f"hard_min_consec_work_{i}_{d}_{g}", + ) + + # Hard: consecutive_days_off (max + min) + h_cdo = hard.get("consecutive_days_off") if isinstance(hard.get("consecutive_days_off"), dict) else None + if h_cdo: + cmax = h_cdo.get("max") + cmin = h_cdo.get("min") + for i in nurse_ids: + if cmax is not None: + window = cmax + 1 + for d in days: + if d + window - 1 > num_days: + break + model.addConstr( + gp.quicksum(w[i, d + k, "None"] for k in range(window)) <= cmax, + name=f"hard_max_consec_off_{i}_{d}", + ) + if cmin is not None: + for g in range(1, cmin): + for d in days: + end_day = d + g - 1 + if end_day > num_days or d == 1 or end_day + 1 > num_days: + continue + model.addConstr( + work_expr(i, d - 1) + + gp.quicksum(w[i, d + k, "None"] for k in range(g)) + + work_expr(i, end_day + 1) + <= g + 1, + name=f"hard_min_consec_off_{i}_{d}_{g}", + ) + + # Hard: consecutive_same_shift (max only) + h_css = hard.get("consecutive_same_shift") if isinstance(hard.get("consecutive_same_shift"), dict) else None + if h_css and "max" in h_css: + cmax = h_css["max"] + window = cmax + 1 + for i in nurse_ids: + for s in shifts: + for d in days: + if d + window - 1 > num_days: + break + model.addConstr( + gp.quicksum(w[i, d + k, s] for k in range(window)) <= cmax, + name=f"hard_max_consec_shift_{i}_{s}_{d}", + ) + + # Hard: consecutive_worked_weekends (max only) + h_cww = hard.get("consecutive_worked_weekends") if isinstance(hard.get("consecutive_worked_weekends"), dict) else None + if h_cww and "max" in h_cww and wk_worked: + cmax = h_cww["max"] + window = cmax + 1 + wks_sorted = sorted({k[1] for k in wk_worked}) + for i in nurse_ids: + for start_idx in range(len(wks_sorted) - window + 1): + wk_window = wks_sorted[start_idx : start_idx + window] + model.addConstr( + gp.quicksum(wk_worked[i, wk] for wk in wk_window) <= cmax, + name=f"hard_max_consec_wkends_{i}_{start_idx}", + ) + + # ----------------------------------------------------------------------- + # Objective: minimize total penalty + # ----------------------------------------------------------------------- + model.setObjective(gp.quicksum(obj_terms), GRB.MINIMIZE) + + return model, w, y, nurse_ids, days, all_shifts, shifts, num_days + + +def extract_solution(model, w, y, nurse_ids, days, all_shifts, shifts, num_days): + """Extract the solution from a solved model and return a dict.""" + if model.SolCount == 0: + return {"objective_value": None, "schedule": {}} + + schedule = {} + skill_assignments = {} + reported_skills = sorted({key[3] for key in y}) + for i in nurse_ids: + nurse_schedule = {} + nurse_skill_schedule = {} + for d in days: + assigned_shift = "None" + for s in all_shifts: + if w[i, d, s].X > 0.5: + assigned_shift = s + break + nurse_schedule[f"day_{d}"] = assigned_shift + assigned_skill = "None" + if assigned_shift != "None": + for sigma in reported_skills: + key = (i, d, assigned_shift, sigma) + if key in y and y[key].X > 0.5: + assigned_skill = sigma + break + nurse_skill_schedule[f"day_{d}"] = assigned_skill + schedule[i] = nurse_schedule + skill_assignments[i] = nurse_skill_schedule + + return { + "objective_value": model.ObjVal, + "schedule": schedule, + "skill_assignments": skill_assignments, + "solver_status": model.Status, + "best_bound": model.ObjBound, + "mip_gap": model.MIPGap, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Solve Nurse Scheduling Problem (Legrain & Omer 2024) with Gurobi" + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to instance JSON file", + ) + parser.add_argument( + "--solution_path", + type=str, + default="gurobi_solution_1.json", + help="Path for output solution JSON (default: gurobi_solution_1.json)", + ) + parser.add_argument( + "--time_limit", + type=int, + default=300, + help="Time limit in seconds (default: 300)", + ) + 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 + inst = load_instance(args.instance_path) + + # Build model + model, w, y, nurse_ids, days, all_shifts, shifts, num_days = build_model(inst) + + # Set parameters + model.setParam("TimeLimit", args.time_limit) + + # Solve + model.optimize() + + # Extract and save solution + if model.Status in (GRB.OPTIMAL, GRB.TIME_LIMIT, GRB.SUBOPTIMAL): + solution = extract_solution(model, w, y, nurse_ids, days, all_shifts, shifts, num_days) + else: + print(f"Model status: {model.Status} — no feasible solution found.") + solution = {"objective_value": None, "schedule": {}} + + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/legrain2024/gurobi_feasi_result/large_feasi_result_1.json b/tasks/legrain2024/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2024/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/legrain2024/gurobi_feasi_result/large_feasi_result_2.json b/tasks/legrain2024/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2024/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/legrain2024/gurobi_feasi_result/large_feasi_result_3.json b/tasks/legrain2024/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2024/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/legrain2024/gurobi_feasi_result/large_feasi_result_4.json b/tasks/legrain2024/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2024/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/legrain2024/gurobi_feasi_result/large_feasi_result_5.json b/tasks/legrain2024/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2024/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/legrain2024/gurobi_feasi_result/tiny_feasi_result.json b/tasks/legrain2024/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/legrain2024/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/legrain2024/gurobi_solution/large_solution_1.json b/tasks/legrain2024/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..42bccd3d3541981d242d86ab5f52dfdd1410535a --- /dev/null +++ b/tasks/legrain2024/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fec3d71647f1c5b5a61818fe77625f520f1d28a9bb13c599e99cfa1126bd313 +size 284642 diff --git a/tasks/legrain2024/gurobi_solution/large_solution_2.json b/tasks/legrain2024/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..5fea73c709855a7cc42324bbc7f9393c057e9e50 --- /dev/null +++ b/tasks/legrain2024/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fef93e32c74755adcc0f72c5187a44d7068b0bfa30e095577913b1f6f1254d9 +size 284422 diff --git a/tasks/legrain2024/gurobi_solution/large_solution_3.json b/tasks/legrain2024/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d8f5cf709a3e8737dda3930f2153b9f8c25e26e0 --- /dev/null +++ b/tasks/legrain2024/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1b1dbb6770d2afde69188f3470c7efe7df498836f2ae9c62136031cd70bd705 +size 284430 diff --git a/tasks/legrain2024/gurobi_solution/large_solution_4.json b/tasks/legrain2024/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e7ac03c15efa55905da9de3903c160b8978b91f7 --- /dev/null +++ b/tasks/legrain2024/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c445fe50776c92d55d8aff8a6a111bc22f184f0f251f8afc45e42a31bc05ebbd +size 284598 diff --git a/tasks/legrain2024/gurobi_solution/large_solution_5.json b/tasks/legrain2024/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..6f3698f73e0ba7306fa72b3cc1a5bff11297e8db --- /dev/null +++ b/tasks/legrain2024/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e90746bb40f8c27f82dd644c2d5523f7b593f40603207d27c08204e73c6540e6 +size 285473 diff --git a/tasks/legrain2024/gurobi_solution/tiny_solution.json b/tasks/legrain2024/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..b00ebff132314f119c16489f0588fea7d01653e3 --- /dev/null +++ b/tasks/legrain2024/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09284ed856b00bb7f1f110e2747eb4c6db59906a0ad56ac46fe6e9380d23b9d6 +size 6047 diff --git a/tasks/legrain2024/gurobi_solution_log/large_log_1.jsonl b/tasks/legrain2024/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6819f5d7e81270bb6cd6e016158a12fde6ebf78c --- /dev/null +++ b/tasks/legrain2024/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:228b4bcc24a5e4f6fcf0239c41c7a3165ae3e31bcb9bb14beb36ac1c68a9a5cd +size 226 diff --git a/tasks/legrain2024/gurobi_solution_log/large_log_2.jsonl b/tasks/legrain2024/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..83d99595874b57234449d6d163f48489018466c6 --- /dev/null +++ b/tasks/legrain2024/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f5cee2d57acdbd2bbdcda6f5af74ae91aef1c3c64758677762de0ac30337236 +size 218 diff --git a/tasks/legrain2024/gurobi_solution_log/large_log_3.jsonl b/tasks/legrain2024/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d2e725b674e129fc599af030c3f98be8020d3a1d --- /dev/null +++ b/tasks/legrain2024/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49c16adef43c3919bada03d9f2c607ff1fc46a88d04fd965265ea2a2be56c42d +size 88 diff --git a/tasks/legrain2024/gurobi_solution_log/large_log_4.jsonl b/tasks/legrain2024/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9968c669ad6cc41d2d25529f0e8eccb38ac76d11 --- /dev/null +++ b/tasks/legrain2024/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a4a9f649083f1327d3517b65c6017c1d88a27ca2ef873cf2f98a1261845863a +size 359 diff --git a/tasks/legrain2024/gurobi_solution_log/large_log_5.jsonl b/tasks/legrain2024/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1d4981bf5c2267eb1571973e44eef389b03898ce --- /dev/null +++ b/tasks/legrain2024/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08f89bae7f6154bf3e38fb3595064fd8b7bd86b78082876cbdb22768b25e7ae6 +size 2653 diff --git a/tasks/legrain2024/gurobi_solution_log/tiny_log.jsonl b/tasks/legrain2024/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..13c50f99f7464ab6f1d22dcebe0442fed2bf773c --- /dev/null +++ b/tasks/legrain2024/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e88f9e81e9dae198ce6872367a2871cd30bc8af46d5236daf9eb79982e823db +size 44 diff --git a/tasks/legrain2024/instance/large_instance_1.json b/tasks/legrain2024/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..092e129839aadd910c7c674c7355598a20282a3c --- /dev/null +++ b/tasks/legrain2024/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff775ea66fc473107f713f36c7d1df896a3739c17f04b602d29c93e0d4daa280 +size 60965 diff --git a/tasks/legrain2024/instance/large_instance_2.json b/tasks/legrain2024/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..fa5ff2130a42cdef5ad7e78a80f12d12f163b48d --- /dev/null +++ b/tasks/legrain2024/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4be31121a5f8393ba3cf7254aab1f5493d523a06a370838514a34cb6dc612f06 +size 60843 diff --git a/tasks/legrain2024/instance/large_instance_3.json b/tasks/legrain2024/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..98c2c47f59136f61a06e45938f7b1594642a08fb --- /dev/null +++ b/tasks/legrain2024/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d11750f1d474573527d6cdae619ec6928062b82b0e5b11de7a76ea4f64da18fc +size 61602 diff --git a/tasks/legrain2024/instance/large_instance_4.json b/tasks/legrain2024/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..186fbf789ccabb4ef8be0296c38eb1067ee78f41 --- /dev/null +++ b/tasks/legrain2024/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2069f0df9d26f802287f0062f5966a3b48199599a9c5ef1011ade987496e61d1 +size 117425 diff --git a/tasks/legrain2024/instance/large_instance_5.json b/tasks/legrain2024/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5b80b127603cbbd4f3366a40c1ee80933dcd7429 --- /dev/null +++ b/tasks/legrain2024/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce786a3fc0c35ea6142350a2fc657bf2a5ab142143d26438cf9099cbd327ea6a +size 61517 diff --git a/tasks/legrain2024/instance/tiny_instance.json b/tasks/legrain2024/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..d392a4416a79b02d22d8e100629278603e44c2c6 --- /dev/null +++ b/tasks/legrain2024/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34d39f269b3a432711ca4f59bc6ccd498e728e7046bcdcb82c55bd5153d4774c +size 4615 diff --git a/tasks/legrain2024/instance_schema.json b/tasks/legrain2024/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..697cb989decf8b254590e00507fda10f50686c2a --- /dev/null +++ b/tasks/legrain2024/instance_schema.json @@ -0,0 +1,86 @@ +{ + "shifts": " Named work shifts available in the scheduling horizon.", + "skills": " Named skills that nurses may possess and perform during shifts.", + "nurses": [ + { + "id": " Unique identifier for the nurse.", + "skills": " Skills this nurse is qualified to perform.", + "preferences": [ + { + "day": " Day number (1-indexed) the preference applies to.", + "type": " Kind of preference, either 'day_off', 'day_on', 'shift_on', or 'shift_off'.", + "shift": " Shift name the preference refers to, or 'None' for day-off preferences.", + "penalty": " Cost incurred if this preference is not honored." + } + ] + } + ], + "weekend_definition": " Which days of the week constitute a weekend.", + "weekends": [ + { + "week": " Week number (1-indexed) this weekend belongs to.", + "saturday": " Day number (1-indexed) of Saturday in this weekend.", + "sunday": " Day number (1-indexed) of Sunday in this weekend." + } + ], + "demand": { + "day_{d}": { + "{shift}": { + "{skill}": " Minimum number of nurses with this skill required on this shift and day." + } + } + }, + "unsatisfied_demand_penalty": " Cost per unit of unmet demand across day-shift-skill combinations.", + "constraints": { + "hard_constraints": { + "forbidden_patterns": [ + { + "pattern": " Sequence of consecutive-day [day_type, shift] pairs that must never appear in any nurse's schedule.", + "description": " Human-readable explanation of the forbidden pattern." + } + ], + "skill_requirement": " Whether nurses may only perform skills they possess.", + "single_assignment_per_day": " Whether each nurse must be assigned exactly one shift per day.", + "demand_equality": " If true, staffing must equal demand exactly and demand slack is disabled." + }, + "soft_constraints": { + "total_working_days": { + "min": " Minimum number of days each nurse should work over the horizon.", + "max": " Maximum number of days each nurse should work over the horizon.", + "penalty_under": " Cost per day below the minimum working-day target.", + "penalty_over": " Cost per day above the maximum working-day target." + }, + "total_worked_weekends": { + "max": " Maximum number of weekends each nurse should work.", + "penalty": " Cost per weekend worked above the maximum." + }, + "consecutive_working_days": { + "min": " Minimum length of any unbroken streak of working days.", + "max": " Maximum length of any unbroken streak of working days.", + "penalty_under": " Cost per occurrence of a working streak shorter than the minimum.", + "penalty_over": " Cost per day a working streak exceeds the maximum." + }, + "consecutive_days_off": { + "min": " Minimum length of any unbroken streak of rest days.", + "max": " Maximum length of any unbroken streak of rest days.", + "penalty_under": " Cost per occurrence of a rest streak shorter than the minimum.", + "penalty_over": " Cost per day a rest streak exceeds the maximum." + }, + "consecutive_same_shift": { + "max": " Maximum number of consecutive days a nurse may be assigned the same work shift.", + "penalty": " Cost per day a same-shift streak exceeds the maximum." + }, + "consecutive_worked_weekends": { + "max": " Maximum number of consecutive weekends a nurse may work.", + "penalty": " Cost per weekend a consecutive-weekend streak exceeds the maximum." + }, + "identical_weekend": { + "enabled": " Whether the identical-weekend rule is active.", + "penalty": " Cost incurred when the shifts on the days named by a weekend record are not all identical." + }, + "skill_requirement_penalty": " Cost per worked day assigned to a skill the nurse does not possess when skill possession is soft.", + "forbidden_patterns": " Soft forbidden shift sequences with per-occurrence penalties.", + "preferences_penalty": " Enables the penalty stored on each unmet nurse preference." + } + } +} diff --git a/tasks/legrain2024/mathematical_formulation.md b/tasks/legrain2024/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..08217b1143d2859b7d867416d1d553e4d777b2da --- /dev/null +++ b/tasks/legrain2024/mathematical_formulation.md @@ -0,0 +1,73 @@ +# Original Formulation: Personalized Nurse Scheduling Problem (NSP) + +*Source: A dedicated pricing algorithm to solve a large family of nurse scheduling problems with branch-and-price, Antoine Legrain & Jérémy Omer, 2024 (INFORMS Journal on Computing).* + +## Sets and Indices + +- $\mathcal{N}$ : set of nurses, indexed by $i$. + +- $\mathcal{D} = \{1,\ldots,n_{\mathcal{D}}\}$ : set of days of the planning horizon, indexed by $d$; $n_{\mathcal{D}}$ is the number of days. + +- $\mathcal{S}$ : set of shifts, indexed by $s$. $\mathcal{S}$ includes a special $\mathrm{None}$ (rest) shift; $(d,\mathrm{None})$ is a day off and $(d,s)$ with $s\neq\mathrm{None}$ is a working day. + +- $\Sigma$ : set of skills, indexed by $\sigma$. + +- An *assignment* is a pair $(d,s)\in\mathcal{D}\times\mathcal{S}$. A generic assignment is denoted $p\in\mathcal{D}\times\mathcal{S}$. + +- $n_{\mathcal{W}}$ : number of weekends over the horizon. + +- $\Omega_i$ : set of all feasible rosters for nurse $i\in\mathcal{N}$. Each roster $j\in\Omega_i$ is characterized by a binary vector $a^j$ with $a^j_{d,s}=1$ iff roster $j$ includes assignment $(d,s)$. + +## Parameters + +- $\mathbf{c_x}$ : vector of roster costs ($c_j$ = cost of roster $j\in\Omega_i$; aggregates the soft individual-roster constraint penalties). + +- $\mathbf{c_y}$ : vector of penalties for skill-assignment violations ($c_y=0$ when the nurse possesses the assigned skill). + +- $\mathbf{c_z}$ : vector of penalties for unsatisfied demands. + +- $b_{p,\sigma}$ : minimum demand on assignment $p\in\mathcal{D}\times\mathcal{S}$ for skill $\sigma\in\Sigma$. + +- $a^j_p$ : binary parameter, $1$ iff roster $j$ covers assignment $p\in\mathcal{D}\times\mathcal{S}$. + +## Decision Variables + +- $x_{ij}\in\{0,1\}$ : $1$ iff roster $j\in\Omega_i$ is assigned to nurse $i\in\mathcal{N}$. + +- $y_{i,p,\sigma}\in\{0,1\}$ : $1$ iff nurse $i\in\mathcal{N}$ performs skill $\sigma\in\Sigma$ on assignment $p\in\mathcal{D}\times\mathcal{S}$. + +- $z_{p\sigma}\ge 0$ : unsatisfied demand for skill $\sigma\in\Sigma$ on assignment $p\in\mathcal{D}\times\mathcal{S}$. + +## Objective + +$$\begin{align} +\min \quad & \mathbf{c_x}^{T}\mathbf{x} + \mathbf{c_y}^{T}\mathbf{y} + + \mathbf{c_z}^{T}\mathbf{z} \tag{1a} +\end{align}$$ + +## Constraints + +$$\begin{align} +& \sum_{j\in\Omega_i} x_{ij} = 1, + && \forall i\in\mathcal{N}, && [\alpha_i] \tag{1b}\\ +& \sum_{j\in\Omega_i} a^j_p\, x_{ij} = \sum_{\sigma\in\Sigma} y_{i,p,\sigma}, + && \forall i\in\mathcal{N},\ \forall p\in\mathcal{D}\times\mathcal{S}, + && [\beta_{i,p}] \tag{1c}\\ +& \sum_{i\in\mathcal{N}} y_{i,p,\sigma} + z_{p\sigma} \ge b_{p,\sigma}, + && \forall p\in\mathcal{D}\times\mathcal{S},\ \forall \sigma\in\Sigma + && \tag{1d}\\ +& x_{ij},\, y_{ip\sigma} \in \{0,1\}, + && \forall i,j,p,\sigma && \tag{1e}\\ +& \mathbf{w},\, \mathbf{z} \ge 0 + && && \tag{1f} +\end{align}$$ + +## Released executable certificate + +The public direct MILP expands each roster into one shift choice for every +nurse-day and emits the parallel complete skill witness. Instance flags select +hard versus soft skill possession and forbidden patterns. If +`demand_equality=true`, (1d) is released as equality with zero slack; +otherwise it remains the stated lower bound. Weekend records are data-driven +and may include Friday. The checker requires exact nurse/day key coverage in +both maps and independently recomputes every objective component. diff --git a/tasks/legrain2024/problem_description.txt b/tasks/legrain2024/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c89be01f6c9712ff2cf7811916fc130b4209ec6b --- /dev/null +++ b/tasks/legrain2024/problem_description.txt @@ -0,0 +1,17 @@ +# Problem Description + +A hospital must build a personalized schedule for each of its nurses over a planning horizon of a given number of days. The horizon spans a known number of complete weekends, where each weekend is defined by its constituent Saturday and Sunday (or, in some settings, may include Friday). Each day is divided into a set of named work shifts (such as Early, Late, or Night); in addition, a special rest shift represents a day off. Every nurse possesses a subset of the available skills. The input specifies, for each day, each work shift, and each skill, a minimum number of nurses that must be on duty performing that skill. Each nurse also has a list of individual preferences, where each preference identifies a particular day and either requests a day off or requests a specific shift assignment, together with a numeric penalty incurred if the preference is not honored. + +The hospital must assign to each nurse, for every day in the horizon, exactly one shift (which may be a work shift or the rest shift). When a nurse is assigned a work shift on a given day, the nurse must also be assigned exactly one skill to perform during that shift. A cost is incurred for each such assignment where the nurse does not possess the assigned skill; depending on the problem instance, skill possession may be a hard requirement or a soft requirement with the stated finite penalty. Normally skill staffing plus unsatisfied-demand slack must be at least the requested demand. When `demand_equality=true`, staffing must equal demand exactly and unmet-demand slack is disabled. + +Several rules govern each nurse's schedule, and each rule may be designated as either hard (must be satisfied) or soft (may be violated at a cost). When a rule is soft, separate penalties apply per unit of violation above the upper bound and per unit of violation below the lower bound, and these two penalties may differ. Hard rules are enforced by assigning a prohibitively large penalty. The rules are as follows. + +For each designated group of shifts (which may be all work shifts, a single specific shift such as Night, the rest shift, or any other specified subset of shifts), the total number of days on which each nurse is assigned a shift from that group over the entire horizon must lie between a specified minimum and maximum. The total number of weekends on which each nurse works must lie between a specified minimum and maximum. For each designated group of shifts, the number of consecutive days in any unbroken streak must lie between the stated bounds; streaks touching the horizon boundary are not penalized below the minimum because they may continue outside the window. The number of consecutive weekends worked is likewise bounded. When the identical-weekend rule is enabled, all days named by the weekend record must carry the same assignment: this covers Friday, Saturday, and Sunday in a three-day-weekend instance and Saturday-Sunday otherwise. The schedule must avoid hard forbidden patterns and pays the stated cost for soft forbidden patterns. Each nurse's per-day preferences contribute their own penalty when unmet. + +The goal is to determine the shift assignment and skill assignment for every nurse on every day so as to minimize the total cost. The total cost is the sum of three components: penalties for violations of the roster rules listed above (total shift-group counts, weekend-work counts, consecutive-assignment bounds, consecutive-weekend bounds, identical-weekend requirements, forbidden-pattern violations, and unmet nurse preferences), penalties for nurse-skill assignments where the nurse does not possess the assigned skill, and penalties for unsatisfied demand across all day-shift-skill combinations. + +The public answer is a complete two-part certificate. `schedule` names one +shift for every nurse-day and `skill_assignments` names exactly one skill on +every worked day (`None` on days off). The checker derives staffing, all +hard/soft penalties, preferences, skill mismatches, and the full objective from +these maps; a missing or extra nurse-day entry is rejected. diff --git a/tasks/legrain2024/solution_logger.py b/tasks/legrain2024/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/legrain2024/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/legrain2024/solution_schema.json b/tasks/legrain2024/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..de7cbadf65f6ac46cac22704cbbe55c690d6364f --- /dev/null +++ b/tasks/legrain2024/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total penalty cost summed over roster-rule violations, nurse-skill mismatches, unmet preferences, and unsatisfied demand.", + "schedule": " Shift assigned to each nurse on each day of the horizon, taking a work-shift name or 'None' for a day off.", + "skill_assignments": " Complete skill witness parallel to schedule: one skill name on every worked day and 'None' on every day off." +} diff --git a/tasks/letelier2022/feasibility_check.py b/tasks/letelier2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e56c4ec349415f8c983f9e61d22194f274f13e44 --- /dev/null +++ b/tasks/letelier2022/feasibility_check.py @@ -0,0 +1,623 @@ +""" +Feasibility checker for the Bin Packing Problem with Time Lags (BPPTL). +Based on Model 2 from Letelier, Clautiaux, Sadykov (2022). + +Constraints (numbered top to bottom in the formulation): + 1. (2b): Each item assigned to exactly one bin-period pair. + 2. (2c): Bin capacity per (bin, period) pair. + 3. (2d): Time lag constraints for arcs between real items. + 4. (2e): x_{i,b,p} in {0,1}. + 5. (2f): u_{b,p} in {0,1}. + 6. Preprocessing: each real item's period lies in [es(i), ls(i)]. + 7. Solution-level domain/consistency of active_bin_periods sub-fields. + 8. Objective consistency: the reported objective_value must equal the + recomputed objective (2a) = sum_{b,p} u_{b,p}, i.e. the number of + distinct bin-period pairs (gurobi format) / non-empty bins (efficient + format) that contain at least one item. Tier C defense against + fabricated objective_value exploits. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('active_bin_periods', 'assignments', 'num_active_bin_periods', '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 load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def detect_solution_format(solution): + """Detect whether solution is from gurobi or efficient algorithm.""" + if "assignments" in solution: + return "gurobi" + elif "bins" in solution: + return "efficient" + else: + raise ValueError("Unknown solution format") + + +def extract_assignments_gurobi(solution): + """Extract item -> (bin, period) mapping from gurobi solution.""" + assignments = {} + for a in solution["assignments"]: + item_id = a["item_id"] + assignments[item_id] = {"bin": a["bin"], "period": a["period"], "weight": a["weight"]} + return assignments + + +def extract_assignments_efficient(solution, instance): + """Extract item -> bin mapping from efficient solution (no period info).""" + weights = {it["item_id"]: it["weight"] for it in instance["items"]} + assignments = {} + for bin_idx, b in enumerate(solution["bins"]): + for item_id in b["items"]: + assignments[item_id] = {"bin": bin_idx, "weight": weights[item_id]} + return assignments + + +def add_violation(violations_list, magnitudes_list, constraint_idx, message, lhs, rhs, violation_amount): + """Record a violation.""" + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations_list.append((constraint_idx, message)) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +def check_feasibility(instance, solution): + violations_list = [] # list of (constraint_idx, message) + magnitudes_list = [] + + fmt = detect_solution_format(solution) + has_periods = (fmt == "gurobi") + + # Get real items from instance + real_items = [it for it in instance["items"] if it["type"] == "treatment"] + real_item_ids = set(it["item_id"] for it in real_items) + weights = {it["item_id"]: it["weight"] for it in instance["items"]} + W = instance["parameters"]["W"] + T = instance["parameters"]["T"] + + # Extract assignments + if has_periods: + assignments = extract_assignments_gurobi(solution) + else: + assignments = extract_assignments_efficient(solution, instance) + + # ------------------------------------------------------------------ + # Constraint 1 (2b): Each real item assigned to exactly one bin(-period) + # sum_{b,p} x_{i,b,p} = 1 for all i in V + # ------------------------------------------------------------------ + assigned_items = set(assignments.keys()) + + for it in real_items: + iid = it["item_id"] + if iid not in assigned_items: + # LHS = 0 (not assigned), RHS = 1 + lhs_val = 0.0 + rhs_val = 1.0 + viol = abs(lhs_val - rhs_val) + if viol > TOL: + add_violation(violations_list, magnitudes_list, 1, + f"Item {iid} is not assigned to any bin", + lhs_val, rhs_val, viol) + + # Check for items assigned multiple times (shouldn't happen with dict, but + # check original data for duplicates) + if has_periods: + item_count = {} + for a in solution["assignments"]: + iid = a["item_id"] + item_count[iid] = item_count.get(iid, 0) + 1 + for iid, count in item_count.items(): + if iid in real_item_ids and count != 1: + lhs_val = float(count) + rhs_val = 1.0 + viol = abs(lhs_val - rhs_val) + if viol > TOL: + add_violation(violations_list, magnitudes_list, 1, + f"Item {iid} assigned {count} times (should be exactly 1)", + lhs_val, rhs_val, viol) + else: + item_count = {} + for b in solution["bins"]: + for iid in b["items"]: + item_count[iid] = item_count.get(iid, 0) + 1 + for iid, count in item_count.items(): + if iid in real_item_ids and count != 1: + lhs_val = float(count) + rhs_val = 1.0 + viol = abs(lhs_val - rhs_val) + if viol > TOL: + add_violation(violations_list, magnitudes_list, 1, + f"Item {iid} assigned {count} times (should be exactly 1)", + lhs_val, rhs_val, viol) + + # Check for non-real items assigned + for iid in assigned_items: + if iid not in real_item_ids: + lhs_val = 1.0 + rhs_val = 0.0 + viol = abs(lhs_val - rhs_val) + if viol > TOL: + add_violation(violations_list, magnitudes_list, 1, + f"Non-real item {iid} (source/sink) is assigned to a bin", + lhs_val, rhs_val, viol) + + # ------------------------------------------------------------------ + # Constraint 2 (2c): Capacity per (bin, period) pair + # sum_i w_i x_{i,b,p} <= W * u_{b,p} + # Since u_{b,p}=1 for active bins: sum weights <= W + # ------------------------------------------------------------------ + if has_periods: + # Group items by (bin, period) + bin_period_items = {} + for iid, asg in assignments.items(): + key = (asg["bin"], asg["period"]) + if key not in bin_period_items: + bin_period_items[key] = [] + bin_period_items[key].append(iid) + + for (b, p), items in bin_period_items.items(): + total_w = sum(weights.get(iid, 0) for iid in items) + # u_{b,p} = 1 if items present, so RHS = W + lhs_val = float(total_w) + rhs_val = float(W) + viol = lhs_val - rhs_val + if viol > TOL: + add_violation(violations_list, magnitudes_list, 2, + f"Capacity exceeded in bin {b}, period {p}: " + f"total weight {total_w} > capacity {W}", + lhs_val, rhs_val, viol) + else: + # Efficient solution: bins without periods, each bin is one "slot" + for bin_idx, b in enumerate(solution["bins"]): + total_w = sum(weights.get(iid, 0) for iid in b["items"]) + lhs_val = float(total_w) + rhs_val = float(W) + viol = lhs_val - rhs_val + if viol > TOL: + add_violation(violations_list, magnitudes_list, 2, + f"Capacity exceeded in bin {bin_idx}: " + f"total weight {total_w} > capacity {W}", + lhs_val, rhs_val, viol) + + # ------------------------------------------------------------------ + # Constraint 3 (2d): Time lag constraints (only if periods available) + # l_{i,j} + p_i <= p_j for each arc (i,j) in A between real items + # ------------------------------------------------------------------ + if has_periods: + # Build period mapping for real items + item_period = {} + for iid, asg in assignments.items(): + if iid in real_item_ids: + item_period[iid] = asg["period"] + + for arc in instance["arcs"]: + i_arc = arc["from"] + j_arc = arc["to"] + lag = arc["lag"] + + # Only check arcs between real items + if i_arc not in real_item_ids or j_arc not in real_item_ids: + continue + + if i_arc not in item_period or j_arc not in item_period: + continue + + p_i = item_period[i_arc] + p_j = item_period[j_arc] + + # Constraint: lag + p_i <= p_j + lhs_val = float(lag + p_i) + rhs_val = float(p_j) + viol = lhs_val - rhs_val # LHS - RHS for <= constraint + if viol > TOL: + add_violation(violations_list, magnitudes_list, 3, + f"Time lag violated for arc ({i_arc}->{j_arc}): " + f"lag {lag} + period {p_i} = {lag + p_i} > period {p_j}", + lhs_val, rhs_val, viol) + + # ------------------------------------------------------------------ + # Constraint 6 (preprocessing): es(i)/ls(i) feasible time windows. + # Source/sink arcs imply each real item's assigned period must lie in + # [es(i), ls(i)] = [d(source, i), (T+1) - d(i, sink)] (longest paths). + # See math_model "PREPROCESSING" section. + # ------------------------------------------------------------------ + if has_periods: + source_id = instance.get("source_item_id") + sink_id = instance.get("sink_item_id") + all_node_ids = [it["item_id"] for it in instance["items"]] + + INF = float("-inf") + dist = {i: {j: INF for j in all_node_ids} for i in all_node_ids} + for i in all_node_ids: + dist[i][i] = 0 + for arc in instance["arcs"]: + u_n, v_n, lag_n = arc["from"], arc["to"], arc["lag"] + if lag_n > dist[u_n][v_n]: + dist[u_n][v_n] = lag_n + for k in all_node_ids: + for i in all_node_ids: + if dist[i][k] == INF: + continue + for j in all_node_ids: + if dist[k][j] == INF: + continue + candidate = dist[i][k] + dist[k][j] + if candidate > dist[i][j]: + dist[i][j] = candidate + + es = {} + ls = {} + for iid in real_item_ids: + d_si = dist[source_id][iid] + es_i = max(1, d_si) if d_si != INF else 1 + d_if = dist[iid][sink_id] + ls_i = (T + 1) - d_if if d_if != INF else T + es[iid] = max(1, es_i) + ls[iid] = min(T, ls_i) + + for iid, asg in assignments.items(): + if iid not in real_item_ids: + continue + p_assigned = asg["period"] + if p_assigned < es[iid] - TOL: + lhs_val = float(es[iid]) + rhs_val = float(p_assigned) + viol = lhs_val - rhs_val + add_violation(violations_list, magnitudes_list, 6, + f"Item {iid} assigned to period {p_assigned} < es({iid})={es[iid]}", + lhs_val, rhs_val, viol) + if p_assigned > ls[iid] + TOL: + lhs_val = float(p_assigned) + rhs_val = float(ls[iid]) + viol = lhs_val - rhs_val + add_violation(violations_list, magnitudes_list, 6, + f"Item {iid} assigned to period {p_assigned} > ls({iid})={ls[iid]}", + lhs_val, rhs_val, viol) + + # ------------------------------------------------------------------ + # Constraint 4 (2e): x_{i,b,p} in {0,1} + # Implicitly satisfied by integer assignment structure. + # Check that assignments are consistent (no fractional assignments). + # ------------------------------------------------------------------ + if has_periods: + for a in solution["assignments"]: + # Each assignment represents x=1; verify no fractional values if present + if "value" in a: + val = a["value"] + viol = min(abs(val - 0.0), abs(val - 1.0)) + if viol > TOL: + lhs_val = float(val) + rhs_val = round(val) + add_violation(violations_list, magnitudes_list, 4, + f"Item {a['item_id']} assignment to bin {a['bin']}, " + f"period {a['period']} is fractional: {val}", + lhs_val, rhs_val, viol) + + # ------------------------------------------------------------------ + # Constraint 5 (2f): u_{b,p} in {0,1} + # Implicitly satisfied by the solution structure (bins are either + # active or not). Check active_bin_periods if available. + # ------------------------------------------------------------------ + if has_periods and "active_bin_periods" in solution: + for abp in solution["active_bin_periods"]: + # u is implicitly 1 for active bins; nothing fractional to check + # unless explicit values are provided + pass + + # ------------------------------------------------------------------ + # Constraint 7: Solution-level domain/consistency of the reported + # objective-related field `num_active_bin_periods` which MUST equal + # the length of active_bin_periods (by the definition of the objective + # sum_{b,p} u_{b,p}). Also validate sub-field domains (bin/period in + # valid ranges, items non-empty and listed as integers, total_weight + # matching the sum of member items' weights). + # ------------------------------------------------------------------ + if has_periods: + n_bins = instance["parameters"].get("N") or instance["parameters"].get("n_bins") + n_periods = instance["parameters"].get("T") or instance["parameters"].get("n_periods") + reported = solution.get("num_active_bin_periods") + abps = solution.get("active_bin_periods", []) + + # num_active_bin_periods == len(active_bin_periods) + if reported is not None and reported != len(abps): + add_violation(violations_list, magnitudes_list, 7, + f"num_active_bin_periods={reported} does not match " + f"len(active_bin_periods)={len(abps)}", + float(reported), float(len(abps)), + abs(reported - len(abps))) + + # Per-abp domain checks + for idx, abp in enumerate(abps): + b = abp.get("bin") + p = abp.get("period") + items = abp.get("items", []) + tw = abp.get("total_weight") + + # Bins are 0-indexed: 0..n_bins-1 (gurobi_code.py uses range(num_bins)) + if n_bins is not None and not (isinstance(b, int) and 0 <= b < n_bins): + add_violation(violations_list, magnitudes_list, 7, + f"active_bin_periods[{idx}]: bin {b!r} out of range " + f"[0,{n_bins - 1}]", + float(b) if isinstance(b, (int, float)) else -1.0, + float(n_bins - 1), 1.0) + # Periods are 1-indexed: 1..T (per math_model set T = {1,...,T}) + if n_periods is not None and not (isinstance(p, int) and 1 <= p <= n_periods): + add_violation(violations_list, magnitudes_list, 7, + f"active_bin_periods[{idx}]: period {p!r} out of range " + f"[1,{n_periods}]", + float(p) if isinstance(p, (int, float)) else -1.0, + float(n_periods), 1.0) + + # items non-empty (since entry represents an ACTIVE bin-period) + if not items: + add_violation(violations_list, magnitudes_list, 7, + f"active_bin_periods[{idx}]: items list empty for " + f"an 'active' bin-period pair (bin={b}, period={p})", + 0.0, 1.0, 1.0) + + # total_weight == sum of member items' weights (cross-check with instance) + if tw is not None and items: + expected_w = 0 + all_known = True + for iid in items: + if iid in weights: + expected_w += weights[iid] + else: + all_known = False + break + if all_known and int(tw) != int(expected_w): + add_violation(violations_list, magnitudes_list, 7, + f"active_bin_periods[{idx}]: total_weight={tw} " + f"does not match sum of member weights={expected_w} " + f"(bin={b}, period={p})", + float(tw), float(expected_w), + abs(tw - expected_w)) + + # ------------------------------------------------------------------ + # Constraint 8: Objective consistency (Tier C anti-gaming defense). + # The reported objective_value MUST equal the recomputed objective (2a), + # min sum_{b in L} sum_{p in T} u_{b,p}, + # i.e. the number of bin-period pairs that contain at least one item. + # This is a FULL recompute: every variable the objective depends on + # (the item-to-(bin,period) assignment, hence which (b,p) pairs are + # non-empty) is present in the solution -- no second-stage / scenario + # variables are missing. For the gurobi format that count is the number + # of distinct (bin, period) pairs over `assignments`; for the efficient + # format (no periods) it is the number of non-empty `bins` entries. + # An LLM candidate that fabricates objective_value (e.g. 0.0 or + # sys.float_info.max) to game the score is rejected here. + # ------------------------------------------------------------------ + 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: + if has_periods: + used_bin_periods = set( + (a["bin"], a["period"]) for a in solution["assignments"] + ) + true_obj = float(len(used_bin_periods)) + else: + true_obj = float(sum(1 for b in solution["bins"] if b.get("items"))) + abs_diff = abs(reported - true_obj) + # Objective (2a) is an integer count of non-empty bin-periods: + # any mismatch of >= 1 must fire. + tol = 0.5 + if abs_diff > tol: + add_violation(violations_list, magnitudes_list, 8, + f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"objective sum_(b,p) u_(b,p)={true_obj} (number of " + f"non-empty bin-period pairs) " + f"(|diff|={abs_diff:.3g}, tol={tol})", + reported, true_obj, abs_diff) + + # ------------------------------------------------------------------ + # Build result + # ------------------------------------------------------------------ + violated_indices = sorted(set(c for c, _ in violations_list)) + # Aggregate messages by constraint index + messages = [] + for idx in violated_indices: + msgs = [msg for c, msg in violations_list if c == idx] + messages.extend(msgs) + + feasible = len(violated_indices) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": messages, + "violation_magnitudes": magnitudes_list if not feasible else [], + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for BPPTL (Letelier et al., 2022)") + 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) + + if result["feasible"]: + print(f"FEASIBLE - no constraint violations found.") + else: + print(f"INFEASIBLE - {len(result['violated_constraints'])} constraint(s) violated:") + for msg in result["violations"]: + print(f" - {msg}") + + +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/letelier2022/gurobi_code.py b/tasks/letelier2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d560dbf7434447e139052bf7e7a68c44e6c745a6 --- /dev/null +++ b/tasks/letelier2022/gurobi_code.py @@ -0,0 +1,316 @@ +""" +BPPTL (Bin Packing Problem with Time Lags) - Compact Formulation (Model 2) +from Letelier et al. (2022), solved with Gurobi. + +_GUROBI_CODE_START_TIME = time.time() +Minimize the total number of non-empty bin-period pairs subject to: + - Each real item assigned to exactly one bin in one period + - Bin capacity respected per (bin, period) pair + - Time lag constraints between items +""" + +import argparse +import json +import math +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/). +_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, "r") as f: + return json.load(f) + + +def solve_bpptl(instance, time_limit=None): + params = instance["parameters"] + T = params["T"] # number of periods (1..T) + W = params["W"] # bin capacity + L_param = params["L"] # max bins per period ("infinity" or int) + + source_id = instance["source_item_id"] + sink_id = instance["sink_item_id"] + + # Collect real items + real_items = [it for it in instance["items"] if it["type"] == "treatment"] + n = len(real_items) + item_ids = [it["item_id"] for it in real_items] + weights = {it["item_id"]: it["weight"] for it in real_items} + + # Number of bins: if L is "infinity", use n as upper bound + if L_param == "infinity": + num_bins = n + else: + num_bins = int(L_param) + + periods = list(range(1, T + 1)) # 1..T + bins = list(range(num_bins)) + + # Build arc list indexed by item ids (including source/sink) + arcs = instance["arcs"] + + # --------------------------------------------------------------- + # Preprocessing: Floyd-Warshall for longest paths + # --------------------------------------------------------------- + all_node_ids = [it["item_id"] for it in instance["items"]] + id_set = set(all_node_ids) + + # Initialize distance matrix with -infinity (no path) + INF = float("-inf") + dist = {i: {j: INF for j in all_node_ids} for i in all_node_ids} + for i in all_node_ids: + dist[i][i] = 0 + + for arc in arcs: + u, v, lag = arc["from"], arc["to"], arc["lag"] + if lag > dist[u][v]: + dist[u][v] = lag + + # Floyd-Warshall: longest paths + for k in all_node_ids: + for i in all_node_ids: + if dist[i][k] == INF: + continue + for j in all_node_ids: + if dist[k][j] == INF: + continue + candidate = dist[i][k] + dist[k][j] + if candidate > dist[i][j]: + dist[i][j] = candidate + + # Earliest start and latest start for each real item + # Source is at time 0, sink at time T+1 + es = {} + ls = {} + for i in item_ids: + # es(i) = d(source, i) (longest path from source to i) + d_source_i = dist[source_id][i] + es[i] = max(1, d_source_i) if d_source_i != INF else 1 + + # ls(i) = (T+1) - d(i, sink) + d_i_sink = dist[i][sink_id] + ls[i] = (T + 1) - d_i_sink if d_i_sink != INF else T + + # Clamp to valid range + es[i] = max(1, es[i]) + ls[i] = min(T, ls[i]) + + # Feasible periods for each item + feasible_periods = {} + for i in item_ids: + feasible_periods[i] = [p for p in periods if es[i] <= p <= ls[i]] + + # --------------------------------------------------------------- + # Build Gurobi model + # --------------------------------------------------------------- + model = gp.Model("BPPTL_Model2") + model.setParam("Threads", 1) + if time_limit is not None: + model.Params.TimeLimit = time_limit + + # Variables: x[i,b,p] binary + x = {} + for i in item_ids: + for b in bins: + for p in feasible_periods[i]: + x[i, b, p] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{b}_{p}") + + # Variables: u[b,p] binary + u = {} + for b in bins: + for p in periods: + u[b, p] = model.addVar(vtype=GRB.BINARY, name=f"u_{b}_{p}") + + model.update() + + # Objective: min sum u[b,p] + model.setObjective( + gp.quicksum(u[b, p] for b in bins for p in periods), GRB.MINIMIZE + ) + + # Constraint (2b): each item assigned exactly once + for i in item_ids: + model.addConstr( + gp.quicksum( + x[i, b, p] for b in bins for p in feasible_periods[i] + ) + == 1, + name=f"assign_{i}", + ) + + # Constraint (2c): capacity + for b in bins: + for p in periods: + items_in_period = [i for i in item_ids if p in feasible_periods[i]] + if items_in_period: + model.addConstr( + gp.quicksum(weights[i] * x[i, b, p] for i in items_in_period) + <= W * u[b, p], + name=f"cap_{b}_{p}", + ) + + # Constraint (2d): time lag constraints between real items + # For arcs between two real items: l_{i,j} + p_i <= p_j + # where p_i = sum_p p * sum_b x[i,b,p] + real_id_set = set(item_ids) + for arc in arcs: + i_arc, j_arc, lag = arc["from"], arc["to"], arc["lag"] + if i_arc in real_id_set and j_arc in real_id_set: + # l + sum_p p * sum_b x[i,b,p] <= sum_p p * sum_b x[j,b,p] + model.addConstr( + lag + + gp.quicksum( + p * x[i_arc, b, p] + for p in feasible_periods[i_arc] + for b in bins + ) + <= gp.quicksum( + p * x[j_arc, b, p] + for p in feasible_periods[j_arc] + for b in bins + ), + name=f"lag_{i_arc}_{j_arc}", + ) + + # Symmetry breaking: order bins within each period + # u[b,p] >= u[b+1,p] to break symmetry among identical bins + for p in periods: + for b in range(num_bins - 1): + model.addConstr( + u[b, p] >= u[b + 1, p], name=f"sym_{b}_{p}" + ) + + model.update() + model.optimize() + + # --------------------------------------------------------------- + # Extract solution + # --------------------------------------------------------------- + result = { + "status": model.Status, + "status_name": _status_name(model.Status), + } + + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + + assignments = [] + for i in item_ids: + for b in bins: + for p in feasible_periods[i]: + if x[i, b, p].X > 0.5: + assignments.append( + {"item_id": i, "bin": b, "period": p, "weight": weights[i]} + ) + break + else: + continue + break + + # Build bin-period usage summary + active_bins = [] + for b in bins: + for p in periods: + if u[b, p].X > 0.5: + items_here = [ + a for a in assignments if a["bin"] == b and a["period"] == p + ] + active_bins.append( + { + "bin": b, + "period": p, + "items": [a["item_id"] for a in items_here], + "total_weight": sum(a["weight"] for a in items_here), + } + ) + + result["assignments"] = assignments + result["active_bin_periods"] = active_bins + result["num_active_bin_periods"] = len(active_bins) + + if model.Status == GRB.OPTIMAL: + result["optimal"] = True + result["gap"] = 0.0 + else: + result["optimal"] = False + result["gap"] = model.MIPGap + else: + result["objective_value"] = None + result["assignments"] = [] + result["active_bin_periods"] = [] + result["num_active_bin_periods"] = None + result["optimal"] = False + + if hasattr(model, "Runtime"): + result["runtime_seconds"] = model.Runtime + + return result + + +def _status_name(status): + mapping = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.INTERRUPTED: "INTERRUPTED", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + } + return mapping.get(status, f"UNKNOWN_{status}") + + +def main(): + parser = argparse.ArgumentParser( + description="Solve BPPTL (Model 2) using Gurobi" + ) + parser.add_argument( + "--instance_path", type=str, required=True, help="Path to instance JSON file" + ) + parser.add_argument( + "--solution_path", + type=str, + default="gurobi_solution_1.json", + help="Path to output solution JSON file", + ) + parser.add_argument( + "--time_limit", + type=float, + default=None, + help="Gurobi 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) + + instance = load_instance(args.instance_path) + result = solve_bpptl(instance, time_limit=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']}") + print(f"Status: {result['status_name']}") + else: + print(f"No feasible solution found. Status: {result['status_name']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/letelier2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/letelier2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/letelier2022/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/letelier2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/letelier2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/letelier2022/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/letelier2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/letelier2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/letelier2022/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/letelier2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/letelier2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/letelier2022/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/letelier2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/letelier2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/letelier2022/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/letelier2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/letelier2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/letelier2022/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/letelier2022/gurobi_solution/large_solution_1.json b/tasks/letelier2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..8b15edc1e6ff03cf44924b4e8eb0c2cd3d762f4d --- /dev/null +++ b/tasks/letelier2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a79957632a0196542c40ef3570f1ce1351e74b6b84bb27b8f153c570aeaf0e77 +size 12719 diff --git a/tasks/letelier2022/gurobi_solution/large_solution_2.json b/tasks/letelier2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7eb71b14ed3eb1e965bbe55465d4c0fe2580550c --- /dev/null +++ b/tasks/letelier2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f4b4acc0bb28b6431269e2ec99da55873abfb0fc5a4e7be327f5b5e5384bf7c +size 14705 diff --git a/tasks/letelier2022/gurobi_solution/large_solution_3.json b/tasks/letelier2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8fdb949e6efafd2984d21e293ca57ad102d3a5 --- /dev/null +++ b/tasks/letelier2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69bfc7c69d6b76e735920a5fc37b5c2fe37a9f1991618c67f29f4584706b47da +size 13414 diff --git a/tasks/letelier2022/gurobi_solution/large_solution_4.json b/tasks/letelier2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a0923e451511eb538c38efe3ee45f933dc67acae --- /dev/null +++ b/tasks/letelier2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c962fa257894a6b7e32b76652514d22964dafb6e275b4528e3e67cc39bc05f12 +size 12295 diff --git a/tasks/letelier2022/gurobi_solution/large_solution_5.json b/tasks/letelier2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3fd1f6d9a031be6ff011a8270617303ca67785ff --- /dev/null +++ b/tasks/letelier2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17660007043d761a3e9b0486496d2c5e6def24d849dab1419a1ea534c7849d0b +size 19376 diff --git a/tasks/letelier2022/gurobi_solution/tiny_solution.json b/tasks/letelier2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..9ae77907fd883773a522a41739fc03d9e28fdf9c --- /dev/null +++ b/tasks/letelier2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59ca36cde7f1ed58c8083b8b9bfccf5bc02b5acebeda5ed0244c578dd63bb087 +size 2127 diff --git a/tasks/letelier2022/gurobi_solution_log/tiny_log.jsonl b/tasks/letelier2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..480455c1e84c51ceaea8463aeed1a375cd72c8fe --- /dev/null +++ b/tasks/letelier2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0addcae66513eebd0affc42eaf1006937a3cd76df88b92f87af569dfdc7bfe89 +size 41 diff --git a/tasks/letelier2022/instance/large_instance_1.json b/tasks/letelier2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..fc8c26fc9ea8568b405a3898bea31116f1d0daf6 --- /dev/null +++ b/tasks/letelier2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af5deaa030483d193b87c193e1c7628e1ba82e6a62ddc025571450d4d8bc1a99 +size 30833 diff --git a/tasks/letelier2022/instance/large_instance_2.json b/tasks/letelier2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7f9304f1f1fa8af09407324178c82410cff8095b --- /dev/null +++ b/tasks/letelier2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ffdc037e17942148dcea331d2a82eff3b057b547f3e3f7728b74d835183c773 +size 195129 diff --git a/tasks/letelier2022/instance/large_instance_3.json b/tasks/letelier2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e5942b4ce3d5ae59e32dda7e93ff49e4ad271cb6 --- /dev/null +++ b/tasks/letelier2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb5e497d99db8cddce1b9c34577ca8d005fc5c400e1ab4b634407c317ea5c601 +size 87799 diff --git a/tasks/letelier2022/instance/large_instance_4.json b/tasks/letelier2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..db3746e8b20b9fb85ecb1a3b28f869d3141e36ea --- /dev/null +++ b/tasks/letelier2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:718441c3f7a414353ab99f2a3b813b24f87823c2aebac9e4e06bb9b35935d289 +size 48218 diff --git a/tasks/letelier2022/instance/large_instance_5.json b/tasks/letelier2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..74a3e1bd10a73aa2bdf943cf7e011d7932be0292 --- /dev/null +++ b/tasks/letelier2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2eb2ab77b80d6b10dc453b2a05fabc3df49d21a595c037bb16d26245f86f440a +size 23714 diff --git a/tasks/letelier2022/instance/tiny_instance.json b/tasks/letelier2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..1583ccc9ecb15f645a821f5dbd99e99884d09844 --- /dev/null +++ b/tasks/letelier2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a35eba54af746507ec6c23584ea1d6ebf152cdf6a6d6838d3b9c5dec10a787da +size 4797 diff --git a/tasks/letelier2022/instance_schema.json b/tasks/letelier2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3a157afe6a653e93f96fffb9806fe351e4efb0f4 --- /dev/null +++ b/tasks/letelier2022/instance_schema.json @@ -0,0 +1,43 @@ +{ + "parameters": { + "Q": " Number of treatment requests to be scheduled.", + "T": " Number of time periods in the planning horizon.", + "N": " Average number of treatments per request.", + "U": " Average number of treatments that can be handled per bin per time period.", + "W": " Maximum total weight that each bin can hold in any time period.", + "L": " Maximum number of bins available per time period ('infinity' if unrestricted)." + }, + "num_real_items": " Total number of treatment items to be scheduled (excluding source and sink).", + "num_total_items": " Total number of items including the source and sink auxiliary items.", + "source_item_id": " Identifier of the auxiliary source item fixed at time zero.", + "sink_item_id": " Identifier of the auxiliary sink item fixed at time T plus one.", + "items": [ + { + "item_id": " Unique identifier for this item.", + "weight": " Weight of this item that consumes bin capacity when assigned.", + "type": " Role of this item: 'treatment' for a real schedulable item, 'source' or 'sink' for auxiliary timing anchors.", + "request_id": " Identifier of the treatment request this item belongs to (treatment items only).", + "treatment_index": " Position of this treatment within its request's ordered sequence (treatment items only)." + } + ], + "requests": [ + { + "request_id": " Unique identifier for this treatment request.", + "e_q": " Ideal number of time periods between consecutive treatments in this request.", + "e_minus": " Minimum allowed number of time periods between consecutive treatments in this request.", + "e_plus": " Maximum allowed number of time periods between consecutive treatments in this request.", + "f_q": " Time period of the last treatment before the planning horizon for this request.", + "n_q": " Number of treatments for this request that fall within the planning horizon.", + "f_q_prime": " Time period of the first treatment after the planning horizon for this request.", + "treatment_item_ids": " Ordered list of item identifiers for each treatment in this request.", + "treatment_weights": " Weight of each treatment item in this request, in the same order as treatment_item_ids." + } + ], + "arcs": [ + { + "from": " Item identifier at the tail of this timing arc.", + "to": " Item identifier at the head of this timing arc.", + "lag": " Minimum number of time periods by which the head item's assigned period must exceed the tail item's assigned period." + } + ] +} diff --git a/tasks/letelier2022/mathematical_formulation.md b/tasks/letelier2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f0d495187030c5e7282eb45a8759c027605fc77e --- /dev/null +++ b/tasks/letelier2022/mathematical_formulation.md @@ -0,0 +1,57 @@ +# Original Formulation: Bin Packing Problem with Time Lags (BPPTL) + +*Source: Bin Packing Problem with Time Lags, Orlando Rivera Letelier, François Clautiaux, Ruslan Sadykov, 2022 (INFORMS Journal on Computing, 34(4), 2249–2270).* + +## Sets and Indices + +$$\begin{align*} +& V = \{1,\dots,n\} && \text{Set of items, indexed by } i,j. \\ +& G = (V, A, l) && \text{Directed valued graph encoding precedence / time-lag relations.} \\ +& A && \text{Set of arcs } (i,j) \text{ between items.} \\ +& \mathcal{L} = \{1,\dots,L\} && \text{Set of bin indices, indexed by } b. \\ +& \mathcal{T} = \{1,\dots,T\} && \text{Set of time periods, indexed by } p. +\end{align*}$$ + +## Parameters + +$$\begin{align*} +& W && \text{Bin capacity (positive).} \\ +& w_i && \text{Weight of item } i \in V, \text{ with } w_i \le W. \\ +& l_{i,j} \in \mathbb{Z} && \text{Time lag associated with arc } (i,j) \in A \text{ (may be positive, zero, or negative).} \\ +& L && \text{Maximum number of bins usable per time period (positive integer; } L=\infty \text{ if } L \ge n). \\ +& T \in \mathbb{Z}_+ && \text{Upper bound on the number of time periods required in an optimal solution.} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +& x_{i,b,p} \in \{0,1\} && 1 \text{ if item } i \in V \text{ is assigned to bin } (b,p),\ b \in \mathcal{L},\ p \in \mathcal{T}. \\ +& u_{b,p} \in \{0,1\} && 1 \text{ if bin } (b,p) \text{ has at least one item assigned, } b \in \mathcal{L},\ p \in \mathcal{T}. +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad & \sum_{b \in \mathcal{L}} \sum_{p \in \mathcal{T}} u_{b,p} \tag{2a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.}\quad +& \sum_{b \in \mathcal{L}} \sum_{p \in \mathcal{T}} x_{i,b,p} = 1 + && \forall i \in V, \tag{2b} \\ +& \sum_{i \in V} w_i\, x_{i,b,p} \leq W\, u_{b,p} + && \forall b \in \mathcal{L},\ p \in \mathcal{T}, \tag{2c} \\ +& l_{i,j} + \sum_{p \in \mathcal{T}} p \cdot \sum_{b \in \mathcal{L}} x_{i,b,p} + \leq \sum_{p \in \mathcal{T}} p \cdot \sum_{b \in \mathcal{L}} x_{j,b,p} + && \forall (i,j) \in A, \tag{2d} \\ +& x_{i,b,p} \in \{0,1\} + && \forall i \in V,\ b \in \mathcal{L},\ p \in \mathcal{T}, \tag{2e} \\ +& u_{b,p} \in \{0,1\} + && \forall b \in \mathcal{L},\ p \in \mathcal{T}. \tag{2f} +\end{align}$$ + +## Preprocessing (not part of the formulation) + +Let $d(i,j)$ be the length of the longest path from $i$ to $j$ in $G$ ($d(i,j)=-\infty$ if no path exists). Adding a source $s$ (time $0$) and sink $f$ (time $T+1$) with arcs $(s,i)$, $(i,f)$ of lag one gives $es(i)=d(s,i)$ and $ls(i)=T+1-d(i,f)$. Variables $x_{i,b,p}$ with $pls(i)$ may be fixed to zero. diff --git a/tasks/letelier2022/problem_description.txt b/tasks/letelier2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..183a5977e9c759e11944df63c1dace17f1d324cb --- /dev/null +++ b/tasks/letelier2022/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A facility must schedule a set of items across a discretized time horizon using identical capacitated bins. The input specifies a set of items, each with a known positive weight no greater than the bin capacity. A positive integer gives the common capacity shared by all bins. The time horizon consists of a set of consecutive time periods numbered from one up to a given upper bound on the number of periods. In each time period, up to a given maximum number of bins may be used; when that maximum is unrestricted (infinite), any number of bins may be used in any period. A directed graph over the items encodes pairwise timing relationships: each arc from one item to another carries an integer-valued lag (which may be positive, zero, or negative). A positive lag on an arc from a first item to a second item means that the time period assigned to the second item must exceed the time period assigned to the first item by at least that lag value. A negative lag on the reverse arc from the second item back to the first item encodes an upper bound on how far apart the two items may be scheduled, so that the pair of arcs between two items together confine the difference in their assigned time periods to a closed interval. Two additional auxiliary nodes, a source fixed to time zero and a sink fixed to one plus the upper bound on the number of periods, are connected by arcs of lag one to every real item, and these arcs together with the item-to-item arcs define the earliest and latest allowable time period for each item. + +Each item must be placed into exactly one bin in exactly one time period. The total weight of all items placed into any single bin in any single time period must not exceed the bin capacity. For every arc in the precedence graph, the lag value plus the time period of the arc's tail item must be no greater than the time period of the arc's head item. A bin-period pair is considered used whenever at least one item is assigned to it. + +The goal is to minimize the total number of used bin-period pairs across the entire time horizon. diff --git a/tasks/letelier2022/solution_logger.py b/tasks/letelier2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/letelier2022/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/letelier2022/solution_schema.json b/tasks/letelier2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8c6d2fe0013b5b2112d4e791f18b683f4f3993ba --- /dev/null +++ b/tasks/letelier2022/solution_schema.json @@ -0,0 +1,20 @@ +{ + "objective_value": " Total number of bin-period pairs used across the entire planning horizon.", + "assignments": [ + { + "item_id": " Identifier of the treatment item being assigned.", + "bin": " Bin to which this item is assigned.", + "period": " Time period in which this item is scheduled.", + "weight": " Weight of this item consuming capacity in the assigned bin-period." + } + ], + "active_bin_periods": [ + { + "bin": " Bin identifier for this used bin-period pair.", + "period": " Time period for this used bin-period pair.", + "items": " Identifiers of all items assigned to this bin in this period.", + "total_weight": " Combined weight of all items assigned to this bin in this period." + } + ], + "num_active_bin_periods": " Total count of bin-period pairs that contain at least one item." +} diff --git a/tasks/levin2017/feasibility_check.py b/tasks/levin2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7a4da294b9db851fa013c2f8dcf217f15b4bdd07 --- /dev/null +++ b/tasks/levin2017/feasibility_check.py @@ -0,0 +1,896 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Congestion-Aware System Optimal SAV Routing LP. + +Based on: Levin (2017) "Congestion-aware system optimal route choice for shared +autonomous vehicles", Transportation Research Part C, 82, 229-247. + +Checks all 22 hard constraints (Eqs. 34-55) from the combined LP formulation, +plus an objective-consistency check (constraint 23) that recomputes TSTT +(Eq. 30/33) from the solution's N_U/N_D/omega variables and rejects reported +objective values that disagree. + +Expected solution JSON format: +{ + "objective_value": float, + "y": {"i|j|k|s|t": float}, // turning flow y_{ijk}^s(t) + "y_centroid": {"i|j|s|t": float}, // centroid departure flow y_{ij}^s(t) + "N_U": {"i|j|s|t": float}, // upstream cumulative count + "N_D": {"i|j|s|t": float}, // downstream cumulative count + "p": {"j|t": float}, // parking at centroid j at time t + "e": {"r|s|t": float}, // departing travelers + "omega": {"r|s|t": float} // waiting demand +} +""" + +import argparse +import json +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('N_D', 'N_U', 'e', 'objective_value', 'omega', 'p', 'y', 'y_centroid') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('N_D', 'N_U', 'y_centroid') +_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 load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def save_json(path, data): + with open(path, "w") as f: + json.dump(data, f, indent=2) + + +def gv(d, key): + """Get value from dict, default 0.0.""" + return d.get(key, 0.0) + + +def compute_violation(lhs, rhs, op): + """Compute violation_amount for a constraint.""" + if op == "eq": + return abs(lhs - rhs) + elif op == "leq": + return max(lhs - rhs, 0.0) + elif op == "geq": + return max(rhs - lhs, 0.0) + return 0.0 + + +def record_violation(violations_list, magnitudes_list, constraint_idx, msg, lhs, rhs, op): + """Check and record a violation if it exceeds tolerance.""" + viol_amt = compute_violation(lhs, rhs, op) + if viol_amt > TOL: + violations_list.append((constraint_idx, msg)) + normalizer = max(abs(rhs), EPS) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(viol_amt), + "normalizer": float(normalizer), + "ratio": float(viol_amt / normalizer), + }) + + +# --- Key construction helpers --- + +def yk(i, j, k, s, t): + """Key for turning flow y_{ijk}^s(t).""" + return f"{i}|{j}|{k}|{s}|{t}" + + +def yck(i, j, s, t): + """Key for centroid departure flow y_{ij}^s(t).""" + return f"{i}|{j}|{s}|{t}" + + +def nk(i, j, s, t): + """Key for cumulative counts N_{ij}^{Us}(t) or N_{ij}^{Ds}(t).""" + return f"{i}|{j}|{s}|{t}" + + +def pk(j, t): + """Key for parking p_j(t).""" + return f"{j}|{t}" + + +def ek(r, s, t): + """Key for e_r^s(t) or omega_r^s(t).""" + return f"{r}|{s}|{t}" + + +def parse_instance(instance): + """Extract network structure and parameters from instance JSON.""" + net = instance["network"] + T = instance["time_parameters"]["time_horizon_T"] + + centroids = set() + junctions = set() + for node in net["nodes"]: + if node["type"] == "centroid": + centroids.add(node["id"]) + else: + junctions.add(node["id"]) + + links = {} + A_o = [] + A_z_plus = [] + A_z_minus = [] + + for link in net["links"]: + i, j = link["from"], link["to"] + links[(i, j)] = link + if link["type"] == "centroid_connector": + if i in centroids: + A_z_plus.append((i, j)) + if j in centroids: + A_z_minus.append((i, j)) + else: + A_o.append((i, j)) + + all_links = list(links.keys()) + + # Gamma_j^+ = outgoing links from j; Gamma_j^- = incoming links to j + gamma_plus = defaultdict(list) + gamma_minus = defaultdict(list) + for (i, j) in all_links: + gamma_plus[i].append((i, j)) + gamma_minus[j].append((i, j)) + + # Demand d[r][s][t] + d = defaultdict(lambda: defaultdict(lambda: defaultdict(float))) + for od in instance["demand"]["od_pairs"]: + r, s = od["origin"], od["destination"] + for t_dep in od["departure_times"]: + d[r][s][t_dep] += 1.0 + + # Initial parking + p0 = {} + for c, count in instance["fleet"]["initial_distribution"].items(): + p0[c] = float(count) + + return { + "T": T, + "centroids": centroids, + "links": links, + "all_links": all_links, + "A_o": A_o, + "A_z_plus": A_z_plus, + "A_z_minus": A_z_minus, + "gamma_plus": gamma_plus, + "gamma_minus": gamma_minus, + "d": d, + "p0": p0, + } + + +def check_feasibility(instance, solution): + # If the solver reported infeasible/unbounded (no solution found), return null + status = solution.get("status") + if status in ("INF_OR_UNBD", "INFEASIBLE", "UNBOUNDED"): + return { + "feasible": None, + "violated_constraints": [], + "violations": [f"No solution to check: solver status is {status}"], + "violation_magnitudes": [], + } + obj = solution.get("objective_value") + if obj is None and not solution.get("y"): + return { + "feasible": None, + "violated_constraints": [], + "violations": ["No solution to check: objective_value is null and no variable data present"], + "violation_magnitudes": [], + } + + inst = parse_instance(instance) + + # Solution variables + y = solution.get("y", {}) + yc = solution.get("y_centroid", {}) + N_U = solution.get("N_U", {}) + N_D = solution.get("N_D", {}) + p_sol = solution.get("p", {}) + e_sol = solution.get("e", {}) + omega_sol = solution.get("omega", {}) + + T = inst["T"] + centroids = inst["centroids"] + links_data = inst["links"] + A_o = inst["A_o"] + A_z_plus = inst["A_z_plus"] + A_z_minus = inst["A_z_minus"] + gamma_plus = inst["gamma_plus"] + gamma_minus = inst["gamma_minus"] + d = inst["d"] + + A_o_Az_plus = A_o + A_z_plus + A_o_Az_minus = A_o + A_z_minus + + def fftt(i, j): + return links_data[(i, j)]["free_flow_travel_time_steps"] + + def cwtt(i, j): + return links_data[(i, j)]["congested_travel_time_steps"] + + dt_sec = instance["time_parameters"]["time_step_duration_seconds"] + + def cap(i, j): + return links_data[(i, j)]["capacity_vph"] * (dt_sec / 3600.0) + + def jam_veh(i, j): + return links_data[(i, j)]["jam_density_vehicles"] + + violations_list = [] + magnitudes_list = [] + + od_pairs = [(r, s) for r in centroids for s in centroids] + + # ========================================================================= + # Constraint 1 (Eq. 34): Upstream cumulative count evolution + # N_{ij}^{Us}(t+1) = N_{ij}^{Us}(t) + sum_{(j,k) in Gamma_j^+} y_{ijk}^s(t) + # for (i,j) in A_o, s in Z, t in [0, T-1] + # (A_z^+ links are handled by constraint 13/Eq.46) + # ========================================================================= + for (i, j) in A_o: + for s in centroids: + for t in range(T): + lhs = gv(N_U, nk(i, j, s, t + 1)) + flow_sum = sum(gv(y, yk(i, j, k, s, t)) + for (_, k) in gamma_plus.get(j, [])) + rhs = gv(N_U, nk(i, j, s, t)) + flow_sum + record_violation(violations_list, magnitudes_list, 1, + f"Constraint 1 (Eq.34) violated: link ({i},{j}), dest {s}, t={t}: " + f"N_U(t+1)={lhs:.6g} != {rhs:.6g}", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint 2 (Eq. 35): Downstream cumulative count evolution + # N_{jk}^{Ds}(t+1) = N_{jk}^{Ds}(t) + sum_{(i,j) in Gamma_j^-} y_{ijk}^s(t) + # for (j,k) in A_o, s in Z, t in [0, T-1] + # (A_z^- links are handled by constraint 14/Eq.47) + # ========================================================================= + for (j, k) in A_o: + for s in centroids: + for t in range(T): + lhs = gv(N_D, nk(j, k, s, t + 1)) + flow_sum = sum(gv(y, yk(i, j, k, s, t)) + for (i, _) in gamma_minus.get(j, [])) + rhs = gv(N_D, nk(j, k, s, t)) + flow_sum + record_violation(violations_list, magnitudes_list, 2, + f"Constraint 2 (Eq.35) violated: link ({j},{k}), dest {s}, t={t}: " + f"N_D(t+1)={lhs:.6g} != {rhs:.6g}", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint 3 (Eq. 36): Sending flow constraint + # sum_{(j,k)} y_{ijk}^s(t) <= N_{ij}^{Us}(t - L/v + 1) - N_{ij}^{Ds}(t) + # for (i,j) in A_o, s in Z, t in [L/v - 1, T] + # (A_z^+ centroid departure bounded by constraint 12/Eq.45) + # ========================================================================= + for (i, j) in A_o: + lv = fftt(i, j) + for s in centroids: + for t in range(lv - 1, T + 1): + lhs = sum(gv(y, yk(i, j, k, s, t)) + for (_, k) in gamma_plus.get(j, [])) + t_shift = t - lv + 1 + rhs = gv(N_U, nk(i, j, s, t_shift)) - gv(N_D, nk(i, j, s, t)) + record_violation(violations_list, magnitudes_list, 3, + f"Constraint 3 (Eq.36) violated: link ({i},{j}), dest {s}, t={t}: " + f"sum_y={lhs:.6g} > {rhs:.6g}", + lhs, rhs, "leq") + + # ========================================================================= + # Constraint 4 (Eq. 37): Zero flow before free-flow travel time elapses + # y_{ijk}^s(t) = 0 for t in [0, L/v - 1) + # for (i,j) in A_o ∪ A_z^+, (j,k) in Gamma_j^+, s in Z + # ========================================================================= + for (i, j) in A_o_Az_plus: + lv = fftt(i, j) + if lv <= 1: + continue + for (_, k) in gamma_plus.get(j, []): + for s in centroids: + for t in range(lv - 1): + val = gv(y, yk(i, j, k, s, t)) + record_violation(violations_list, magnitudes_list, 4, + f"Constraint 4 (Eq.37) violated: y({i},{j},{k},{s},{t})={val:.6g} != 0", + val, 0.0, "eq") + + # ========================================================================= + # Constraint 5 (Eq. 38): Sending flow capacity + # sum_s sum_k y_{ijk}^s(t) <= Q_{ij} + # for (i,j) in A_o, t in [0, T] + # ========================================================================= + for (i, j) in A_o: + Q = cap(i, j) + for t in range(T + 1): + lhs = sum(gv(y, yk(i, j, k, s, t)) + for s in centroids + for (_, k) in gamma_plus.get(j, [])) + record_violation(violations_list, magnitudes_list, 5, + f"Constraint 5 (Eq.38) violated: link ({i},{j}), t={t}: " + f"sum_y={lhs:.6g} > Q={Q}", + lhs, Q, "leq") + + # ========================================================================= + # Constraint 6 (Eq. 39): Receiving flow capacity + # sum_i sum_s y_{ijk}^s(t) <= Q_{jk} + # for (j,k) in A_o, t in [0, T] + # ========================================================================= + for (j, k) in A_o: + Q = cap(j, k) + for t in range(T + 1): + lhs = sum(gv(y, yk(i, j, k, s, t)) + for (i, _) in gamma_minus.get(j, []) + for s in centroids) + record_violation(violations_list, magnitudes_list, 6, + f"Constraint 6 (Eq.39) violated: link ({j},{k}), t={t}: " + f"sum_y={lhs:.6g} > Q={Q}", + lhs, Q, "leq") + + # ========================================================================= + # Constraint 7 (Eq. 40): Receiving flow congested wave constraint + # sum_i sum_s y_{ijk}^s(t) <= sum_s(N_{jk}^{Us}(t-L/w+1) - N_{jk}^{Ds}(t)) + KL + # for (j,k) in A_o, t in [L/w - 1, T] + # ========================================================================= + for (j, k) in A_o: + lw = cwtt(j, k) + KL = jam_veh(j, k) + for t in range(lw - 1, T + 1): + lhs = sum(gv(y, yk(i, j, k, s, t)) + for (i, _) in gamma_minus.get(j, []) + for s in centroids) + t_shift = t - lw + 1 + rhs_flow = sum(gv(N_U, nk(j, k, s, t_shift)) - gv(N_D, nk(j, k, s, t)) + for s in centroids) + rhs = rhs_flow + KL + record_violation(violations_list, magnitudes_list, 7, + f"Constraint 7 (Eq.40) violated: link ({j},{k}), t={t}: " + f"sum_y={lhs:.6g} > {rhs:.6g}", + lhs, rhs, "leq") + + # ========================================================================= + # Constraint 8 (Eq. 41): Initial upstream counts zero + # N_{ij}^{Us}(0) = 0 for all (i,j) in A, s in Z + # ========================================================================= + for (i, j) in inst["all_links"]: + for s in centroids: + val = gv(N_U, nk(i, j, s, 0)) + record_violation(violations_list, magnitudes_list, 8, + f"Constraint 8 (Eq.41) violated: N_U({i},{j},{s},0)={val:.6g} != 0", + val, 0.0, "eq") + + # ========================================================================= + # Constraint 9 (Eq. 42): Initial downstream counts zero + # N_{ij}^{Ds}(0) = 0 for all (i,j) in A, s in Z + # ========================================================================= + for (i, j) in inst["all_links"]: + for s in centroids: + val = gv(N_D, nk(i, j, s, 0)) + record_violation(violations_list, magnitudes_list, 9, + f"Constraint 9 (Eq.42) violated: N_D({i},{j},{s},0)={val:.6g} != 0", + val, 0.0, "eq") + + # ========================================================================= + # Constraint 10 (Eq. 43): Parking evolution at centroids + # p_j(t+1) = p_j(t) + sum_{(i,j) in Gamma_j^-}(N_{ij}^{Uj}(t) - N_{ij}^{Dj}(t)) + # - sum_{(j,k) in Gamma_j^+} sum_s y_{jk}^s(t) + # for j in Z, t in [0, T-1] + # Note: superscript j on N means only vehicles destined for centroid j. + # y_{jk}^s is the centroid departure flow (from y_centroid dict). + # ========================================================================= + for j in centroids: + for t in range(T): + p_next = gv(p_sol, pk(j, t + 1)) + p_curr = gv(p_sol, pk(j, t)) + + # Arriving: vehicles on incoming links destined for j (occupancy) + arriving = sum(gv(N_U, nk(i, j, j, t)) - gv(N_D, nk(i, j, j, t)) + for (i, _) in gamma_minus.get(j, [])) + + # Departing: centroid departure flow from j to all destinations + departing = sum(gv(yc, yck(j, k, s, t)) + for (_, k) in gamma_plus.get(j, []) + for s in centroids) + + rhs = p_curr + arriving - departing + record_violation(violations_list, magnitudes_list, 10, + f"Constraint 10 (Eq.43) violated: centroid {j}, t={t}: " + f"p(t+1)={p_next:.6g} != {rhs:.6g}", + p_next, rhs, "eq") + + # ========================================================================= + # Constraint 11 (Eq. 44): No through-flow on centroid connectors to centroid + # y_{ijk}^s(t) = 0 for (j,k) in A_z^-, (i,j) in Gamma_j^-, s != k, t in [0,T] + # ========================================================================= + for (j, k) in A_z_minus: + for (i, _) in gamma_minus.get(j, []): + for s in centroids: + if s != k: + for t in range(T + 1): + val = gv(y, yk(i, j, k, s, t)) + if abs(val) > TOL: + record_violation(violations_list, magnitudes_list, 11, + f"Constraint 11 (Eq.44) violated: " + f"y({i},{j},{k},{s},{t})={val:.6g} but s={s} != k={k}", + val, 0.0, "eq") + + # ========================================================================= + # Constraint 12 (Eq. 45): Outgoing flow bounded by parked vehicles + # sum_{(i,j) in Gamma_i^+} sum_s y_{ij}^s(t) <= p_i(t) + # for i in Z, t in [0, T] + # ========================================================================= + for i in centroids: + for t in range(T + 1): + lhs = sum(gv(yc, yck(i, j, s, t)) + for (_, j) in gamma_plus.get(i, []) + for s in centroids) + rhs = gv(p_sol, pk(i, t)) + record_violation(violations_list, magnitudes_list, 12, + f"Constraint 12 (Eq.45) violated: centroid {i}, t={t}: " + f"sum_y={lhs:.6g} > p={rhs:.6g}", + lhs, rhs, "leq") + + # ========================================================================= + # Constraint 13 (Eq. 46): Upstream count on outgoing centroid connectors + # N_{ij}^{Us}(t+1) = N_{ij}^{Us}(t) + y_{ij}^s(t) + # for (i,j) in A_z^+, s in Z, t in [0, T-1] + # ========================================================================= + for (i, j) in A_z_plus: + for s in centroids: + for t in range(T): + lhs = gv(N_U, nk(i, j, s, t + 1)) + rhs = gv(N_U, nk(i, j, s, t)) + gv(yc, yck(i, j, s, t)) + record_violation(violations_list, magnitudes_list, 13, + f"Constraint 13 (Eq.46) violated: link ({i},{j}), dest {s}, t={t}: " + f"N_U(t+1)={lhs:.6g} != {rhs:.6g}", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint 14 (Eq. 47): Downstream count on incoming centroid connectors + # N_{ij}^{Ds}(t+1) = N_{ij}^{Us}(t) + # for (i,j) in A_z^-, s in Z, t in [0, T-1] + # ========================================================================= + for (i, j) in A_z_minus: + for s in centroids: + for t in range(T): + lhs = gv(N_D, nk(i, j, s, t + 1)) + rhs = gv(N_U, nk(i, j, s, t)) + record_violation(violations_list, magnitudes_list, 14, + f"Constraint 14 (Eq.47) violated: link ({i},{j}), dest {s}, t={t}: " + f"N_D(t+1)={lhs:.6g} != N_U(t)={rhs:.6g}", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint 15 (Eq. 48): Fleet conservation + # sum_{i in Z} p_i(0) = sum_{i in Z} p_i(T) + # ========================================================================= + sum_p0 = sum(gv(p_sol, pk(j, 0)) for j in centroids) + sum_pT = sum(gv(p_sol, pk(j, T)) for j in centroids) + record_violation(violations_list, magnitudes_list, 15, + f"Constraint 15 (Eq.48) violated: sum p(0)={sum_p0:.6g} != sum p(T)={sum_pT:.6g}", + sum_p0, sum_pT, "eq") + + # ========================================================================= + # Constraint 16 (Eq. 49): Departing travelers bounded by waiting demand + # e_r^s(t) <= omega_r^s(t) + # for (r,s) in Z^2, t in [0, T] + # ========================================================================= + for (r, s) in od_pairs: + for t in range(T + 1): + e_val = gv(e_sol, ek(r, s, t)) + omega_val = gv(omega_sol, ek(r, s, t)) + record_violation(violations_list, magnitudes_list, 16, + f"Constraint 16 (Eq.49) violated: ({r},{s}), t={t}: " + f"e={e_val:.6g} > omega={omega_val:.6g}", + e_val, omega_val, "leq") + + # ========================================================================= + # Constraint 17 (Eq. 50): Departing travelers bounded by departing vehicles + # e_r^s(t) <= sum_{(r,j) in Gamma_r^+} y_{rj}^s(t) + # for (r,s) in Z^2, t in [0, T] + # ========================================================================= + for (r, s) in od_pairs: + for t in range(T + 1): + e_val = gv(e_sol, ek(r, s, t)) + dep_flow = sum(gv(yc, yck(r, j, s, t)) + for (_, j) in gamma_plus.get(r, [])) + record_violation(violations_list, magnitudes_list, 17, + f"Constraint 17 (Eq.50) violated: ({r},{s}), t={t}: " + f"e={e_val:.6g} > sum_y={dep_flow:.6g}", + e_val, dep_flow, "leq") + + # ========================================================================= + # Constraint 18 (Eq. 51): Waiting demand evolution + # omega_r^s(t+1) = omega_r^s(t) + d_r^s(t) - e_r^s(t) + # for (r,s) in Z^2, t in [0, T-1] + # ========================================================================= + for (r, s) in od_pairs: + for t in range(T): + lhs = gv(omega_sol, ek(r, s, t + 1)) + rhs = gv(omega_sol, ek(r, s, t)) + d[r][s][t] - gv(e_sol, ek(r, s, t)) + record_violation(violations_list, magnitudes_list, 18, + f"Constraint 18 (Eq.51) violated: ({r},{s}), t={t}: " + f"omega(t+1)={lhs:.6g} != {rhs:.6g}", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint 19 (Eq. 52): All demand served by end of horizon + # omega_r^s(T) = 0 for all (r,s) in Z^2 + # ========================================================================= + for (r, s) in od_pairs: + val = gv(omega_sol, ek(r, s, T)) + record_violation(violations_list, magnitudes_list, 19, + f"Constraint 19 (Eq.52) violated: omega({r},{s},T)={val:.6g} != 0", + val, 0.0, "eq") + + # ========================================================================= + # Constraint 20 (Eq. 53): Non-negativity of turning flows + # y_{ijk}^s(t) >= 0 + # for (i,j) in A_o ∪ A_z^+, (j,k) in Gamma_j^+, s in Z, t in [0,T] + # ========================================================================= + for (i, j) in A_o_Az_plus: + for (_, k) in gamma_plus.get(j, []): + for s in centroids: + for t in range(T + 1): + val = gv(y, yk(i, j, k, s, t)) + if val < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"Constraint 20 (Eq.53) violated: " + f"y({i},{j},{k},{s},{t})={val:.6g} < 0", + val, 0.0, "geq") + + # ========================================================================= + # Constraint 21 (Eq. 54): Non-negativity of centroid departure flow + # y_{ij}^s(t) >= 0 + # for (i,j) in A_z^+, s in Z, t in [0, T] + # ========================================================================= + for (i, j) in A_z_plus: + for s in centroids: + for t in range(T + 1): + val = gv(yc, yck(i, j, s, t)) + if val < -TOL: + record_violation(violations_list, magnitudes_list, 21, + f"Constraint 21 (Eq.54) violated: " + f"y_c({i},{j},{s},{t})={val:.6g} < 0", + val, 0.0, "geq") + + # ========================================================================= + # Constraint 22 (Eq. 55): Non-negativity of departing travelers + # e_r^s(t) >= 0 for (r,s) in Z^2, t in [0, T] + # ========================================================================= + for (r, s) in od_pairs: + for t in range(T + 1): + val = gv(e_sol, ek(r, s, t)) + if val < -TOL: + record_violation(violations_list, magnitudes_list, 22, + f"Constraint 22 (Eq.55) violated: " + f"e({r},{s},{t})={val:.6g} < 0", + val, 0.0, "geq") + + _domain_check_vars_binary = [] + _domain_check_vars_integer = [] + + # ===================================================================== + # Non-negativity checks for levin2017 + # All continuous flow/count variables must be >= 0 + for field in ("y", "y_centroid", "N_U", "N_D", "p", "e", "omega"): + var_dict = solution.get(field, {}) + if not isinstance(var_dict, dict): + continue + for key, val in var_dict.items(): + try: + v = float(val) + except (TypeError, ValueError): + continue + if v < -TOL: + violations_list.append((3, f"{field}[{key}] = {v} < 0 (non-negativity)")) + magnitudes_list.append({ + "constraint": 3, "lhs": v, "rhs": 0.0, + "raw_excess": -v, "normalizer": max(abs(v), EPS), + "ratio": -v / max(abs(v), EPS), + }) + + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # Adapted: writes (idx, msg) tuples to violations_list so aggregation + # below picks them up. Constraint indices reused: 1 (binary), 2 (integer). + # ===================================================================== + # Constraint 1: Binary domain — variables must be 0 or 1 + for var_name, var_dict in _domain_check_vars_binary: + if isinstance(var_dict, dict): + for key, val in var_dict.items(): + try: + v = float(val) + except (TypeError, ValueError): + continue + if abs(v - round(v)) > TOL or round(v) not in (0, 1): + viol = min(abs(v - 0), abs(v - 1)) + if viol > TOL: + violations_list.append((1, + f"Constraint 1 (binary domain): {var_name}[{key}] = {v} not in {0, 1}")) + magnitudes_list.append({ + "constraint": 1, + "lhs": v, + "rhs": 1.0, + "raw_excess": float(viol), + "normalizer": 1.0, + "ratio": float(viol), + }) + + # Constraint 2: Integer domain — variables must be integral + for var_name, var_dict in _domain_check_vars_integer: + if isinstance(var_dict, dict): + for key, val in var_dict.items(): + try: + v = float(val) + except (TypeError, ValueError): + continue + frac = abs(v - round(v)) + if frac > TOL: + violations_list.append((2, + f"Constraint 2 (integer domain): {var_name}[{key}] = {v} is not integer")) + magnitudes_list.append({ + "constraint": 2, + "lhs": v, + "rhs": round(v), + "raw_excess": float(frac), + "normalizer": max(abs(round(v)), EPS), + "ratio": float(frac / max(abs(round(v)), EPS)), + }) + + # ========================================================================= + # Constraint 23 (Eq. 30/33): Objective consistency (Tier C defense) + # Recompute TSTT from solution variables and compare to reported obj. + # Z = sum_{(i,j) in A} sum_s sum_{t=0..T} (N_U(t) - N_D(t)) + # + sum_{(r,s) in Z^2} sum_{t=0..T} omega(t) + # All variables required by this formula (N_U, N_D, omega) are written + # to the solution by every program, so a full recompute is exact. + # ========================================================================= + 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: + link_term = 0.0 + for (i, j) in inst["all_links"]: + for s in centroids: + for t in range(T + 1): + link_term += (gv(N_U, nk(i, j, s, t)) + - gv(N_D, nk(i, j, s, t))) + wait_term = 0.0 + for (r, s) in od_pairs: + for t in range(T + 1): + wait_term += gv(omega_sol, ek(r, s, t)) + true_obj = float(link_term + wait_term) + 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: + record_violation(violations_list, magnitudes_list, 23, + f"Constraint 23 (Eq.30/33) violated: reported " + f"objective_value={reported} differs from recomputed " + f"TSTT={true_obj} (link_term={link_term:.6g}, " + f"wait_term={wait_term:.6g}, |diff|={abs_diff:.3g}, " + f"tol={tol:.3g})", + reported, true_obj, "eq") + + # ========================================================================= + # Aggregate results (moved here so it picks up domain-check writes) + # ========================================================================= + violated_indices = sorted(set(idx for idx, _ in violations_list)) + msg_by_idx = defaultdict(list) + for idx, msg in violations_list: + msg_by_idx[idx].append(msg) + + aggregated_msgs = [] + for idx in violated_indices: + msgs = msg_by_idx[idx] + if len(msgs) <= 3: + aggregated_msgs.extend(msgs) + else: + aggregated_msgs.append( + f"{msgs[0]} (and {len(msgs)-1} more violations of constraint {idx})") + + feasible = len(violated_indices) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": aggregated_msgs, + "violation_magnitudes": magnitudes_list if not feasible else [], + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for SAV routing LP (Levin 2017)") + parser.add_argument("--instance_path", required=True, + help="Path to the instance JSON file") + parser.add_argument("--solution_path", required=True, + help="Path to the candidate solution JSON file") + parser.add_argument("--result_path", required=True, + help="Path to write the feasibility result JSON file") + 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) + + if result["feasible"] is None: + print("NO SOLUTION: Nothing to check.") + for msg in result["violations"]: + print(f" - {msg}") + elif result["feasible"]: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. " + f"Violated constraints: {result['violated_constraints']}") + for msg in result["violations"][:10]: + print(f" - {msg}") + if len(result["violations"]) > 10: + print(f" ... and {len(result['violations']) - 10} more") + + +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/levin2017/gurobi_code.py b/tasks/levin2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..90ac19d6db2366d52f697e3eb26dff6481ac3aec --- /dev/null +++ b/tasks/levin2017/gurobi_code.py @@ -0,0 +1,636 @@ +""" +Gurobi LP implementation of the SAV routing problem from Levin (2017). + +Implements the linear program defined by constraints (33)-(55) for +shared autonomous vehicle (SAV) fleet routing on a cell-transmission- +model-based network. +""" + +import json +import argparse +import os +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 SAV routing LP via Gurobi (Levin 2017 formulation)" + ) + parser.add_argument("--instance_path", type=str, required=True) + parser.add_argument("--solution_path", type=str, required=True) + parser.add_argument("--time_limit", type=int, required=True) + 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 data + # ---------------------------------------------------------------- + with open(args.instance_path) as f: + data = json.load(f) + + nodes = data["network"]["nodes"] + links = data["network"]["links"] + T = data["time_parameters"]["time_horizon_T"] + dt_sec = data["time_parameters"]["time_step_duration_seconds"] + od_pairs = data["demand"]["od_pairs"] + fleet = data["fleet"]["initial_distribution"] # dict: centroid_id -> count + + # ---------------------------------------------------------------- + # Build network sets + # ---------------------------------------------------------------- + # Centroid set Z + Z = set() + for node in nodes: + if node["type"] == "centroid": + Z.add(node["id"]) + + # All node ids + all_node_ids = set(n["id"] for n in nodes) + + # Link sets with parameters + A_o = set() # road links + A_z_plus = set() # centroid connectors outgoing from centroid + A_z_minus = set() # centroid connectors incoming to centroid + + # Link parameters indexed by (from, to) tuple + fftt = {} # free-flow travel time in time steps + cwtt = {} # congested wave travel time in time steps + Q = {} # capacity per time step + KL = {} # jam density * length (max vehicles on link) + + for link in links: + i = link["from"] + j = link["to"] + arc = (i, j) + + fftt[arc] = link["free_flow_travel_time_steps"] + cwtt[arc] = link["congested_travel_time_steps"] + Q[arc] = link["capacity_vph"] * (dt_sec / 3600.0) + KL[arc] = link["jam_density_vehicles"] + + if link["type"] == "road": + A_o.add(arc) + elif link["type"] == "centroid_connector": + if i in Z: + A_z_plus.add(arc) + if j in Z: + A_z_minus.add(arc) + + # Combined sets + A_o_plus = A_o | A_z_plus # A_o ∪ A_z_plus + A_o_minus = A_o | A_z_minus # A_o ∪ A_z_minus + A_all = A_o | A_z_plus | A_z_minus # all links + + # Adjacency: gamma_plus[j] = outgoing links from j, gamma_minus[j] = incoming links to j + gamma_plus = {n["id"]: [] for n in nodes} + gamma_minus = {n["id"]: [] for n in nodes} + + for arc in A_all: + i, j = arc + gamma_plus[i].append(arc) + gamma_minus[j].append(arc) + + # ---------------------------------------------------------------- + # Build demand dictionary d[r, s, t] + # ---------------------------------------------------------------- + d = {} + for od in od_pairs: + r = od["origin"] + s = od["destination"] + for t_dep in od["departure_times"]: + key = (r, s, t_dep) + d[key] = d.get(key, 0) + 1 + + # Collect active OD pairs (r, s) that have nonzero demand + od_set = set() + for od in od_pairs: + od_set.add((od["origin"], od["destination"])) + # We need all (r, s) in Z x Z for completeness of omega / e variables + ZxZ = [(r, s) for r in Z for s in Z] + + # ---------------------------------------------------------------- + # Pre-compute valid index sets for variables + # ---------------------------------------------------------------- + Z_list = sorted(Z) + + # y_turn indices: (i, j, k, s, t) where (i,j) in A_o_plus, (j,k) in gamma_plus[j] + # For efficiency, build a list of (i,j,k) triples + turn_triples = [] # list of (i, j, k) + for (i, j) in A_o_plus: + for (j2, k) in gamma_plus[j]: + assert j2 == j + turn_triples.append((i, j, k)) + + # For constraint (44): identify which y_turn vars must be zero + # For (j,k) in A_z_minus, the centroid is k. y_turn[i,j,k,s,t] = 0 if s != k. + # We implement this by not creating those variables (or fixing them). + # Build set of A_z_minus destination nodes for quick lookup. + az_minus_dest = {} # arc (j,k) -> centroid k + for (j, k) in A_z_minus: + az_minus_dest[(j, k)] = k + + # ---------------------------------------------------------------- + # Create Gurobi model + # ---------------------------------------------------------------- + model = gp.Model("SAV_routing_LP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + model.setParam("Method", 2) # barrier often good for large LPs + + # ---------------------------------------------------------------- + # Decision variables + # ---------------------------------------------------------------- + time_range = range(T + 1) # 0..T + + # y_turn[i,j,k,s,t] -- turning flow + # For constraint (44) efficiency: skip s != k when (j,k) in A_z_minus + y_turn_keys = [] + for (i, j, k) in turn_triples: + if (j, k) in az_minus_dest: + # Only destination = k allowed + dest_k = az_minus_dest[(j, k)] + for t in time_range: + y_turn_keys.append((i, j, k, dest_k, t)) + else: + for s in Z_list: + for t in time_range: + y_turn_keys.append((i, j, k, s, t)) + + y_turn = model.addVars(y_turn_keys, lb=0.0, name="y_turn") + + # y_cent[i,j,s,t] -- centroid departure flow, (i,j) in A_z_plus + y_cent_keys = [ + (i, j, s, t) + for (i, j) in A_z_plus + for s in Z_list + for t in time_range + ] + y_cent = model.addVars(y_cent_keys, lb=0.0, name="y_cent") + + # N_U[i,j,s,t] and N_D[i,j,s,t] -- cumulative counts on all links + NU_keys = [ + (i, j, s, t) + for (i, j) in A_all + for s in Z_list + for t in time_range + ] + N_U = model.addVars(NU_keys, lb=0.0, name="N_U") + N_D = model.addVars(NU_keys, lb=0.0, name="N_D") + + # p[j,t] -- parked vehicles at centroid j + p_keys = [(j, t) for j in Z_list for t in time_range] + p = model.addVars(p_keys, lb=0.0, name="p") + + # e[r,s,t] -- departing travelers + e_keys = [(r, s, t) for (r, s) in ZxZ for t in time_range] + e = model.addVars(e_keys, lb=0.0, name="e") + + # omega[r,s,t] -- waiting demand + omega_keys = [(r, s, t) for (r, s) in ZxZ for t in time_range] + omega = model.addVars(omega_keys, lb=0.0, name="omega") + + model.update() + + # ---------------------------------------------------------------- + # Helper: get y_turn variable, returning 0 if key doesn't exist + # (handles constraint 44 implicitly -- variables not created are 0) + # ---------------------------------------------------------------- + def get_y_turn(i, j, k, s, t): + key = (i, j, k, s, t) + if key in y_turn: + return y_turn[key] + return 0.0 + + # ---------------------------------------------------------------- + # Fix initial conditions + # ---------------------------------------------------------------- + # (41) N_U[i,j,s,0] = 0 + # (42) N_D[i,j,s,0] = 0 + for (i, j) in A_all: + for s in Z_list: + model.addConstr(N_U[i, j, s, 0] == 0, name=f"init_NU_{i}_{j}_{s}") + model.addConstr(N_D[i, j, s, 0] == 0, name=f"init_ND_{i}_{j}_{s}") + + # Fix p[j,0] = fleet[j] + for j in Z_list: + fleet_j = fleet.get(str(j), fleet.get(j, 0)) + model.addConstr(p[j, 0] == fleet_j, name=f"init_p_{j}") + + # Fix omega[r,s,0] = 0 + for (r, s) in ZxZ: + model.addConstr(omega[r, s, 0] == 0, name=f"init_omega_{r}_{s}") + + # ---------------------------------------------------------------- + # Constraint (34): N_U evolution for A_o only + # N_U[i,j,s,t+1] = N_U[i,j,s,t] + sum_{(j,k) in gamma_plus[j]} y_turn[i,j,k,s,t] + # Note: A_z_plus links are handled by constraint (46) using y_cent instead. + # ---------------------------------------------------------------- + for (i, j) in A_o: + for s in Z_list: + for t in range(T): + outflow = gp.quicksum( + get_y_turn(i, j, k, s, t) + for (j2, k) in gamma_plus[j] + ) + model.addConstr( + N_U[i, j, s, t + 1] == N_U[i, j, s, t] + outflow, + name=f"c34_{i}_{j}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (35): N_D evolution for A_o only + # N_D[j,k,s,t+1] = N_D[j,k,s,t] + sum_{(i,j) in gamma_minus[j] ∩ A_o_plus} y_turn[i,j,k,s,t] + # Note: A_z_minus is handled by constraint (47), A_z_plus by constraint (46b). + # ---------------------------------------------------------------- + for (j, k) in A_o: + # Incoming links to j that are in A_o_plus (since y_turn only defined there) + incoming = [(i2, j2) for (i2, j2) in gamma_minus[j] if (i2, j2) in A_o_plus] + for s in Z_list: + for t in range(T): + inflow = gp.quicksum( + get_y_turn(i2, j, k, s, t) + for (i2, j2) in incoming + ) + model.addConstr( + N_D[j, k, s, t + 1] == N_D[j, k, s, t] + inflow, + name=f"c35_{j}_{k}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (36): Sending flow constraint for A_o only + # sum_{(j,k)} y_turn[i,j,k,s,t] <= N_U[i,j,s,t - fftt + 1] - N_D[i,j,s,t] + # for t in [fftt-1, T] + # Note: A_z_plus links use centroid departure flow (constraint 45/46). + # ---------------------------------------------------------------- + for (i, j) in A_o: + tau = fftt[(i, j)] + for s in Z_list: + for t in range(tau - 1, T + 1): + lhs = gp.quicksum( + get_y_turn(i, j, k, s, t) + for (j2, k) in gamma_plus[j] + ) + model.addConstr( + lhs <= N_U[i, j, s, t - tau + 1] - N_D[i, j, s, t], + name=f"c36_{i}_{j}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (37): Zero flow before free-flow time + # y_turn[i,j,k,s,t] = 0 for t < fftt[(i,j)] - 1 + # ---------------------------------------------------------------- + for (i, j) in A_o_plus: + tau = fftt[(i, j)] + if tau <= 1: + continue # range(0, 0) is empty + for (j2, k) in gamma_plus[j]: + for s in Z_list: + for t in range(0, tau - 1): + var = get_y_turn(i, j, k, s, t) + if isinstance(var, gp.Var): + model.addConstr( + var == 0, + name=f"c37_{i}_{j}_{k}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (38): Sending capacity for A_o + # sum_{s, (j,k)} y_turn[i,j,k,s,t] <= Q[(i,j)] + # ---------------------------------------------------------------- + for (i, j) in A_o: + cap = Q[(i, j)] + for t in time_range: + lhs = gp.quicksum( + get_y_turn(i, j, k, s, t) + for (j2, k) in gamma_plus[j] + for s in Z_list + ) + model.addConstr(lhs <= cap, name=f"c38_{i}_{j}_{t}") + + # ---------------------------------------------------------------- + # Constraint (39): Receiving capacity for A_o + # sum_{(i,j) in gamma_minus[j] ∩ A_o_plus, s} y_turn[i,j,k,s,t] <= Q[(j,k)] + # ---------------------------------------------------------------- + for (j, k) in A_o: + cap = Q[(j, k)] + incoming = [(i2, j2) for (i2, j2) in gamma_minus[j] if (i2, j2) in A_o_plus] + for t in time_range: + lhs = gp.quicksum( + get_y_turn(i2, j, k, s, t) + for (i2, j2) in incoming + for s in Z_list + ) + model.addConstr(lhs <= cap, name=f"c39_{j}_{k}_{t}") + + # ---------------------------------------------------------------- + # Constraint (40): Receiving congested wave constraint for A_o + # sum_{(i,j), s} y_turn[i,j,k,s,t] <= sum_s (N_U[j,k,s,t-cwtt+1] - N_D[j,k,s,t]) + KL[(j,k)] + # for t >= cwtt - 1 + # ---------------------------------------------------------------- + for (j, k) in A_o: + w = cwtt[(j, k)] + kl = KL[(j, k)] + incoming = [(i2, j2) for (i2, j2) in gamma_minus[j] if (i2, j2) in A_o_plus] + for t in range(w - 1, T + 1): + lhs = gp.quicksum( + get_y_turn(i2, j, k, s, t) + for (i2, j2) in incoming + for s in Z_list + ) + rhs = gp.quicksum( + N_U[j, k, s, t - w + 1] - N_D[j, k, s, t] + for s in Z_list + ) + kl + model.addConstr(lhs <= rhs, name=f"c40_{j}_{k}_{t}") + + # ---------------------------------------------------------------- + # Constraint (43): Parking evolution + # p[j,t+1] = p[j,t] + # + sum_{(i,j) in gamma_minus[j]} (N_U[i,j,j,t] - N_D[i,j,j,t]) (arrivals) + # - sum_{(j,k) in gamma_plus[j], s} y_cent[j,k,s,t] (departures) + # ---------------------------------------------------------------- + for j in Z_list: + for t in range(T): + # Arrivals: vehicles with destination j arriving at centroid j + arrivals = gp.quicksum( + N_U[i2, j, j, t] - N_D[i2, j, j, t] + for (i2, j2) in gamma_minus[j] + ) + # Departures: vehicles leaving centroid j + departures = gp.quicksum( + y_cent[j, k, s, t] + for (j2, k) in gamma_plus[j] + for s in Z_list + ) + model.addConstr( + p[j, t + 1] == p[j, t] + arrivals - departures, + name=f"c43_{j}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (44): No through-flow on A_z_minus for wrong destinations + # Already handled by not creating y_turn variables for s != k + # when (j,k) in A_z_minus. No additional constraints needed. + # ---------------------------------------------------------------- + + # ---------------------------------------------------------------- + # Constraint (45): Outgoing flow bounded by parking + # sum_{(i,j) in gamma_plus[i], s} y_cent[i,j,s,t] <= p[i,t] + # ---------------------------------------------------------------- + for i in Z_list: + for t in time_range: + lhs = gp.quicksum( + y_cent[i, j, s, t] + for (i2, j) in gamma_plus[i] + for s in Z_list + ) + model.addConstr(lhs <= p[i, t], name=f"c45_{i}_{t}") + + # ---------------------------------------------------------------- + # Constraint (46): N_U evolution for A_z_plus using centroid departure flow + # N_U[i,j,s,t+1] = N_U[i,j,s,t] + y_cent[i,j,s,t] + # ---------------------------------------------------------------- + for (i, j) in A_z_plus: + for s in Z_list: + for t in range(T): + model.addConstr( + N_U[i, j, s, t + 1] == N_U[i, j, s, t] + y_cent[i, j, s, t], + name=f"c46_{i}_{j}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (46b): N_D evolution for A_z_plus (fftt = 1 for centroid connectors) + # N_D[i,j,s,t+1] = N_U[i,j,s,t] + # ---------------------------------------------------------------- + for (i, j) in A_z_plus: + for s in Z_list: + for t in range(T): + model.addConstr( + N_D[i, j, s, t + 1] == N_U[i, j, s, t], + name=f"c46b_{i}_{j}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (47): N_D evolution for A_z_minus + # N_D[i,j,s,t+1] = N_U[i,j,s,t] + # ---------------------------------------------------------------- + for (i, j) in A_z_minus: + for s in Z_list: + for t in range(T): + model.addConstr( + N_D[i, j, s, t + 1] == N_U[i, j, s, t], + name=f"c47_{i}_{j}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (48): Fleet conservation + # sum_i p[i, T] == total_fleet + # ---------------------------------------------------------------- + total_fleet = sum(fleet.get(str(j), fleet.get(j, 0)) for j in Z_list) + model.addConstr( + gp.quicksum(p[j, T] for j in Z_list) == total_fleet, + name="c48_fleet_conservation" + ) + + # ---------------------------------------------------------------- + # Constraint (49): Departing travelers bounded by waiting demand + # e[r,s,t] <= omega[r,s,t] + # ---------------------------------------------------------------- + for (r, s) in ZxZ: + for t in time_range: + model.addConstr( + e[r, s, t] <= omega[r, s, t], + name=f"c49_{r}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (50): Departing travelers bounded by departing vehicles + # e[r,s,t] <= sum_{(r,j) in gamma_plus[r]} y_cent[r,j,s,t] + # ---------------------------------------------------------------- + for (r, s) in ZxZ: + for t in time_range: + rhs = gp.quicksum( + y_cent[r, j, s, t] + for (r2, j) in gamma_plus[r] + ) + model.addConstr( + e[r, s, t] <= rhs, + name=f"c50_{r}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (51): Waiting demand evolution + # omega[r,s,t+1] = omega[r,s,t] + d[r,s,t] - e[r,s,t] + # ---------------------------------------------------------------- + for (r, s) in ZxZ: + for t in range(T): + demand_rst = d.get((r, s, t), 0) + model.addConstr( + omega[r, s, t + 1] == omega[r, s, t] + demand_rst - e[r, s, t], + name=f"c51_{r}_{s}_{t}" + ) + + # ---------------------------------------------------------------- + # Constraint (52): All demand served by T + # omega[r,s,T] = 0 + # ---------------------------------------------------------------- + for (r, s) in ZxZ: + model.addConstr(omega[r, s, T] == 0, name=f"c52_{r}_{s}") + + # ---------------------------------------------------------------- + # Objective (33): Minimize total system time + # sum_{(i,j), s, t} (N_U[i,j,s,t] - N_D[i,j,s,t]) + # + sum_{(r,s), t} omega[r,s,t] + # ---------------------------------------------------------------- + obj_network = gp.quicksum( + N_U[i, j, s, t] - N_D[i, j, s, t] + for (i, j) in A_all + for s in Z_list + for t in time_range + ) + obj_waiting = gp.quicksum( + omega[r, s, t] + for (r, s) in ZxZ + for t in time_range + ) + model.setObjective(obj_network + obj_waiting, GRB.MINIMIZE) + + # ---------------------------------------------------------------- + # Solve + # ---------------------------------------------------------------- + model.optimize() + + # ---------------------------------------------------------------- + # Output solution + # ---------------------------------------------------------------- + result = {} + + if model.status == GRB.OPTIMAL or model.status == GRB.TIME_LIMIT: + try: + result["objective_value"] = model.ObjVal + except Exception: + result["objective_value"] = None + else: + result["objective_value"] = None + + status_map = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + GRB.LOADED: "LOADED", + GRB.CUTOFF: "CUTOFF", + } + result["status"] = status_map.get(model.status, f"UNKNOWN_{model.status}") + + result["variables"] = { + "num_y_turn": len(y_turn_keys), + "num_y_cent": len(y_cent_keys), + "num_N_U": len(NU_keys), + "num_N_D": len(NU_keys), + "num_p": len(p_keys), + "num_e": len(e_keys), + "num_omega": len(omega_keys), + "total_variables": model.NumVars, + "total_constraints": model.NumConstrs, + } + + # Export variable values for feasibility checking + if model.status == GRB.OPTIMAL or (model.status == GRB.TIME_LIMIT and model.SolCount > 0): + # y_turn: key "i|j|k|s|t" + y_dict = {} + for key, var in y_turn.items(): + i, j, k, s, t = key + val = var.X + if abs(val) > 1e-9: + y_dict[f"{i}|{j}|{k}|{s}|{t}"] = val + result["y"] = y_dict + + # y_centroid: key "i|j|s|t" + yc_dict = {} + for key, var in y_cent.items(): + i, j, s, t = key + val = var.X + if abs(val) > 1e-9: + yc_dict[f"{i}|{j}|{s}|{t}"] = val + result["y_centroid"] = yc_dict + + # N_U: key "i|j|s|t" + nu_dict = {} + for key, var in N_U.items(): + i, j, s, t = key + val = var.X + if abs(val) > 1e-9: + nu_dict[f"{i}|{j}|{s}|{t}"] = val + result["N_U"] = nu_dict + + # N_D: key "i|j|s|t" + nd_dict = {} + for key, var in N_D.items(): + i, j, s, t = key + val = var.X + if abs(val) > 1e-9: + nd_dict[f"{i}|{j}|{s}|{t}"] = val + result["N_D"] = nd_dict + + # p: key "j|t" + p_dict = {} + for key, var in p.items(): + j, t = key + val = var.X + if abs(val) > 1e-9: + p_dict[f"{j}|{t}"] = val + result["p"] = p_dict + + # e: key "r|s|t" + e_dict = {} + for key, var in e.items(): + r, s, t = key + val = var.X + if abs(val) > 1e-9: + e_dict[f"{r}|{s}|{t}"] = val + result["e"] = e_dict + + # omega: key "r|s|t" + omega_dict = {} + for key, var in omega.items(): + r, s, t = key + val = var.X + if abs(val) > 1e-9: + omega_dict[f"{r}|{s}|{t}"] = val + result["omega"] = omega_dict + + # Write solution + sol_dir = os.path.dirname(args.solution_path) + if sol_dir: + os.makedirs(sol_dir, exist_ok=True) + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Status: {result['status']}") + print(f"Objective: {result['objective_value']}") + print(f"Variables: {model.NumVars}, Constraints: {model.NumConstrs}") + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/levin2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/levin2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/levin2017/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/levin2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/levin2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/levin2017/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/levin2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/levin2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/levin2017/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/levin2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/levin2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/levin2017/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/levin2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/levin2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/levin2017/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/levin2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/levin2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/levin2017/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/levin2017/gurobi_solution/large_solution_1.json b/tasks/levin2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..85557b445286b72ffc389308c85f5b79457732c2 --- /dev/null +++ b/tasks/levin2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc00c83b2a07e05fed7294f23d5fe393fe16194ef132d85e05dbec4d2b92ae8c +size 3060708 diff --git a/tasks/levin2017/gurobi_solution/large_solution_2.json b/tasks/levin2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e501aa38c218b127c80421d1c19f18ca5720ba85 --- /dev/null +++ b/tasks/levin2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fe90206d1154a9174e29272748022ecd388082cfb87c384a25f0fae715a362b +size 433340 diff --git a/tasks/levin2017/gurobi_solution/large_solution_3.json b/tasks/levin2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..21aef8fc7822a05c44fe4da11e12ee0ddcb52a71 --- /dev/null +++ b/tasks/levin2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0072d08fea56dd4607a6f360acc0f5a219b901ca948cf599ac1c99542f7ab475 +size 3009006 diff --git a/tasks/levin2017/gurobi_solution/large_solution_4.json b/tasks/levin2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..085f651301a387bcc21f75f63c2019024f6c4d18 --- /dev/null +++ b/tasks/levin2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43e08fc8498aa2680455514ce91742b86203bc6fec775c4288c1b10b076a1541 +size 430576 diff --git a/tasks/levin2017/gurobi_solution/large_solution_5.json b/tasks/levin2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..cb21b6085da0e84d5980299a54e878bd09698ae6 --- /dev/null +++ b/tasks/levin2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa8d4d32489c4c16d8549a88986eb6a9b9de498c4cb92354a9f011bab2e6cdf2 +size 426770 diff --git a/tasks/levin2017/gurobi_solution/tiny_solution.json b/tasks/levin2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..0dbfb2e7015412955b8ac188d2598169954e73d1 --- /dev/null +++ b/tasks/levin2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c74705d2b676966d1c84558179f28738564d31ed82ab5da08a952cc99b886663 +size 9935 diff --git a/tasks/levin2017/gurobi_solution_log/large_log_1.jsonl b/tasks/levin2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/levin2017/gurobi_solution_log/large_log_2.jsonl b/tasks/levin2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/levin2017/gurobi_solution_log/large_log_3.jsonl b/tasks/levin2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/levin2017/gurobi_solution_log/large_log_4.jsonl b/tasks/levin2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/levin2017/gurobi_solution_log/large_log_5.jsonl b/tasks/levin2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/levin2017/gurobi_solution_log/tiny_log.jsonl b/tasks/levin2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/levin2017/instance/large_instance_1.json b/tasks/levin2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..967871e0c6b2ea8ee7a2b6dd45b5f15b78a5e6ba --- /dev/null +++ b/tasks/levin2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2cbf57eaca9cf8e900c808f1e26f2463ebf2d21a30f390564ae8b17b6392805 +size 304804 diff --git a/tasks/levin2017/instance/large_instance_2.json b/tasks/levin2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..41fdee711e0e3dbc4224609c24692f56dbbd25ea --- /dev/null +++ b/tasks/levin2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae25601e2096ae7fb1bf3e47f7bd01c1834a4bdc6bccd81491e91485f70b69bb +size 297757 diff --git a/tasks/levin2017/instance/large_instance_3.json b/tasks/levin2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..992caa5e7d224707bc9509fc1ad24a7f560dd6e9 --- /dev/null +++ b/tasks/levin2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c0249270791f5da2f2b87b006a1fc6b1dc9ca4dd6c401eae0abc9537239278e +size 186808 diff --git a/tasks/levin2017/instance/large_instance_4.json b/tasks/levin2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..563297f434344a684b34849fa792b734969830c9 --- /dev/null +++ b/tasks/levin2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e95b462bee0e7ab9e67c368dc1a5a4192ba88787eab691f2d9cdba0785fd4c0 +size 179762 diff --git a/tasks/levin2017/instance/large_instance_5.json b/tasks/levin2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..85c915b170b5a1779243922c688b519dcd546db5 --- /dev/null +++ b/tasks/levin2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3144de1370ff464c230387b6c3f015a1947384e71dcea927a62a12bb8677b801 +size 120760 diff --git a/tasks/levin2017/instance/tiny_instance.json b/tasks/levin2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..aa69262e8d4805e1b5220e78305d81cd47983951 --- /dev/null +++ b/tasks/levin2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca70b191c4c8ef121c6a74d0fff1618bf7480624e84098d6d95ffcee2089c37e +size 11583 diff --git a/tasks/levin2017/instance_schema.json b/tasks/levin2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a1626fe0c41a8ea7df2c053fcfb53b240e3c0a6d --- /dev/null +++ b/tasks/levin2017/instance_schema.json @@ -0,0 +1,55 @@ +{ + "network": { + "num_nodes": " Total number of nodes in the network, including both junctions and centroids.", + "num_links": " Total number of directed links in the network, including road links and centroid connectors.", + "num_junctions": " Number of junction nodes representing road intersections.", + "num_centroids": " Number of centroid nodes representing zones where travelers originate, arrive, and vehicles park.", + "grid_rows": " Number of rows in the rectangular grid of junction nodes.", + "grid_cols": " Number of columns in the rectangular grid of junction nodes.", + "nodes": [ + { + "id": " Unique identifier for the node.", + "type": " Whether this node is a 'junction' (road intersection) or a 'centroid' (traveler origin/destination zone)." + } + ], + "links": [ + { + "id": " Unique identifier for the directed link.", + "from": " Node identifier at the upstream (tail) end of the link.", + "to": " Node identifier at the downstream (head) end of the link.", + "type": " Whether this link is a 'road' between junctions or a 'centroid_connector' linking a centroid to the road network.", + "length_ft": " Physical length of the link in feet.", + "free_flow_speed_mph": " Speed at which vehicles traverse the link under uncongested conditions, in miles per hour.", + "capacity_vph": " Maximum flow rate of vehicles that can enter or exit the link per hour.", + "free_flow_travel_time_steps": " Number of time steps required to traverse the link at free-flow speed.", + "congested_wave_speed_mph": " Speed at which a congestion wave propagates backward along the link, in miles per hour.", + "congested_travel_time_steps": " Number of time steps for a congestion wave to traverse the full link length.", + "jam_density_vehicles": " Maximum number of vehicles that can physically occupy the link at standstill." + } + ] + }, + "time_parameters": { + "time_horizon_T": " Total number of discrete time steps in the analysis period.", + "time_step_duration_seconds": " Duration of each time step in seconds.", + "demand_period_steps": " Number of time steps during which new traveler demand arises.", + "demand_period_duration_minutes": " Duration of the demand arrival period in minutes." + }, + "demand": { + "scenario": " Label describing the spatial pattern of demand across origin-destination pairs.", + "demand_percentage": " Scaling factor applied to the base demand level.", + "total_travelers": " Total number of person-trips across all origin-destination pairs.", + "od_pairs": [ + { + "origin": " Centroid identifier where travelers in this group begin their trip.", + "destination": " Centroid identifier where travelers in this group wish to arrive.", + "num_travelers": " Number of travelers wishing to travel from this origin to this destination.", + "departure_times": " Time step at which each individual traveler wishes to depart from the origin centroid." + } + ] + }, + "fleet": { + "total_fleet_size": " Total number of shared autonomous vehicles available in the system.", + "fleet_rule": " Rule used to determine the fleet size relative to total demand.", + "initial_distribution": " Number of vehicles initially parked at each centroid at the start of the analysis." + } +} \ No newline at end of file diff --git a/tasks/levin2017/mathematical_formulation.md b/tasks/levin2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..736c19f1f9cb3aaaf4cde18958dc731f51ee3591 --- /dev/null +++ b/tasks/levin2017/mathematical_formulation.md @@ -0,0 +1,94 @@ +# Original Formulation: Congestion-Aware System Optimal SAV Routing (SAV Routing Problem) + +*Source: Congestion-aware system optimal route choice for shared autonomous vehicles, Michael W. Levin, Transportation Research Part C 82 (2017) 229–247.* + +## Sets and Indices + +$$\begin{align*} +&\mathcal{G} = (\mathcal{N}, \mathcal{A}) && \text{traffic network with node set } \mathcal{N} \text{ and link set } \mathcal{A};\ (i,j)\in\mathcal{A} \text{ is the link } i\to j \\ +&\mathcal{Z} \subset \mathcal{N} && \text{set of centroids (origins / destinations of trips; vehicle parking)} \\ +&\mathcal{A}_o \subseteq \mathcal{A} && \text{links not starting or ending at a centroid: } \mathcal{A}_o=\{(i,j):(i,j)\in\mathcal{A},\, i,j\in\mathcal{N}\setminus\mathcal{Z}\} \\ +&\mathcal{A}_z \subseteq \mathcal{A} && \text{complement of } \mathcal{A}_o \text{ in } \mathcal{A} \text{ (centroid connectors)} \\ +&\mathcal{A}_z^- = \{(i,j)\in\mathcal{A}_z : j\in\mathcal{Z}\} && \text{centroid connectors ending in a centroid} \tag{13} \\ +&\mathcal{A}_z^+ = \{(i,j)\in\mathcal{A}_z : i\in\mathcal{Z}\} && \text{centroid connectors starting from a centroid} \tag{14} \\ +&\Gamma_j^- && \text{set of incoming links to node } j \\ +&\Gamma_j^+ && \text{set of outgoing links from node } j \\ +&\mathcal{Z}^2 && \text{set of origin-destination centroid pairs } (r,s),\ r,s\in\mathcal{Z} \\ +&t \in \{0,1,2,\dots,T\} && \text{discrete time steps (unit time step }=1) \\ +&s \in \mathcal{Z} && \text{destination index of disaggregated flows} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +&L_{ij} && \text{length of link } (i,j) \\ +&Q_{ij} && \text{capacity of link } (i,j) \quad (Q_{ij}=\infty \text{ for } (i,j)\in\mathcal{A}_z) \\ +&v_{ij} && \text{free-flow speed of link } (i,j) \quad (L_{ij}/v_{ij} \text{ is a positive integer; } =1 \text{ for } (i,j)\in\mathcal{A}_z) \\ +&w_{ij} && \text{congested wave speed of link } (i,j) \\ +&K && \text{jam density } (KL_{ij} = \text{max number of vehicles that can occupy link } (i,j)) \\ +&T && \text{length of analysis period (number of time steps)} \\ +&p_i(0) && \text{number of vehicles parked at centroid } i \text{ at the start of the analysis period} \\ +&d_r^s(t) && \text{person-trip demand from } r \text{ to } s \text{ departing at time } t +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +&y_{ijk}^s(t) \ge 0 && \text{flow of vehicles destined for } s \text{ turning from link } (i,j) \text{ onto link } (j,k) \text{ at time } t \\ +&y_{ij}^s(t) \ge 0 && \text{number of vehicles departing centroid } i \text{ via connector } (i,j)\in\mathcal{A}_z^+ \text{ toward } s \text{ at time } t \\ +&N_{ij}^{Us}(t) \ge 0 && \text{upstream cumulative count for destination } s \text{ on link } (i,j) \text{ at time } t \\ +&N_{ij}^{Ds}(t) \ge 0 && \text{downstream cumulative count for destination } s \text{ on link } (i,j) \text{ at time } t \\ +&p_j(t) \ge 0 && \text{number of vehicles parked at centroid } j\in\mathcal{Z} \text{ at time } t \\ +&e_r^s(t) \ge 0 && \text{number of travelers departing from } r \text{ to } s \text{ at time } t \\ +&\omega_r^s(t) \ge 0 && \text{unserviced demand waiting at } r \text{ for destination } s \text{ at time } t +\end{align*}$$ + +## Objective + +Minimize the total system travel time (TSTT), Eq. (30), used in the LP (33): $$\begin{align} +\min\ Z \;=\; \mathcal{T} \;=\; \sum_{(i,j)\in\mathcal{A}}\sum_{s\in\mathcal{Z}}\sum_{t=0}^{T} +\left( N_{ij}^{Us}(t) - N_{ij}^{Ds}(t) \right) +\;+\; \sum_{(r,s)\in\mathcal{Z}^2}\sum_{t=0}^{T}\omega_r^s(t) +\tag{30/33} +\end{align}$$ The first term is total vehicle-time on links (link occupancy summed over time); the second term is total traveler waiting time at origins. + +## Constraints + +$$\begin{align} +& N_{ij}^{Us}(t+1) = N_{ij}^{Us}(t) + \sum_{(j,k)\in\Gamma_j^+} y_{ijk}^s(t) +&& \forall (i,j)\in\mathcal{A}_o\cup\mathcal{A}_z^+,\ \forall s\in\mathcal{Z},\ \forall t\in[0,T-1] \tag{34} \\ +& N_{jk}^{Ds}(t+1) = N_{jk}^{Ds}(t) + \sum_{(i,j)\in\Gamma_j^-} y_{ijk}^s(t) +&& \forall (j,k)\in\mathcal{A}_o\cup\mathcal{A}_z^-,\ \forall s\in\mathcal{Z},\ \forall t\in[0,T-1] \tag{35} \\ +& \sum_{(j,k)\in\Gamma_j^+} y_{ijk}^s(t) \le N_{ij}^{Us}\!\left(t-\tfrac{L_{ij}}{v_{ij}}+1\right) - N_{ij}^{Ds}(t) +&& \forall (i,j)\in\mathcal{A}_o\cup\mathcal{A}_z^+,\ \forall s\in\mathcal{Z},\ \forall t\in\left[\tfrac{L_{ij}}{v_{ij}}-1,\,T\right] \tag{36} \\ +& y_{ijk}^s(t) = 0 +&& \forall (i,j)\in\mathcal{A}_o\cup\mathcal{A}_z^+,\ \forall (j,k)\in\Gamma_j^+,\ \forall s\in\mathcal{Z},\ \forall t\in\left[0,\,\tfrac{L_{ij}}{v_{ij}}-1\right) \tag{37} \\ +& \sum_{(j,k)\in\Gamma_j^+}\sum_{s\in\mathcal{Z}} y_{ijk}^s(t) \le Q_{ij} +&& \forall (i,j)\in\mathcal{A}_o,\ \forall t\in[0,T] \tag{38} \\ +& \sum_{(i,j)\in\Gamma_j^-}\sum_{s\in\mathcal{Z}} y_{ijk}^s(t) \le Q_{jk} +&& \forall (j,k)\in\mathcal{A}_o,\ \forall t\in[0,T] \tag{39} \\ +& \sum_{(i,j)\in\Gamma_j^-}\sum_{s\in\mathcal{Z}} y_{ijk}^s(t) +\le \sum_{s\in\mathcal{Z}}\!\left( N_{jk}^{Us}\!\left(t-\tfrac{L_{jk}}{w_{jk}}+1\right) - N_{jk}^{Ds}(t) \right) + KL_{jk} +&& \forall (j,k)\in\mathcal{A}_o,\ \forall t\in\left[\tfrac{L_{jk}}{w_{jk}}-1,\,T\right] \tag{40} \\ +& N_{ij}^{Us}(0) = 0 && \forall (i,j)\in\mathcal{A},\ \forall s\in\mathcal{Z} \tag{41} \\ +& N_{ij}^{Ds}(0) = 0 && \forall (i,j)\in\mathcal{A},\ \forall s\in\mathcal{Z} \tag{42} \\ +& p_j(t+1) = p_j(t) + \sum_{(i,j)\in\Gamma_j^-}\!\left( N_{ij}^{Uj}(t) - N_{ij}^{Dj}(t) \right) +- \sum_{(j,k)\in\Gamma_j^+}\sum_{s\in\mathcal{Z}} y_{jk}^s(t) +&& \forall j\in\mathcal{Z},\ \forall t\in[0,T-1] \tag{43} \\ +& y_{ijk}^s(t) = 0 +&& \forall (j,k)\in\mathcal{A}_z^-,\ \forall (i,j)\in\Gamma_j^-,\ s\neq k,\ \forall t\in[0,T] \tag{44} \\ +& \sum_{(i,j)\in\Gamma_i^+}\sum_{s\in\mathcal{Z}} y_{ij}^s(t) \le p_i(t) +&& \forall i\in\mathcal{Z},\ \forall t\in[0,T] \tag{45} \\ +& N_{ij}^{Us}(t+1) = N_{ij}^{Us}(t) + y_{ij}^s(t) +&& \forall (i,j)\in\mathcal{A}_z^+,\ \forall s\in\mathcal{Z},\ \forall t\in[0,T-1] \tag{46} \\ +& N_{ij}^{Ds}(t+1) = N_{ij}^{Us}(t) +&& \forall (i,j)\in\mathcal{A}_z^-,\ \forall s\in\mathcal{Z},\ \forall t\in[0,T-1] \tag{47} \\ +& \sum_{i\in\mathcal{Z}} p_i(0) = \sum_{i\in\mathcal{Z}} p_i(T) && \tag{48} \\ +& e_r^s(t) \le \omega_r^s(t) && \forall (r,s)\in\mathcal{Z}^2,\ \forall t\in[0,T] \tag{49} \\ +& e_r^s(t) \le \sum_{(r,j)\in\Gamma_r^+} y_{rj}^s(t) && \forall (r,s)\in\mathcal{Z}^2,\ \forall t\in[0,T] \tag{50} \\ +& \omega_r^s(t+1) = \omega_r^s(t) + d_r^s(t) - e_r^s(t) && \forall (r,s)\in\mathcal{Z}^2,\ \forall t\in[0,T-1] \tag{51} \\ +& \omega_r^s(T) = 0 && \forall (r,s)\in\mathcal{Z}^2 \tag{52} \\ +& y_{ijk}^s(t) \ge 0 && \forall (i,j)\in\mathcal{A}_o\cup\mathcal{A}_z^+,\ \forall (j,k)\in\Gamma_j^+,\ \forall s\in\mathcal{Z},\ \forall t\in[0,T] \tag{53} \\ +& y_{rj}^s(t) \ge 0 && \forall (r,j)\in\mathcal{A}_z^+,\ \forall s\in\mathcal{Z},\ \forall t\in[0,T] \tag{54} \\ +& e_r^s(t) \ge 0 && \forall (r,s)\in\mathcal{Z}^2,\ \forall t\in[0,T] \tag{55} +\end{align}$$ diff --git a/tasks/levin2017/problem_description.txt b/tasks/levin2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..2f84fb1a35a7dc07796013dedbb0153f881e7128 --- /dev/null +++ b/tasks/levin2017/problem_description.txt @@ -0,0 +1,21 @@ +# Problem Description + +A fleet of shared autonomous vehicles (SAVs) operates on a directed traffic network consisting of nodes and links. Nodes are partitioned into junctions, which represent road intersections, and centroids, which represent zones where travelers originate, arrive, and where vehicles may park. Each centroid is connected to the road network through special centroid connector links. The analysis covers a discrete time horizon from time step zero through the final time step, with each time step representing one unit of time. + +Each directed road link has a known length, free-flow speed, congested wave speed, and flow capacity. The ratio of length to free-flow speed for every link is a positive integer giving the free-flow travel time in time steps. A jam density parameter, common across the network, determines the maximum number of vehicles that can physically occupy any link, equal to the jam density multiplied by the link length. Centroid connectors have a free-flow travel time of exactly one time step and effectively unlimited capacity. The network is assumed empty at the start of the analysis period, meaning no vehicles are in transit on any link at time zero. + +A known number of vehicles are parked at each centroid at the start of the analysis. Person-trip demand is specified for each origin-destination centroid pair at each time step, giving the number of travelers wishing to depart from a given origin to a given destination at that time. Each vehicle serves exactly one traveler at a time with no ride-sharing. All vehicular travel in the network is by SAVs; there are no personal vehicles. Because the number of vehicles is large, all vehicle flows and traveler quantities are treated as continuous quantities rather than whole numbers. + +The planner must determine, for every time step and every link, how many vehicles destined for each centroid turn from that link onto each successor link. The planner must also determine how many vehicles depart each centroid via each outgoing centroid connector toward each destination at each time step, how many travelers are picked up at each origin for each destination at each time step, and how many travelers remain waiting at each origin for each destination at each time step. The number of vehicles parked at each centroid at each time step is also determined. All vehicle flow quantities, traveler pickup counts, parked vehicle counts, and waiting traveler counts must be zero or positive. + +Traffic flow on road links is governed by the link transmission model, which tracks cumulative vehicle counts at the upstream and downstream ends of each link, disaggregated by destination. At time zero, all upstream and downstream cumulative counts on every link are zero. For each road link and each outgoing centroid connector, the upstream cumulative count for a given destination at the next time step equals the current upstream count plus the total turning flow of vehicles with that destination from that link onto all of its successor links at the current time step. For each road link and each incoming centroid connector, the downstream cumulative count for a given destination at the next time step equals the current downstream count plus the total turning flow of vehicles with that destination from all predecessor links onto that link at the current time step. + +No vehicle flow may exit a link before the free-flow travel time has elapsed; turning flows on any link are zero for all time steps strictly before the free-flow travel time of that link. For each destination separately, the total turning flow of vehicles with that destination from a road link or outgoing centroid connector onto successor links at a given time step is bounded by the sending flow for that destination on that link. The sending flow for a given destination on a link equals the upstream cumulative count for that destination evaluated at a time equal to the current time step minus the free-flow travel time of the link plus one, minus the downstream cumulative count for that destination at the current time step. On road links only, the total outgoing flow of vehicles of all destinations at any time step may not exceed the link capacity. Similarly, on road links only, the total incoming flow of vehicles of all destinations turning onto that link at any time step may not exceed the link capacity. Additionally, on road links, the total incoming flow is limited by a congested-wave bound: the sum of all incoming turning flows may not exceed the sum over all destinations of the difference between the upstream cumulative count evaluated at a time equal to the current time step minus the ratio of link length to congested wave speed plus one and the downstream cumulative count at the current time step, plus the maximum vehicle occupancy of that link. + +For incoming centroid connectors, the downstream cumulative count for each destination at the next time step simply equals the upstream cumulative count at the current time step. Vehicles cannot pass through an incoming centroid connector unless their destination matches the centroid at which that connector terminates; turning flows on incoming centroid connectors are zero whenever the vehicle destination differs from the connector's terminal centroid. + +The number of vehicles parked at a centroid at the next time step equals the current parked count plus the number of vehicles arriving at that centroid via incoming centroid connectors (measured as the difference between upstream and downstream cumulative counts for vehicles destined for that centroid) minus the total number of vehicles departing that centroid via outgoing centroid connectors toward all destinations. The total number of vehicles departing a centroid across all outgoing connectors and all destinations at any time step cannot exceed the number of vehicles currently parked there. The upstream cumulative count on an outgoing centroid connector for a given destination at the next time step equals the current count plus the number of vehicles departing the centroid along that connector toward that destination. The total number of vehicles parked across all centroids at the final time step must equal the total number parked across all centroids at time zero. + +Unserviced traveler demand waiting at each origin for each destination evolves over time: the waiting count at the next time step equals the current waiting count plus newly arriving demand minus travelers picked up at that time step. The number of travelers picked up at an origin for a given destination at any time step cannot exceed the number of travelers currently waiting there for that destination, and it also cannot exceed the total number of vehicles departing that origin toward that destination at that time step. By the end of the time horizon, all waiting demand must have been served, so the unserviced count for every origin-destination pair at the final time step must be zero. + +The goal is to minimize the total system travel time, defined as the sum of two components: the total vehicle-time spent on links, computed by summing over all links, all destinations, and all time steps the difference between the upstream and downstream cumulative counts, plus the total traveler waiting time, computed by summing over all origin-destination pairs and all time steps the unserviced waiting demand. diff --git a/tasks/levin2017/solution_logger.py b/tasks/levin2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/levin2017/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/levin2017/solution_schema.json b/tasks/levin2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..02be820679f78a5ff86859b8f545a8a85cee48a0 --- /dev/null +++ b/tasks/levin2017/solution_schema.json @@ -0,0 +1,10 @@ +{ + "objective_value": " Total system travel time, combining vehicle time spent traversing links and traveler time spent waiting at origins.", + "y": " Number of vehicles destined for a given centroid that turn from an incoming link onto a successor link at a given time step.", + "y_centroid": " Number of vehicles departing a centroid via its outgoing connector toward a given destination at a given time step.", + "N_U": " Cumulative count of vehicles destined for a given centroid that have entered the upstream end of a link by a given time step.", + "N_D": " Cumulative count of vehicles destined for a given centroid that have exited the downstream end of a link by a given time step.", + "p": " Number of vehicles parked at a centroid at a given time step.", + "e": " Number of travelers picked up at an origin centroid heading to a given destination at a given time step.", + "omega": " Number of travelers waiting at an origin centroid for service to a given destination at a given time step." +} \ No newline at end of file diff --git a/tasks/li2020/feasibility_check.py b/tasks/li2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7a22c0a3ce1e7fdd2953b7ae0c35c6e98d2093ef --- /dev/null +++ b/tasks/li2020/feasibility_check.py @@ -0,0 +1,649 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the bi-level partial interdiction problem on +capacitated nested hierarchical facilities. + +Reference: Forghani, Dehghanian, Salari, Ghiami (2020) +Computers and Operations Research 114 (2020) 104831 + +Checks all hard constraints from the mathematical formulation. +Constraint numbering (top to bottom in formulation): + Constraint 1 = eq (2): Exactly one interdiction level per facility + Constraint 2 = eq (3): Interdiction budget + Constraint 3 = eq (4): Binary integrality of x_{jk} + Constraint 4 = eq (6): Type I demand balance + Constraint 5 = eq (7): Type II demand balance + Constraint 6 = eq (8): Referral type II balance + Constraint 7 = eq (9): Type I capacity at level I facilities + Constraint 8 = eq (10): Type I capacity at level II facilities + Constraint 9 = eq (11): Type II capacity at level II facilities + Constraint 10 = eq (12): Non-negativity of continuous variables + Constraint 11 = obj (5): Objective consistency -- the reported + objective_value must equal the recomputed lower-level + LP optimum H(z) (defender's minimum cost) for the + reported interdiction pattern. The solution only + carries the upper-level interdiction pattern; the + defender's reassignment/outsourcing variables are, + by definition (eq 5), the optimal lower-level LP + solution -- which this checker already solves exactly + via linprog. This is therefore a FULL recompute, not + a lower bound. Defends against score-gaming exploits + that report a fabricated objective_value. +""" + +import argparse +import json +import math +import numpy as np +from scipy.optimize import linprog + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('interdiction_pattern', '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 load_json(path): + with open(path) as f: + return json.load(f) + + +def parse_interdiction_pattern(sol, nS1, nS2): + """Parse interdiction pattern from either efficient or gurobi solution format. + + Returns a list of length nS1+nS2 with the interdiction level for each facility. + """ + nFac = nS1 + nS2 + pat = sol["interdiction_pattern"] + + # Detect format + sample_key = next(iter(pat)) + if sample_key.startswith("S"): + # Gurobi format: "S1_0", "S1_1", ..., "S2_0", ... + levels = [0] * nFac + for key, val in pat.items(): + parts = key.split("_") + fac_type = parts[0] # "S1" or "S2" + fac_idx = int(parts[1]) + if fac_type == "S1": + levels[fac_idx] = int(val) + else: + levels[nS1 + fac_idx] = int(val) + else: + # Efficient format: "0", "1", ..., "9" + levels = [0] * nFac + for key, val in pat.items(): + levels[int(key)] = int(val) + + return levels + + +def add_violation(violations_list, magnitudes_list, constraint_idx, message, lhs, rhs, violation_amount): + """Record a constraint violation.""" + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations_list.append((constraint_idx, message)) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +def check_feasibility(inst, sol): + gp_ = inst["global_parameters"] + ip = inst["instance_parameters"] + inter = inst["interdiction_parameters"] + + theta = gp_["theta"] + sigma = gp_["sigma"] + alpha = gp_["alpha"] + beta = gp_["beta"] + gamma_ = gp_["gamma"] + alpha_p = gp_["alpha_prime"] + beta_p = gp_["beta_prime"] + gamma_p = gp_["gamma_prime"] + + nI = ip["num_customers"] + nS1 = ip["num_level1_facilities"] + nS2 = ip["num_level2_facilities"] + k_max = ip["k_max"] + B = ip["total_interdiction_budget"] + nFac = nS1 + nS2 + + # Interdiction costs + h1 = {0: 0.0} + for ks, v in inter["interdiction_cost_level1_h1"].items(): + h1[int(ks)] = v + h2 = {0: 0.0} + for ks, v in inter["interdiction_cost_level2_h2"].items(): + h2[int(ks)] = v + + # Capacity reduction ratios + d1 = {0: 0.0} + for ks, v in inter["capacity_reduction_level1_d1"].items(): + d1[int(ks)] = v + d2 = {0: 0.0} + for ks, v in inter["capacity_reduction_level2_d2"].items(): + d2[int(ks)] = v + + # Data arrays + z = np.array(inst["customers"]["demands"]) + c1_s1 = np.array(inst["level1_facilities"]["capacity_type1"]) + c1_s2 = np.array(inst["level2_facilities"]["capacity_type1"]) + c2_s2 = np.array(inst["level2_facilities"]["capacity_type2"]) + + l_cs1 = np.array(inst["distances"]["customer_to_level1_facility"]) + l_cs2 = np.array(inst["distances"]["customer_to_level2_facility"]) + l_s1s2 = np.array(inst["distances"]["level1_to_level2_facility"]) + + # S2-to-S2 distances + s2x = np.array(inst["level2_facilities"]["x_coordinates"]) + s2y = np.array(inst["level2_facilities"]["y_coordinates"]) + l_s2s2 = np.sqrt( + np.subtract.outer(s2x, s2x) ** 2 + np.subtract.outer(s2y, s2y) ** 2 + ) + l_fac_s2 = np.vstack([l_s1s2, l_s2s2]) + + # Parse interdiction pattern + pattern = parse_interdiction_pattern(sol, nS1, nS2) + + violations_list = [] + magnitudes_list = [] + + # ========================================================= + # Constraint 1 (eq 2): sum_k x_{jk} = 1 for all j + # Each facility must have exactly one interdiction level. + # Since we parsed pattern as a single level per facility, + # we check that each level is in {0, ..., k_max}. + # ========================================================= + for j in range(nFac): + k = pattern[j] + if k < 0 or k > k_max: + lhs_val = k + rhs_val = k_max + viol_amt = abs(k - (k_max if k > k_max else 0)) + fac_label = f"S1_{j}" if j < nS1 else f"S2_{j - nS1}" + add_violation(violations_list, magnitudes_list, 1, + f"Facility {fac_label} has invalid interdiction level {k} (must be 0..{k_max})", + lhs_val, rhs_val, viol_amt) + + # Also check that every facility has exactly one level assigned + pat_dict = sol["interdiction_pattern"] + expected_keys_count = nFac + sample_key = next(iter(pat_dict)) + if sample_key.startswith("S"): + actual_count = len(pat_dict) + else: + actual_count = len(pat_dict) + if actual_count != expected_keys_count: + viol_amt = abs(actual_count - expected_keys_count) + add_violation(violations_list, magnitudes_list, 1, + f"Expected {expected_keys_count} facility entries in interdiction pattern, got {actual_count}", + float(actual_count), float(expected_keys_count), float(viol_amt)) + + # ========================================================= + # Constraint 2 (eq 3): Budget constraint + # sum_{j in S1} h1_k * x_{jk} + sum_{j in S2} h2_k * x_{jk} <= B + # ========================================================= + total_cost = 0.0 + for j in range(nS1): + total_cost += h1.get(pattern[j], 0.0) + for j in range(nS2): + total_cost += h2.get(pattern[nS1 + j], 0.0) + + lhs_budget = total_cost + rhs_budget = B + viol_budget = max(0.0, lhs_budget - rhs_budget) + if viol_budget > tol: + add_violation(violations_list, magnitudes_list, 2, + f"Interdiction budget exceeded: cost {lhs_budget:.2f} > budget {rhs_budget:.2f}", + lhs_budget, rhs_budget, viol_budget) + + # ========================================================= + # Constraint 3 (eq 4): Binary integrality x_{jk} in {0,1} + # Since pattern stores the chosen level as an integer, this + # is inherently satisfied. We verify values are integers. + # ========================================================= + for j in range(nFac): + k = pattern[j] + if not isinstance(k, int) and abs(k - round(k)) > tol: + viol_amt = abs(k - round(k)) + fac_label = f"S1_{j}" if j < nS1 else f"S2_{j - nS1}" + add_violation(violations_list, magnitudes_list, 3, + f"Facility {fac_label} interdiction level {k} is not integer", + float(k), float(round(k)), viol_amt) + + # ========================================================= + # Constraints 4-10 (eqs 6-12): Lower-level constraints + # Solve the lower-level LP and check constraints from solution. + # ========================================================= + # Remaining capacities after interdiction + rem_c1_s1 = np.array([ + c1_s1[j] * (1 - d1.get(pattern[j], 0.0)) + for j in range(nS1) + ]) + rem_c1_s2 = np.array([ + c1_s2[j] * (1 - d2.get(pattern[nS1 + j], 0.0)) + for j in range(nS2) + ]) + rem_c2_s2 = np.array([ + c2_s2[j] * (1 - d2.get(pattern[nS1 + j], 0.0)) + for j in range(nS2) + ]) + + # Variable layout (same as efficient_algorithm.py) + off_u1 = 0 + off_u2 = nI * nFac + off_u3 = off_u2 + nI * nS2 + off_o1 = off_u3 + nFac * nS2 + off_o2 = off_o1 + nI + off_o3 = off_o2 + nI + n_vars = off_o3 + nFac + + # Cost vector (eq 5) + c_vec = np.zeros(n_vars) + for i in range(nI): + for j in range(nS1): + c_vec[off_u1 + i * nFac + j] = l_cs1[i][j] * alpha + for j in range(nS2): + c_vec[off_u1 + i * nFac + nS1 + j] = l_cs2[i][j] * beta + for i in range(nI): + for j in range(nS2): + c_vec[off_u2 + i * nS2 + j] = l_cs2[i][j] * beta + for j in range(nFac): + for f in range(nS2): + c_vec[off_u3 + j * nS2 + f] = l_fac_s2[j][f] * gamma_ + for i in range(nI): + c_vec[off_o1 + i] = alpha_p + sigma * gamma_p + for i in range(nI): + c_vec[off_o2 + i] = beta_p + for j in range(nFac): + c_vec[off_o3 + j] = gamma_p + + # Equality constraints: (6), (7), (8) + n_eq = nI + nI + nFac + A_eq = np.zeros((n_eq, n_vars)) + b_eq = np.zeros(n_eq) + row = 0 + + # (6): theta*z_i = sum_j u1[i,j] + o1[i] + for i in range(nI): + for j in range(nFac): + A_eq[row, off_u1 + i * nFac + j] = 1.0 + A_eq[row, off_o1 + i] = 1.0 + b_eq[row] = theta * z[i] + row += 1 + + # (7): (1-theta)*z_i = sum_{j in S2} u2[i,j] + o2[i] + for i in range(nI): + for j in range(nS2): + A_eq[row, off_u2 + i * nS2 + j] = 1.0 + A_eq[row, off_o2 + i] = 1.0 + b_eq[row] = (1 - theta) * z[i] + row += 1 + + # (8): sigma*sum_i u1[i,j] = sum_f u3[j,f] + o3[j] + for j in range(nFac): + for i in range(nI): + A_eq[row, off_u1 + i * nFac + j] = sigma + for f in range(nS2): + A_eq[row, off_u3 + j * nS2 + f] = -1.0 + A_eq[row, off_o3 + j] = -1.0 + b_eq[row] = 0.0 + row += 1 + + # Inequality constraints: (9), (10), (11) + n_ineq = nS1 + nS2 + nS2 + A_ub = np.zeros((n_ineq, n_vars)) + b_ub = np.zeros(n_ineq) + row = 0 + + # (9): sum_i u1[i,j] <= rem_c1_s1[j] + for j in range(nS1): + for i in range(nI): + A_ub[row, off_u1 + i * nFac + j] = 1.0 + b_ub[row] = rem_c1_s1[j] + row += 1 + + # (10): sum_i u1[i,nS1+j] <= rem_c1_s2[j] + for j in range(nS2): + for i in range(nI): + A_ub[row, off_u1 + i * nFac + nS1 + j] = 1.0 + b_ub[row] = rem_c1_s2[j] + row += 1 + + # (11): sum_i u2[i,j] + sum_f u3[f,j] <= rem_c2_s2[j] + for j in range(nS2): + for i in range(nI): + A_ub[row, off_u2 + i * nS2 + j] = 1.0 + for f in range(nFac): + A_ub[row, off_u3 + f * nS2 + j] = 1.0 + b_ub[row] = rem_c2_s2[j] + row += 1 + + bounds = [(0, None)] * n_vars + result = linprog(c_vec, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, + bounds=bounds, method='highs') + + if not result.success: + # LP infeasible means lower-level constraints can't all be satisfied + add_violation(violations_list, magnitudes_list, 4, + "Lower-level LP is infeasible: type I demand balance (eq 6) cannot be satisfied", + 0.0, 0.0, 1.0) + add_violation(violations_list, magnitudes_list, 5, + "Lower-level LP is infeasible: type II demand balance (eq 7) cannot be satisfied", + 0.0, 0.0, 1.0) + else: + x_sol = result.x + + # ---- Constraint 4 (eq 6): theta*z_i = sum_j u1[i,j] + o1[i] ---- + for i in range(nI): + lhs = sum(x_sol[off_u1 + i * nFac + j] for j in range(nFac)) + x_sol[off_o1 + i] + rhs = theta * z[i] + viol = abs(lhs - rhs) + if viol > tol: + add_violation(violations_list, magnitudes_list, 4, + f"Type I demand balance violated for customer {i}: LHS={lhs:.6f}, RHS={rhs:.6f}", + lhs, rhs, viol) + + # ---- Constraint 5 (eq 7): (1-theta)*z_i = sum_{j in S2} u2[i,j] + o2[i] ---- + for i in range(nI): + lhs = sum(x_sol[off_u2 + i * nS2 + j] for j in range(nS2)) + x_sol[off_o2 + i] + rhs = (1 - theta) * z[i] + viol = abs(lhs - rhs) + if viol > tol: + add_violation(violations_list, magnitudes_list, 5, + f"Type II demand balance violated for customer {i}: LHS={lhs:.6f}, RHS={rhs:.6f}", + lhs, rhs, viol) + + # ---- Constraint 6 (eq 8): sigma*sum_i u1[i,j] = sum_f u3[j,f] + o3[j] ---- + for j in range(nFac): + lhs = sigma * sum(x_sol[off_u1 + i * nFac + j] for i in range(nI)) + rhs = sum(x_sol[off_u3 + j * nS2 + f] for f in range(nS2)) + x_sol[off_o3 + j] + viol = abs(lhs - rhs) + if viol > tol: + fac_label = f"S1_{j}" if j < nS1 else f"S2_{j - nS1}" + add_violation(violations_list, magnitudes_list, 6, + f"Referral balance violated for facility {fac_label}: LHS={lhs:.6f}, RHS={rhs:.6f}", + lhs, rhs, viol) + + # ---- Constraint 7 (eq 9): sum_i u1[i,j] <= rem_c1_s1[j] for j in S1 ---- + for j in range(nS1): + lhs = sum(x_sol[off_u1 + i * nFac + j] for i in range(nI)) + rhs = rem_c1_s1[j] + viol = max(0.0, lhs - rhs) + if viol > tol: + add_violation(violations_list, magnitudes_list, 7, + f"Type I capacity exceeded at S1 facility {j}: allocated={lhs:.2f}, capacity={rhs:.2f}", + lhs, rhs, viol) + + # ---- Constraint 8 (eq 10): sum_i u1[i,nS1+j] <= rem_c1_s2[j] for j in S2 ---- + for j in range(nS2): + lhs = sum(x_sol[off_u1 + i * nFac + nS1 + j] for i in range(nI)) + rhs = rem_c1_s2[j] + viol = max(0.0, lhs - rhs) + if viol > tol: + add_violation(violations_list, magnitudes_list, 8, + f"Type I capacity exceeded at S2 facility {j}: allocated={lhs:.2f}, capacity={rhs:.2f}", + lhs, rhs, viol) + + # ---- Constraint 9 (eq 11): sum_i u2[i,j] + sum_f u3[f,j] <= rem_c2_s2[j] ---- + for j in range(nS2): + lhs = (sum(x_sol[off_u2 + i * nS2 + j] for i in range(nI)) + + sum(x_sol[off_u3 + f * nS2 + j] for f in range(nFac))) + rhs = rem_c2_s2[j] + viol = max(0.0, lhs - rhs) + if viol > tol: + add_violation(violations_list, magnitudes_list, 9, + f"Type II capacity exceeded at S2 facility {j}: allocated={lhs:.2f}, capacity={rhs:.2f}", + lhs, rhs, viol) + + # ---- Constraint 10 (eq 12): Non-negativity ---- + min_val = np.min(x_sol) + if min_val < -tol: + viol = abs(min_val) + idx = np.argmin(x_sol) + add_violation(violations_list, magnitudes_list, 10, + f"Non-negativity violated: variable index {idx} has value {min_val:.6e}", + float(min_val), 0.0, viol) + + # ---- Constraint 11 (obj, eq 5): Objective consistency ---- + # The reported objective_value is, by definition (eq 5), the + # defender's minimum total cost H(z) for the chosen interdiction + # pattern. The lower-level problem is an LP whose optimum we just + # computed exactly above -- result.fun. The defender's + # reassignment/outsourcing variables are NOT in the solution + # (only the interdiction pattern is), but they are determined + # deterministically as the optimal lower-level LP solution, so + # this is a FULL recompute. Reject when the reported value + # disagrees with the recomputed optimum (defends against + # score-gaming exploits that fabricate objective_value). + 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 and math.isfinite(reported): + true_obj = float(result.fun) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + add_violation(violations_list, magnitudes_list, 11, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed lower-level LP optimum " + f"H(z)={true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported, true_obj, abs_diff) + elif reported is not None: + # Non-finite reported objective (inf / nan) is never a + # valid cost -- treat as an objective inconsistency. + true_obj = float(result.fun) + add_violation(violations_list, magnitudes_list, 11, + f"Objective consistency violated: reported objective_value=" + f"{reported} is not a finite number; recomputed lower-level " + f"LP optimum H(z)={true_obj}", + 0.0, true_obj, abs(true_obj)) + + # ========================================================= + # Build output + # ========================================================= + violated_indices = sorted(set(v[0] for v in violations_list)) + violation_messages = [] + for ci in violated_indices: + msgs = [v[1] for v in violations_list if v[0] == ci] + if len(msgs) <= 3: + violation_messages.extend(msgs) + else: + violation_messages.append(msgs[0]) + violation_messages.append(f"... and {len(msgs) - 1} more violations for constraint {ci}") + + feasible = len(violated_indices) == 0 + + output = { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": violation_messages, + "violation_magnitudes": magnitudes_list if not feasible else [], + } + + return output + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for bi-level partial interdiction on hierarchical facilities") + 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() + + inst = 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(inst, sol) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE: All constraints satisfied.") + else: + print(f"INFEASIBLE: 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/li2020/gurobi_code.py b/tasks/li2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..7af74abbab42f044807960856c7883199aebbd77 --- /dev/null +++ b/tasks/li2020/gurobi_code.py @@ -0,0 +1,458 @@ +#!/usr/bin/env python3 +""" +Gurobi-based solver for the bi-level partial interdiction problem on +capacitated nested hierarchical facilities. + +Reference: Forghani, Dehghanian, Salari, Ghiami (2020) +"A bi-level model and solution methods for partial interdiction problem +on capacitated hierarchical facilities" +Computers and Operations Research 114 (2020) 104831 + +Approach: Single-level MILP reformulation via LP duality of the lower level. +The upper level (interdictor) maximizes H(z), the lower level (defender) minimizes +cost. Since the lower level is an LP, we replace it with its dual and jointly +optimize: max_{x, dual} dual_obj s.t. upper-level constraints + dual feasibility. +Bilinear terms (binary x * dual variable) in the dual objective's capacity terms +are linearized using standard big-M techniques. +""" + +import argparse +import json +import math +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: + return json.load(f) + + +def compute_s2_distances(inst): + """Compute Euclidean distances between level-2 facilities (not in instance data).""" + s2x = inst["level2_facilities"]["x_coordinates"] + s2y = inst["level2_facilities"]["y_coordinates"] + nS2 = len(s2x) + return [[math.sqrt((s2x[j] - s2x[f]) ** 2 + (s2y[j] - s2y[f]) ** 2) + for f in range(nS2)] for j in range(nS2)] + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for bi-level partial interdiction on hierarchical facilities") + parser.add_argument("--instance_path", type=str, required=True) + parser.add_argument("--solution_path", type=str, required=True) + parser.add_argument("--time_limit", type=int, required=True) + 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) + + inst = load_instance(args.instance_path) + gp_ = inst["global_parameters"] + ip = inst["instance_parameters"] + inter = inst["interdiction_parameters"] + + # Global parameters + theta = gp_["theta"] + sigma = gp_["sigma"] + alpha = gp_["alpha"] + beta = gp_["beta"] + gamma = gp_["gamma"] + alpha_p = gp_["alpha_prime"] + beta_p = gp_["beta_prime"] + gamma_p = gp_["gamma_prime"] + + # Instance dimensions + nI = ip["num_customers"] + nS1 = ip["num_level1_facilities"] + nS2 = ip["num_level2_facilities"] + k_max = ip["k_max"] + B = ip["total_interdiction_budget"] + nFac = nS1 + nS2 + K = list(range(k_max + 1)) # {0, 1, ..., k_max} + + # Interdiction costs: h1[k], h2[k]; h[0]=0 by convention + h1 = {0: 0.0} + for ks, v in inter["interdiction_cost_level1_h1"].items(): + h1[int(ks)] = v + h2 = {0: 0.0} + for ks, v in inter["interdiction_cost_level2_h2"].items(): + h2[int(ks)] = v + + # Capacity reduction ratios: d1[k], d2[k]; d[0]=0 + d1 = {0: 0.0} + for ks, v in inter["capacity_reduction_level1_d1"].items(): + d1[int(ks)] = v + d2 = {0: 0.0} + for ks, v in inter["capacity_reduction_level2_d2"].items(): + d2[int(ks)] = v + + # Data arrays + z = inst["customers"]["demands"] + c1_s1 = inst["level1_facilities"]["capacity_type1"] + c1_s2 = inst["level2_facilities"]["capacity_type1"] + c2_s2 = inst["level2_facilities"]["capacity_type2"] + + l_cs1 = inst["distances"]["customer_to_level1_facility"] + l_cs2 = inst["distances"]["customer_to_level2_facility"] + l_s1s2 = inst["distances"]["level1_to_level2_facility"] + l_s2s2 = compute_s2_distances(inst) + + # Combined facility-to-S2 distances: S1 rows first, then S2 rows + l_fac_s2 = l_s1s2 + l_s2s2 + + # --- Compute big-M for linearization --- + # Dual variable bounds analysis: + # lambda_i <= alpha' + sigma*gamma' (from D5) + # mu_i <= beta' (from D6) + # nu_j <= gamma' (from D7) + # pi_j, rho_j, tau_j <= 0 + # Lower bounds on pi/rho/tau: determined by dual constraints. + # Conservative estimate: max outsourcing cost provides an upper bound on magnitude. + BIG_M = max(alpha_p + sigma * gamma_p, beta_p, gamma_p) * 2.0 + + # --- Build the single-level MILP reformulation --- + m = gp.Model("bilevel_partial_interdiction") + m.setParam("Threads", 1) + m.setParam("TimeLimit", args.time_limit) + m.setParam("OutputFlag", 1) + + # === Upper-level binary variables: x[j,k] === + # x[j,k] = 1 if facility j is interdicted at level k + x = {} + for j in range(nFac): + for k in K: + x[j, k] = m.addVar(vtype=GRB.BINARY, name=f"x_{j}_{k}") + + # === Lower-level dual variables === + # lambda_i (dual of constraint 6 - type I demand balance, equality -> free) + lam = [m.addVar(lb=-GRB.INFINITY, ub=alpha_p + sigma * gamma_p, + name=f"lam_{i}") for i in range(nI)] + # mu_i (dual of constraint 7 - type II demand balance, equality -> free) + mu = [m.addVar(lb=-GRB.INFINITY, ub=beta_p, + name=f"mu_{i}") for i in range(nI)] + # nu_j (dual of constraint 8 - referral balance, equality -> free) + nu = [m.addVar(lb=-GRB.INFINITY, ub=gamma_p, + name=f"nu_{j}") for j in range(nFac)] + # pi_j <= 0 (dual of constraint 9 - type I capacity at S1, <= ineq) + pi_ = [m.addVar(ub=0.0, lb=-BIG_M, name=f"pi_{j}") for j in range(nS1)] + # rho_j <= 0 (dual of constraint 10 - type I capacity at S2, <= ineq) + rho = [m.addVar(ub=0.0, lb=-BIG_M, name=f"rho_{j}") for j in range(nS2)] + # tau_j <= 0 (dual of constraint 11 - type II capacity at S2, <= ineq) + tau = [m.addVar(ub=0.0, lb=-BIG_M, name=f"tau_{j}") for j in range(nS2)] + + # === Linearization variables for bilinear terms in dual objective === + # The dual objective contains terms like: + # [c1_j - c1_j * sum_k d_k * x_{jk}] * pi_j + # The bilinear product x_{jk} * pi_j is linearized as w1_{jk}. + # w1[j,k] = x[j,k] * pi_[j] for j in S1, k >= 1 + w1 = {} + for j in range(nS1): + for k in range(1, k_max + 1): + w1[j, k] = m.addVar(ub=0.0, lb=-BIG_M, name=f"w1_{j}_{k}") + # w2[j,k] = x[nS1+j,k] * rho[j] for j in S2, k >= 1 + w2 = {} + for j in range(nS2): + for k in range(1, k_max + 1): + w2[j, k] = m.addVar(ub=0.0, lb=-BIG_M, name=f"w2_{j}_{k}") + # w3[j,k] = x[nS1+j,k] * tau[j] for j in S2, k >= 1 + w3 = {} + for j in range(nS2): + for k in range(1, k_max + 1): + w3[j, k] = m.addVar(ub=0.0, lb=-BIG_M, name=f"w3_{j}_{k}") + + # === Primal variables (express explicit strong duality condition) === + u1 = {} + for i in range(nI): + for j in range(nFac): + u1[i, j] = m.addVar(lb=0.0, name=f"u1_{i}_{j}") + u2 = {} + for i in range(nI): + for j in range(nS2): + u2[i, j] = m.addVar(lb=0.0, name=f"u2_{i}_{j}") + u3 = {} + for j in range(nFac): + for f in range(nS2): + u3[j, f] = m.addVar(lb=0.0, name=f"u3_{j}_{f}") + o1 = [m.addVar(lb=0.0, name=f"o1_{i}") for i in range(nI)] + o2 = [m.addVar(lb=0.0, name=f"o2_{i}") for i in range(nI)] + o3 = [m.addVar(lb=0.0, name=f"o3_{j}") for j in range(nFac)] + + m.update() + + # ============================================= + # Upper-level constraints + # ============================================= + + # (2): Exactly one interdiction level per facility + for j in range(nFac): + m.addConstr(gp.quicksum(x[j, k] for k in K) == 1, name=f"one_level_{j}") + + # (3): Interdiction budget constraint + m.addConstr( + gp.quicksum(h1[k] * x[j, k] for j in range(nS1) for k in K) + + gp.quicksum(h2[k] * x[nS1 + j, k] for j in range(nS2) for k in K) + <= B, name="budget" + ) + + # ============================================= + # Dual feasibility constraints + # ============================================= + + # Dual of u1[i,j] for j in S1: + # Primal cost coeff: l_cs1[i][j] * alpha + # Appears in (6) coeff +1, (8) coeff -sigma (rewritten), (9) coeff +1 + # => lam[i] - sigma*nu[j] + pi_[j] <= l_cs1[i][j]*alpha + for i in range(nI): + for j in range(nS1): + m.addConstr( + lam[i] - sigma * nu[j] + pi_[j] <= l_cs1[i][j] * alpha, + name=f"du1s1_{i}_{j}") + + # Dual of u1[i,j] for j in S2 (j indexes S2 as 0..nS2-1, facility index nS1+j): + # Primal cost coeff: l_cs2[i][j] * beta + # Appears in (6) coeff +1, (8) coeff -sigma, (10) coeff +1 + # => lam[i] - sigma*nu[nS1+j] + rho[j] <= l_cs2[i][j]*beta + for i in range(nI): + for j in range(nS2): + m.addConstr( + lam[i] - sigma * nu[nS1 + j] + rho[j] <= l_cs2[i][j] * beta, + name=f"du1s2_{i}_{j}") + + # Dual of u2[i,j] for j in S2: + # Primal cost coeff: l_cs2[i][j] * beta + # Appears in (7) coeff +1, (11) coeff +1 + # => mu[i] + tau[j] <= l_cs2[i][j]*beta + for i in range(nI): + for j in range(nS2): + m.addConstr( + mu[i] + tau[j] <= l_cs2[i][j] * beta, + name=f"du2_{i}_{j}") + + # Dual of u3[j,f] for j in S1 union S2, f in S2: + # Primal cost coeff: l_fac_s2[j][f] * gamma + # Appears in (8) coeff +1 for facility j, (11) coeff +1 for facility f + # => nu[j] + tau[f] <= l_fac_s2[j][f]*gamma + for j in range(nFac): + for f in range(nS2): + m.addConstr( + nu[j] + tau[f] <= l_fac_s2[j][f] * gamma, + name=f"du3_{j}_{f}") + + # Dual of o1[i]: lam[i] <= alpha' + sigma*gamma' (set as UB on lam) + # Dual of o2[i]: mu[i] <= beta' (set as UB on mu) + # Dual of o3[j]: nu[j] <= gamma' (set as UB on nu) + # These are already enforced via variable upper bounds. + + # ============================================= + # Linearization constraints + # ============================================= + # For w = x_bin * y_nonpos where x in {0,1}, y <= 0: + # x=0 => w=0; x=1 => w=y + # Enforced by: + # w >= y - M*(1-x) [x=1: w>=y; x=0: w>=y-M (loose)] + # w <= y + M*(1-x) [x=1: w<=y; x=0: w<=y+M (loose)] + # w >= -M*x [x=0: w>=0; x=1: w>=-M (loose)] + # w <= 0 (variable upper bound) + + for j in range(nS1): + for k in range(1, k_max + 1): + xvar = x[j, k] + m.addConstr(w1[j, k] >= pi_[j] - BIG_M * (1 - xvar), + name=f"lin1a_{j}_{k}") + m.addConstr(w1[j, k] <= pi_[j] + BIG_M * (1 - xvar), + name=f"lin1b_{j}_{k}") + m.addConstr(w1[j, k] >= -BIG_M * xvar, + name=f"lin1c_{j}_{k}") + + for j in range(nS2): + for k in range(1, k_max + 1): + xvar = x[nS1 + j, k] + m.addConstr(w2[j, k] >= rho[j] - BIG_M * (1 - xvar), + name=f"lin2a_{j}_{k}") + m.addConstr(w2[j, k] <= rho[j] + BIG_M * (1 - xvar), + name=f"lin2b_{j}_{k}") + m.addConstr(w2[j, k] >= -BIG_M * xvar, + name=f"lin2c_{j}_{k}") + + m.addConstr(w3[j, k] >= tau[j] - BIG_M * (1 - xvar), + name=f"lin3a_{j}_{k}") + m.addConstr(w3[j, k] <= tau[j] + BIG_M * (1 - xvar), + name=f"lin3b_{j}_{k}") + m.addConstr(w3[j, k] >= -BIG_M * xvar, + name=f"lin3c_{j}_{k}") + + # ============================================= + # Primal feasibility (eqs 6-11) + strong duality + # ============================================= + for i in range(nI): + m.addConstr( + gp.quicksum(u1[i, j] for j in range(nFac)) + o1[i] == theta * z[i], + name=f"primal6_{i}") + m.addConstr( + gp.quicksum(u2[i, j] for j in range(nS2)) + o2[i] == (1 - theta) * z[i], + name=f"primal7_{i}") + + for j in range(nFac): + m.addConstr( + sigma * gp.quicksum(u1[i, j] for i in range(nI)) + == gp.quicksum(u3[j, f] for f in range(nS2)) + o3[j], + name=f"primal8_{j}") + + for j in range(nS1): + m.addConstr( + gp.quicksum(u1[i, j] for i in range(nI)) + <= c1_s1[j] - c1_s1[j] * gp.quicksum(d1[k] * x[j, k] + for k in range(1, k_max + 1)), + name=f"primal9_{j}") + + for j in range(nS2): + m.addConstr( + gp.quicksum(u1[i, nS1 + j] for i in range(nI)) + <= c1_s2[j] - c1_s2[j] * gp.quicksum(d2[k] * x[nS1 + j, k] + for k in range(1, k_max + 1)), + name=f"primal10_{j}") + m.addConstr( + gp.quicksum(u2[i, j] for i in range(nI)) + + gp.quicksum(u3[f, j] for f in range(nFac)) + <= c2_s2[j] - c2_s2[j] * gp.quicksum(d2[k] * x[nS1 + j, k] + for k in range(1, k_max + 1)), + name=f"primal11_{j}") + + # Strong duality: primal_obj == dual_obj (dual side uses w1/w2/w3 to linearize x*pi/x*rho/x*tau) + primal_obj_expr = gp.LinExpr() + for i in range(nI): + for j in range(nS1): + primal_obj_expr += l_cs1[i][j] * alpha * u1[i, j] + for j in range(nS2): + primal_obj_expr += l_cs2[i][j] * beta * u1[i, nS1 + j] + primal_obj_expr += l_cs2[i][j] * beta * u2[i, j] + for j in range(nFac): + for f in range(nS2): + primal_obj_expr += l_fac_s2[j][f] * gamma * u3[j, f] + for i in range(nI): + primal_obj_expr += alpha_p * o1[i] + primal_obj_expr += beta_p * o2[i] + primal_obj_expr += sigma * gamma_p * o1[i] + for j in range(nFac): + primal_obj_expr += gamma_p * o3[j] + + dual_obj_expr = gp.LinExpr() + for i in range(nI): + dual_obj_expr += theta * z[i] * lam[i] + dual_obj_expr += (1 - theta) * z[i] * mu[i] + for j in range(nS1): + dual_obj_expr += c1_s1[j] * pi_[j] + for k in range(1, k_max + 1): + dual_obj_expr -= c1_s1[j] * d1[k] * w1[j, k] + for j in range(nS2): + dual_obj_expr += c1_s2[j] * rho[j] + for k in range(1, k_max + 1): + dual_obj_expr -= c1_s2[j] * d2[k] * w2[j, k] + for j in range(nS2): + dual_obj_expr += c2_s2[j] * tau[j] + for k in range(1, k_max + 1): + dual_obj_expr -= c2_s2[j] * d2[k] * w3[j, k] + + m.addConstr(primal_obj_expr == dual_obj_expr, name="strong_duality") + + # ============================================= + # Objective: maximize dual objective of lower-level LP + # ============================================= + # dual_obj = sum_i theta*z_i*lam_i + sum_i (1-theta)*z_i*mu_i + # + sum_{j in S1} [c1_j * pi_j - sum_{k>=1} c1_j * d1_k * w1_{jk}] + # + sum_{j in S2} [c1_j * rho_j - sum_{k>=1} c1_j * d2_k * w2_{jk}] + # + sum_{j in S2} [c2_j * tau_j - sum_{k>=1} c2_j * d2_k * w3_{jk}] + # + # The negative terms -c*d*w = -c*d*x*pi become positive when x=1 and pi<0, + # reflecting that interdiction removes capacity and increases defender cost. + + obj = gp.LinExpr() + + # Demand-related dual terms + for i in range(nI): + obj += theta * z[i] * lam[i] + obj += (1 - theta) * z[i] * mu[i] + + # S1 capacity terms (constraint 9 duals) + for j in range(nS1): + obj += c1_s1[j] * pi_[j] + for k in range(1, k_max + 1): + obj -= c1_s1[j] * d1[k] * w1[j, k] + + # S2 type-I capacity terms (constraint 10 duals) + for j in range(nS2): + obj += c1_s2[j] * rho[j] + for k in range(1, k_max + 1): + obj -= c1_s2[j] * d2[k] * w2[j, k] + + # S2 type-II capacity terms (constraint 11 duals) + for j in range(nS2): + obj += c2_s2[j] * tau[j] + for k in range(1, k_max + 1): + obj -= c2_s2[j] * d2[k] * w3[j, k] + + m.setObjective(obj, GRB.MAXIMIZE) + + # ============================================= + # Solve + # ============================================= + m.optimize() + + # ============================================= + # Extract and output solution + # ============================================= + result = {"objective_value": None, "status": "no_solution"} + + if m.SolCount > 0: + result["objective_value"] = m.ObjVal + + # Extract interdiction pattern + pattern = {} + for j in range(nFac): + for k in K: + if x[j, k].X > 0.5: + fac_type = "S1" if j < nS1 else "S2" + fac_idx = j if j < nS1 else j - nS1 + pattern[f"{fac_type}_{fac_idx}"] = k + break + result["interdiction_pattern"] = pattern + + if m.Status == GRB.OPTIMAL: + result["status"] = "optimal" + result["mip_gap"] = m.MIPGap + elif m.Status == GRB.TIME_LIMIT: + result["status"] = "time_limit" + result["mip_gap"] = m.MIPGap + else: + result["status"] = "feasible" + else: + if m.Status == GRB.INFEASIBLE: + result["status"] = "infeasible" + elif m.Status == GRB.TIME_LIMIT: + result["status"] = "time_limit_no_solution" + + with open(args.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']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/li2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/li2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/li2020/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/li2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/li2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/li2020/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/li2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/li2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/li2020/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/li2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/li2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/li2020/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/li2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/li2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/li2020/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/li2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/li2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/li2020/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/li2020/gurobi_solution/large_solution_1.json b/tasks/li2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d97bede1a8b83f2db4b5ec3b9148f202c6df52f2 --- /dev/null +++ b/tasks/li2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8ef9a95bfc74575064fb30d0e395668c40fb0c0e88e8e9e3eef0420a0837bef +size 698 diff --git a/tasks/li2020/gurobi_solution/large_solution_2.json b/tasks/li2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..81373a1812a04813303934bcda795b9772d7f61e --- /dev/null +++ b/tasks/li2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8feb736ecf0e25f50e6d62e5f1184c44a0747295bbecec006be0d9ae5e9b3f38 +size 697 diff --git a/tasks/li2020/gurobi_solution/large_solution_3.json b/tasks/li2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c7bd83aa958c1336a1185c1a4e058edcb7a3c4e2 --- /dev/null +++ b/tasks/li2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ad3acffbecf77aba1c7f9e1e40417f3e57c9ccb425c534f67dfee1dd70421ee +size 699 diff --git a/tasks/li2020/gurobi_solution/large_solution_4.json b/tasks/li2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..48ec2a5adde887f491da80edca1c37692e1d47b4 --- /dev/null +++ b/tasks/li2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15f3c5ebeca94801c40e82b77d6e5833b4a235a35559a964fad221e4c8f16e76 +size 697 diff --git a/tasks/li2020/gurobi_solution/large_solution_5.json b/tasks/li2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e5ec03b6ad707989f32b202a4b1f2f2abd42cfa4 --- /dev/null +++ b/tasks/li2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2d1b912e25032355cc820919b5bb4f133ae47fff85303e10f3b934785fd0a97 +size 675 diff --git a/tasks/li2020/gurobi_solution/tiny_solution.json b/tasks/li2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2c91180fd0238ce88d311401636aece093b8d0e9 --- /dev/null +++ b/tasks/li2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08ffb09076d0032acfa9e3b80996e29da909b622b3d3de1ed99901acdbb4c98e +size 285 diff --git a/tasks/li2020/gurobi_solution_log/large_log_1.jsonl b/tasks/li2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7b850ed8c60cda5e2c737b69fc9f91d472a00287 --- /dev/null +++ b/tasks/li2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8bbee838beee5fa2d39329edef27b3286ea7facd0bf8b41a71ab55977f00c7b +size 54 diff --git a/tasks/li2020/gurobi_solution_log/large_log_2.jsonl b/tasks/li2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ad53b932d869ca0593e71350accbd6dc4c2eaa1 --- /dev/null +++ b/tasks/li2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cae5f2003cdfda770c68beab9a24738b6a8bfc0e546a6746e74c167295a272de +size 55 diff --git a/tasks/li2020/gurobi_solution_log/large_log_3.jsonl b/tasks/li2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..97b5b514f90b8b6a5408ab1bf8c49d1dea8913e1 --- /dev/null +++ b/tasks/li2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:053627a4117c41a96f83de1ba7173d8b675420a01bb8582072357e61a58c5d9e +size 54 diff --git a/tasks/li2020/gurobi_solution_log/large_log_4.jsonl b/tasks/li2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..69cd191ff93917b1b6fa70673058d65591d60363 --- /dev/null +++ b/tasks/li2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a12dc504087ee8dacebc6d54142cde9983061de0ecdae3b69d728eabfabaddb +size 54 diff --git a/tasks/li2020/gurobi_solution_log/large_log_5.jsonl b/tasks/li2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7b83dec8c29c02bfd1c4f4b7a5f1d422776f1bfb --- /dev/null +++ b/tasks/li2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5cbe167cfcbe939ddd49e2da6ac0f6502896a069d03208dd69fd6752330d590 +size 54 diff --git a/tasks/li2020/gurobi_solution_log/tiny_log.jsonl b/tasks/li2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a287602d79c7ffd3cec964f1e18613e0640e3c42 --- /dev/null +++ b/tasks/li2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0024d6626d38eb8fd0d6278446d435ef4a0e378d7944b985c28c3eb53cc6c83 +size 55 diff --git a/tasks/li2020/instance/large_instance_1.json b/tasks/li2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..72616eafd7a64ee0bc2ee2d9ed5fcf61bac07c79 --- /dev/null +++ b/tasks/li2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:331f240b981ea35b9438182a89f7c7b7d6e15a52191f4c93882a082e6131edd8 +size 134243 diff --git a/tasks/li2020/instance/large_instance_2.json b/tasks/li2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..334f4154d9bdf60c778bae94a320835031f2761b --- /dev/null +++ b/tasks/li2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98075cb951a9fe3055eec9eaf7b0ed99b8288c0af0a268504177dae4dad71133 +size 134351 diff --git a/tasks/li2020/instance/large_instance_3.json b/tasks/li2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e2a824c604cfb43a547c00c0b77ac801fbb01f6d --- /dev/null +++ b/tasks/li2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9079755d5727cd7a822723b65a9e8d601baa9d5dfc4b24ab58f78036e76f710 +size 134088 diff --git a/tasks/li2020/instance/large_instance_4.json b/tasks/li2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..820b92742dd949d88e1225b44174212155aaeb21 --- /dev/null +++ b/tasks/li2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e35ca4a78739edd37093ef1375a00418eafb7c76ae192bf8c892de75151a00af +size 134549 diff --git a/tasks/li2020/instance/large_instance_5.json b/tasks/li2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..940562a28a4b3d40595f07a70616d031afe3f039 --- /dev/null +++ b/tasks/li2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d94ef4de23bd019b61586145587d7b1c64d47d2f002b79554ca4a768c7ab8ec +size 134104 diff --git a/tasks/li2020/instance/tiny_instance.json b/tasks/li2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..299335b75756f14656a83c7783367eea85a95986 --- /dev/null +++ b/tasks/li2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cca5b5dcb6b6a415fad24a75e275b082abf733b9bb588e24516b3acd0a45689 +size 15739 diff --git a/tasks/li2020/instance_schema.json b/tasks/li2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..78ee997f471f426b3aba8262b506446e06726561 --- /dev/null +++ b/tasks/li2020/instance_schema.json @@ -0,0 +1,52 @@ +{ + "global_parameters": { + "theta": " Fraction of each customer's total demand that requires type I service.", + "sigma": " Fraction of type I demand served at any facility that generates a subsequent referral need for type II service.", + "alpha": " Per-unit-demand per-unit-distance cost for shipping type I demand from a customer to a level I facility.", + "beta": " Per-unit-demand per-unit-distance cost for shipping type I or type II demand from a customer to a level II facility.", + "gamma": " Per-unit-demand per-unit-distance cost for forwarding referral demand from any facility to a level II facility.", + "alpha_prime": " Per-unit cost of outsourcing type I demand.", + "beta_prime": " Per-unit cost of outsourcing type II demand.", + "gamma_prime": " Per-unit cost of outsourcing referral demand.", + "R": " Radius of the circular region in which customers are located.", + "L": " Side length of the square region in which facilities are placed.", + "rho1": " Cost of fully interdicting one level I facility.", + "rho2": " Cost of fully interdicting one level II facility." + }, + "instance_parameters": { + "num_level1_facilities": " Number of level I facilities that provide only type I service.", + "num_level2_facilities": " Number of level II facilities that provide both type I and type II service.", + "num_customers": " Number of customers with demand to be served.", + "num_interdiction_levels_K": " Total number of interdiction intensity levels available, including level zero (no attack).", + "k_max": " Maximum interdiction intensity level that can be assigned to a facility.", + "budget_level": " Qualitative label indicating the interdiction budget tier.", + "total_interdiction_budget": " Maximum total expenditure the interdictor may spend across all facility attacks." + }, + "interdiction_parameters": { + "interdiction_cost_level1_h1": " Cost incurred by the interdictor for attacking a level I facility at each positive intensity level.", + "interdiction_cost_level2_h2": " Cost incurred by the interdictor for attacking a level II facility at each positive intensity level.", + "capacity_reduction_level1_d1": " Fraction of original type I capacity lost at a level I facility for each positive intensity level.", + "capacity_reduction_level2_d2": " Fraction of original capacity lost at a level II facility for each positive intensity level, applied to both type I and type II capacity." + }, + "customers": { + "x_coordinates": " Horizontal coordinate of each customer in the two-dimensional plane.", + "y_coordinates": " Vertical coordinate of each customer in the two-dimensional plane.", + "demands": " Total service demand of each customer, split between type I and type II according to theta." + }, + "level1_facilities": { + "x_coordinates": " Horizontal coordinate of each level I facility.", + "y_coordinates": " Vertical coordinate of each level I facility.", + "capacity_type1": " Maximum amount of type I demand each level I facility can serve before interdiction." + }, + "level2_facilities": { + "x_coordinates": " Horizontal coordinate of each level II facility.", + "y_coordinates": " Vertical coordinate of each level II facility.", + "capacity_type1": " Maximum amount of type I demand each level II facility can serve before interdiction.", + "capacity_type2": " Maximum combined type II and referral demand each level II facility can serve before interdiction." + }, + "distances": { + "customer_to_level1_facility": " Euclidean distance from each customer to each level I facility.", + "customer_to_level2_facility": " Euclidean distance from each customer to each level II facility.", + "level1_to_level2_facility": " Euclidean distance from each level I facility to each level II facility, used for referral forwarding costs." + } +} \ No newline at end of file diff --git a/tasks/li2020/mathematical_formulation.md b/tasks/li2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..0f9ec0eba3e3eb516a7efbee645fa0752c2ec1e4 --- /dev/null +++ b/tasks/li2020/mathematical_formulation.md @@ -0,0 +1,106 @@ +# Original Formulation: Bi-Level Partial Interdiction on Capacitated Hierarchical Facilities + +*Source*: Forghani, Dehghanian, Salari, Ghiami (2020), “A bi-level model and solution methods for partial interdiction problem on capacitated hierarchical facilities,” *Computers & Operations Research* 114:104831. Equations (1)–(12). Original model is a bilevel min–max; we transcribe it in bilevel form (no KKT / LP-dual substitution). + +## Sets and Indices + +- $I$: set of customers, index $i$. + +- $S_1$: existing facilities at level I (lower-level facilities). + +- $S_2$: existing facilities at level II (upper-level facilities), indices $j,f$. + +- $K = \{0,1,\ldots,k_{\max}\}$: interdiction intensity levels ($k=0$ means no interdiction). + +## Parameters + +- $\alpha,\beta,\gamma$: unit per-distance transportation costs (customer$\to$level I, customer$\to$level II, level I$\to$level II). + +- $\alpha',\beta',\gamma'$: unit outsourcing costs (type I, type II, referential type II). + +- $h^1_k,\,h^2_k$: cost of attacking a level I / level II facility at interdiction intensity $k$. + +- $z_i$: demand at customer $i$; $\theta$: fraction receiving type I service; $\sigma$: fraction of type I recipients requiring referential type II. + +- $B$: total interdiction budget. + +- $c^1_j,\,c^2_j$: initial type I / type II capacity of facility $j$ ($c^2_j=0$ for $j \in S_1$). + +- $d^1_k,\,d^2_k$: cumulative capacity-reduction ratio at interdiction level $k$ for level I / level II facilities. + +- $\ell_{ij}$: distance from customer $i$ to facility $j$; $\ell'_{jf}$: distance between facilities $j$ and $f$. + +## Decision Variables + +#### Upper-level (leader, interdictor). + +- $x_{jk} \in \{0,1\}$: $1$ if facility $j \in S_1 \cup S_2$ is interdicted at level $k \in K$. + +#### Lower-level (follower, defender; all continuous $\ge 0$). + +- $u^1_{ij}$: demand of customer $i$ allocated to facility $j \in S_1 \cup S_2$ for type I service. + +- $u^2_{ij}$: demand of customer $i$ allocated to facility $j \in S_2$ for type II service. + +- $u^3_{jf}$: demand referred from facility $j \in S_1 \cup S_2$ to facility $f \in S_2$ for referential type II service. + +- $o^1_i,\,o^2_i$: outsourced type I / type II demand of customer $i$. + +- $o^3_j$: outsourced referential type II demand originating at facility $j \in S_1 \cup S_2$. + +## Bi-Level Formulation + +#### Upper level (interdictor — leader). + +$$\begin{align} + \max_{x} \quad & H(x) \tag{1}\\[2pt] + \text{s.t.} \quad + & \sum_{k \in K} x_{jk} \;=\; 1, + && \forall\, j \in S_1 \cup S_2, \tag{2}\\[2pt] + & \sum_{j \in S_1} \sum_{k \in K} h^1_k\, x_{jk} + + \sum_{j \in S_2} \sum_{k \in K} h^2_k\, x_{jk} + \;\le\; B, \tag{3}\\[2pt] + & x_{jk} \;\in\; \{0,1\}, + && \forall\, j \in S_1 \cup S_2,\; k \in K. \tag{4} +\end{align}$$ + +#### Lower level (defender — follower). + +For fixed $x$, $H(x)$ is the optimal value of $$\begin{align} + H(x) \;=\; \min_{u,o} \quad + &\ \sum_{i \in I} \sum_{j \in S_1} \ell_{ij}\,\alpha\, u^1_{ij} + + \sum_{i \in I} \sum_{j \in S_2} \ell_{ij}\,\beta\, u^1_{ij} + + \sum_{i \in I} \sum_{j \in S_2} \ell_{ij}\,\beta\, u^2_{ij} \notag\\ + &\ + \sum_{j \in S_1 \cup S_2} \sum_{f \in S_2} \ell'_{jf}\,\gamma\, u^3_{jf} + + \sum_{i \in I} \alpha'\, o^1_i + + \sum_{i \in I} \beta'\, o^2_i \notag\\ + &\ + \sum_{j \in S_1 \cup S_2} \gamma'\, o^3_j + + \sigma \sum_{i \in I} \gamma'\, o^1_i + \tag{5}\\[2pt] + \text{s.t.} \quad + & \theta\, z_i + \;=\; \sum_{j \in S_1 \cup S_2} u^1_{ij} + o^1_i, + && \forall\, i \in I, \tag{6}\\[2pt] + & (1-\theta)\, z_i + \;=\; \sum_{j \in S_2} u^2_{ij} + o^2_i, + && \forall\, i \in I, \tag{7}\\[2pt] + & \sigma \sum_{i \in I} u^1_{ij} + \;=\; \sum_{f \in S_2} u^3_{jf} + o^3_j, + && \forall\, j \in S_1 \cup S_2, \tag{8}\\[2pt] + & \sum_{i \in I} u^1_{ij} + \;\le\; c^1_j \;-\; c^1_j \sum_{k=1}^{k_{\max}} d^1_k\, x_{jk}, + && \forall\, j \in S_1, \tag{9}\\[2pt] + & \sum_{i \in I} u^1_{ij} + \;\le\; c^1_j \;-\; c^1_j \sum_{k=1}^{k_{\max}} d^2_k\, x_{jk}, + && \forall\, j \in S_2, \tag{10}\\[2pt] + & \sum_{i \in I} u^2_{ij} + + \sum_{f \in S_1 \cup S_2} u^3_{fj} + \;\le\; c^2_j \;-\; c^2_j \sum_{k=1}^{k_{\max}} d^2_k\, x_{jk}, + && \forall\, j \in S_2, \tag{11}\\[2pt] + & u^1_{ij},\, u^2_{ij},\, u^3_{jf},\, o^1_i,\, o^2_i,\, o^3_j + \;\ge\; 0. \tag{12} +\end{align}$$ + +**Bilevel structure.** The lower-level variables satisfy $$(u^1,u^2,u^3,o^1,o^2,o^3) \;\in\; + \arg\min_{u,o \ge 0}\ + \bigl\{\; (5) \;:\; \text{(6)--(11) hold at given } x \;\bigr\},$$ rendering (1)–(12) a bi-level (max–min) interdiction model. diff --git a/tasks/li2020/problem_description.txt b/tasks/li2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..28cbaf461a3e22aa16eebfd587bb74c3d45b4b04 --- /dev/null +++ b/tasks/li2020/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A region contains a set of customers, a set of lower-level facilities (level I), and a set of upper-level facilities (level II), all positioned at known coordinates in a two-dimensional plane. The system is a capacitated nested hierarchical service network: level II facilities can provide both type I and type II services, while level I facilities can provide only type I service. Each customer has a known demand, a fixed fraction theta of which requires type I service and the remaining fraction (one minus theta) requires type II service. Additionally, of the type I demand that any facility serves, a fixed fraction sigma generates a subsequent need for referential type II service, which must be forwarded to a level II facility or outsourced. + +An interdictor (attacker) and a defender operate in sequence. The interdictor acts first and selects an interdiction intensity level for every facility. The set of possible intensity levels ranges from zero (no attack) through a maximum level; exactly one intensity level must be assigned to each facility. Each intensity level at each facility tier has an associated attack cost, and the total attack expenditure across all facilities must not exceed a given interdiction budget. When a level I facility is interdicted at a given intensity, its type I service capacity is reduced by the corresponding level I reduction ratio applied to its original type I capacity. When a level II facility is interdicted at a given intensity, its type I capacity is reduced by the level II reduction ratio, and its type II capacity is similarly reduced by the same level II reduction ratio. At intensity zero the reduction ratios are zero, so no capacity is lost. + +After the interdictor commits to an interdiction pattern, the defender allocates customer demand to the surviving capacity of the facilities and may also outsource unmet demand. The defender determines, for each customer, how much of that customer's type I demand is sent to each level I or level II facility and how much is outsourced, and similarly how much of that customer's type II demand is sent to each level II facility and how much is outsourced. For referential type II demand, the defender determines how much of each facility's generated referral demand is forwarded to each level II facility and how much is outsourced. A customer's type I demand fraction must be fully covered by the sum of allocations to facilities (level I or level II) and the outsourced amount. Likewise, a customer's type II demand fraction must be fully covered by allocations to level II facilities plus outsourcing. For every facility, the referential type II demand it generates (sigma times the total type I demand it serves) must equal the sum of its referral flows to level II facilities plus the outsourced referral amount for that facility. Furthermore, any type I demand that a customer outsources also generates referential type II demand at the rate sigma, and this referral demand is automatically outsourced as well. + +The total type I demand served by a level I facility must not exceed that facility's original type I capacity minus the capacity lost to interdiction. The total type I demand served by a level II facility must not exceed that facility's original type I capacity minus the capacity lost to interdiction (using the level II reduction ratio). The combined type II demand and incoming referral flows served by a level II facility must not exceed that facility's original type II capacity minus the capacity lost to interdiction. + +The cost the defender incurs has several components. Allocating type I demand from a customer to a level I facility costs alpha per unit of demand per unit of distance between them. Allocating type I demand from a customer to a level II facility costs beta per unit of demand per unit of distance. Allocating type II demand from a customer to a level II facility also costs beta per unit of demand per unit of distance. Forwarding referral demand from any facility to a level II facility costs gamma per unit of demand per unit of distance between those two facilities. Outsourcing type I demand costs alpha-prime per unit. Outsourcing type II demand costs beta-prime per unit. Outsourcing referral demand at a facility costs gamma-prime per unit. Outsourced type I demand also incurs an additional referral outsourcing charge of sigma times gamma-prime per unit of outsourced type I demand. + +The interdictor's goal is to choose the interdiction pattern that maximizes the defender's minimum total cost. The defender's goal is to choose the demand allocation and outsourcing plan that minimizes the total cost, given the interdiction pattern selected by the interdictor. The overall problem is therefore to find the interdiction pattern and the corresponding optimal defender response that together yield the maximum possible minimum cost. diff --git a/tasks/li2020/solution_logger.py b/tasks/li2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/li2020/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/li2020/solution_schema.json b/tasks/li2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2716417975b852ebfe6d3f7e6701f79104fe4be5 --- /dev/null +++ b/tasks/li2020/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Defender's minimum total cost achieved under the interdictor's chosen attack pattern.", + "interdiction_pattern": " Interdiction intensity level assigned to each facility, where the key identifies the facility tier ('S1' for level I, 'S2' for level II) and its index within that tier, and the value is the chosen intensity level." +} diff --git a/tasks/liao2020/feasibility_check.py b/tasks/liao2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..ce917b45b13a4440dfab02f8fcccee15ed6a73bf --- /dev/null +++ b/tasks/liao2020/feasibility_check.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Distributionally Robust Outpatient Colonoscopy +Scheduling (DROCS) problem. + +Reference: Shehadeh, Cohn, and Jiang (2019/2020), EJOR. + +Checks the hard constraints of the DR-bimodal MILP (Proposition 4, Eq. 15): + Constraint 1: Assignment constraints (Eq. 1 / 15b) + Constraint 2: Scheduling constraints (Eq. 2 / 15b) + Constraints 3-12: complete auxiliary/dual witness satisfies the trusted + offline coefficient system. + Constraint 13: objective_value equals the submitted complete witness cost. +""" + +import argparse +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from solverless_witness import require_linked_variables, validate_complete_witness + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'c_g', 'c_o', 'c_w', 'cost_structure', 'model_variables', 'objective_value', 'patient_start_times', 'schedule') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('assignment', 'model_variables', 'patient_start_times', '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: + 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 record_violation(violations_list, magnitudes_list, constraint_idx, + message, lhs, rhs, violation_amount): + """Record a constraint violation.""" + violations_list.append((constraint_idx, 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(instance, solution, instance_path): + P = instance["num_patients_P"] + L = instance["provider_service_hours_L_minutes"] + + violations = [] # list of (constraint_idx, message) + magnitudes = [] # list of violation magnitude dicts + + cost_key = next(iter(instance["cost_structures"])) + expected_cost = instance["cost_structures"][cost_key] + if solution["cost_structure"] != cost_key: + record_violation( + violations, magnitudes, 13, + f"cost_structure must be the benchmark selector {cost_key!r}", + 1.0, 0.0, 1.0, + ) + for field in ("c_w", "c_g", "c_o"): + difference = abs(float(solution[field]) - float(expected_cost[field])) + if difference > TOL: + record_violation( + violations, magnitudes, 13, + f"{field}={solution[field]} does not match " + f"{cost_key}.{field}={expected_cost[field]}", + float(solution[field]), float(expected_cost[field]), difference, + ) + + # ------------------------------------------------------------------ + # Reconstruct x_{p,i} (binary assignment) and t_i (schedule) + # ------------------------------------------------------------------ + # Detect solution format: + # efficient_solution: assignment maps position(str) -> patient(int) + # also has "sequence" key + # gurobi_solution: assignment maps patient(str) -> position(int) + # also has "patient_start_times" key + raw_assignment = solution["assignment"] + schedule_raw = solution["schedule"] + + if "sequence" in solution: + # efficient format: key=position, value=patient + pos_to_pat = {int(k): int(v) for k, v in raw_assignment.items()} + pat_to_pos = {v: k for k, v in pos_to_pat.items()} + elif "patient_start_times" in solution: + # gurobi format: key=patient, value=position + pat_to_pos = {int(k): int(v) for k, v in raw_assignment.items()} + pos_to_pat = {v: k for k, v in pat_to_pos.items()} + else: + # Fallback: try to detect by checking if values form valid positions + # Assume position->patient (efficient format) + pos_to_pat = {int(k): int(v) for k, v in raw_assignment.items()} + pat_to_pos = {v: k for k, v in pos_to_pat.items()} + + # Build x[p][i] matrix + x = {} + for p in range(1, P + 1): + for i in range(1, P + 1): + x[(p, i)] = 0 + for pos, pat in pos_to_pat.items(): + if 1 <= pos <= P and 1 <= pat <= P: + x[(pat, pos)] = 1 + + # Build t[i] schedule + t = {} + for i in range(1, P + 1): + key = str(i) + if key in schedule_raw: + t[i] = float(schedule_raw[key]) + else: + t[i] = 0.0 + + expected_indices = set(range(1, P + 1)) + if set(pos_to_pat) != expected_indices or set(pat_to_pos) != expected_indices: + record_violation( + violations, magnitudes, 1, + "assignment must contain every patient and position exactly once", + float(len(pos_to_pat)), float(P), 1.0, + ) + parsed_schedule_keys = {int(key) for key in schedule_raw} + if parsed_schedule_keys != expected_indices: + record_violation( + violations, magnitudes, 2, + f"schedule keys must exactly cover positions 1..{P}", + float(len(parsed_schedule_keys)), float(P), 1.0, + ) + + patient_start_times = solution["patient_start_times"] + parsed_patient_times = { + int(patient): float(start) + for patient, start in patient_start_times.items() + } + if set(parsed_patient_times) != expected_indices: + record_violation( + violations, magnitudes, 2, + f"patient_start_times keys must exactly cover patients 1..{P}", + float(len(parsed_patient_times)), float(P), 1.0, + ) + for patient in expected_indices & set(parsed_patient_times) & set(pat_to_pos): + expected_start = t[pat_to_pos[patient]] + difference = abs(parsed_patient_times[patient] - expected_start) + if difference > TOL: + record_violation( + violations, magnitudes, 2, + f"patient_start_times[{patient}]={parsed_patient_times[patient]} " + f"does not match schedule position {pat_to_pos[patient]}=" + f"{expected_start}", + parsed_patient_times[patient], expected_start, difference, + ) + + # ================================================================== + # Constraint 1: Assignment constraints (Eq. 1) + # sum_p x_{p,i} = 1 for all i = 1..P (each position one patient) + # sum_i x_{p,i} = 1 for all p = 1..P (each patient one position) + # x_{p,i} in {0,1} + # ================================================================== + + # Check binary: x values should be 0 or 1 + for p in range(1, P + 1): + for i in range(1, P + 1): + val = x[(p, i)] + if val not in (0, 1): + viol = abs(val - round(val)) + if viol > TOL: + record_violation(violations, magnitudes, 1, + f"x[{p},{i}]={val} is not binary", + val, round(val), viol) + + # Each position gets exactly one patient + for i in range(1, P + 1): + lhs_val = sum(x[(p, i)] for p in range(1, P + 1)) + rhs_val = 1.0 + viol_amount = abs(lhs_val - rhs_val) + if viol_amount > TOL: + record_violation(violations, magnitudes, 1, + f"Position {i}: sum of assignments = {lhs_val}, expected 1", + lhs_val, rhs_val, viol_amount) + + # Each patient assigned to exactly one position + for p in range(1, P + 1): + lhs_val = sum(x[(p, i)] for i in range(1, P + 1)) + rhs_val = 1.0 + viol_amount = abs(lhs_val - rhs_val) + if viol_amount > TOL: + record_violation(violations, magnitudes, 1, + f"Patient {p}: sum of assignments = {lhs_val}, expected 1", + lhs_val, rhs_val, viol_amount) + + # Check that assignment is a valid permutation (no duplicate patients/positions) + assigned_patients = list(pos_to_pat.values()) + assigned_positions = list(pos_to_pat.keys()) + if len(set(assigned_patients)) != len(assigned_patients): + dup_pats = [p for p in assigned_patients if assigned_patients.count(p) > 1] + record_violation(violations, magnitudes, 1, + f"Duplicate patient assignments: patients {set(dup_pats)} assigned multiple times", + len(set(assigned_patients)), P, P - len(set(assigned_patients))) + + if len(set(assigned_positions)) != len(assigned_positions): + dup_pos = [i for i in assigned_positions if assigned_positions.count(i) > 1] + record_violation(violations, magnitudes, 1, + f"Duplicate position assignments: positions {set(dup_pos)} used multiple times", + len(set(assigned_positions)), P, P - len(set(assigned_positions))) + + # Check all patients 1..P are assigned + expected_patients = set(range(1, P + 1)) + actual_patients = set(assigned_patients) + if actual_patients != expected_patients: + missing = expected_patients - actual_patients + extra = actual_patients - expected_patients + msg_parts = [] + if missing: + msg_parts.append(f"missing patients {missing}") + if extra: + msg_parts.append(f"unexpected patients {extra}") + record_violation(violations, magnitudes, 1, + f"Assignment coverage error: {'; '.join(msg_parts)}", + len(actual_patients & expected_patients), P, + len(missing | extra)) + + # Check all positions 1..P are filled + expected_positions = set(range(1, P + 1)) + actual_positions = set(assigned_positions) + if actual_positions != expected_positions: + missing = expected_positions - actual_positions + extra = actual_positions - expected_positions + msg_parts = [] + if missing: + msg_parts.append(f"unfilled positions {missing}") + if extra: + msg_parts.append(f"unexpected positions {extra}") + record_violation(violations, magnitudes, 1, + f"Position coverage error: {'; '.join(msg_parts)}", + len(actual_positions & expected_positions), P, + len(missing | extra)) + + # ================================================================== + # Constraint 2: Scheduling constraints (Eq. 2) + # t_1 = 0 + # 0 <= t_i <= L for all i = 1..P + # t_i >= t_{i-1} for all i = 2..P + # ================================================================== + + # t_1 = 0 + viol_amount = abs(t[1] - 0.0) + if viol_amount > TOL: + record_violation(violations, magnitudes, 2, + f"t_1 = {t[1]}, expected 0", + t[1], 0.0, viol_amount) + + # 0 <= t_i <= L + for i in range(1, P + 1): + # t_i >= 0 (i.e., 0 <= t_i; equivalently, -t_i <= 0) + if t[i] < -TOL: + viol_amount = -t[i] + record_violation(violations, magnitudes, 2, + f"t_{i} = {t[i]} < 0 (lower bound violated)", + t[i], 0.0, viol_amount) + + # t_i <= L + if t[i] > L + TOL: + viol_amount = t[i] - L + record_violation(violations, magnitudes, 2, + f"t_{i} = {t[i]} > L = {L} (upper bound violated)", + t[i], L, viol_amount) + + # t_i >= t_{i-1} for i = 2..P + for i in range(2, P + 1): + # t_i >= t_{i-1} <==> t_{i-1} - t_i <= 0 (lhs=t_{i-1}, rhs=t_i as >= constraint) + if t[i] < t[i - 1] - TOL: + viol_amount = t[i - 1] - t[i] + record_violation(violations, magnitudes, 2, + f"t_{i} = {t[i]} < t_{i-1} = {t[i-1]} (non-decreasing order violated)", + t[i], t[i - 1], viol_amount) + + # ================================================================== + # Constraints 3-13: validate every auxiliary/dual variable and the + # objective by direct substitution into the trusted model coefficients. + # ================================================================== + valid_perm = ( + set(pos_to_pat) == set(range(1, P + 1)) + and set(pat_to_pos) == set(range(1, P + 1)) + ) + valid_schedule = set(int(key) for key in schedule_raw) == set( + range(1, P + 1) + ) + if valid_perm and valid_schedule: + expected_links = { + f"x[{patient},{position}]": float(pat_to_pos[patient] == position) + for patient in range(1, P + 1) + for position in range(1, P + 1) + } + expected_links.update({f"t[{position}]": t[position] for position in range(1, P + 1)}) + expected_objective, witness_errors, _ = validate_complete_witness( + instance_path, solution, Path(__file__).resolve().parent + ) + witness_errors.extend(require_linked_variables(solution, expected_links)) + for message in witness_errors: + record_violation(violations, magnitudes, 13, message, 1.0, 0.0, 1.0) + reported_objective = float(solution["objective_value"]) + difference = abs(reported_objective - float(expected_objective or 0.0)) + objective_tolerance = max( + 1e-3, 2e-6 * abs(float(expected_objective or 0.0)) + ) + if expected_objective is not None and difference > objective_tolerance: + record_violation( + violations, magnitudes, 13, + f"Objective consistency: objective_value={reported_objective} " + f"does not match complete-witness DRO value " + f"{expected_objective} (|diff|={difference:.4g}, " + f"tol={objective_tolerance:.4g}).", + reported_objective, expected_objective, difference, + ) + + # ------------------------------------------------------------------ + # Build output + # ------------------------------------------------------------------ + violated_indices = sorted(set(idx for idx, _ in violations)) + violation_messages = [] + for idx in violated_indices: + msgs = [msg for c_idx, msg in violations if c_idx == idx] + violation_messages.append(f"Constraint {idx}: " + "; ".join(msgs)) + + feasible = len(violated_indices) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": violation_messages, + "violation_magnitudes": magnitudes if not feasible else [], + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for DROCS (DR-bimodal MILP)" + ) + 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, args.instance_path) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE: All checkable constraints satisfied.") + else: + print(f"INFEASIBLE: {len(result['violated_constraints'])} constraint(s) violated.") + for msg in result["violations"]: + print(f" - {msg}") + + +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/liao2020/gurobi_code.py b/tasks/liao2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..58fc99ef7d50ea851d6651e5d03b2b3fec6b6ad3 --- /dev/null +++ b/tasks/liao2020/gurobi_code.py @@ -0,0 +1,707 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the DR-bimodal MILP (Equation 15) for the +Distributionally Robust Outpatient Colonoscopy Scheduling (DROCS) problem. + +Reference: Shehadeh, Cohn, Jiang (2019), "A Distributionally Robust Optimization +Approach for Outpatient Colonoscopy Scheduling", European Journal of Operational +Research, 283(2), 549-561. + +This implements Proposition 4 (Equation 15) -- the MILP reformulation that +jointly optimizes patient sequencing and appointment scheduling under +distributional ambiguity with bimodal procedure durations. +""" + +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 solve_drocs(instance_path, solution_path, time_limit, + fixed_assignment=None, fixed_schedule=None, quiet=False): + # ---------------------------------------------------------------- + # Load instance data + # ---------------------------------------------------------------- + with open(instance_path) as f: + instance = json.load(f) + + P = instance["num_patients_P"] + L = instance["provider_service_hours_L_minutes"] + + # Use the first cost structure (Cost1) + cost_key = list(instance["cost_structures"].keys())[0] + cost = instance["cost_structures"][cost_key] + c_w = cost["c_w"] + c_g = cost["c_g"] + c_o = cost["c_o"] + + patients = instance["patients"] + + # ---------------------------------------------------------------- + # Patient parameters (1-indexed: p = 1,...,P) + # Convention: index P+1 has zero values for durations and arrivals. + # ---------------------------------------------------------------- + mu_A = {} + mu_I = {} + mu_u = {} + mu_q = {} + d_AL = {} + d_AU = {} + d_IL = {} + d_IU = {} + u_L = {} + u_U = {} + + for p in range(1, P + 1): + pat = patients[p - 1] + mu_A[p] = pat["mean_duration_adequate_prep"] + mu_I[p] = pat["mean_duration_inadequate_prep"] + mu_u[p] = pat["mean_arrival_time_deviation"] + mu_q[p] = pat["mean_prep_adequacy"] + d_AL[p] = pat["lower_bound_duration_adequate_prep"] + d_AU[p] = pat["upper_bound_duration_adequate_prep"] + d_IL[p] = pat["lower_bound_duration_inadequate_prep"] + d_IU[p] = pat["upper_bound_duration_inadequate_prep"] + u_L[p] = pat["lower_bound_arrival_time_deviation"] + u_U[p] = pat["upper_bound_arrival_time_deviation"] + + # Convention: P+1 values are zero + d_AL[P + 1] = 0.0 + d_AU[P + 1] = 0.0 + d_IL[P + 1] = 0.0 + d_IU[P + 1] = 0.0 + u_L[P + 1] = 0.0 + u_U[P + 1] = 0.0 + + # ---------------------------------------------------------------- + # Cost arrays indexed by position (paper's 1-indexed) + # c_w_pos[i]: c_w for i=1,...,P; c_o for i=P+1 + # c_g_pos[j]: c_g for j=1,...,P; 0 for j=P+1; 0 for j=P+2 + # ---------------------------------------------------------------- + c_w_pos = {} + for i in range(1, P + 1): + c_w_pos[i] = c_w + c_w_pos[P + 1] = c_o + + c_g_pos = {} + for j in range(1, P + 1): + c_g_pos[j] = c_g + c_g_pos[P + 1] = 0.0 + c_g_pos[P + 2] = 0.0 + + # ---------------------------------------------------------------- + # Precompute pi[i][j] for 1 <= i <= j <= P+2 + # pi[i,j] = -c_g_pos[j] + sum_{ell=i}^{j-1} c_w_pos[ell] + # Special case: pi[P+2, P+2] = 0 + # ---------------------------------------------------------------- + pi = {} + for i in range(1, P + 3): + pi[i] = {} + for j in range(i, P + 3): + if i == P + 2 and j == P + 2: + pi[i][j] = 0.0 + else: + pi[i][j] = -c_g_pos[j] + sum( + c_w_pos[ell] for ell in range(i, j) + ) + + # ---------------------------------------------------------------- + # Precomputed patient-level quantities + # ---------------------------------------------------------------- + # min(d_AL[p], d_IL[p]) and max(d_AU[p], d_IU[p]) for each patient + min_d_pat = {p: min(d_AL[p], d_IL[p]) for p in range(1, P + 2)} + max_d_pat = {p: max(d_AU[p], d_IU[p]) for p in range(1, P + 2)} + + # ---------------------------------------------------------------- + # Bounds for McCormick linearization (from Appendix G structure) + # ---------------------------------------------------------------- + # For eta[p,i] = x[p,i]*rho[i]: rho bounded by [d_AL[p], d_AU[p]] + # For tau[p,i] = x[p,i]*alpha[i]: alpha bounded by [d_IL[p], d_IU[p]] + # For nu[p,i] = x[p,i]*lambda[i]: lambda bounded by [u_L[p], u_U[p]] + # For Gamma[p,i] = x[p,i]*gamma[i]: gamma bounded by [-M_gam, M_gam] + # For zeta[p,i] = x[p,i]*z[i]: z bounded by [0, d_AU[p]] + # For psi[p,i] = x[p,i]*v[i]: v bounded by [0, d_IU[p]] + # For phi[p,i] = x[p,i]*r[i]: r bounded by [0, u_U[p]] + + # Global bounds on dual variables (for variable declaration) + max_d_AU = max(d_AU[p] for p in range(1, P + 1)) + min_d_AL = min(d_AL[p] for p in range(1, P + 1)) + max_d_IU = max(d_IU[p] for p in range(1, P + 1)) + min_d_IL = min(d_IL[p] for p in range(1, P + 1)) + max_u_U = max(u_U[p] for p in range(1, P + 1)) + min_u_L = min(u_L[p] for p in range(1, P + 1)) + + # Bound for gamma: use a big-M derived from pi values + max_pi_abs = max( + abs(pi[i][j]) for i in range(1, P + 3) for j in range(i, P + 3) + ) + M_gam = max_pi_abs + L + + # ---------------------------------------------------------------- + # Build Gurobi model + # ---------------------------------------------------------------- + model = gp.Model("DR_bimodal_DROCS") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 0 if quiet else 1) + + # ================================================================ + # DECISION VARIABLES + # ================================================================ + + # x[p,i]: binary assignment of patient p to position i + x = model.addVars( + range(1, P + 1), range(1, P + 1), vtype=GRB.BINARY, name="x" + ) + + # t[i]: scheduled start time of appointment position i + t = model.addVars(range(1, P + 1), lb=0.0, ub=L, name="t") + + # Trusted-checker mode: fix the public first-stage witness and optimize + # only the omitted DRO dual/linearization variables. + if fixed_assignment is not None: + normalized_assignment = { + int(patient): int(position) + for patient, position in fixed_assignment.items() + } + for p in range(1, P + 1): + for i in range(1, P + 1): + fixed_value = 1.0 if normalized_assignment[p] == i else 0.0 + x[p, i].lb = fixed_value + x[p, i].ub = fixed_value + if fixed_schedule is not None: + normalized_schedule = { + int(position): float(start) + for position, start in fixed_schedule.items() + } + for i in range(1, P + 1): + t[i].lb = normalized_schedule[i] + t[i].ub = normalized_schedule[i] + + # Dual variables (free, but with global bounds for McCormick validity) + rho = model.addVars( + range(1, P + 1), lb=min_d_AL, ub=max_d_AU, name="rho" + ) + alpha = model.addVars( + range(1, P + 1), lb=min_d_IL, ub=max_d_IU, name="alpha" + ) + lam = model.addVars( + range(1, P + 1), lb=min_u_L, ub=max_u_U, name="lambda" + ) + gam = model.addVars( + range(1, P + 1), lb=-M_gam, ub=M_gam, name="gamma" + ) + + # beta[i] for i=1,...,P+2; beta[P+2] >= 0 + beta = model.addVars( + range(1, P + 3), lb=-GRB.INFINITY, name="beta" + ) + beta[P + 2].lb = 0.0 + + # z[i] >= 0, z[i] >= rho[i] + z = model.addVars(range(1, P + 1), lb=0.0, ub=max_d_AU, name="z") + # v[i] >= 0, v[i] >= alpha[i] + v = model.addVars(range(1, P + 1), lb=0.0, ub=max_d_IU, name="v") + # r[i] >= 0, r[i] >= lambda[i] + r = model.addVars(range(1, P + 1), lb=0.0, ub=max_u_U, name="r") + # e[i] >= 0, e[i] >= -gamma[i] + e = model.addVars(range(1, P + 1), lb=0.0, ub=M_gam, name="e") + + # ================================================================ + # McCormick linearization variables + # ================================================================ + # eta[p,i] = x[p,i] * rho[i] + eta = model.addVars( + range(1, P + 1), range(1, P + 1), + lb=-GRB.INFINITY, ub=GRB.INFINITY, name="eta" + ) + # tau[p,i] = x[p,i] * alpha[i] + tau = model.addVars( + range(1, P + 1), range(1, P + 1), + lb=-GRB.INFINITY, ub=GRB.INFINITY, name="tau" + ) + # nu[p,i] = x[p,i] * lambda[i] + nu = model.addVars( + range(1, P + 1), range(1, P + 1), + lb=-GRB.INFINITY, ub=GRB.INFINITY, name="nu" + ) + # Gam_mc[p,i] = x[p,i] * gamma[i] + Gam_mc = model.addVars( + range(1, P + 1), range(1, P + 1), + lb=-GRB.INFINITY, ub=GRB.INFINITY, name="Gam" + ) + # zeta[p,i] = x[p,i] * z[i] + zeta = model.addVars( + range(1, P + 1), range(1, P + 1), lb=0.0, ub=GRB.INFINITY, name="zeta" + ) + # psi[p,i] = x[p,i] * v[i] + psi = model.addVars( + range(1, P + 1), range(1, P + 1), lb=0.0, ub=GRB.INFINITY, name="psi" + ) + # phi[p,i] = x[p,i] * r[i] + phi = model.addVars( + range(1, P + 1), range(1, P + 1), lb=0.0, ub=GRB.INFINITY, name="phi" + ) + + # ================================================================ + # OBJECTIVE FUNCTION (Equation 15a) + # ================================================================ + # min sum_{i=1}^{P} sum_{p=1}^{P} (mu_A[p]*eta[p,i] + mu_I[p]*tau[p,i] + # + mu_u[p]*nu[p,i] + mu_q[p]*Gam_mc[p,i]) + sum_{i=1}^{P+2} beta[i] + obj = gp.quicksum( + mu_A[p] * eta[p, i] + + mu_I[p] * tau[p, i] + + mu_u[p] * nu[p, i] + + mu_q[p] * Gam_mc[p, i] + for i in range(1, P + 1) + for p in range(1, P + 1) + ) + gp.quicksum(beta[i] for i in range(1, P + 3)) + + model.setObjective(obj, GRB.MINIMIZE) + + # ================================================================ + # CONSTRAINTS + # ================================================================ + + # ---------------------------------------------------------------- + # (15b / Eq 1) Assignment constraints + # ---------------------------------------------------------------- + for i in range(1, P + 1): + model.addConstr( + gp.quicksum(x[p, i] for p in range(1, P + 1)) == 1, + name=f"assign_pos_{i}", + ) + for p in range(1, P + 1): + model.addConstr( + gp.quicksum(x[p, i] for i in range(1, P + 1)) == 1, + name=f"assign_pat_{p}", + ) + + # ---------------------------------------------------------------- + # (15b / Eq 2) Scheduling constraints + # ---------------------------------------------------------------- + model.addConstr(t[1] == 0.0, name="t1_zero") + for i in range(2, P + 1): + model.addConstr(t[i] >= t[i - 1], name=f"t_order_{i}") + + # ---------------------------------------------------------------- + # (13d) Sign constraints on auxiliary variables + # ---------------------------------------------------------------- + for i in range(1, P + 1): + model.addConstr(z[i] >= rho[i], name=f"z_ge_rho_{i}") + model.addConstr(v[i] >= alpha[i], name=f"v_ge_alpha_{i}") + model.addConstr(r[i] >= lam[i], name=f"r_ge_lam_{i}") + model.addConstr(e[i] >= -gam[i], name=f"e_ge_neg_gam_{i}") + + # ---------------------------------------------------------------- + # McCormick linearization constraints (Appendix F) + # ---------------------------------------------------------------- + for p in range(1, P + 1): + for i in range(1, P + 1): + # ---------------------------------------------------------- + # eta[p,i] = x[p,i] * rho[i]; rho bounds: [d_AL[p], d_AU[p]] + # ---------------------------------------------------------- + LB_r = d_AL[p] + UB_r = d_AU[p] + model.addConstr( + eta[p, i] <= UB_r * x[p, i], name=f"mc_eta_ub1_{p}_{i}" + ) + model.addConstr( + eta[p, i] >= LB_r * x[p, i], name=f"mc_eta_lb1_{p}_{i}" + ) + model.addConstr( + eta[p, i] <= rho[i] - LB_r * (1 - x[p, i]), + name=f"mc_eta_ub2_{p}_{i}", + ) + model.addConstr( + eta[p, i] >= rho[i] - UB_r * (1 - x[p, i]), + name=f"mc_eta_lb2_{p}_{i}", + ) + + # ---------------------------------------------------------- + # tau[p,i] = x[p,i] * alpha[i]; alpha bounds: [d_IL[p], d_IU[p]] + # ---------------------------------------------------------- + LB_a = d_IL[p] + UB_a = d_IU[p] + model.addConstr( + tau[p, i] <= UB_a * x[p, i], name=f"mc_tau_ub1_{p}_{i}" + ) + model.addConstr( + tau[p, i] >= LB_a * x[p, i], name=f"mc_tau_lb1_{p}_{i}" + ) + model.addConstr( + tau[p, i] <= alpha[i] - LB_a * (1 - x[p, i]), + name=f"mc_tau_ub2_{p}_{i}", + ) + model.addConstr( + tau[p, i] >= alpha[i] - UB_a * (1 - x[p, i]), + name=f"mc_tau_lb2_{p}_{i}", + ) + + # ---------------------------------------------------------- + # nu[p,i] = x[p,i] * lambda[i]; lambda bounds: [u_L[p], u_U[p]] + # ---------------------------------------------------------- + LB_l = u_L[p] + UB_l = u_U[p] + model.addConstr( + nu[p, i] <= UB_l * x[p, i], name=f"mc_nu_ub1_{p}_{i}" + ) + model.addConstr( + nu[p, i] >= LB_l * x[p, i], name=f"mc_nu_lb1_{p}_{i}" + ) + model.addConstr( + nu[p, i] <= lam[i] - LB_l * (1 - x[p, i]), + name=f"mc_nu_ub2_{p}_{i}", + ) + model.addConstr( + nu[p, i] >= lam[i] - UB_l * (1 - x[p, i]), + name=f"mc_nu_lb2_{p}_{i}", + ) + + # ---------------------------------------------------------- + # Gam_mc[p,i] = x[p,i] * gamma[i]; gamma bounds: [-M_gam, M_gam] + # ---------------------------------------------------------- + model.addConstr( + Gam_mc[p, i] <= M_gam * x[p, i], + name=f"mc_Gam_ub1_{p}_{i}", + ) + model.addConstr( + Gam_mc[p, i] >= -M_gam * x[p, i], + name=f"mc_Gam_lb1_{p}_{i}", + ) + model.addConstr( + Gam_mc[p, i] <= gam[i] - (-M_gam) * (1 - x[p, i]), + name=f"mc_Gam_ub2_{p}_{i}", + ) + model.addConstr( + Gam_mc[p, i] >= gam[i] - M_gam * (1 - x[p, i]), + name=f"mc_Gam_lb2_{p}_{i}", + ) + + # ---------------------------------------------------------- + # zeta[p,i] = x[p,i] * z[i]; z bounds: [0, d_AU[p]] + # ---------------------------------------------------------- + UB_z = d_AU[p] + model.addConstr( + zeta[p, i] <= UB_z * x[p, i], name=f"mc_zeta_ub1_{p}_{i}" + ) + # zeta >= 0 already from lb + model.addConstr( + zeta[p, i] <= z[i], name=f"mc_zeta_ub2_{p}_{i}" + ) + model.addConstr( + zeta[p, i] >= z[i] - UB_z * (1 - x[p, i]), + name=f"mc_zeta_lb2_{p}_{i}", + ) + + # ---------------------------------------------------------- + # psi[p,i] = x[p,i] * v[i]; v bounds: [0, d_IU[p]] + # ---------------------------------------------------------- + UB_v = d_IU[p] + model.addConstr( + psi[p, i] <= UB_v * x[p, i], name=f"mc_psi_ub1_{p}_{i}" + ) + # psi >= 0 already from lb + model.addConstr( + psi[p, i] <= v[i], name=f"mc_psi_ub2_{p}_{i}" + ) + model.addConstr( + psi[p, i] >= v[i] - UB_v * (1 - x[p, i]), + name=f"mc_psi_lb2_{p}_{i}", + ) + + # ---------------------------------------------------------- + # phi[p,i] = x[p,i] * r[i]; r bounds: [0, u_U[p]] + # ---------------------------------------------------------- + UB_rr = u_U[p] + model.addConstr( + phi[p, i] <= UB_rr * x[p, i], name=f"mc_phi_ub1_{p}_{i}" + ) + # phi >= 0 already from lb + model.addConstr( + phi[p, i] <= r[i], name=f"mc_phi_ub2_{p}_{i}" + ) + model.addConstr( + phi[p, i] >= r[i] - UB_rr * (1 - x[p, i]), + name=f"mc_phi_lb2_{p}_{i}", + ) + + # ---------------------------------------------------------------- + # Helper: position-dependent parameter expressions + # When patient p is assigned to position pos, the position inherits + # that patient's parameters. These are linear in x. + # ---------------------------------------------------------------- + def u_L_at(pos): + """u_L at position pos (1-indexed). Returns 0 for pos > P.""" + if 1 <= pos <= P: + return gp.quicksum(u_L[p] * x[p, pos] for p in range(1, P + 1)) + return 0.0 + + def u_U_at(pos): + """u_U at position pos (1-indexed). Returns 0 for pos > P.""" + if 1 <= pos <= P: + return gp.quicksum(u_U[p] * x[p, pos] for p in range(1, P + 1)) + return 0.0 + + def min_d_at(pos): + """min(d_AL, d_IL) at position pos. Returns 0 for pos > P.""" + if 1 <= pos <= P: + return gp.quicksum( + min_d_pat[p] * x[p, pos] for p in range(1, P + 1) + ) + return 0.0 + + def max_d_at(pos): + """max(d_AU, d_IU) at position pos. Returns 0 for pos > P.""" + if 1 <= pos <= P: + return gp.quicksum( + max_d_pat[p] * x[p, pos] for p in range(1, P + 1) + ) + return 0.0 + + # ---------------------------------------------------------------- + # K'_i (linearized via McCormick variables), for i = 1,...,P + # + # K'_i = -(sum_p d_AU[p]*eta[p,i] + sum_p (d_AL[p]-d_AU[p])*zeta[p,i]) + # -(sum_p d_IU[p]*tau[p,i] + sum_p (d_IL[p]-d_IU[p])*psi[p,i]) + # -(sum_p u_U[p]*nu[p,i] + sum_p (u_L[p]-u_U[p])*phi[p,i]) + # + e[i] + # ---------------------------------------------------------------- + def K_prime(i): + return ( + -gp.quicksum(d_AU[p] * eta[p, i] for p in range(1, P + 1)) + - gp.quicksum( + (d_AL[p] - d_AU[p]) * zeta[p, i] for p in range(1, P + 1) + ) + - gp.quicksum(d_IU[p] * tau[p, i] for p in range(1, P + 1)) + - gp.quicksum( + (d_IL[p] - d_IU[p]) * psi[p, i] for p in range(1, P + 1) + ) + - gp.quicksum(u_U[p] * nu[p, i] for p in range(1, P + 1)) + - gp.quicksum( + (u_L[p] - u_U[p]) * phi[p, i] for p in range(1, P + 1) + ) + + e[i] + ) + + # ---------------------------------------------------------------- + # Constraint (13b): for j = 1, ..., P+2 + # + # sum_{i=1}^{j} beta[i] >= + # (-t[1] - u_L_at(1)) * pi[1,j] + # + sum_{i=2}^{min(j,P)} (-t[i] - u_L_at(i) + t[i-1] + # + u_L_at(i-1) + min_d_at(i-1)) * pi[i,j] + # + sum_{i=2}^{min(j,P+1)} (max_d_at(i-1) + # - min_d_at(i-1)) * max(pi[i,j], 0) + # + sum_{i=1}^{min(j,P)} K'_i + # + [if j >= P+1]: (t[P] + u_L_at(P) - L + # + min_d_at(P)) * pi[P+1,j] + # ---------------------------------------------------------------- + for j in range(1, P + 3): + lhs = gp.quicksum(beta[i] for i in range(1, j + 1)) + rhs = 0 + + # First term: i=1 contributes if j >= 1 + rhs += (-t[1] - u_L_at(1)) * pi[1][j] + + # Second term: i=2,...,min(j,P) + for i in range(2, min(j, P) + 1): + rhs += ( + -t[i] - u_L_at(i) + t[i - 1] + u_L_at(i - 1) + min_d_at(i - 1) + ) * pi[i][j] + + # Third term: i=2,...,min(j,P+1) + for i in range(2, min(j, P + 1) + 1): + pi_plus = max(pi[i][j], 0.0) + if pi_plus > 0: + rhs += (max_d_at(i - 1) - min_d_at(i - 1)) * pi_plus + + # Fourth term: sum of K'_i for i=1,...,min(j,P) + for i in range(1, min(j, P) + 1): + rhs += K_prime(i) + + # Fifth term: overtime (i=P+1), only if j >= P+1 + if j >= P + 1: + rhs += ( + t[P] + u_L_at(P) - L + min_d_at(P) + ) * pi[P + 1][j] + + model.addConstr(lhs >= rhs, name=f"c13b_j{j}") + + # ---------------------------------------------------------------- + # Constraint (13c): for k = 2,...,P+1; j = k,...,P+2 + # + # sum_{i=k}^{j} beta[i] >= + # (u_U_at(k-1) - u_L_at(k-1)) * max(pi[k,j]+c_g_pos[k-1], 0) + # + sum_{i=min(k,P+1)}^{min(j,P)} (-t[i] - u_L_at(i) + t[i-1] + # + u_L_at(i-1) + min_d_at(i-1)) * pi[i,j] + # + sum_{i=min(k,P+1)}^{min(j,P+1)} (max_d_at(i-1) + # - min_d_at(i-1)) * max(pi[i,j], 0) + # + sum_{i=min(k,P+1)}^{min(j,P)} K'_i + # + [if j >= P+1 and P+1 >= k]: (t[P] + u_L_at(P) - L + # + min_d_at(P)) * pi[P+1,j] + # ---------------------------------------------------------------- + for k in range(2, P + 2): + for j in range(k, P + 3): + lhs = gp.quicksum(beta[i] for i in range(k, j + 1)) + rhs = 0 + + # First term: (u_U_at(k-1) - u_L_at(k-1)) * max(pi[k,j] + c_g_pos[k-1], 0) + pi_plus_cg = max(pi[k][j] + c_g_pos[k - 1], 0.0) + if pi_plus_cg > 0: + rhs += (u_U_at(k - 1) - u_L_at(k - 1)) * pi_plus_cg + + # Starting index for the sums + i_start = min(k, P + 1) + + # Second term + for i in range(i_start, min(j, P) + 1): + rhs += ( + -t[i] + - u_L_at(i) + + t[i - 1] + + u_L_at(i - 1) + + min_d_at(i - 1) + ) * pi[i][j] + + # Third term + for i in range(i_start, min(j, P + 1) + 1): + pi_plus = max(pi[i][j], 0.0) + if pi_plus > 0: + rhs += (max_d_at(i - 1) - min_d_at(i - 1)) * pi_plus + + # Fourth term + for i in range(i_start, min(j, P) + 1): + rhs += K_prime(i) + + # Fifth term: overtime, only if P+1 is in range [k, j] + if j >= P + 1 and k <= P + 1: + rhs += ( + t[P] + u_L_at(P) - L + min_d_at(P) + ) * pi[P + 1][j] + + model.addConstr(lhs >= rhs, name=f"c13c_k{k}_j{j}") + + # ================================================================ + # SOLVE + # ================================================================ + model.optimize() + + # ================================================================ + # EXTRACT SOLUTION + # ================================================================ + result = { + "instance_path": instance_path, + "cost_structure": cost_key, + "c_w": c_w, + "c_g": c_g, + "c_o": c_o, + "num_patients": P, + "session_length": L, + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["mip_gap"] = model.MIPGap if model.Status != GRB.OPTIMAL else 0.0 + result["status"] = ( + "optimal" if model.Status == GRB.OPTIMAL else f"status_{model.Status}" + ) + result["solve_time_seconds"] = model.Runtime + + # Patient-to-position assignment + assignment = {} + for p in range(1, P + 1): + for i in range(1, P + 1): + if x[p, i].X > 0.5: + assignment[str(p)] = i + break + result["assignment"] = assignment + + # Appointment schedule (start times indexed by position) + schedule = {} + for i in range(1, P + 1): + schedule[str(i)] = round(t[i].X, 6) + result["schedule"] = schedule + + # Appointment schedule indexed by patient (for convenience) + patient_schedule = {} + for p_str, pos in assignment.items(): + patient_schedule[p_str] = round(t[pos].X, 6) + result["patient_start_times"] = patient_schedule + + else: + result["objective_value"] = None + result["status"] = f"status_{model.Status}" + result["solve_time_seconds"] = model.Runtime + + if solution_path is not None: + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + if not quiet: + print(f"\nSolution written to: {solution_path}") + if model.SolCount > 0: + print(f"Objective value: {model.ObjVal:.6f}") + print(f"Status: {result['status']}") + print(f"Solve time: {model.Runtime:.2f}s") + print(f"Assignment (patient -> position): {assignment}") + print( + f"Schedule (position -> start time): " + + ", ".join(f"{k}: {v}" for k, v in sorted(schedule.items())) + ) + else: + print(f"No feasible solution found. Status: {model.Status}") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description=( + "Solve the DR-bimodal MILP (Eq. 15) for the DROCS problem " + "using 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="gurobi_solution_1.json", + help="Path for the output solution JSON file.", + ) + parser.add_argument( + "--time_limit", + type=int, + default=3600, + help="Solver 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) + solve_drocs(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/liao2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/liao2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/liao2020/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/liao2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/liao2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/liao2020/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/liao2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/liao2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/liao2020/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/liao2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/liao2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/liao2020/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/liao2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/liao2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/liao2020/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/liao2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/liao2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/liao2020/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/liao2020/gurobi_solution/large_solution_1.json b/tasks/liao2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..aaf386735b614b8d966e9a053bb434b8e9d633d4 --- /dev/null +++ b/tasks/liao2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ec497fa0e87a8c179297b43a131253fdf7addb09658e744c81f7b62faea5423 +size 14245 diff --git a/tasks/liao2020/gurobi_solution/large_solution_2.json b/tasks/liao2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8f6bbf0c68e151a17a6e76dc56bb238dd04dc3f2 --- /dev/null +++ b/tasks/liao2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a41e33489520156fcded2249da26ef6514ccb7a8678bbcd2cd6d04677ba25a68 +size 15645 diff --git a/tasks/liao2020/gurobi_solution/large_solution_3.json b/tasks/liao2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b95770f2b8996de38951d6382219966fd16f8975 --- /dev/null +++ b/tasks/liao2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:407237add96e61ac49f8634a90b456bb456863696ac345ab7f857d3de2795ed0 +size 14981 diff --git a/tasks/liao2020/gurobi_solution/large_solution_4.json b/tasks/liao2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c9e0798584df0c6c33ab5c340dc482d0f6b1b240 --- /dev/null +++ b/tasks/liao2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c59291efae4093d60750678d270056c49f20135d92797f38b91bfda73ed5560d +size 15529 diff --git a/tasks/liao2020/gurobi_solution/large_solution_5.json b/tasks/liao2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9c82e9d61aa53b9073b86cfe59fecc03fe42e5fd --- /dev/null +++ b/tasks/liao2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55f834c92c74af1043bc2bce648f2b0e3c47127b5af28c9cedd469e18397b76f +size 14522 diff --git a/tasks/liao2020/gurobi_solution/tiny_solution.json b/tasks/liao2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..0b62a4caef39c9afe7bd3a0ae65d66e0f6cf661c --- /dev/null +++ b/tasks/liao2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1a8131b5be441dd382703ea0aed2c7d5b4b32001a62bf33a595dab1f2f20f47 +size 2344 diff --git a/tasks/liao2020/gurobi_solution_log/large_log_1.jsonl b/tasks/liao2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e07e125349a1e1b95ca2ef3ff6477e3b1fe91436 --- /dev/null +++ b/tasks/liao2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a388c07d03296ebd47d99f5813dd7954c2fead79749d70594d15b7dbccdc060 +size 2419 diff --git a/tasks/liao2020/gurobi_solution_log/large_log_2.jsonl b/tasks/liao2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d946d29338200d7db93b090e3c9bf27dbd27a68d --- /dev/null +++ b/tasks/liao2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1b332853adbd4c2b557392da4246f4ddba9772121c3582e55df399743cc41e0 +size 1772 diff --git a/tasks/liao2020/gurobi_solution_log/large_log_3.jsonl b/tasks/liao2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eed26afcba4e09e647b17596fd2b1b3aa5971a8a --- /dev/null +++ b/tasks/liao2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e57abedfd1b91a7551eab6dffe3271c1672233e6b51141ec56687bff526c8b86 +size 2496 diff --git a/tasks/liao2020/gurobi_solution_log/large_log_4.jsonl b/tasks/liao2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a3d26bfa9f0f73c85e797ec4fc09e500329ca4a4 --- /dev/null +++ b/tasks/liao2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f0d144373b667fac36c937704b1e81eb39fcd265c00c032e442b6b5eb8f354f +size 2317 diff --git a/tasks/liao2020/gurobi_solution_log/large_log_5.jsonl b/tasks/liao2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b6f86a658c5e645fdcd0e35bd5eae761555934b7 --- /dev/null +++ b/tasks/liao2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:908a1407e7b17f0ad087b3638a10f13338b08938e18a9f90740947202abeae3e +size 1460 diff --git a/tasks/liao2020/gurobi_solution_log/tiny_log.jsonl b/tasks/liao2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4267b29ff0ba4d93bbe5e1f8cd335d4c5aa0acb9 --- /dev/null +++ b/tasks/liao2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2e565ab10080de934eac09327b14dae1849dcd21fa77ae0d81ab75e84bd5bd6 +size 55 diff --git a/tasks/liao2020/instance/large_instance_1.json b/tasks/liao2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..61891056acbaad8f87a806869ee1d259208357f4 --- /dev/null +++ b/tasks/liao2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c602b62c1e590251c96a355d13029c163d15875480389c21b51b5cc6372bb1b +size 16773 diff --git a/tasks/liao2020/instance/large_instance_2.json b/tasks/liao2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f961e8ad8c17a8cfc319bbd0ed4310967deff54f --- /dev/null +++ b/tasks/liao2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:966a604c6e736b5f044a86be5e22be9e42765e47c27ff31cd0950b8ddcb37050 +size 16744 diff --git a/tasks/liao2020/instance/large_instance_3.json b/tasks/liao2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..5ea5ebfd30fdd85e388f87fd765c9e0e4e1ca011 --- /dev/null +++ b/tasks/liao2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f277bb8318f7f5d9a5284e76f9f17890fe89778259f2e83b49b4e5b75da1d374 +size 16781 diff --git a/tasks/liao2020/instance/large_instance_4.json b/tasks/liao2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2a57d4159a4711c096593d8f2e458b9cbc4e5c01 --- /dev/null +++ b/tasks/liao2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6793f5dadcaf4546985ac22d4210e2cc2e6f4c74cdac38b0ced48e42fb9ac6c +size 16785 diff --git a/tasks/liao2020/instance/large_instance_5.json b/tasks/liao2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fc04b51b0af1feb134136868193a6c3fb88bcab4 --- /dev/null +++ b/tasks/liao2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac843796ad0fe72a15e205b4211c5a6d7e9bf4edc04d6b1c05d89694312768a7 +size 16801 diff --git a/tasks/liao2020/instance/tiny_instance.json b/tasks/liao2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..590d72453aba31c99017aa41b59974052e8064bd --- /dev/null +++ b/tasks/liao2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4b92c4380e1c1c4358f57d1ee360bcdf8ab81e6b4fc3ca0969d2ad1860f1bc2 +size 3560 diff --git a/tasks/liao2020/instance_schema.json b/tasks/liao2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..4962df7ae61cc53fe1c6eea9eeda9384d75bfd94 --- /dev/null +++ b/tasks/liao2020/instance_schema.json @@ -0,0 +1,30 @@ +{ + "num_patients_P": " Total number of patients to be scheduled in the session.", + "num_colonoscopy_C": " Number of patients receiving a colonoscopy procedure.", + "num_upper_endoscopy_colonoscopy_UC": " Number of patients receiving a combined upper endoscopy and colonoscopy procedure.", + "provider_service_hours_L_minutes": " Total length of the provider's session in minutes.", + "procedure_types": " Type of procedure for each patient, either colonoscopy ('C') or combined upper endoscopy and colonoscopy ('UC').", + "cost_structures": { + "{cost_structure_name}": { + "c_w": " Per-minute cost of patient waiting time before their procedure begins.", + "c_g": " Per-minute cost of provider idle time between consecutive procedures.", + "c_o": " Per-minute cost of provider overtime beyond the scheduled session length." + } + }, + "patients": [ + { + "patient_index": " One-based identifier for the patient.", + "procedure_type": " Type of procedure for this patient, either colonoscopy ('C') or combined upper endoscopy and colonoscopy ('UC').", + "mean_duration_adequate_prep": " Mean procedure duration in minutes when the patient has adequate bowel preparation.", + "mean_duration_inadequate_prep": " Mean procedure duration in minutes when the patient has inadequate bowel preparation.", + "lower_bound_duration_adequate_prep": " Lower support bound on procedure duration in minutes with adequate bowel preparation.", + "upper_bound_duration_adequate_prep": " Upper support bound on procedure duration in minutes with adequate bowel preparation.", + "lower_bound_duration_inadequate_prep": " Lower support bound on procedure duration in minutes with inadequate bowel preparation.", + "upper_bound_duration_inadequate_prep": " Upper support bound on procedure duration in minutes with inadequate bowel preparation.", + "mean_prep_adequacy": " Probability that the patient has adequate bowel preparation.", + "mean_arrival_time_deviation": " Mean deviation in minutes of the patient's actual arrival time from their scheduled time.", + "lower_bound_arrival_time_deviation": " Lower support bound on the patient's arrival time deviation in minutes.", + "upper_bound_arrival_time_deviation": " Upper support bound on the patient's arrival time deviation in minutes." + } + ] +} diff --git a/tasks/liao2020/mathematical_formulation.md b/tasks/liao2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f2c44227b3caaf9a439a60684807644dff913ff6 --- /dev/null +++ b/tasks/liao2020/mathematical_formulation.md @@ -0,0 +1,96 @@ +# Original Formulation: Distributionally Robust Outpatient Colonoscopy Scheduling (DROCS) + +*Source*: Shehadeh, Cohn, Jiang (2020), “A distributionally robust optimization approach for outpatient colonoscopy scheduling,” *EJOR*. First-stage variables satisfy assignment (1) and scheduling (2); the outer problem is the distributionally robust min–max given by Eq. (6). The Prop. 4 MILP reformulation is *not* substituted here. + +**Benchmark cost selector.** If the JSON instance provides multiple named cost +structures, the first declared entry (`Cost1` in the released data) supplies +$c^w$, $c^g$, and $c^o$ for this task. + +## Sets and Indices + +- $p \in \{1,\ldots,P\}$: patients / procedures. + +- $i \in \{1,\ldots,P\}$: positions in the appointment sequence. + +## Parameters + +- $c^w_i$: unit waiting-time cost of appointment $i$. + +- $c^g_i$: unit provider idle-time cost between appointments $i-1$ and $i$. + +- $c^o$: unit provider overtime cost. + +- $L$: scheduled service-hour length of the provider. + +- $\mu^A_p,\,\mu^I_p$: mean procedure durations with adequate / inadequate bowel prep for patient $p$. + +- $\mu^u_p$: mean arrival-time deviation of patient $p$. + +- $\mu^q_p$: probability of adequate prep for patient $p$. + +- $d^{AL}_p,d^{AU}_p$: lower / upper bounds of procedure duration with adequate prep. + +- $d^{IL}_p,d^{IU}_p$: lower / upper bounds of procedure duration with inadequate prep. + +- $u^L_p,u^U_p$: lower / upper bounds of the arrival-time deviation. + +## Decision Variables (first stage) + +- $x_{p,i} \in \{0,1\}$: $1$ if patient $p$ is assigned to appointment position $i$. + +- $t_i \ge 0$: scheduled start time of appointment $i$, with $t_1 = 0$. + +## Random Parameters and Ambiguity Set + +Let $\xi = (d^A, d^I, u, q)$ denote the random procedure durations (adequate and inadequate prep), arrival deviations, and bowel-prep adequacy indicators, with support $S = S^A \times S^I \times S^u \times S^q$ where $$\begin{align*} + S^A &= \{d^A \ge 0 : d^{AL}_p \le d^A_p \le d^{AU}_p,\ d^A_{P+1}=0\},\\ + S^I &= \{d^I \ge 0 : d^{IL}_p \le d^I_p \le d^{IU}_p,\ d^I_{P+1}=0\},\\ + S^u &= \{u : u^L_p \le u_p \le u^U_p,\ u_{P+1}=0\},\qquad + S^q = \{0,1\}^{P}. +\end{align*}$$ The ambiguity set is $$\begin{equation} + \mathcal{F}(S,\mu) \;=\; + \Bigl\{\, P \in \mathcal{P}(S) \;\Big|\; + \mathbb{E}_P[d^A_p] = \mu^A_p,\; + \mathbb{E}_P[d^I_p] = \mu^I_p,\; + \mathbb{E}_P[u_p] = \mu^u_p,\; + \mathbb{E}_P[q_p] = \mu^q_p,\ \forall p \,\Bigr\}. + \tag{A} +\end{equation}$$ + +## First-Stage Constraints + +#### Assignment constraints (1). + +$$\begin{align} + \sum_{p=1}^{P} x_{p,i} &\;=\; 1, + && \forall\, i = 1,\ldots,P, \tag{1a}\\[2pt] + \sum_{i=1}^{P} x_{p,i} &\;=\; 1, + && \forall\, p = 1,\ldots,P, \tag{1b}\\[2pt] + x_{p,i} &\;\in\; \{0,1\}, + && \forall\, p,i = 1,\ldots,P. \tag{1c} +\end{align}$$ + +#### Scheduling constraints (2). + +$$\begin{align} + t_1 &\;=\; 0, \tag{2a}\\[2pt] + 0 \;\le\; t_i &\;\le\; L, + && \forall\, i = 1,\ldots,P, \tag{2b}\\[2pt] + t_i &\;\ge\; t_{i-1}, + && \forall\, i = 2,\ldots,P. \tag{2c} +\end{align}$$ + +## Second-Stage Recourse $Q(x,t,\xi)$ + +Given first-stage $(x,t)$ and realization $\xi$, let $Q(x,t,\xi)$ denote the operational cost (patient waiting + provider idle + provider overtime) as defined in the paper; it is the optimal value of the second-stage LP that determines waiting, idle, and overtime quantities. + +## DRO Objective (Equation 6) + +$$\begin{equation} + \min_{(x,t)\,\in\,\mathcal{X}\times\mathcal{T}} \; + \sup_{P \,\in\, \mathcal{F}(S,\mu)} \; + \mathbb{E}_P\!\bigl[\, Q(x,t,\xi) \,\bigr], + \tag{6} +\end{equation}$$ where $\mathcal{X}$ is the set of $x$ satisfying (1a)–(1c) and $\mathcal{T}$ is the set of $t$ satisfying (2a)–(2c). + +**Original (non-reformulated) structure.** The outer DRO problem is a min–max over the infinite-dimensional ambiguity set $\mathcal{F}(S,\mu)$. The tractable MILP obtained via Proposition 4 / Eq. (15) is *not* substituted here. diff --git a/tasks/liao2020/problem_description.txt b/tasks/liao2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..51a26df7fbda75503aa156b2320ca1ff73b5bc9f --- /dev/null +++ b/tasks/liao2020/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +Benchmark cost convention: when an instance contains several named cost structures, the first declared structure (`Cost1` in all released instances) is authoritative. The solution repeats its name and its `c_w`, `c_g`, and `c_o` values, and the checker verifies them against the instance. + +An outpatient procedure clinic schedules P colonoscopy patients for a single provider within a session of L minutes. Each patient must be assigned to exactly one appointment position in the sequence (positions one through P), and each position receives exactly one patient. The clinic must also determine the scheduled start time for each position. The first position always starts at time zero, every start time must lie between zero and L, and start times must be non-decreasing across positions. + +On the day of service, three sources of variability affect operations and are treated as uncertain random parameters: (i) the quality of each patient's bowel preparation, which is either adequate or inadequate; (ii) the procedure duration, which has a known lower and upper bound and a known mean separately for the adequate-preparation case and for the inadequate-preparation case; (iii) each patient's deviation from the scheduled arrival time, which has known lower/upper bounds and a known mean. For each patient p the input data specifies the mean procedure duration with adequate preparation mu_A_p and with inadequate preparation mu_I_p, the lower and upper bounds on duration with adequate preparation d_AL_p and d_AU_p, the lower and upper bounds with inadequate preparation d_IL_p and d_IU_p, the probability of adequate preparation mu_q_p, the mean arrival-time deviation mu_u_p, and the lower and upper bounds on arrival-time deviation u_L_p and u_U_p. Only these per-patient marginal means and support intervals are given; the full joint distribution of preparation quality, procedure durations, and arrival deviations across all patients is NOT known. + +After a schedule is realized, each position incurs operational costs as follows. A patient's waiting time at a given position is the amount by which the patient's actual procedure-ready time (the later of its arrival time and the completion of the preceding patient's procedure) exceeds the scheduled start time of that position. A provider idle time between two consecutive positions is the amount by which the scheduled start of the later position exceeds the completion of the earlier position plus any incurred waiting. Provider overtime is the amount by which the completion time of the final position exceeds L. The cost structure specifies a unit waiting cost c_w_i per appointment position i, a unit provider idle cost c_g_i per gap between consecutive positions, and a unit provider overtime cost c_o. The total operational cost for a given realization of uncertainty is the sum over all positions of the unit waiting cost times the waiting time, plus the sum over all gaps of the unit idle cost times the idle time, plus the unit overtime cost times the overtime. + +The clinic seeks an appointment assignment and schedule that minimizes the worst-case expected total operational cost, where the worst case is taken over all joint probability distributions of preparation quality, procedure durations, and arrival-time deviations that are consistent with the given patient-level means and support intervals. Equivalently, let the set of distributions consistent with the given marginal means and support intervals form an ambiguity set; the objective is the supremum over distributions in this ambiguity set of the expected operational cost induced by the chosen assignment and schedule. The clinic chooses the assignment and schedule to minimize this worst-case expected cost. diff --git a/tasks/liao2020/solution_logger.py b/tasks/liao2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/liao2020/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/liao2020/solution_schema.json b/tasks/liao2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..611a67b77c2e6d17a436cf7124ffc252356a0a67 --- /dev/null +++ b/tasks/liao2020/solution_schema.json @@ -0,0 +1,11 @@ +{ + "objective_value": " Worst-case expected total operational cost represented by the complete submitted witness.", + "model_variables": " Sparse complete DRO reformulation witness, including assignment, schedule, dual, and McCormick variables. Omitted model variables are exactly zero.", + "cost_structure": " Authoritative instance cost structure; this benchmark uses the first declared structure, Cost1.", + "c_w": " Waiting-time unit cost copied from the authoritative cost structure.", + "c_g": " Provider-idle unit cost copied from the authoritative cost structure.", + "c_o": " Overtime unit cost copied from the authoritative cost structure.", + "assignment": " Appointment position (1 through P) to which each patient is assigned in the sequence.", + "schedule": " Scheduled start time, in minutes from the beginning of the session, for each appointment position.", + "patient_start_times": " Scheduled start time, in minutes from the beginning of the session, for each patient based on their assigned position." +} diff --git a/tasks/liao2020/solverless_models/3c602b62c1e590251c96a355d13029c163d15875480389c21b51b5cc6372bb1b.npz b/tasks/liao2020/solverless_models/3c602b62c1e590251c96a355d13029c163d15875480389c21b51b5cc6372bb1b.npz new file mode 100644 index 0000000000000000000000000000000000000000..68b0cb55c6f5288acebc79541832045191e458e6 --- /dev/null +++ b/tasks/liao2020/solverless_models/3c602b62c1e590251c96a355d13029c163d15875480389c21b51b5cc6372bb1b.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa76f42f9e5a3328292ca6f4bf5d1eff8a0e930f0d3c62d13d64cc74ff2c3ec6 +size 1236989 diff --git a/tasks/liao2020/solverless_models/966a604c6e736b5f044a86be5e22be9e42765e47c27ff31cd0950b8ddcb37050.npz b/tasks/liao2020/solverless_models/966a604c6e736b5f044a86be5e22be9e42765e47c27ff31cd0950b8ddcb37050.npz new file mode 100644 index 0000000000000000000000000000000000000000..1b0809ab80051360233dbbeda369ca0eba8c6a3e --- /dev/null +++ b/tasks/liao2020/solverless_models/966a604c6e736b5f044a86be5e22be9e42765e47c27ff31cd0950b8ddcb37050.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:605473381024be928efcd471645bf66e9c98f564e24637d366a5dcbd7c889901 +size 1233529 diff --git a/tasks/liao2020/solverless_models/ac843796ad0fe72a15e205b4211c5a6d7e9bf4edc04d6b1c05d89694312768a7.npz b/tasks/liao2020/solverless_models/ac843796ad0fe72a15e205b4211c5a6d7e9bf4edc04d6b1c05d89694312768a7.npz new file mode 100644 index 0000000000000000000000000000000000000000..5129fab546b021fbe6a5984f44c737855d3370f2 --- /dev/null +++ b/tasks/liao2020/solverless_models/ac843796ad0fe72a15e205b4211c5a6d7e9bf4edc04d6b1c05d89694312768a7.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea0f7e9e9b791dea9d8bb0fe833a79827c2cc67677956ad0b51d981c39cfafa6 +size 1236559 diff --git a/tasks/liao2020/solverless_models/b4b92c4380e1c1c4358f57d1ee360bcdf8ab81e6b4fc3ca0969d2ad1860f1bc2.npz b/tasks/liao2020/solverless_models/b4b92c4380e1c1c4358f57d1ee360bcdf8ab81e6b4fc3ca0969d2ad1860f1bc2.npz new file mode 100644 index 0000000000000000000000000000000000000000..2aeb7aa1f098caf2c076b96d6acf1d642b072b6c --- /dev/null +++ b/tasks/liao2020/solverless_models/b4b92c4380e1c1c4358f57d1ee360bcdf8ab81e6b4fc3ca0969d2ad1860f1bc2.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cb77609528cc68d422e7b985339155795a79299c7cfc0ce92663e35fe541273 +size 10579 diff --git a/tasks/liao2020/solverless_models/b6793f5dadcaf4546985ac22d4210e2cc2e6f4c74cdac38b0ced48e42fb9ac6c.npz b/tasks/liao2020/solverless_models/b6793f5dadcaf4546985ac22d4210e2cc2e6f4c74cdac38b0ced48e42fb9ac6c.npz new file mode 100644 index 0000000000000000000000000000000000000000..45b7e759306f30a8990a38b81a6f96741d72335b --- /dev/null +++ b/tasks/liao2020/solverless_models/b6793f5dadcaf4546985ac22d4210e2cc2e6f4c74cdac38b0ced48e42fb9ac6c.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6d77a9a6d1c54866cd8b475e9365e4308e36827c942882afe48b047c2ae6f94 +size 1235664 diff --git a/tasks/liao2020/solverless_models/f277bb8318f7f5d9a5284e76f9f17890fe89778259f2e83b49b4e5b75da1d374.npz b/tasks/liao2020/solverless_models/f277bb8318f7f5d9a5284e76f9f17890fe89778259f2e83b49b4e5b75da1d374.npz new file mode 100644 index 0000000000000000000000000000000000000000..35b66720f808aa0fa9344b73b2ab9c4dcfdb2503 --- /dev/null +++ b/tasks/liao2020/solverless_models/f277bb8318f7f5d9a5284e76f9f17890fe89778259f2e83b49b4e5b75da1d374.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6f6efc007e43840f8751757f2296a4a6220539e387e964aad13d2d846370b0e +size 1232569 diff --git a/tasks/liao2020/solverless_witness.py b/tasks/liao2020/solverless_witness.py new file mode 100644 index 0000000000000000000000000000000000000000..6e8d1c0a2a83a5aa314a7405d6b50f6d5dacaf8c --- /dev/null +++ b/tasks/liao2020/solverless_witness.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Solver-free validation of complete sparse optimization witnesses.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import Any + +import numpy as np + +WITNESS_FIELD = "model_variables" + + +def _digest(path: str | Path) -> str: + value = hashlib.sha256() + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + value.update(block) + return value.hexdigest() + + +def _strings(values: np.ndarray) -> list[str]: + return [str(value) for value in values.tolist()] + + +def validate_complete_witness( + instance_path: str | Path, + solution: dict[str, Any], + case_directory: str | Path, + *, + absolute_tolerance: float = 1e-5, + relative_tolerance: float = 1e-7, +) -> tuple[float | None, list[str], dict[str, float]]: + """Return recomputed objective, validation errors, and diagnostics.""" + errors: list[str] = [] + diagnostics: dict[str, float] = {} + witness = solution.get(WITNESS_FIELD) + if not isinstance(witness, dict): + return None, [f"{WITNESS_FIELD} must be an object"], diagnostics + + digest = _digest(instance_path) + snapshot = Path(case_directory) / "solverless_models" / f"{digest}.npz" + if not snapshot.is_file(): + return None, [f"no trusted solverless model for instance sha256={digest}"], diagnostics + + with np.load(snapshot, allow_pickle=False) as model: + if str(model["instance_sha256"].item()) != digest: + return None, ["trusted model instance digest mismatch"], diagnostics + names = _strings(model["var_names"]) + name_to_index = {name: index for index, name in enumerate(names)} + values = np.zeros(len(names), dtype=np.float64) + unknown: list[str] = [] + for name, raw in witness.items(): + index = name_to_index.get(str(name)) + if index is None: + if len(unknown) < 5: + unknown.append(str(name)) + continue + if isinstance(raw, bool) or not isinstance(raw, (int, float)): + errors.append(f"model variable {name!r} must be a finite number") + continue + value = float(raw) + if not np.isfinite(value): + errors.append(f"model variable {name!r} must be finite") + continue + values[index] = value + if unknown: + errors.append("unknown model variable(s): " + ", ".join(unknown)) + + lower = model["lower_bounds"] + upper = model["upper_bounds"] + scale = np.maximum(1.0, np.maximum(np.abs(lower), np.abs(upper))) + scale[~np.isfinite(scale)] = 1.0 + bound_tol = absolute_tolerance + relative_tolerance * scale + low_bad = np.flatnonzero(values < lower - bound_tol) + high_bad = np.flatnonzero(values > upper + bound_tol) + if low_bad.size: + diagnostics["max_lower_bound_violation"] = float(np.max(lower[low_bad] - values[low_bad])) + for index in low_bad[:5]: + errors.append(f"lower bound violated: {names[index]}={values[index]:.12g} < {lower[index]:.12g}") + if high_bad.size: + diagnostics["max_upper_bound_violation"] = float(np.max(values[high_bad] - upper[high_bad])) + for index in high_bad[:5]: + errors.append(f"upper bound violated: {names[index]}={values[index]:.12g} > {upper[index]:.12g}") + + integer_mask = model["integer_mask"].astype(bool) + integer_indices = np.flatnonzero(integer_mask) + fractionality = np.abs(values[integer_mask] - np.rint(values[integer_mask])) + bad_local = np.flatnonzero(fractionality > absolute_tolerance) + if bad_local.size: + diagnostics["max_integrality_violation"] = float(np.max(fractionality[bad_local])) + for local_index in bad_local[:5]: + index = integer_indices[local_index] + errors.append(f"integrality violated: {names[index]}={values[index]:.12g}") + + row_count = int(model["constraint_count"].item()) + rows = model["row_indices"] + columns = model["column_indices"] + coefficients = model["coefficients"] + activity = np.bincount(rows, weights=coefficients * values[columns], minlength=row_count) + absolute_activity = np.bincount(rows, weights=np.abs(coefficients * values[columns]), minlength=row_count) + rhs = model["rhs"] + senses = model["senses"] + row_tol = absolute_tolerance + relative_tolerance * np.maximum.reduce( + [np.ones(row_count), np.abs(rhs), absolute_activity] + ) + violation = np.zeros(row_count, dtype=np.float64) + violation[senses == -1] = np.maximum(0.0, activity[senses == -1] - rhs[senses == -1]) + violation[senses == 0] = np.abs(activity[senses == 0] - rhs[senses == 0]) + violation[senses == 1] = np.maximum(0.0, rhs[senses == 1] - activity[senses == 1]) + bad_rows = np.flatnonzero(violation > row_tol) + if bad_rows.size: + diagnostics["max_constraint_violation"] = float(np.max(violation[bad_rows])) + constraint_names = _strings(model["constraint_names"]) + sense_text = {-1: "<=", 0: "==", 1: ">="} + for row in bad_rows[:10]: + errors.append( + f"constraint violated: {constraint_names[row]}: {activity[row]:.12g} " + f"{sense_text[int(senses[row])]} {rhs[row]:.12g} (excess {violation[row]:.6g})" + ) + + objective = float(model["objective_constant"].item()) + objective += float(np.dot(model["linear_objective"], values)) + q_coefficients = model["quadratic_coefficients"] + if q_coefficients.size: + objective += float(np.sum( + q_coefficients * values[model["quadratic_rows"]] * values[model["quadratic_columns"]] + )) + diagnostics["recomputed_objective"] = objective + return objective, errors, diagnostics + + +def require_linked_variables( + solution: dict[str, Any], expected: dict[str, float], *, tolerance: float = 1e-6 +) -> list[str]: + """Ensure public fields and the complete vector describe one plan.""" + witness = solution.get(WITNESS_FIELD) + if not isinstance(witness, dict): + return [f"{WITNESS_FIELD} must be an object"] + errors: list[str] = [] + for name, expected_value in expected.items(): + raw = witness.get(name, 0.0) + try: + actual = float(raw) + except (TypeError, ValueError): + errors.append(f"linked model variable {name!r} is not numeric") + continue + if not np.isfinite(actual) or abs(actual - float(expected_value)) > tolerance: + errors.append( + f"public decision and model witness disagree for {name}: {expected_value} versus {actual}" + ) + if len(errors) >= 10: + break + return errors diff --git a/tasks/lozano2017/feasibility_check.py b/tasks/lozano2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e249a59a7f8ab410f0d9a8c4ed8205f5f9ab4f14 --- /dev/null +++ b/tasks/lozano2017/feasibility_check.py @@ -0,0 +1,452 @@ +""" +Feasibility checker for the Bilevel Mixed-Integer Linear Program (BMILP) +from Lozano & Smith (2017). + +Checks the three hard constraints of the BMILP formulation (14a)-(14d): + Constraint 1 (14b): A1*x + B1*y <= b1 (upper-level constraints) + Constraint 2 (14c): submitted complete follower response y is feasible and + its reported value is internally consistent. + Constraint 3 (14d): x in H^x (x >= 0, all integer) + Constraint 4 : objective_value consistency (Tier C anti-gaming check) + reported objective_value must equal the recomputed + leader objective phi^l(x,y) = c*x + d1*y of (14a). + d1 (leader's coefficients on follower variables) is + explicitly fixed to zero by the released instance + contract, matching the Gurobi reference solver. +""" + +import json +import math +import argparse +import numpy as np + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', '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: + 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 main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for BMILP (Lozano & Smith 2017)") + parser.add_argument("--instance_path", required=True, + help="Path to instance JSON file") + parser.add_argument("--solution_path", required=True, + help="Path to candidate solution JSON file") + parser.add_argument("--result_path", required=True, + help="Path to write feasibility result JSON file") + args = parser.parse_args() + + with open(args.instance_path) as f: + data = json.load(f) + with open(args.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(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + tol = 1e-5 + eps = 1e-5 + + # Instance data + n1 = data["n1"] + n2 = data["n2"] + m1 = data["m1"] + m2 = data["m2"] + A1 = np.array(data["A1"], dtype=float) + B1 = np.array(data["B1"], dtype=float) + b1 = np.array(data["b1"], dtype=float) + A2 = np.array(data["A2"], dtype=float) + B2 = np.array(data["B2"], dtype=float) + b2 = np.array(data["b2"], dtype=float) + d2 = np.array(data["d2"], dtype=float) + integer_follower = set(data["integer_follower_vars"]) # 1-indexed + + # Solution vectors + x = np.array(sol["x"], dtype=float) + y = np.array(sol["y"], dtype=float) + + violations = [] + violation_magnitudes = [] + violated_set = set() + + # ------------------------------------------------------------------ + # Constraint 1 (14b): A1*x + B1*y <= b1, for j = 1, ..., m1 + # ------------------------------------------------------------------ + for j in range(m1): + lhs_val = float(A1[j] @ x + B1[j] @ y) + rhs_val = float(b1[j]) + excess = lhs_val - rhs_val # <= constraint + if excess > tol: + violated_set.add(1) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Upper-level constraint {j+1}: " + f"A1[{j+1}]*x + B1[{j+1}]*y = {lhs_val:.6f} > b1[{j+1}] = {rhs_val:.6f}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": excess, + "normalizer": normalizer, + "ratio": excess / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 2 (14c): Follower optimality + # y in argmax{d2*y^f | A2*x + B2*y^f <= b2; y^f in H^y} + # + # Sub-checks: + # 2a. Follower feasibility: A2*x + B2*y <= b2 + # 2b. y >= 0 + # 2c. Integrality of follower integer variables + # 2d. Follower optimality (d2*y equals optimal follower objective) + # ------------------------------------------------------------------ + + # 2a: Follower feasibility — A2*x + B2*y <= b2 + follower_feasible = True + for j in range(m2): + lhs_val = float(A2[j] @ x + B2[j] @ y) + rhs_val = float(b2[j]) + excess = lhs_val - rhs_val + if excess > tol: + follower_feasible = False + violated_set.add(2) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Follower feasibility constraint {j+1}: " + f"A2[{j+1}]*x + B2[{j+1}]*y = {lhs_val:.6f} > b2[{j+1}] = {rhs_val:.6f}" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": excess, + "normalizer": normalizer, + "ratio": excess / normalizer, + }) + + # 2b: y >= 0 + for k in range(n2): + if y[k] < -tol: + violated_set.add(2) + lhs_val = float(y[k]) + rhs_val = 0.0 + excess = -lhs_val # >= constraint: violation = RHS - LHS + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Follower non-negativity: y[{k+1}] = {lhs_val:.6f} < 0" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": excess, + "normalizer": normalizer, + "ratio": excess / normalizer, + }) + + # 2c: Integrality of integer follower variables + for j_idx in sorted(integer_follower): # 1-indexed + val = y[j_idx - 1] + frac = abs(val - round(val)) + if frac > tol: + violated_set.add(2) + lhs_val = float(val) + rhs_val = float(round(val)) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Follower integrality: y[{j_idx}] = {val:.6f} " + f"not integer (frac = {frac:.6f})" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": frac, + "normalizer": normalizer, + "ratio": frac / normalizer, + }) + + # 2d: Complete follower witness objective consistency. The checker does + # not run an optimizer; benchmark quality is evaluated from the submitted + # complete solution and its reported objectives. + if follower_feasible: + computed = float(d2 @ y) + reported_follower = float(sol.get("follower_objective_value", computed)) + gap = abs(reported_follower - computed) + if gap > tol: + violated_set.add(2) + normalizer = max(abs(computed), eps) + violations.append( + f"Follower objective mismatch: reported={reported_follower:.6f}, " + f"d2*y={computed:.6f}" + ) + violation_magnitudes.append({ + "constraint": 2, "lhs": reported_follower, "rhs": computed, + "raw_excess": gap, "normalizer": normalizer, + "ratio": gap / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 3 (14d): x in H^x (x >= 0, all integer) + # ------------------------------------------------------------------ + + # 3a: x >= 0 + for k in range(n1): + if x[k] < -tol: + violated_set.add(3) + lhs_val = float(x[k]) + rhs_val = 0.0 + excess = -lhs_val + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Leader non-negativity: x[{k+1}] = {lhs_val:.6f} < 0" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": excess, + "normalizer": normalizer, + "ratio": excess / normalizer, + }) + + # 3b: All leader variables must be integer (Assumption 3) + for k in range(n1): + frac = abs(x[k] - round(x[k])) + if frac > tol: + violated_set.add(3) + lhs_val = float(x[k]) + rhs_val = float(round(x[k])) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Leader integrality: x[{k+1}] = {x[k]:.6f} " + f"not integer (frac = {frac:.6f})" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": frac, + "normalizer": normalizer, + "ratio": frac / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 4: Objective consistency (Tier C anti-gaming defense) + # + # The reported objective_value must equal the recomputed leader + # objective phi^l(x, y) = c*x + d1*y of (14a). d1 (the leader's + # coefficients on the follower variables) is explicitly fixed to zero + # by the released BMILP instance contract. + # + # This catches LLM-evolved candidates that pass every constraint + # above but lie about objective_value (e.g. report 0 or + # sys.float_info.max) to game the eval score. + # ------------------------------------------------------------------ + c = np.array(data["c"], dtype=float) + if data.get("leader_follower_objective_coefficients_fixed_zero") is not True: + violations.append("instance contract does not explicitly fix d1=0") + violated_set.add(4) + d1 = np.zeros(n2, dtype=float) + 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: + true_obj = float(c @ x + d1 @ y) + # 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) + is_violation = abs_diff > obj_tol + else: + # non-finite reported value (inf / nan) is always a lie + abs_diff = abs(true_obj) + 1.0 # finite sentinel for reporting + is_violation = True + if is_violation: + violated_set.add(4) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Objective consistency: reported objective_value = " + f"{reported} differs from recomputed leader objective " + f"c*x + d1*y = {true_obj:.6f} " + f"(|diff| = {abs_diff:.6f} > tol = {obj_tol:.6f})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": reported if math.isfinite(reported) else true_obj, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + # ------------------------------------------------------------------ + # Build and write result + # ------------------------------------------------------------------ + violated_constraints = sorted(violated_set) + result = { + "feasible": len(violated_constraints) == 0, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + 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/lozano2017/gurobi_code.py b/tasks/lozano2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..7b835f8e999b8ccea101547fff6b7b2b87e6d625 --- /dev/null +++ b/tasks/lozano2017/gurobi_code.py @@ -0,0 +1,355 @@ +""" +Gurobi implementation of Algorithm 1 (REHPP-based sampling) for the +Bilevel Mixed-Integer Linear Program (BMILP) from: + + Lozano & Smith (2017), "A Value-Function-Based Exact Approach for the + Bilevel Mixed-Integer Programming Problem", Operations Research. + +Mathematical model: EHPP / REHPP formulation (Equations 10a-10e). +Solver: Gurobi. + +BENCHMARK SPECIALIZATION: The leader objective coefficient vector d^1 is fixed +to zero and recorded by an explicit instance flag (the leader values only +x-variables). This is consistent +with the BMILP testbed where only 'c' and 'd2' are provided. + +ASSUMPTION (not specified in paper): Variable upper bounds are set to +2 * max(b^1, b^2), since the paper states variables are bounded but does not +give explicit bound values for the BMILP testbed. +""" + +import json +import argparse +import time +import numpy as np +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 + + +def load_instance(path): + with open(path) as f: + return json.load(f) + + +def get_var_ub(data): + """Compute a uniform upper bound for all variables (x and y). + Valid since all constraint coefficients >= 0, so each variable is + bounded by max(b1, b2) / min_nonzero_coeff <= 2*max(b1,b2).""" + b1 = np.array(data['b1']) + b2 = np.array(data['b2']) + return float(2.0 * max(np.max(b1), np.max(b2))) + + +def compute_lf(data, ub): + """l^f = min d2*y over joint feasible region Omega (LP relaxation). + Used to compute M^2 values (Table D.2 in paper).""" + n1, n2, m1, m2 = data['n1'], data['n2'], data['m1'], data['m2'] + A1 = np.array(data['A1']) + B1 = np.array(data['B1']) + b1 = np.array(data['b1']) + A2 = np.array(data['A2']) + B2 = np.array(data['B2']) + b2 = np.array(data['b2']) + d2 = np.array(data['d2']) + + mdl = gp.Model() + mdl.setParam("Threads", 1) + mdl.setParam('OutputFlag', 0) + x = [mdl.addVar(lb=0.0, ub=ub) for _ in range(n1)] + y = [mdl.addVar(lb=0.0, ub=ub) for _ in range(n2)] + for i in range(m1): + mdl.addConstr( + gp.quicksum(A1[i, k] * x[k] for k in range(n1)) + + gp.quicksum(B1[i, k] * y[k] for k in range(n2)) <= b1[i]) + for i in range(m2): + mdl.addConstr( + gp.quicksum(A2[i, k] * x[k] for k in range(n1)) + + gp.quicksum(B2[i, k] * y[k] for k in range(n2)) <= b2[i]) + mdl.setObjective(gp.quicksum(d2[k] * y[k] for k in range(n2)), GRB.MINIMIZE) + mdl.optimize() + return mdl.ObjVal if mdl.status == GRB.OPTIMAL else -1e9 + + +def solve_follower(x_val, data, ub, time_remaining=None): + """Solve follower's problem: max d2*y s.t. A2*x + B2*y <= b2, y in H^y. + Returns (y_val, obj_val) or (None, None).""" + n2, m2 = data['n2'], data['m2'] + A2 = np.array(data['A2']) + B2 = np.array(data['B2']) + b2 = np.array(data['b2']) + d2 = np.array(data['d2']) + integer_follower = set(data['integer_follower_vars']) # 1-indexed + + mdl = gp.Model() + mdl.setParam("Threads", 1) + mdl.setParam('OutputFlag', 0) + if time_remaining is not None: + mdl.setParam('TimeLimit', max(float(time_remaining), 1.0)) + + y = [] + for j in range(n2): + vtype = GRB.INTEGER if (j + 1) in integer_follower else GRB.CONTINUOUS + y.append(mdl.addVar(lb=0.0, ub=ub, vtype=vtype)) + + rhs = b2 - A2 @ x_val + for i in range(m2): + mdl.addConstr(gp.quicksum(B2[i, k] * y[k] for k in range(n2)) <= rhs[i]) + mdl.setObjective(gp.quicksum(d2[k] * y[k] for k in range(n2)), GRB.MAXIMIZE) + mdl.optimize() + + if mdl.SolCount > 0: + return np.array([y[k].X for k in range(n2)]), float(mdl.ObjVal) + return None, None + + +def compute_gamma(y_hat, data): + """gamma_{y_hat,j} = floor(b2_j - B2_j * y_hat) + 1 (Proposition 2). + The leader blocks y_hat via constraint j iff [A2*x]_j >= gamma_{y_hat,j}.""" + B2 = np.array(data['B2']) + b2 = np.array(data['b2']) + return (np.floor(b2 - B2 @ y_hat) + 1).astype(int) + + +def solve_rehpp(Y_hat, data, lf, ub, time_remaining=None): + """Solve REHPP(Y_hat): relaxed EHPP over sample Y_hat (Equations 10a-10e). + + With M^1_j = 0 (valid since A^2*x >= 0 for non-negative x, A^2; Table D.2): + Constraint (10b): [A2*x]_j >= sum_{y_hat} gamma_{y_hat,j} * w_{y_hat,j} + Constraint (10c): d2*y >= d2*y_hat - M2_{y_hat} * sum_{B(y_hat)} w + + M^2_{y_hat} = d2*y_hat - l^f (Table D.2) + + Returns (x_val, y_val, obj_val, status_str). + """ + n1, n2, m1, m2 = data['n1'], data['n2'], data['m1'], data['m2'] + c = np.array(data['c']) + if data.get('leader_follower_objective_coefficients_fixed_zero') is not True: + raise ValueError('released Lozano 2017 instances must explicitly fix d1=0') + d1 = np.zeros(n2) + d2 = np.array(data['d2']) + A1 = np.array(data['A1']) + B1 = np.array(data['B1']) + b1 = np.array(data['b1']) + A2 = np.array(data['A2']) + B2 = np.array(data['B2']) + b2 = np.array(data['b2']) + integer_follower = set(data['integer_follower_vars']) + + K = len(Y_hat) + gammas = [compute_gamma(yh, data) for yh in Y_hat] + # M^2_{y_hat} = max(d2*y_hat - l^f, 0) + epsilon for numerical stability + M2 = [max(float(d2 @ yh) - lf, 0.0) + 1.0 for yh in Y_hat] + + mdl = gp.Model() + mdl.setParam("Threads", 1) + mdl.setParam('OutputFlag', 0) + if time_remaining is not None: + mdl.setParam('TimeLimit', max(float(time_remaining), 1.0)) + + # Leader variables: all integer (Assumption 3) + x = [mdl.addVar(lb=0.0, ub=ub, vtype=GRB.INTEGER) for _ in range(n1)] + # Follower variables: partially integer + y = [] + for j in range(n2): + vtype = GRB.INTEGER if (j + 1) in integer_follower else GRB.CONTINUOUS + y.append(mdl.addVar(lb=0.0, ub=ub, vtype=vtype)) + + # Binary w_{y_hat, j} for each y_hat in Y_hat, constraint j + w = [[mdl.addVar(vtype=GRB.BINARY) for _ in range(m2)] for _ in range(K)] + + # Objective: max c*x + d1*y (14a) + mdl.setObjective( + gp.quicksum(c[k] * x[k] for k in range(n1)) + + gp.quicksum(d1[k] * y[k] for k in range(n2)), + GRB.MAXIMIZE) + + # Upper-level constraints: A1*x + B1*y <= b1 (14b) + for i in range(m1): + mdl.addConstr( + gp.quicksum(A1[i, k] * x[k] for k in range(n1)) + + gp.quicksum(B1[i, k] * y[k] for k in range(n2)) <= b1[i]) + + # Lower-level constraints: A2*x + B2*y <= b2 (part of Omega, 10d) + for i in range(m2): + mdl.addConstr( + gp.quicksum(A2[i, k] * x[k] for k in range(n1)) + + gp.quicksum(B2[i, k] * y[k] for k in range(n2)) <= b2[i]) + + if K > 0: + # Constraint (10b) with M1=0: [A2*x]_j >= sum_i gamma[i][j]*w[i][j] + for j in range(m2): + mdl.addConstr( + gp.quicksum(A2[j, k] * x[k] for k in range(n1)) >= + gp.quicksum(gammas[i][j] * w[i][j] for i in range(K))) + + # Constraint (10c): d2*y >= d2*y_hat - M2[i]*sum_{B(y_hat_i)} w + for i, yh in enumerate(Y_hat): + # B(y_hat_i, Y_hat) = {(ip, q) | gamma[ip][q] >= gamma[i][q]} + B_sum = gp.quicksum( + w[ip][q] + for ip in range(K) + for q in range(m2) + if gammas[ip][q] >= gammas[i][q]) + mdl.addConstr( + gp.quicksum(d2[k] * y[k] for k in range(n2)) >= + float(d2 @ yh) - M2[i] * B_sum) + + mdl.optimize() + + if mdl.status == GRB.INFEASIBLE: + return None, None, None, 'infeasible' + if mdl.SolCount > 0: + x_val = np.array([x[k].X for k in range(n1)]) + y_val = np.array([y[k].X for k in range(n2)]) + status = 'optimal' if mdl.status == GRB.OPTIMAL else 'time_limit' + return x_val, y_val, float(mdl.ObjVal), status + return None, None, None, 'no_solution' + + +def main(): + parser = argparse.ArgumentParser( + description='Solve BMILP via REHPP-based Algorithm 1 (Lozano & Smith 2017)') + parser.add_argument('--instance_path', required=True, + help='Path to instance JSON file') + parser.add_argument('--solution_path', required=True, + help='Path to write solution JSON (e.g., gurobi_solution_1.json)') + 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) + start_time = time.time() + + ub = get_var_ub(data) + lf = compute_lf(data, ub) + + n2 = data['n2'] + d2 = np.array(data['d2']) + c = np.array(data['c']) + if data.get('leader_follower_objective_coefficients_fixed_zero') is not True: + raise ValueError('released Lozano 2017 instances must explicitly fix d1=0') + d1 = np.zeros(n2) + A1 = np.array(data['A1']) + B1 = np.array(data['B1']) + b1 = np.array(data['b1']) + + # Algorithm 1 (Section 2.3) + UB = float('inf') + LB = float('-inf') + Y_hat = [] # REHPP with empty Y_hat = HPP (first iteration) + best_x = None + best_y = None + best_obj = None + iteration = 0 + status_str = 'running' + + while UB > LB + 1e-8: + elapsed = time.time() - start_time + remaining = args.time_limit - elapsed + if remaining <= 0: + status_str = 'time_limit' + break + + iteration += 1 + + # Step 4-8: Solve REHPP(Y_hat^i) + x_val, y_val, obj_val, rehpp_status = solve_rehpp( + Y_hat, data, lf, ub, time_remaining=remaining) + + if rehpp_status == 'infeasible': + # Remark 3: original BMIP is infeasible + status_str = 'infeasible' + break + + if x_val is None: + # Time limit hit inside REHPP + status_str = 'time_limit' + break + + UB = obj_val + + elapsed = time.time() - start_time + remaining = args.time_limit - elapsed + if remaining <= 0: + status_str = 'time_limit' + break + + # Step 9: Obtain optimal follower response y_f in Psi(x^i) + yf, yf_obj = solve_follower(x_val, data, ub, time_remaining=remaining) + + if yf is None: + status_str = 'time_limit' + break + + # Step 10: Y_hat^{i+1} = Y_hat^i union {y_f^i} + Y_hat.append(yf) + + # Step 11: Check bilevel feasibility d2*y_i == d2*y_f + follower_obj_yi = float(d2 @ y_val) + if abs(follower_obj_yi - yf_obj) < 1e-6: + # Step 12: Bilevel feasible => update LB and incumbent + LB = UB + best_x = x_val.copy() + best_y = y_val.copy() + best_obj = UB + status_str = 'optimal' + else: + # Step 13: Check if x^i in X(y_f): A1*x^i + B1*y_f <= b1 + leader_obj_yf = float(c @ x_val + d1 @ yf) + in_X_yf = all( + float(A1[j] @ x_val + B1[j] @ yf) <= b1[j] + 1e-6 + for j in range(data['m1'])) + + if in_X_yf and leader_obj_yf > LB + 1e-8: + # Step 14: Update LB and incumbent + LB = leader_obj_yf + best_x = x_val.copy() + best_y = yf.copy() + best_obj = leader_obj_yf + status_str = 'incumbent_updated' + # Step 16: else LB unchanged + + elapsed = time.time() - start_time + if elapsed >= args.time_limit: + status_str = 'time_limit' + break + + # If no bilevel feasible solution found but UB is finite, return UB as best estimate + if best_obj is None: + if LB > float('-inf'): + best_obj = LB + elif UB < float('inf'): + best_obj = UB + + solution = { + 'objective_value': best_obj, + 'x': best_x.tolist() if best_x is not None else None, + 'y': best_y.tolist() if best_y is not None else None, + 'iterations': iteration, + 'status': status_str, + 'upper_bound': UB if UB < float('inf') else None, + 'lower_bound': LB if LB > float('-inf') else None, + } + + 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/lozano2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/lozano2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lozano2017/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/lozano2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/lozano2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lozano2017/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/lozano2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/lozano2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lozano2017/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/lozano2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/lozano2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lozano2017/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/lozano2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/lozano2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lozano2017/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/lozano2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/lozano2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/lozano2017/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/lozano2017/gurobi_solution/large_solution_1.json b/tasks/lozano2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..af4706ea896a30dfe40cdbea396e2b7492385ece --- /dev/null +++ b/tasks/lozano2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:931c821264922b98819a9caec361b46eff9f8b092b12d0e1beb170f92134a8d4 +size 45149 diff --git a/tasks/lozano2017/gurobi_solution/large_solution_2.json b/tasks/lozano2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7587300314f3b5f3395bab74e0460bb7541ee69f --- /dev/null +++ b/tasks/lozano2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:656092cda892c84e1e3be726c98fe25d762a35733f0a76e4439d052b7fb0d342 +size 44612 diff --git a/tasks/lozano2017/gurobi_solution/large_solution_3.json b/tasks/lozano2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e4bdb45bf6979ef2a2dc73015a2f899229b4547a --- /dev/null +++ b/tasks/lozano2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7baae14805dd5645db78a01727da2b00cf179d57fb764d59f9aa8666d5250817 +size 44805 diff --git a/tasks/lozano2017/gurobi_solution/large_solution_4.json b/tasks/lozano2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..86cef859caaa8b38144b4116a1aa7bf7941deb7f --- /dev/null +++ b/tasks/lozano2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:260a82df092452733896652b30ec0e300bd0e592106b187f6a2144ba33d35c5c +size 45610 diff --git a/tasks/lozano2017/gurobi_solution/large_solution_5.json b/tasks/lozano2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..66f9cbab3cf28af48910dfae4a9f8fc1051804eb --- /dev/null +++ b/tasks/lozano2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ad6e1c771b6ed73b800d332e74045fc0bcca810d27d559442860eb1e8c0cbd1 +size 46744 diff --git a/tasks/lozano2017/gurobi_solution/tiny_solution.json b/tasks/lozano2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..4d6bcb82f26f0bd99974edd0c91c571602c00244 --- /dev/null +++ b/tasks/lozano2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e36a6a177d526cc9352ac89beb2caa86f09d8215ce8c4cba0ffaf017332ffee +size 375 diff --git a/tasks/lozano2017/gurobi_solution_log/large_log_1.jsonl b/tasks/lozano2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b29cb17b2001b2206923fb3c1f05ef09ec3eb575 --- /dev/null +++ b/tasks/lozano2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13d0aba319085fd291d5dcc7f771abfea6bd4e01c543e2e1feb5d253b39ca957 +size 86 diff --git a/tasks/lozano2017/gurobi_solution_log/large_log_2.jsonl b/tasks/lozano2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e10f08324965acba055440e6f3da48c79f054615 --- /dev/null +++ b/tasks/lozano2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe6fb7ef12afa2c4e4d03f7228b1641460297523072fd4acb0957e7a1caf5494 +size 85 diff --git a/tasks/lozano2017/gurobi_solution_log/large_log_3.jsonl b/tasks/lozano2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..848f160722346acd0c8f4b6c83e9beea0c781cf8 --- /dev/null +++ b/tasks/lozano2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1ee84752acb5343a819a8ec74619b7c293ac739cea6814e85360fdf5fa77dca +size 85 diff --git a/tasks/lozano2017/gurobi_solution_log/large_log_4.jsonl b/tasks/lozano2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..391b556dd5213e10bfbadf951cd503afa3c61adb --- /dev/null +++ b/tasks/lozano2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03c32e7cba03180c95d2f57296a33420012342f5dfcdb311a52fccc828f3b988 +size 83 diff --git a/tasks/lozano2017/gurobi_solution_log/large_log_5.jsonl b/tasks/lozano2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d3463f7764b87f4aa4927103e7f441465e3fb741 --- /dev/null +++ b/tasks/lozano2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:caf5c6754f9097913ea60708c952e7da4fd7f5facc29a5ab7c97cbbbd498065c +size 84 diff --git a/tasks/lozano2017/gurobi_solution_log/tiny_log.jsonl b/tasks/lozano2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..26f910810efdcf6034bad297481492d8d74f12a4 --- /dev/null +++ b/tasks/lozano2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:276dda08574ce1417c5de12e079fa749ddbc73cf845b374d5698eb091ed6b682 +size 41 diff --git a/tasks/lozano2017/instance/large_instance_1.json b/tasks/lozano2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..73289d94c456ebfea1e1da797589faeb4008fd4d --- /dev/null +++ b/tasks/lozano2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfe3d9e2aa368d395d1cb0173296c0646bcdc9c0fa7f6241a5971b05db0f67e2 +size 78957155 diff --git a/tasks/lozano2017/instance/large_instance_2.json b/tasks/lozano2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6da93787ac207f688766f44d942a08948003e5a3 --- /dev/null +++ b/tasks/lozano2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ab08a840242033ece8d3ead8a31913a29dabfbaf13b0d4fda6c90fa4cd201f3 +size 78947000 diff --git a/tasks/lozano2017/instance/large_instance_3.json b/tasks/lozano2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..0effdd6ab9e551a6fef65f89bd0ff76bd87670ff --- /dev/null +++ b/tasks/lozano2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea8fc9f7afd46f07c58ee8d03d73e5a651dbdf3828fd3e595eec9fbe3b745020 +size 78951339 diff --git a/tasks/lozano2017/instance/large_instance_4.json b/tasks/lozano2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..810f7c36950adc5c595cec9b2be0fd5a16f8ed77 --- /dev/null +++ b/tasks/lozano2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a240338149683465f218e29f02bdafd56a236058b8afc8538bdb2120ec2351a +size 78963535 diff --git a/tasks/lozano2017/instance/large_instance_5.json b/tasks/lozano2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..57f4a34fc49bebbd192f3f479234a86ef308aa63 --- /dev/null +++ b/tasks/lozano2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab119e46df65144ad9b6a17f4162878db3ed06fbdae8899911383424bb750477 +size 78966535 diff --git a/tasks/lozano2017/instance/tiny_instance.json b/tasks/lozano2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..bea0625191649a38a8f259d48eb3b85547954742 --- /dev/null +++ b/tasks/lozano2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d257d974dca269b30f61996feae23d146b7bde860236214026657bc04e97f6d4 +size 2330 diff --git a/tasks/lozano2017/instance_schema.json b/tasks/lozano2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d1f88cc4540a3b2e3428a2a787d7420ed2b88490 --- /dev/null +++ b/tasks/lozano2017/instance_schema.json @@ -0,0 +1,19 @@ +{ + "n": " Total number of variables across both the leader and the follower.", + "n1": " Number of variables controlled by the leader.", + "n2": " Number of variables controlled by the follower.", + "m1": " Number of upper-level inequality constraints.", + "m2": " Number of lower-level inequality constraints.", + "all_leader_vars_integer": " Whether all leader variables are restricted to nonnegative integer values.", + "leader_follower_objective_coefficients_fixed_zero": " This released benchmark fixes every d1 coefficient on follower variables in the leader objective to zero.", + "num_integer_follower_vars": " Number of follower variables that are restricted to nonnegative integer values.", + "integer_follower_vars": " One-based indices identifying which follower variables must take nonnegative integer values.", + "c": " Leader's objective function coefficients applied to the leader's variables.", + "d2": " Follower's objective function coefficients applied only to the follower objective.", + "A1": " Upper-level constraint coefficients applied to the leader's variables.", + "B1": " Upper-level constraint coefficients applied to the follower's variables.", + "b1": " Right-hand side limits for the upper-level constraints.", + "A2": " Lower-level constraint coefficients applied to the leader's variables.", + "B2": " Lower-level constraint coefficients applied to the follower's variables.", + "b2": " Right-hand side limits for the lower-level constraints." +} diff --git a/tasks/lozano2017/mathematical_formulation.md b/tasks/lozano2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..1f8d3e7029b3efed9c44f35a2871dd20e8e9f146 --- /dev/null +++ b/tasks/lozano2017/mathematical_formulation.md @@ -0,0 +1,81 @@ +# Original Formulation: Bilevel Mixed-Integer Programming Problem (BMIP / BMILP) + +*Source*: Lozano & Smith (2017), “A Value-Function-Based Exact Approach for the Bilevel Mixed-Integer Programming Problem,” *Operations Research*. Equations (1a)–(1d) give the general BMIP; Equations (14a)–(14d) give the linear special case (BMILP). Both are transcribed below in bilevel form without KKT / value-function reformulation. + +## Sets, Indices, and Domains + +- $n_1$: number of leader variables; $n_2$: number of follower variables. + +- $m_1$: number of upper-level constraints; $m_2$: number of lower-level constraints. + +- $\mathcal{I} \subseteq \{1,\ldots,n_1\}$: indices of integer leader variables. + +- $\mathcal{J} \subseteq \{1,\ldots,n_2\}$: indices of integer follower variables. + +- $\mathcal{H}^x = \{\mathbf{x} \ge \mathbf{0} :\ x_i \in \mathbb{Z}, + \ \forall\, i \in \mathcal{I}\}$. + +- $\mathcal{H}^y = \{\mathbf{y} \ge \mathbf{0} :\ y_j \in \mathbb{Z}, + \ \forall\, j \in \mathcal{J}\}$. + +- Functions $\phi^l,\phi^f,g_j^k,h_j^k$ are continuous over $\mathcal{H}^x \times \mathcal{H}^y$ ($k=1,2$; $j=1,\ldots,m_k$). + +## Decision Variables + +- $\mathbf{x} \in \mathcal{H}^x$: leader (upper-level) decision vector. + +- $\mathbf{y} \in \mathcal{H}^y$: follower (lower-level) decision vector. + +## General BMIP (Equations 1a–1d) + +$$\begin{align} + z^{*} \;=\; \max_{\mathbf{x},\mathbf{y}}\; & \phi^l(\mathbf{x},\mathbf{y}) + \tag{1a}\\[2pt] + \text{s.t.}\quad + & g_j^1(\mathbf{x}) + h_j^1(\mathbf{y}) \;\le\; b_j^1, + \quad \forall\, j = 1,\ldots,m_1, + \tag{1b}\\[2pt] + & \mathbf{y} \;\in\; + \arg\max_{\mathbf{y}^f}\Bigl\{\; \phi^f(\mathbf{x},\mathbf{y}^f) \;\Big|\; + g_j^2(\mathbf{x}) + h_j^2(\mathbf{y}^f) \le b_j^2,\ + \forall\, j=1,\ldots,m_2;\; + \mathbf{y}^f \in \mathcal{H}^y \,\Bigr\}, + \tag{1c}\\[2pt] + & \mathbf{x} \;\in\; \mathcal{H}^x. + \tag{1d} +\end{align}$$ Equation (1c) encodes the optimistic assumption (the follower breaks ties in favor of the leader). + +## Linear Special Case: BMILP (Equations 14a–14d) + +Given conforming coefficient matrices and vectors $\mathbf{c},\mathbf{d}^1, +\mathbf{d}^2,\mathbf{A}^1,\mathbf{A}^2,\mathbf{B}^1,\mathbf{B}^2, +\mathbf{b}^1,\mathbf{b}^2$: $$\begin{align} + \max_{\mathbf{x},\mathbf{y}}\; + & \mathbf{c}\,\mathbf{x} + \mathbf{d}^1 \mathbf{y} + \tag{14a}\\[2pt] + \text{s.t.}\quad + & \mathbf{A}^1 \mathbf{x} + \mathbf{B}^1 \mathbf{y} \;\le\; \mathbf{b}^1, + \tag{14b}\\[2pt] + & \mathbf{y} \;\in\; + \arg\max_{\mathbf{y}^f}\Bigl\{\; \mathbf{d}^2 \mathbf{y}^f \;\Big|\; + \mathbf{A}^2 \mathbf{x} + \mathbf{B}^2 \mathbf{y}^f \;\le\; \mathbf{b}^2;\; + \mathbf{y}^f \in \mathcal{H}^y \,\Bigr\}, + \tag{14c}\\[2pt] + & \mathbf{x} \;\in\; \mathcal{H}^x. + \tag{14d} +\end{align}$$ + +## Released benchmark specialization + +For every bundled instance, $\mathbf{d}^1=\mathbf{0}$, so (14a) reduces to +$\max\;\mathbf{c}\mathbf{x}$. The instance flag +`leader_follower_objective_coefficients_fixed_zero=true` is part of the +contract. Entries of `integer_follower_vars` are one-based. + +## Assumptions (reproduction-critical) + +1. Both upper- and lower-level feasible regions are compact sets. + +2. $g_j^2(\mathbf{x})$ is integer-valued for all $\mathbf{x} \in \mathcal{H}^x$, $j = 1,\ldots,m_2$. + +3. All leader variables are integer-valued. diff --git a/tasks/lozano2017/problem_description.txt b/tasks/lozano2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c88edf9b0bbb3fb6fe4f0a1ce613eaf171934e17 --- /dev/null +++ b/tasks/lozano2017/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A bilevel mixed-integer linear program involves two sequential decision makers, called the leader and the follower, who each control a separate set of variables and pursue separate goals, but whose choices are coupled through shared conditions. The leader acts first by selecting values for its own set of variables, after which the follower observes the leader's choices and responds by selecting values for a second set of variables that maximize the follower's own goal, subject to conditions that depend on both players' variables. The leader must anticipate this rational response when making its decision. The total number of variables is split equally between the two players: the leader controls n1 variables and the follower controls n2 variables, where n1 equals n2. All leader variables take nonnegative integer values. A designated subset of the follower's variables, comprising half of them, must also take nonnegative integer values; the remaining follower variables take nonnegative real values. The specific indices identifying which follower variables are integer-restricted are given as part of the input. + +The input data specifies two sets of linear inequalities. The first set, called the upper-level conditions, consists of m1 inequalities, where m1 equals the integer part of four-tenths of n1. Each such inequality involves both leader and follower variables: a row of coefficients applied to the leader variables, a row of coefficients applied to the follower variables, and a right-hand side value. The second set, called the lower-level conditions, consists of m2 inequalities with the same structure, where m2 equals m1. The coefficient matrices for both levels have nonnegative integer entries drawn from zero to ten. The right-hand side values of the upper-level conditions are positive integers drawn from thirty to one hundred thirty, and the right-hand side values of the lower-level conditions are positive integers drawn from ten to one hundred ten. + +The leader's objective is to maximize a linear function of the leader's own variables. In this released benchmark profile, the coefficients d1 applied to follower variables in the general leader objective are explicitly fixed to zero; each instance records this convention with `leader_follower_objective_coefficients_fixed_zero=true`. The coefficients applied to the leader's variables are integers ranging from negative fifty to positive fifty. The follower's objective is to maximize a different linear function of the follower's variables only, with coefficients drawn as integers from negative fifty to positive fifty. The follower's objective does not depend on the leader's variables. Entries of `integer_follower_vars` use one-based indices. + +The interaction between the two players proceeds as follows. The leader selects values for its variables. Both the upper-level and lower-level conditions must be satisfied jointly by the leader's and follower's variable values. Given the leader's fixed choice, the follower selects variable values that maximize the follower's objective among all follower solutions satisfying the lower-level conditions (with the leader's variables treated as fixed parameters in those conditions). The leader must choose its variables so that, after the follower responds optimally, the upper-level conditions are also satisfied. Under the optimistic assumption, when the follower has multiple optimal solutions yielding the same follower objective value, the follower selects the one that is most favorable to the leader. + +The goal is to find the leader's variable values and the corresponding follower response that maximize the leader's objective, subject to all upper-level and lower-level conditions being satisfied and subject to the requirement that the follower's response is optimal for the follower's own problem given the leader's choice. diff --git a/tasks/lozano2017/solution_logger.py b/tasks/lozano2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/lozano2017/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/lozano2017/solution_schema.json b/tasks/lozano2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..dc2c052548b94c32920e2e4f837564b90683611d --- /dev/null +++ b/tasks/lozano2017/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Value of the leader's objective achieved by the chosen leader and follower variable values.", + "x": " Value chosen by the leader for each of its variables.", + "y": " Complete submitted follower response to the leader's choice.", + "follower_objective_value": " Value d2*y computed from the complete submitted follower vector." +} diff --git a/tasks/luo2017/feasibility_check.py b/tasks/luo2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc59e8e1a626fc3899dc68bb8de19c1090f86b5 --- /dev/null +++ b/tasks/luo2017/feasibility_check.py @@ -0,0 +1,741 @@ +""" +Feasibility checker for the Split-Delivery Vehicle Routing Problem with +Time Windows and Linear Weight-Related Cost (SDVRPTWL). + +Based on: Luo, Qin, Zhu, Lim (2017), Transportation Science 51(2):668-687. + +Checks constraints (2)-(9) from the arc-flow formulation in Section 3. + +This is the "_new" variant: identical to feasibility_check.py except that +it adds constraint 10 (objective consistency, Tier C defense) — recomputes +the reported objective from the routes/edge-loads and rejects when the +program's self-reported objective_value disagrees with the recomputation. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'routes') +_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_json(path): + with open(path) as f: + return json.load(f) + + +def build_problem(instance): + """Build problem data structures from instance JSON.""" + n = instance["num_customers"] + Q = instance["vehicle_capacity"] + a_cost = instance["cost_function"]["a"] + b_cost = instance["cost_function"]["b"] + depot = instance["depot"] + customers = instance["customers"] + dm = instance["distance_matrix"] + n1 = n + 1 # depot return vertex + + # Build extended distance matrix (n+2 vertices: 0..n, n+1) + nv = n + 2 + c = [[0.0] * nv for _ in range(nv)] + for i in range(n + 1): + for j in range(n + 1): + c[i][j] = dm[i][j] + c[i][n1] = dm[i][0] # n+1 is at depot location + for j in range(n + 1): + c[n1][j] = dm[0][j] + c[0][n1] = 0.0 + c[n1][n1] = 0.0 + + # Customer data + d = [0] * nv # demand + s = [0] * nv # service time + e = [0] * nv # earliest time + l = [0] * nv # latest time + + s[0] = depot["service_time"] + e[0] = depot["time_window"][0] + l[0] = depot["time_window"][1] + + for cu in customers: + i = cu["id"] + d[i] = cu["demand"] + s[i] = cu["service_time"] + e[i] = cu["time_window"][0] + l[i] = cu["time_window"][1] + + d[n1] = 0 + s[n1] = 0 + e[n1] = depot["time_window"][0] + l[n1] = depot["time_window"][1] + + return { + "n": n, "Q": Q, "a": a_cost, "b": b_cost, + "nv": nv, "n1": n1, + "c": c, "d": d, "s": s, "e": e, "l": l, + } + + +def parse_solution(solution, P): + """ + Parse solution JSON into a uniform structure. + Returns list of vehicle dicts, each with: + - route: list of vertex ids [0, ..., n+1] + - deliveries: dict {customer_id(int): quantity(float)} + - edges: list of (i, j, load_weight) if available, else None + """ + n = P["n"] + n1 = P["n1"] + vehicles = [] + + for r in solution.get("routes", []): + route = list(r["route"]) + # Remove duplicate depot at end (gurobi format sometimes has it) + while len(route) > 1 and route[-1] == route[-2]: + route.pop() + + deliveries = {} + for k, v in r.get("deliveries", {}).items(): + deliveries[int(k)] = float(v) + + # Parse edges if available (gurobi format) + edges = None + if "edges" in r: + edges = [] + for ed in r["edges"]: + edges.append((int(ed["from"]), int(ed["to"]), float(ed["load_weight"]))) + + vehicles.append({ + "route": route, + "deliveries": deliveries, + "edges": edges, + }) + + return vehicles + + +def compute_edge_loads(vehicle, P): + """ + Compute load on each edge for a vehicle. + This is a delivery problem: vehicle leaves depot loaded, load decreases. + Load on edge (i,j) = total remaining delivery after node i. + + For the first edge (0, first_customer), load = sum of all deliveries. + After delivering at node i, load decreases by delivery[i]. + """ + route = vehicle["route"] + deliveries = vehicle["deliveries"] + + # If explicit edges with loads are provided, use them + if vehicle["edges"] is not None: + return vehicle["edges"] + + # Otherwise compute from route and deliveries + # Total load leaving depot + total_load = sum(deliveries.values()) + edge_loads = [] + current_load = total_load + + for idx in range(len(route) - 1): + i = route[idx] + j = route[idx + 1] + edge_loads.append((i, j, current_load)) + # After arriving at j and delivering + if j in deliveries: + current_load -= deliveries[j] + + return edge_loads + + +def check_feasibility(instance, solution): + """ + Check all hard constraints (2)-(9) from the SDVRPTWL formulation, plus + constraint (10) — objective consistency (Tier C exploit defense). + """ + # large_31 had violation amount 2e-4 (delivered=49.9998 vs 50.0); MIP + # rounding artifacts on continuous flow vars can exceed 1e-4 -- relax to + # 1e-3 (still 0.002% relative for typical demand ~50). + tol = 1e-3 + eps = 1e-5 + + P = build_problem(instance) + vehicles = parse_solution(solution, P) + n = P["n"] + n1 = P["n1"] + Q = P["Q"] + c = P["c"] + d = P["d"] + s = P["s"] + e = P["e"] + l = P["l"] + a_cost = P["a"] + b_cost = P["b"] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + m = len(vehicles) # number of vehicles used + + # Pre-compute edge loads for all vehicles + all_edge_loads = [] + for k, veh in enumerate(vehicles): + all_edge_loads.append(compute_edge_loads(veh, P)) + + # ========================================================================= + # Constraint (2): Demand fulfillment + # sum_k (sum_{j in V^-(i)} w_{j,i,k} - sum_{j in V^+(i)} w_{i,j,k}) >= d_i + # For each customer i, the total delivered must be >= d_i. + # The LHS is the net flow into each customer = total delivered to customer i. + # ========================================================================= + for i in range(1, n + 1): + total_delivered = 0.0 + for k, veh in enumerate(vehicles): + total_delivered += veh["deliveries"].get(i, 0.0) + + lhs = total_delivered + rhs = float(d[i]) + violation_amount = rhs - lhs # >= constraint: violation when rhs > lhs + + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Constraint (2): Customer {i} demand not fulfilled: " + f"delivered={lhs:.4f}, required={rhs:.4f}" + ) + 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) SKIPPED: min-visits valid inequality + # `sum_k sum_{j in V^-(i)} x_{j,i,k} >= ceil(d_i / Q)` is a strengthening + # VI (the paper's math_model notes it is "redundant, strengthens LP + # relaxation"). Any feasible routing that fulfills customer demand + # satisfies this inequality automatically, so it is not checked. + # ========================================================================= + + # ========================================================================= + # Constraint (4): Each vehicle departs from depot (vertex 0) + # sum_{i in V_C ∪ {n+1}} x_{0,i,k} = 1 for each vehicle k + # Each vehicle's route must start at vertex 0 and have exactly one arc + # leaving vertex 0. + # ========================================================================= + for k, veh in enumerate(vehicles): + route = veh["route"] + # Count arcs leaving vertex 0 + departures_from_depot = 0 + for idx in range(len(route) - 1): + if route[idx] == 0: + departures_from_depot += 1 + + lhs = float(departures_from_depot) + rhs = 1.0 + violation_amount = abs(lhs - rhs) # = constraint + + if violation_amount > tol: + violated_constraints.add(4) + violations.append( + f"Constraint (4): Vehicle {k} has {departures_from_depot} " + f"departures from depot, expected 1" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (5): Flow conservation and single visit per vehicle + # sum_{j in V^+(i)} x_{i,j,k} = sum_{j in V^-(i)} x_{j,i,k} <= 1 + # For each vehicle k and customer i: + # (a) in-degree = out-degree (flow conservation) + # (b) in-degree <= 1 (visit at most once) + # ========================================================================= + for k, veh in enumerate(vehicles): + route = veh["route"] + for i in range(1, n + 1): + # Count arcs into and out of customer i for this vehicle + in_degree = 0 + out_degree = 0 + for idx in range(len(route) - 1): + if route[idx + 1] == i: + in_degree += 1 + if route[idx] == i: + out_degree += 1 + + # (5a) Flow conservation: out_degree = in_degree + lhs_a = float(out_degree) + rhs_a = float(in_degree) + violation_amount_a = abs(lhs_a - rhs_a) + + if violation_amount_a > tol: + violated_constraints.add(5) + violations.append( + f"Constraint (5): Vehicle {k}, customer {i}: " + f"out-degree={out_degree} != in-degree={in_degree} " + f"(flow conservation violated)" + ) + normalizer = max(abs(rhs_a), eps) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs_a, + "rhs": rhs_a, + "raw_excess": violation_amount_a, + "normalizer": normalizer, + "ratio": violation_amount_a / normalizer, + }) + + # (5b) in_degree <= 1 (each vehicle visits each customer at most once) + lhs_b = float(in_degree) + rhs_b = 1.0 + violation_amount_b = lhs_b - rhs_b # <= constraint + + if violation_amount_b > tol: + violated_constraints.add(5) + violations.append( + f"Constraint (5): Vehicle {k}, customer {i}: " + f"visited {in_degree} times, at most 1 allowed" + ) + normalizer = max(abs(rhs_b), eps) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs_b, + "rhs": rhs_b, + "raw_excess": violation_amount_b, + "normalizer": normalizer, + "ratio": violation_amount_b / normalizer, + }) + + # ========================================================================= + # Constraint (6): Each vehicle returns to depot (vertex n+1) + # sum_{i in V_C ∪ {0}} x_{i,n+1,k} = 1 for each vehicle k + # ========================================================================= + for k, veh in enumerate(vehicles): + route = veh["route"] + arrivals_at_depot = 0 + for idx in range(len(route) - 1): + if route[idx + 1] == n1: + arrivals_at_depot += 1 + + lhs = float(arrivals_at_depot) + rhs = 1.0 + violation_amount = abs(lhs - rhs) # = constraint + + if violation_amount > tol: + violated_constraints.add(6) + violations.append( + f"Constraint (6): Vehicle {k} has {arrivals_at_depot} " + f"arrivals at depot (n+1), expected 1" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (7): Vehicle capacity on each edge + # w_{i,j,k} <= Q * x_{i,j,k} + # For each edge traversed (x=1), load must be <= Q. + # For edges not traversed (x=0), load must be 0. + # ========================================================================= + for k, veh in enumerate(vehicles): + edge_loads = all_edge_loads[k] + for (i, j, w_ij) in edge_loads: + lhs = float(w_ij) + rhs = float(Q) # x_{i,j,k}=1 for traversed edges + violation_amount = lhs - rhs # <= constraint + + if violation_amount > tol: + violated_constraints.add(7) + violations.append( + f"Constraint (7): Vehicle {k}, edge ({i},{j}): " + f"load={w_ij:.4f} exceeds capacity Q={Q}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (8): Time window precedence (big-M) + # a_{j,k} >= a_{i,k} + s_i + t_{i,j} + M(x_{i,j,k} - 1) + # For traversed edges (x=1): a_{j,k} >= a_{i,k} + s_i + t_{i,j} + # i.e., arrival at j must be no earlier than departure from i + travel time. + # We check this by simulating the schedule along each route. + # ========================================================================= + for k, veh in enumerate(vehicles): + route = veh["route"] + if len(route) < 2: + continue + + # Simulate schedule + a_k = {} # service start times + t_cur = float(e[route[0]]) # start at depot earliest time + a_k[route[0]] = t_cur + + for idx in range(1, len(route)): + i = route[idx - 1] + j = route[idx] + t_ij = c[i][j] # travel time = distance + arrival = t_cur + s[i] + t_ij + start_j = max(float(e[j]), arrival) # wait if early + a_k[j] = start_j + + # Check: a_{j,k} >= a_{i,k} + s_i + t_{i,j} + # Which means arrival <= start_j (satisfied by max with e[j]) + # But start_j must also be <= l[j] (checked in constraint 9) + # The precedence itself: start_j >= a_k[i] + s[i] + t_ij + lhs = start_j + rhs_val = a_k[route[idx - 1]] + s[i] + t_ij + violation_amount = rhs_val - lhs # >= constraint (reversed: rhs > lhs means violation) + + if violation_amount > tol: + violated_constraints.add(8) + violations.append( + f"Constraint (8): Vehicle {k}, edge ({i},{j}): " + f"service start at {j} is {lhs:.4f}, but must be >= {rhs_val:.4f} " + f"(time precedence violated)" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 8, + "lhs": lhs, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + t_cur = start_j + + # ========================================================================= + # Constraint (9): Time window bounds + # e_i <= a_{i,k} <= l_i for each vehicle k, vertex i + # ========================================================================= + for k, veh in enumerate(vehicles): + route = veh["route"] + if len(route) < 2: + continue + + # Simulate schedule + t_cur = float(e[route[0]]) + for idx in range(len(route)): + vertex = route[idx] + if idx == 0: + a_ik = t_cur + else: + prev = route[idx - 1] + t_ij = c[prev][vertex] + arrival = t_cur + s[prev] + t_ij + a_ik = max(float(e[vertex]), arrival) + t_cur = a_ik + + # Check e_i <= a_{i,k} + lhs_lower = float(e[vertex]) + rhs_lower = a_ik + violation_lower = lhs_lower - rhs_lower # e_i <= a_ik means violation if e_i > a_ik + + if violation_lower > tol: + violated_constraints.add(9) + violations.append( + f"Constraint (9): Vehicle {k}, vertex {vertex}: " + f"service start {a_ik:.4f} < earliest time {e[vertex]}" + ) + normalizer = max(abs(lhs_lower), eps) + violation_magnitudes.append({ + "constraint": 9, + "lhs": rhs_lower, + "rhs": lhs_lower, + "raw_excess": violation_lower, + "normalizer": normalizer, + "ratio": violation_lower / normalizer, + }) + + # Check a_{i,k} <= l_i + lhs_upper = a_ik + rhs_upper = float(l[vertex]) + violation_upper = lhs_upper - rhs_upper # <= constraint + + if violation_upper > tol: + violated_constraints.add(9) + violations.append( + f"Constraint (9): Vehicle {k}, vertex {vertex}: " + f"service start {a_ik:.4f} > latest time {l[vertex]}" + ) + normalizer = max(abs(rhs_upper), eps) + violation_magnitudes.append({ + "constraint": 9, + "lhs": lhs_upper, + "rhs": rhs_upper, + "raw_excess": violation_upper, + "normalizer": normalizer, + "ratio": violation_upper / normalizer, + }) + + # ========================================================================= + # Constraint (10): Objective consistency (Tier C exploit defense). + # Recompute the obj (Eq. 1) from the solution variables and reject when + # the reported value disagrees. All variables the obj depends on + # (x_{i,j,k} via the traversed edges, w_{i,j,k} via load_weight) are + # carried in the solution, so a full recompute is exact. + # + # obj = sum_k sum_{(i,j) traversed by k} c_{i,j} * (a * w_{i,j,k} + b) + # ========================================================================= + 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 and not (math.isnan(reported) or math.isinf(reported)): + true_obj = 0.0 + for k, veh in enumerate(vehicles): + for (i, j, w_ij) in all_edge_loads[k]: + true_obj += c[i][j] * (a_cost * float(w_ij) + b_cost) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor; Gurobi obj + # for large instances is ~1e4-1e5 so this is far tighter than + # any meaningful exploit gap (LLM exploits return 0, 1.8e308, + # or 1e6 x truth -- all >> 0.1%). + tol_obj = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + violated_constraints.add(10) + violations.append( + f"Constraint (10): Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed sum c_ij*(a*w_ijk + b*x_ijk)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol_obj:.6g})" + ) + 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, + }) + elif reported is not None: + # NaN / Inf reported obj -- always a lie since the true obj is + # bounded by sum |c_ij| * (a*Q + b) over all edges. Treat as + # objective-consistency violation. + violated_constraints.add(10) + violations.append( + f"Constraint (10): Objective consistency violated: " + f"reported objective_value={reported_obj} is NaN or Inf" + ) + violation_magnitudes.append({ + "constraint": 10, + "lhs": reported, + "rhs": 0.0, + "raw_excess": float("inf"), + "normalizer": eps, + "ratio": float("inf"), + }) + + # Build result + 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 SDVRPTWL (Luo et al. 2017)" + ) + 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 to the candidate solution JSON file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the feasibility result JSON file") + 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"Result: {status}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["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/luo2017/gurobi_code.py b/tasks/luo2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c860caea9cfa627a8e8090e12c3a8a66a8ee1beb --- /dev/null +++ b/tasks/luo2017/gurobi_code.py @@ -0,0 +1,418 @@ +""" +Gurobi MIP implementation for the Split-Delivery Vehicle Routing Problem +with Time Windows and Linear Weight-Related Cost (SDVRPTWL). + +Arc-flow formulation from Luo, Qin, Zhu, and Lim (2017), +"Branch and Price and Cut for the Split-Delivery Vehicle Routing Problem +with Time Windows and Linear Weight-Related Cost," +Transportation Science, 51(2):668-687. + +Formulation: Equations (1)-(9) from the paper (Section 3). +""" + +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 + + +def load_instance(instance_path): + """Load the JSON instance 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 SDVRPTWL arc-flow MIP model using Gurobi. + + The model follows the formulation in Section 3 of Luo et al. (2017): + min sum_{k} sum_{i} sum_{j in V+(i)} c_{i,j} * (a * w_{i,j,k} + b * x_{i,j,k}) (1) + s.t. Constraints (2)-(9) + """ + # ---- Extract data ---- + n = data["num_customers"] + Q = data["vehicle_capacity"] + a_cost = data["cost_function"]["a"] + b_cost = data["cost_function"]["b"] + + depot = data["depot"] + customers = data["customers"] + dist = data["distance_matrix"] # (n+1) x (n+1), indices 0..n (0 = depot, 1..n = customers) + + # The distance matrix in the JSON is (n+1) x (n+1) for vertices 0..n. + # In the model, vertex 0 = depot exit, vertex n+1 = depot entrance. + # We create an extended distance matrix for n+2 vertices (0..n+1). + num_vertices = n + 2 # 0, 1, ..., n, n+1 + + # Build extended distance/time matrix + # dist[0] is depot, dist[1..n] are customers + # Vertex n+1 (depot entrance) has same location as vertex 0 + c = {} + t_travel = {} + for i in range(n + 1): + for j in range(n + 1): + if i != j: + c[i, j] = dist[i][j] + t_travel[i, j] = dist[i][j] # travel time = distance per instance spec + + # Add edges to/from vertex n+1 (same distances as vertex 0) + for j in range(1, n + 1): + c[j, n + 1] = dist[j][0] + t_travel[j, n + 1] = dist[j][0] + c[0, n + 1] = 0.0 # depot to depot + t_travel[0, n + 1] = 0.0 + # Edges from n+1 are not needed (n+1 is only an entrance) + + # ---- Vertex parameters ---- + demand = [0] * num_vertices + service = [0] * num_vertices + early = [0] * num_vertices + late = [0] * num_vertices + + # Depot exit (vertex 0) + demand[0] = 0 # d_0 = +inf conceptually, but not used in constraints + service[0] = depot["service_time"] + early[0] = depot["time_window"][0] + late[0] = depot["time_window"][1] + + # Customers (vertices 1..n) + for cust in customers: + idx = cust["id"] + demand[idx] = cust["demand"] + service[idx] = cust["service_time"] + early[idx] = cust["time_window"][0] + late[idx] = cust["time_window"][1] + + # Depot entrance (vertex n+1) + demand[n + 1] = 0 + service[n + 1] = 0 + early[n + 1] = depot["time_window"][0] + late[n + 1] = depot["time_window"][1] + + # ---- Compute V+(i) and V-(i) ---- + # V+(i) = {j in V : e_i + s_i + t_{i,j} <= l_j, (i,j) in E} + # E = {(i,j) | i,j in V, i != j, i != n+1, j != 0} + V_plus = {i: [] for i in range(num_vertices)} + V_minus = {i: [] for i in range(num_vertices)} + + for i in range(num_vertices): + if i == n + 1: + continue # no outgoing edges from n+1 + for j in range(num_vertices): + if j == 0: + continue # no incoming edges to 0 + if i == j: + continue + if (i, j) not in t_travel: + continue + if early[i] + service[i] + t_travel[i, j] <= late[j]: + V_plus[i].append(j) + V_minus[j].append(i) + + # ---- Number of vehicles ---- + # Paper says unlimited. We set m = sum of ceil(d_i / Q) as upper bound. + # INFERRED ASSUMPTION: m is set as the sum of ceil(d_i/Q) for all customers, + # which is an upper bound on the number of vehicles needed. + m = sum(math.ceil(demand[i] / Q) for i in range(1, n + 1)) + m = max(m, n) # ensure at least n vehicles available + K = list(range(m)) + + # ---- Big-M ---- + # NOT SPECIFIED IN PAPER: Big-M value. + # Standard choice: M >= max_{(i,j)} (l_i + s_i + t_{i,j} - e_j) + big_M = 0 + for i in range(num_vertices): + if i == n + 1: + continue + for j in V_plus[i]: + val = late[i] + service[i] + t_travel[i, j] - early[j] + if val > big_M: + big_M = val + big_M = big_M + 1 # add small buffer + + # ---- Build Gurobi model ---- + model = gp.Model("SDVRPTWL") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i,j,k] binary: vehicle k traverses edge (i,j) + x = {} + # w[i,j,k] >= 0: load weight of vehicle k on edge (i,j) + w = {} + # arr[i,k] >= 0: service starting time of vehicle k at vertex i + arr = {} + + # Only create variables for valid edges (i in V_C union {0}, j in V+(i)) + for k in K: + for i in range(num_vertices): + if i == n + 1: + continue # no outgoing edges from n+1 + for j in V_plus[i]: + x[i, j, k] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}_{k}") + w[i, j, k] = model.addVar(lb=0, ub=Q, name=f"w_{i}_{j}_{k}") + + for k in K: + for i in range(num_vertices): + arr[i, k] = model.addVar(lb=early[i], ub=late[i], name=f"a_{i}_{k}") + + model.update() + + # ---- Objective (1) ---- + # min sum_{k} sum_{i in V_C union {0}} sum_{j in V+(i)} c_{i,j} * (a * w_{i,j,k} + b * x_{i,j,k}) + obj = gp.LinExpr() + for k in K: + for i in range(num_vertices): + if i == n + 1: + continue + for j in V_plus[i]: + obj += c[i, j] * (a_cost * w[i, j, k] + b_cost * x[i, j, k]) + model.setObjective(obj, GRB.MINIMIZE) + + # ---- Constraint (2): Demand fulfillment ---- + for i in range(1, n + 1): + lhs = gp.LinExpr() + for k in K: + for j in V_minus[i]: + if (j, i, k) in w: + lhs += w[j, i, k] + for j in V_plus[i]: + if (i, j, k) in w: + lhs -= w[i, j, k] + model.addConstr(lhs >= demand[i], name=f"demand_{i}") + + # ---- Constraint (3): Minimum number of vehicles ---- + for i in range(1, n + 1): + lhs = gp.LinExpr() + for k in K: + for j in V_minus[i]: + if (j, i, k) in x: + lhs += x[j, i, k] + model.addConstr(lhs >= math.ceil(demand[i] / Q), name=f"min_vehicles_{i}") + + # ---- Constraint (4): Each vehicle departs from depot ---- + for k in K: + lhs = gp.LinExpr() + for j in V_plus[0]: + if (0, j, k) in x: + lhs += x[0, j, k] + model.addConstr(lhs == 1, name=f"depart_{k}") + + # ---- Constraint (5): Flow conservation ---- + for k in K: + for i in range(1, n + 1): + out_flow = gp.LinExpr() + in_flow = gp.LinExpr() + for j in V_plus[i]: + if (i, j, k) in x: + out_flow += x[i, j, k] + for j in V_minus[i]: + if (j, i, k) in x: + in_flow += x[j, i, k] + model.addConstr(out_flow == in_flow, name=f"flow_eq_{i}_{k}") + model.addConstr(out_flow <= 1, name=f"flow_le_{i}_{k}") + + # ---- Constraint (6): Each vehicle returns to depot ---- + for k in K: + lhs = gp.LinExpr() + for j in V_minus[n + 1]: + if (j, n + 1, k) in x: + lhs += x[j, n + 1, k] + model.addConstr(lhs == 1, name=f"return_{k}") + + # ---- Constraint (7): Capacity on each edge ---- + for k in K: + for i in range(num_vertices): + if i == n + 1: + continue + for j in V_plus[i]: + if (i, j, k) in w: + model.addConstr(w[i, j, k] <= Q * x[i, j, k], + name=f"cap_{i}_{j}_{k}") + + # ---- Constraint (8): Time window precedence ---- + for k in K: + for i in range(num_vertices): + if i == n + 1: + continue + for j in V_plus[i]: + if (i, j, k) in x: + model.addConstr( + arr[j, k] >= arr[i, k] + service[i] + t_travel[i, j] + + big_M * (x[i, j, k] - 1), + name=f"tw_{i}_{j}_{k}" + ) + + # ---- Constraint (9): Time window bounds ---- + # Already enforced by variable bounds (lb=e_i, ub=l_i) + + # ---- Symmetry breaking (optional, helps solver) ---- + # INFERRED ASSUMPTION: We add symmetry-breaking constraints to help + # the MIP solver since all vehicles are identical. Vehicles are ordered + # by their departure time from the depot. + for k in range(len(K) - 1): + model.addConstr(arr[0, K[k]] <= arr[0, K[k + 1]], + name=f"symbreak_{k}") + + # ---- Solve ---- + model.optimize() + + # ---- Extract solution ---- + result = { + "problem": "SDVRPTWL", + "solver": "Gurobi", + "status": model.Status, + "status_str": "", + } + + if model.Status == GRB.OPTIMAL: + result["status_str"] = "OPTIMAL" + elif model.Status == GRB.TIME_LIMIT: + result["status_str"] = "TIME_LIMIT" + elif model.Status == GRB.INFEASIBLE: + result["status_str"] = "INFEASIBLE" + result["objective_value"] = None + return result + else: + result["status_str"] = f"OTHER_{model.Status}" + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["gap"] = model.MIPGap + + # Extract routes + routes = [] + for k in K: + route_edges = [] + for i in range(num_vertices): + if i == n + 1: + continue + for j in V_plus[i]: + if (i, j, k) in x and x[i, j, k].X > 0.5: + route_edges.append({ + "from": i, + "to": j, + "load_weight": round(w[i, j, k].X, 6) if (i, j, k) in w else 0, + }) + + # Build ordered route from edges + if route_edges: + # Check if vehicle actually visits customers + visits_customer = any( + e["from"] in range(1, n + 1) or e["to"] in range(1, n + 1) + for e in route_edges + ) + if visits_customer: + # Reconstruct route sequence + edge_map = {e["from"]: e for e in route_edges} + route_seq = [] + deliveries = {} + current = 0 + visited = set() + while current is not None and current not in visited: + visited.add(current) + route_seq.append(current) + if current in edge_map: + nxt = edge_map[current]["to"] + current = nxt + else: + break + if current == n + 1: + route_seq.append(n + 1) + + # Compute deliveries: delta_i = sum w_{j,i,k} - sum w_{i,j,k} + for i in range(1, n + 1): + inflow = sum( + w[j, i, k].X for j in V_minus[i] + if (j, i, k) in w + ) + outflow = sum( + w[i, j, k].X for j in V_plus[i] + if (i, j, k) in w + ) + delta = inflow - outflow + if delta > 0.001: + deliveries[i] = round(delta, 6) + + if deliveries: + routes.append({ + "vehicle": k, + "route": route_seq, + "deliveries": deliveries, + "edges": route_edges + }) + + result["routes"] = routes + result["num_vehicles_used"] = len(routes) + else: + result["objective_value"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve SDVRPTWL using Gurobi MIP (arc-flow 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") + 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(f"Loading instance from: {args.instance_path}") + data = load_instance(args.instance_path) + + print(f"Problem: {data['problem']}") + print(f"Customers: {data['num_customers']}") + print(f"Capacity Q: {data['vehicle_capacity']}") + print(f"Cost function: f(w) = {data['cost_function']['a']}*w + {data['cost_function']['b']}") + print(f"Time limit: {args.time_limit} seconds") + + start_time = time.time() + result = build_and_solve(data, args.time_limit) + elapsed = time.time() - start_time + + result["computation_time_seconds"] = round(elapsed, 2) + + print(f"\nStatus: {result.get('status_str', 'UNKNOWN')}") + if result.get("objective_value") is not None: + print(f"Objective value: {result['objective_value']:.4f}") + print(f"Vehicles used: {result.get('num_vehicles_used', 'N/A')}") + print(f"Computation time: {elapsed:.2f}s") + + # Write solution + with open(args.solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2, default=str) + + print(f"Solution written to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/luo2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/luo2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/luo2017/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/luo2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/luo2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/luo2017/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/luo2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/luo2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/luo2017/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/luo2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/luo2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/luo2017/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/luo2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/luo2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/luo2017/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/luo2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/luo2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/luo2017/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/luo2017/gurobi_solution/large_solution_1.json b/tasks/luo2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..28411cee5fc2af4a5abc013893e739137dd62301 --- /dev/null +++ b/tasks/luo2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fab541ea8bb83adc4cb44cbdd259f9c5cba14475b2eb79c6393fdf8c1d8ee280 +size 6720 diff --git a/tasks/luo2017/gurobi_solution/large_solution_2.json b/tasks/luo2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..13fa758678f9bfd7e7776f2044ae89ffbf904e9b --- /dev/null +++ b/tasks/luo2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f411e20b885acaea94cb1bd09ff14b0ab3b68442d66764b0f81426bb168a9c42 +size 7727 diff --git a/tasks/luo2017/gurobi_solution/large_solution_3.json b/tasks/luo2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..00508ae59795772fb9e6feb23641073b8267fa87 --- /dev/null +++ b/tasks/luo2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85c81d853e3d0f5a59d4644d5f031c3021a02ceeada0f708789dd75a3a47fe06 +size 11724 diff --git a/tasks/luo2017/gurobi_solution/large_solution_4.json b/tasks/luo2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c02a1333df03d57b55701e4bd1f079c9816abc54 --- /dev/null +++ b/tasks/luo2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ed14b73c9ea6c7f3a59400f1a5497368d59af0de9545ef7916cbc2f10159e68 +size 7798 diff --git a/tasks/luo2017/gurobi_solution/large_solution_5.json b/tasks/luo2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e61f80b555a7727c07978d6c6a2c4557ce4955d5 --- /dev/null +++ b/tasks/luo2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c589a7835058aca0648da35e3ab06404ebd65dc5d56ae09b965a5f068b70653b +size 6749 diff --git a/tasks/luo2017/gurobi_solution/tiny_solution.json b/tasks/luo2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..e31807b30debf81211024421757e3f1b11bf1501 --- /dev/null +++ b/tasks/luo2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51d14325b3b4e370faf299cd352b2861a7e1a478118744378a95bed69e63bfa7 +size 5761 diff --git a/tasks/luo2017/gurobi_solution_log/large_log_1.jsonl b/tasks/luo2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57ce1c3a8f124a0ca848b91a641690dc48f0263b --- /dev/null +++ b/tasks/luo2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:669e483aff9858269aef3e7cfd25c98382240c36466888cc9d96c129814b9000 +size 530 diff --git a/tasks/luo2017/gurobi_solution_log/large_log_2.jsonl b/tasks/luo2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4635a9f6a26d9a75a71c089b3d9df35a29e9eb99 --- /dev/null +++ b/tasks/luo2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa70ad42ccf6d56306e538482194a00aa77ec3fdbbe28ca65b9400f132446bbf +size 359 diff --git a/tasks/luo2017/gurobi_solution_log/large_log_3.jsonl b/tasks/luo2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..61d958103f10a44c0ae69f85aed2c0acd611e70c --- /dev/null +++ b/tasks/luo2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f4d21caeedaf62e1d97695664fd0f585b1e608f136432a06d8a364d10b2935c +size 462 diff --git a/tasks/luo2017/gurobi_solution_log/large_log_4.jsonl b/tasks/luo2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..084eb1ce8f42b5df344a720c9058e38b39d5e59e --- /dev/null +++ b/tasks/luo2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6632495226c22ff701cca6ddc4a156ed83eaf673233b58d6ddd012ba3498107e +size 558 diff --git a/tasks/luo2017/gurobi_solution_log/large_log_5.jsonl b/tasks/luo2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c9c655c7bbee2dccb35a5c1baab1cf0a6e5a253c --- /dev/null +++ b/tasks/luo2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f65a894a7799125fbee83825cbb47c8551c3a7215468d73698b057b10811f21 +size 961 diff --git a/tasks/luo2017/gurobi_solution_log/tiny_log.jsonl b/tasks/luo2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..341eab347a24835f38f0b1a2b2a800fd94e3c1cd --- /dev/null +++ b/tasks/luo2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:825d9827c1ccac9b3dfa9074af862826914fe128fcafba370823c039f11ab74c +size 216 diff --git a/tasks/luo2017/instance/large_instance_1.json b/tasks/luo2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4d1b284dd8f4cea4b9b2f03e0629fc66764d14e5 --- /dev/null +++ b/tasks/luo2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbfba8686a1c5dcdc7ee7294a091d5e1bb41ba2b03615944ef233b23a189ac9b +size 20664 diff --git a/tasks/luo2017/instance/large_instance_2.json b/tasks/luo2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7de33930fe70890e82ba1c11528bd5d7b8fa3384 --- /dev/null +++ b/tasks/luo2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65a75fa24ebfefd3886274a30786f7ed230439125b0d1b99a804b3eefdc7b438 +size 20662 diff --git a/tasks/luo2017/instance/large_instance_3.json b/tasks/luo2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8dc78c40ffa1d34154ebd9b03337528871f9f68a --- /dev/null +++ b/tasks/luo2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2af94d3b22ce6591a85fd89fd144b982b725916ba342f0bcaa4c21ccee5147af +size 20640 diff --git a/tasks/luo2017/instance/large_instance_4.json b/tasks/luo2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ed8c414e84f1491816646c2e8261f7549e57171b --- /dev/null +++ b/tasks/luo2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fde930cb207690eedafa87314f0c95170a9e1bb9609399a4899bf0d78df6613 +size 20671 diff --git a/tasks/luo2017/instance/large_instance_5.json b/tasks/luo2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..dcc41834c6e52d55cecf4e8b8cfcc493ea377b56 --- /dev/null +++ b/tasks/luo2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cdc10385824ed8bbdaeb702d71f92f37bb2820e5e54f607174d393e59ef4929 +size 20635 diff --git a/tasks/luo2017/instance/tiny_instance.json b/tasks/luo2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..cdb70f159d37a0a5ab65d0b52314629074a34fb6 --- /dev/null +++ b/tasks/luo2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:916d59f43c1d4a625715125a7a738f79246857900ab374300b43fe6f256bb272 +size 14569 diff --git a/tasks/luo2017/instance_schema.json b/tasks/luo2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2279977e76caad2bd7873de6ba7acae9912fae2d --- /dev/null +++ b/tasks/luo2017/instance_schema.json @@ -0,0 +1,28 @@ +{ + "num_customers": " Number of customers to be served.", + "vehicle_capacity": " Maximum total weight each vehicle can carry.", + "scheduling_horizon": " Latest time by which all vehicles must return to the depot.", + "cost_function": { + "a": " Slope of the linear weight-related cost function applied to the load weight on each edge.", + "b": " Intercept of the linear weight-related cost function, representing the cost attributable to the vehicle's own curb weight." + }, + "depot": { + "id": " Index of the depot node in the distance matrix.", + "x": " Horizontal coordinate of the depot.", + "y": " Vertical coordinate of the depot.", + "time_window": " Earliest and latest time at which vehicles may depart from or return to the depot.", + "service_time": " Time spent at the depot for loading or unloading.", + "demand": " Delivery demand at the depot, always zero." + }, + "customers": [ + { + "id": " Unique index of the customer in the distance matrix.", + "x": " Horizontal coordinate of the customer location.", + "y": " Vertical coordinate of the customer location.", + "demand": " Total weight of goods that must be delivered to this customer.", + "time_window": " Earliest and latest time at which service may begin at this customer.", + "service_time": " Time a vehicle must spend at this customer per visit, regardless of delivery quantity." + } + ], + "distance_matrix": " Travel distance between each pair of locations, where row and column 0 is the depot and rows/columns 1 through num_customers are customers." +} diff --git a/tasks/luo2017/mathematical_formulation.md b/tasks/luo2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..6bc46ba28ea3debbba2834abab7ab7336a622fcf --- /dev/null +++ b/tasks/luo2017/mathematical_formulation.md @@ -0,0 +1,90 @@ +# Original Formulation: Split-Delivery VRP with Time Windows and Linear Weight-Related Cost (SDVRPTWL) — Arc-Flow Model + +*Source*: Luo, Qin, Zhu, Lim (2017), “Branch and Price and Cut for the Split-Delivery Vehicle Routing Problem with Time Windows and Linear Weight-Related Cost,” *Transportation Science*, Section 3 (arc-flow formulation). Equations (1)–(9). + +## Sets and Indices + +- $V = \{0,1,\ldots,n,n+1\}$: vertex set; vertex $0$ is the exit from the depot, vertex $n+1$ is the entrance to the depot. + +- $V_C = \{1,\ldots,n\}$: set of $n$ customers. + +- $E = \{(i,j) : i,j \in V,\ i \ne j,\ i \ne n+1,\ j \ne 0\}$: directed edge set. + +- $V^{+}(i) = \{j \in V : e_i + s_i + t_{i,j} \le l_j,\ (i,j) \in E\}$: immediate successors of $i$. + +- $V^{-}(i) = \{j \in V : e_j + s_j + t_{j,i} \le l_i,\ (j,i) \in E\}$: immediate predecessors of $i$. + +- $K = \{1,2,\ldots,m\}$: set of $m$ available (homogeneous) vehicles. + +## Parameters + +- $d_i$: weight demand of customer $i \in V_C$ ($d_0 = +\infty$, $d_{n+1} = 0$). + +- $s_i$: service time at vertex $i$ ($s_0 = s_{n+1} = 0$). + +- $[e_i, l_i]$: time window at vertex $i$ ($e_0=e_{n+1}=0$, $l_0=l_{n+1}=+\infty$). + +- $c_{i,j} \ge 0$: distance of edge $(i,j)$. + +- $t_{i,j} \ge 0$: travel time of edge $(i,j)$ (distances and travel times satisfy the triangle inequality). + +- $Q$: vehicle weight capacity (homogeneous fleet). + +- $M$: a sufficiently large positive constant (big-$M$). + +- $a,b$: parameters of the linear weight-related cost $f(w) = a w + b$. + +## Decision Variables + +- $x_{i,j,k} \in \{0,1\}$: $1$ if vehicle $k$ traverses edge $(i,j)$. + +- $w_{i,j,k} \ge 0$: load weight of vehicle $k$ on edge $(i,j)$. + +- $a_{i,k} \ge 0$: service-start time of vehicle $k$ at vertex $i$. + +## Objective + +$$\begin{equation} + \min \ \sum_{k \in K} + \sum_{i \in V_C \cup \{0\}} + \sum_{j \in V^{+}(i)} + c_{i,j}\,\bigl(a \cdot w_{i,j,k} + b \cdot x_{i,j,k}\bigr). + \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} + \sum_{k \in K} + \Bigl(\sum_{j \in V^{-}(i)} w_{j,i,k} \;-\; \sum_{j \in V^{+}(i)} w_{i,j,k}\Bigr) + &\;\ge\; d_i, + && \forall\, i \in V_C, \tag{2}\\[2pt] + \sum_{k \in K} \sum_{j \in V^{-}(i)} x_{j,i,k} + &\;\ge\; \lceil d_i / Q \rceil, + && \forall\, i \in V_C, \tag{3}\\[2pt] + \sum_{i \in V_C \cup \{n+1\}} x_{0,i,k} + &\;=\; 1, + && \forall\, k \in K, \tag{4}\\[2pt] + \sum_{j \in V^{+}(i)} x_{i,j,k} + \;=\; \sum_{j \in V^{-}(i)} x_{j,i,k} + &\;\le\; 1, + && \forall\, k \in K,\ i \in V_C, \tag{5}\\[2pt] + \sum_{i \in V_C \cup \{0\}} x_{i,n+1,k} + &\;=\; 1, + && \forall\, k \in K, \tag{6}\\[2pt] + w_{i,j,k} &\;\le\; Q\, x_{i,j,k}, + && \forall\, k \in K,\ i \in V_C \cup \{0\},\ j \in V^{+}(i), \tag{7}\\[2pt] + a_{j,k} &\;\ge\; a_{i,k} + s_i + t_{i,j} + M\bigl(x_{i,j,k} - 1\bigr), + && \forall\, k \in K,\ i \in V_C \cup \{0\},\ j \in V^{+}(i), \tag{8}\\[2pt] + e_i \;\le\; a_{i,k} &\;\le\; l_i, + && \forall\, k \in K,\ i \in V. \tag{9} +\end{align}$$ + +## Variable Domains + +$$\begin{equation*} + x_{i,j,k} \in \{0,1\},\qquad + w_{i,j,k} \ge 0,\qquad + a_{i,k} \ge 0, + \quad \forall\, k \in K,\ i \in V_C \cup \{0\},\ j \in V^{+}(i). +\end{equation*}$$ diff --git a/tasks/luo2017/problem_description.txt b/tasks/luo2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..180d8c466c163055ea0897ccb5fb9b11e6455e89 --- /dev/null +++ b/tasks/luo2017/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A delivery company operates a fleet of identical vehicles from a single depot to serve a set of customers. The depot and each customer occupy known locations in a plane, and every pair of locations has a given nonnegative travel distance and a given nonnegative travel time, both satisfying the triangle inequality. Each customer has a positive weight demand that must be delivered in full, a service time that is incurred once per vehicle visit regardless of the quantity delivered, and a time window defined by an earliest and a latest time at which service may begin. If a vehicle arrives at a customer before the earliest time, it must wait until that time to start service. The depot has its own time window within which all vehicle departures and returns must occur, and its service time is zero. + +An unlimited number of vehicles is available, each with the same weight capacity. A customer's demand may exceed the vehicle capacity, and in that case the demand must be split across multiple vehicles. More generally, any customer's demand may be fulfilled by deliveries from one or more vehicles, so split deliveries are permitted for every customer. Each vehicle departs the depot, visits a subset of customers along a route, delivers some quantity of goods at each visited customer, and returns to the depot. A vehicle may visit each customer at most once on its route. The total weight loaded onto a vehicle at the depot equals the sum of all deliveries it will make, and this total may not exceed the vehicle capacity. As the vehicle traverses its route the onboard load decreases with each delivery. + +The cost of traversing an edge between two locations depends on both the distance of that edge and the weight the vehicle is carrying on that edge. Specifically, the cost incurred on an edge equals the edge distance multiplied by a linear function of the vehicle's load weight on that edge: the function has the form of a slope parameter times the load weight plus an intercept parameter, where the intercept represents the cost attributable to the vehicle's own curb weight. The slope and intercept are given constants that apply uniformly to all vehicles and all edges. + +The planner must determine how many vehicles to dispatch, the route each vehicle follows from the depot through its assigned customers and back, the quantity each vehicle delivers to each customer it visits, and the service start time at each customer for each visiting vehicle. Every customer's full demand must be satisfied by the combined deliveries of all vehicles that visit it. The total quantity carried by any vehicle on any edge of its route must not exceed the vehicle capacity. For each customer visited by a vehicle, the difference between the total weight arriving at that customer across all incoming edges and the total weight leaving across all outgoing edges must account for the delivery made. For each vehicle, the number of times it arrives at any given customer equals the number of times it departs from that customer, and this count is at most one. Every vehicle must leave the depot exactly once and return to the depot exactly once. If a vehicle traverses an edge from one location to another, the service start time at the destination must be no earlier than the service start time at the origin plus the origin's service time plus the travel time of that edge. Service at every location must begin within that location's time window. + +The goal is to minimize the total transportation cost, which is the sum over all vehicles and all edges traversed of the edge distance times the linear weight-related cost evaluated at the vehicle's load weight on that edge. diff --git a/tasks/luo2017/solution_logger.py b/tasks/luo2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/luo2017/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/luo2017/solution_schema.json b/tasks/luo2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2de4fc575e77b5ace8b67e1e915da4555d08d61a --- /dev/null +++ b/tasks/luo2017/solution_schema.json @@ -0,0 +1,17 @@ +{ + "objective_value": " Total transportation cost summed over all vehicles and all traversed edges, equal to edge distance times the linear weight-related cost evaluated at the vehicle's load weight.", + "routes": [ + { + "vehicle": " Identifier of the dispatched vehicle that follows this route.", + "route": " Ordered sequence of nodes visited by this vehicle, starting at the depot exit, passing through the assigned customers in visit order, and ending at the depot entrance.", + "deliveries": " Quantity of goods this vehicle delivers to each customer it visits on this route.", + "edges": [ + { + "from": " Origin node of the traversed edge.", + "to": " Destination node of the traversed edge.", + "load_weight": " Weight of goods carried by this vehicle while traversing this edge from the origin to the destination." + } + ] + } + ] +} diff --git a/tasks/mansini2020/feasibility_check.py b/tasks/mansini2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..4470309eff384e1c74336645dee5bc663a522b83 --- /dev/null +++ b/tasks/mansini2020/feasibility_check.py @@ -0,0 +1,399 @@ +""" +Feasibility checker for the Multidimensional Multiple Choice Knapsack Problem (MMKP). + +Reference: Mansini and Zanotti (2020), "A Core-Based Exact Algorithm for the + Multidimensional Multiple Choice Knapsack Problem", + INFORMS Journal on Computing. + +Constraints (numbered top-to-bottom from the formulation): + Constraint 1 (eq 2): Resource capacity constraints + sum_{i,j} w_{ij}^k x_{ij} <= c_k, for each k = 1,...,m + Constraint 2 (eq 3): Multiple choice constraints + sum_j x_{ij} = 1, for each i = 1,...,n + Constraint 3 (eq 4): Binary domain + x_{ij} in {0, 1} + Constraint 4 (obj consistency): Reported objective_value must equal the + profit sum recomputed from the instance's true p_{ij} for each + selected (group_id, item_id) pair. Defends against LLM score-gaming + where the candidate solution returns a fabricated objective_value + while keeping the constraint variables feasible. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'selected_items') +_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 check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + n = instance["parameters"]["n_groups"] + m = instance["parameters"]["m_resources"] + capacities = instance["capacities"] + groups = instance["groups"] + + selected = solution["selected_items"] + + # Build lookup: group_id -> list of selected items + selected_by_group = {} + for item in selected: + gid = item["group_id"] + selected_by_group.setdefault(gid, []).append(item) + + # Build instance item lookup for binary domain check + instance_items = {} + for group in groups: + gid = group["group_id"] + for it in group["items"]: + instance_items[(gid, it["item_id"])] = it + + # ------------------------------------------------------------------ + # Constraint 1 (eq 2): Resource capacity constraints + # sum_{i,j} w_{ij}^k x_{ij} <= c_k, for k = 1,...,m + # ------------------------------------------------------------------ + constraint_1_msgs = [] + for k in range(m): + lhs = sum(item["weights"][k] for item in selected) + rhs = capacities[k] + violation_amount = max(0.0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(1) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + constraint_1_msgs.append( + f"Resource {k}: total weight {lhs} exceeds capacity {rhs}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + if constraint_1_msgs: + violations.append( + "Resource capacity violated: " + "; ".join(constraint_1_msgs) + ) + + # ------------------------------------------------------------------ + # Constraint 2 (eq 3): Multiple choice constraints + # sum_j x_{ij} = 1, for each i = 1,...,n + # ------------------------------------------------------------------ + constraint_2_msgs = [] + for i in range(n): + count = len(selected_by_group.get(i, [])) + lhs = float(count) + 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 count == 0: + constraint_2_msgs.append(f"Group {i}: no item selected") + else: + constraint_2_msgs.append( + f"Group {i}: {count} items selected instead of 1" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + if constraint_2_msgs: + violations.append( + "Multiple choice violated: " + "; ".join(constraint_2_msgs) + ) + + # ------------------------------------------------------------------ + # Constraint 3 (eq 4): Binary domain + # x_{ij} in {0, 1} + # Check that every selected item references a valid (group_id, item_id) + # in the instance. Since the solution format lists selected items + # explicitly (x=1), x values are inherently 0 or 1; we verify that + # the referenced items actually exist. + # ------------------------------------------------------------------ + constraint_3_msgs = [] + for item in selected: + gid = item["group_id"] + jid = item["item_id"] + if (gid, jid) not in instance_items: + violated_constraints.add(3) + lhs = 1.0 # solution sets x=1 for this item + rhs = 0.0 # but item doesn't exist, so valid domain is empty + violation_amount = 1.0 + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + constraint_3_msgs.append( + f"Item ({gid}, {jid}) does not exist in the instance" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + if constraint_3_msgs: + violations.append( + "Binary domain violated: " + "; ".join(constraint_3_msgs) + ) + + # ------------------------------------------------------------------ + # Constraint 4 (objective consistency, Tier C defense) + # reported objective_value must equal sum_{(i,j) selected} p_{ij} + # recomputed from the instance's true profits. Only fires when the + # prior constraints don't already render the comparison meaningless + # (skip if any selected item references an unknown (gid,jid), since + # we can't look up its true profit -- that case is already flagged + # by constraint 3). + # ------------------------------------------------------------------ + 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: + # Recompute using only items that exist in the instance. If any + # selected (gid,jid) is unknown, constraint 3 already fires; we + # still recompute over the known ones so the obj check remains + # useful for the common case where all items exist. + true_obj = 0.0 + unknown_in_selected = False + for item in selected: + key = (item["group_id"], item["item_id"]) + inst_item = instance_items.get(key) + if inst_item is None: + unknown_in_selected = True + continue + true_obj += float(inst_item["profit"]) + if not unknown_in_selected: + abs_diff = abs(reported - true_obj) + # Profits are integers; tighten tolerance so an integer + # mismatch by >=1 fires. Use absolute floor of 0.5 plus + # a 0.1% relative band for very large objectives. + tol_obj = max(0.5, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + violated_constraints.add(4) + normalizer = max(abs(true_obj), eps) + ratio = abs_diff / normalizer + violations.append( + f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum p_ij over selected items={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={tol_obj:.3g})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + 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 MMKP (Mansini & Zanotti, 2020)" + ) + 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() + + 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 + + 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"]: + 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/mansini2020/gurobi_code.py b/tasks/mansini2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..07b0612077ab905ac634516cf027a4de5a96b359 --- /dev/null +++ b/tasks/mansini2020/gurobi_code.py @@ -0,0 +1,151 @@ +""" +Gurobi MIP formulation for the Multidimensional Multiple Choice Knapsack Problem (MMKP). + +Reference: Mansini and Zanotti (2020), "A Core-Based Exact Algorithm for the + Multidimensional Multiple Choice Knapsack Problem", + INFORMS Journal on Computing. + +Model: + Maximize sum_{i,j} p_{ij} x_{ij} (1) + s.t. sum_{i,j} w_{ij}^k x_{ij} <= c_k, k=1..m (2) + sum_{j} x_{ij} = 1, i=1..n (3) + x_{ij} in {0,1} (4) +""" + +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(path): + with open(path, 'r') as f: + data = json.load(f) + return data + + +def solve_mmkp(instance_path, solution_path, time_limit): + data = load_instance(instance_path) + + n = data["parameters"]["n_groups"] + m = data["parameters"]["m_resources"] + capacities = data["capacities"] + groups = data["groups"] + + model = gp.Model("MMKP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + # Suppress output to keep solution clean; remove if verbose output desired + model.setParam("OutputFlag", 1) + + # Decision variables: x[i][j] binary + x = {} + for group in groups: + i = group["group_id"] + for item in group["items"]: + j = item["item_id"] + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + model.update() + + # Objective (1): maximize total profit + model.setObjective( + gp.quicksum( + item["profit"] * x[group["group_id"], item["item_id"]] + for group in groups + for item in group["items"] + ), + GRB.MAXIMIZE + ) + + # Constraints (2): resource capacity constraints + for k in range(m): + model.addConstr( + gp.quicksum( + item["weights"][k] * x[group["group_id"], item["item_id"]] + for group in groups + for item in group["items"] + ) <= capacities[k], + name=f"resource_{k}" + ) + + # Constraints (3): exactly one item per group + for group in groups: + i = group["group_id"] + model.addConstr( + gp.quicksum(x[i, item["item_id"]] for item in group["items"]) == 1, + name=f"choice_{i}" + ) + + # Solve + model.optimize() + + # Extract solution + result = {} + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = model.Status + result["mip_gap"] = model.MIPGap if model.Status != GRB.OPTIMAL else 0.0 + result["selected_items"] = [] + for group in groups: + i = group["group_id"] + for item in group["items"]: + j = item["item_id"] + if x[i, j].X > 0.5: + result["selected_items"].append({ + "group_id": i, + "item_id": j, + "profit": item["profit"], + "weights": item["weights"] + }) + break + else: + result["objective_value"] = None + result["status"] = model.Status + result["mip_gap"] = None + result["selected_items"] = [] + + 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']}") + else: + print("No feasible solution found.") + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi MIP solver for the MMKP (Mansini & Zanotti, 2020)" + ) + 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_mmkp(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/mansini2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/mansini2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mansini2020/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/mansini2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/mansini2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/mansini2020/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