diff --git a/tasks/bollapragada2001/instance_schema.json b/tasks/bollapragada2001/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a208ff13b3c73c9c94ac8411636ea6a806fdd953 --- /dev/null +++ b/tasks/bollapragada2001/instance_schema.json @@ -0,0 +1,71 @@ +{ + "structure_type": " Identifier for the truss topology used in this instance.", + "dimension": " Number of spatial dimensions of the truss (2 for planar, 3 for space trusses).", + "num_bars": " Total number of bars in the truss structure.", + "num_nodes": " Total number of nodes in the truss structure, including supports.", + "num_loading_conditions": " Number of independent external loading conditions the structure must withstand.", + "num_free_dofs": " Number of unconstrained nodal displacement directions across all free nodes.", + "num_linking_groups": " Number of groups of symmetrically located bars that must share the same cross-sectional area.", + "linking_groups": " Groups of bars required to receive identical cross-sectional areas due to structural symmetry.", + "nodes": [ + { + "node_id": " Unique identifier for this node.", + "x": " Horizontal coordinate of the node.", + "y": " Vertical coordinate of the node.", + "is_support": " Whether this node is a fixed support with no freedom of movement.", + "fixed_dofs": " Coordinate directions in which this support node is fixed (present only for support nodes)." + } + ], + "bars": [ + { + "bar_id": " Unique identifier for this bar.", + "node_i": " Node at the start end of the bar.", + "node_j": " Node at the finish end of the bar.", + "length": " Physical length of the bar computed from node coordinates.", + "direction_cosines": " Cosines of the angle between the bar's orientation and each coordinate axis." + } + ], + "degrees_of_freedom": [ + { + "dof_id": " Unique identifier for this degree of freedom.", + "node": " Node to which this degree of freedom belongs.", + "direction": " Coordinate direction of this degree of freedom." + } + ], + "material_properties": { + "modulus_of_elasticity": " Young's modulus of the bar material, relating stress to strain.", + "cost_density": " Cost per unit volume used to compute the total structural cost." + }, + "discrete_areas": " Candidate cross-sectional areas from which exactly one must be chosen for each bar.", + "num_discrete_areas": " Number of candidate cross-sectional areas available for selection.", + "stress_bounds": { + "lower": " Default minimum allowable stress in any bar (negative denotes compression).", + "upper": " Default maximum allowable stress in any bar (positive denotes tension)." + }, + "bar_specific_stress_bounds": [ + { + "bar_id": " Bar to which these stress limits apply.", + "lower": " Minimum allowable stress for this bar.", + "upper": " Maximum allowable stress for this bar." + } + ], + "displacement_bounds": { + "lower": " Minimum allowable nodal displacement at any free degree of freedom, or null if unbounded.", + "upper": " Maximum allowable nodal displacement at any free degree of freedom, or null if unbounded." + }, + "loading_conditions": [ + { + "load_id": " Unique identifier for this loading condition.", + "description": " Human-readable summary of the applied loads.", + "loads": [ + { + "node": " Node at which this external force is applied.", + "direction": " Coordinate direction of the applied force.", + "dof_id": " Degree of freedom at which the force acts.", + "force": " Magnitude and sign of the applied external force." + } + ] + } + ], + "expected_optimal_mass": " Known best objective value for this instance from the literature." +} diff --git a/tasks/bollapragada2001/mathematical_formulation.md b/tasks/bollapragada2001/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f60c9baeb9be4556f6603c822bcc24f92432c361 --- /dev/null +++ b/tasks/bollapragada2001/mathematical_formulation.md @@ -0,0 +1,68 @@ +# Original Formulation: Optimal Design of Truss Structures (Truss Design Problem) + +*Source: Optimal Design of Truss Structures by Logic-Based Branch and Cut, S. Bollapragada, O. Ghattas, and J. N. Hooker, 2001 (Operations Research 49(1):42–51).* + +## Sets and Indices + +$$\begin{align*} +& i = 1, \dots, I && \text{bars} \\ +& j = 1, \dots, J && \text{degrees of freedom (summed over all nodes)} \\ +& \ell = 1, \dots, L && \text{loading conditions} \\ +& k = 1, \dots, K_i && \text{discrete cross-sectional areas available for bar } i +\end{align*}$$ + +## Parameters + +$$\begin{align*} +& I && \text{number of bars} \\ +& J && \text{number of degrees of freedom (summed over all nodes)} \\ +& L && \text{number of loading conditions} \\ +& K_i && \text{number of discrete cross-sectional areas for bar } i \\ +& h_i && \text{length of bar } i \\ +& A_{ik} && k\text{-th discrete cross-sectional area of bar } i,\ \text{with } 0 \leqslant A_{i1} \leqslant \cdots \leqslant A_{iK_i} \\ +& E_i && \text{modulus of elasticity of bar } i \\ +& p_{j\ell} && \text{force imposed by load condition } \ell \text{ at degree of freedom } j \\ +& b_{ij} && \text{cosine of the angle between bar } i \text{ and degree of freedom } j \\ +& c_i && \text{cost per unit volume of bar } i \text{ (typically the weight density)} \\ +& \sigma_i^L,\ \sigma_i^U && \text{minimum and maximum allowable stress in bar } i \\ +& v_i^L,\ v_i^U && \text{limits on elongation (contraction if negative) of bar } i \\ +& d_j^L,\ d_j^U && \text{limits on displacement for degree of freedom } j +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +& A_i && \text{cross-sectional area of bar } i \\ +& s_{i\ell} && \text{force in bar } i \text{ due to loading condition } \ell \\ +& \sigma_{i\ell}&& \text{stress in bar } i \text{ due to loading condition } \ell \\ +& v_{i\ell} && \text{elongation (contraction if negative) of bar } i \text{ due to loading condition } \ell \\ +& d_{j\ell} && \text{node displacement along degree of freedom } j \text{ for loading condition } \ell +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad & \sum_{i=1}^{I} c_i h_i A_i \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.} \quad +& \sum_{i=1}^{I} b_{ij}\, s_{i\ell} = p_{j\ell}, && \forall\, j,\, \ell + && \text{(equilibrium equations)} \\ +& \sum_{j=1}^{J} b_{ij}\, d_{j\ell} = v_{i\ell}, && \forall\, i,\, \ell + && \text{(compatibility equations)} \\ +& \frac{E_i}{h_i}\, A_i\, v_{i\ell} = s_{i\ell}, && \forall\, i,\, \ell + && \text{(Hooke's law)} \\ +& \sigma_{i\ell} = \frac{E_i}{h_i}\, v_{i\ell}, && \forall\, i,\, \ell + && \text{(stress equations)} \\ +& v_i^L \leqslant v_{i\ell} \leqslant v_i^U, && \forall\, i,\, \ell + && \text{(elongation bounds)} \\ +& \sigma_i^L \leqslant \sigma_{i\ell} \leqslant \sigma_i^U, && \forall\, i,\, \ell + && \text{(stress bounds)} \\ +& d_j^L \leqslant d_{j\ell} \leqslant d_j^U, && \forall\, j,\, \ell + && \text{(displacement bounds)} \\ +& \bigvee_{k=1}^{K_i} \left( A_i = A_{ik} \right), && \forall\, i + && \text{(logical disjunction)} \tag{1} +\end{align}$$ diff --git a/tasks/bollapragada2001/problem_description.txt b/tasks/bollapragada2001/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..f17392a3502b870f63e2bfca6079637f0de01485 --- /dev/null +++ b/tasks/bollapragada2001/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A truss structure consists of a network of nodes connected by bars (structural members). The positions of the nodes and the topology of the network (which pairs of nodes are connected by bars) are given. Some nodes are fixed supports with no freedom of movement, while the remaining free nodes can displace along each coordinate direction, giving rise to a set of degrees of freedom across the structure. The structure must withstand one or more independent loading conditions, each of which specifies external forces applied at certain degrees of freedom. + +The input data for each problem instance includes the number of bars, the number of free degrees of freedom, and the number of loading conditions. For every bar, the data specifies its length, the modulus of elasticity of its material, and the direction cosines that relate the bar's orientation to each degree of freedom. Each bar also has a cost per unit volume (typically its weight density) and a list of discrete cross-sectional areas from which exactly one must be chosen; the smallest available area is a near-zero value (such as 0.01) representing the bar being effectively absent from the structure. For every loading condition, the data gives the external force applied at each degree of freedom. The data further specifies, for each bar, lower and upper bounds on allowable stress, and lower and upper bounds on allowable elongation (where negative elongation denotes contraction). For each degree of freedom, the data may specify lower and upper bounds on nodal displacement. In some instances, certain groups of symmetrically located bars are required to share the same cross-sectional area, and the data identifies which bars belong to each such linking group. + +The task is to select a discrete cross-sectional area for each bar and to determine, for each loading condition, the internal force in every bar, the elongation of every bar, and the displacement at every free degree of freedom. Exactly one discrete area must be chosen per bar, and if bars belong to a linking group they must all receive the same area selection. + +The choices must satisfy several physical laws and engineering limits. First, equilibrium must hold at every degree of freedom under every loading condition: the sum over all bars of the product of a bar's direction cosine for that degree of freedom and the bar's internal force must equal the external load applied at that degree of freedom. Second, compatibility must hold for every bar under every loading condition: the sum over all degrees of freedom of the product of the bar's direction cosine for that degree of freedom and the corresponding nodal displacement must equal the bar's elongation. Third, Hooke's law must be satisfied for every bar under every loading condition: the product of the bar's modulus of elasticity divided by its length, the bar's chosen cross-sectional area, and its elongation must equal the bar's internal force. The elongation of every bar under every loading condition must lie within its allowable elongation bounds, and the induced stress in the bar, equal to the modulus of elasticity divided by the bar length times the elongation, must lie within its allowable stress bounds. Nodal displacements at each degree of freedom under each loading condition must lie within their specified bounds when such bounds are provided. + +The goal is to minimize the total cost of the structure, computed as the sum over all bars of the product of the bar's cost per unit volume, its length, and its chosen cross-sectional area. diff --git a/tasks/bollapragada2001/solution_logger.py b/tasks/bollapragada2001/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/bollapragada2001/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/bollapragada2001/solution_schema.json b/tasks/bollapragada2001/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..85ea6a3c5cf39eb13cc93e3adb02bb17deb1caab --- /dev/null +++ b/tasks/bollapragada2001/solution_schema.json @@ -0,0 +1,24 @@ +{ + "objective_value": " Total cost of the truss structure, summing cost density times length times chosen area for every bar.", + "bar_areas": [ + { + "bar_id": " Bar to which this area assignment applies.", + "area": " Cross-sectional area selected for this bar from the discrete candidate set.", + "area_index": " Zero-based position of the selected area within the discrete candidate list." + } + ], + "displacements": [ + { + "dof_id": " Degree of freedom at which this displacement occurs.", + "load": " Loading condition under which this displacement occurs.", + "value": " Nodal displacement at this degree of freedom under this loading condition." + } + ], + "bar_forces": [ + { + "bar_id": " Bar in which this internal force acts.", + "load": " Loading condition under which this force occurs.", + "force": " Internal axial force in this bar under this loading condition (positive is tension, negative is compression)." + } + ] +} diff --git a/tasks/borndorfer2007/feasibility_check.py b/tasks/borndorfer2007/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2eb6bf6ed66cba993e1db2371737f149ea6c69 --- /dev/null +++ b/tasks/borndorfer2007/feasibility_check.py @@ -0,0 +1,958 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Line Planning Problem (LPP). + +Paper: "A Column-Generation Approach to Line Planning in Public Transport" +Authors: Borndoerfer, Groetschel, Pfetsch (2007), Transportation Science 41(1), pp. 123-132. + +Constraints (numbered top-to-bottom from the mathematical formulation): + (1) y(P_st) = d_st for all (s,t) in D + (2) y(P_a) - sum_{l: e(a) in l} kappa_l f_l <= 0 for all a in A + (3) f(L_e) <= Lambda_e for all e in E + (4) f_l <= F x_l for all l in L + (5) x_l in {0, 1} for all l in L + (6) f_l >= 0 for all l in L + (7) y_p >= 0 for all p in P + (8) [Tier C defense] objective_value reported by the program must be + consistent with the variables in the solution. Specifically: + obj_true = lambda * (sum_l C_l + sum_l f_l * sum_{e in l} c_e) + + (1 - lambda) * sum_a tau_a * y_a + The first term (line costs) is exactly recomputable from active_lines. + The second term (passenger travel time) is recomputed exactly when the + solution provides either `arc_total_flow` or `active_passenger_paths`. + When neither is provided (e.g. the Gurobi reference, which writes only + the line plan), we bracket the travel time with + lower = sum_{(s,t)} d_st * shortest_path_tt(s,t) (full graph, no cap) + upper = sum_a cap_a * tau_a (every arc full) + and require the reported objective to lie in [obj_lb, obj_ub] within + tolerance. + +Since the solution files store only the line plan (active lines with edges and +frequencies) but not individual passenger path flows, constraints (1), (2), and (7) +are verified by solving a feasibility LP that checks whether a valid passenger +routing exists given the line capacities. +""" + +import argparse +import heapq +import json +import sys +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ( + 'active_lines', + 'active_passenger_paths', + 'objective_value', +) +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ( + 'active_lines', + 'active_passenger_paths', +) +_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 + + +# Numerical tolerances. Gurobi default FeasibilityTol/IntFeasTol = 1e-6, +# but accumulated FP error on multi-thousand-arc instances can drift to ~1e-5. +# 1e-4 absolute floor + 1e-5 relative gives ~10x slack over solver default -- +# enough to absorb floating-point noise without masking real violations. +tol = 1e-4 +eps = 1e-5 +rel_tol = 1e-5 + + +def load_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def compute_violation(lhs, rhs, op): + """ + Compute violation_amount for a constraint. + op: 'le' (<=), 'ge' (>=), 'eq' (=) + """ + if op == 'le': + return max(0.0, lhs - rhs) + elif op == 'ge': + return max(0.0, rhs - lhs) + elif op == 'eq': + return abs(lhs - rhs) + return 0.0 + + +def record_violation(violations_list, magnitudes_list, constraint_idx, msg, lhs, rhs, op): + """Check and record a violation if violation_amount > tol (absolute or relative).""" + va = compute_violation(lhs, rhs, op) + threshold = max(tol, rel_tol * max(abs(lhs), abs(rhs))) + if va > threshold: + violations_list.append((constraint_idx, msg)) + normalizer = max(abs(rhs), eps) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + }) + return True + return False + + +def _shortest_path_demand_sum(edges_data, od_pairs): + """Lower bound on sum_p tau_p * y_p: each passenger takes the shortest + s-t path on the full undirected graph (capacity ignored). Since the actual + feasible set is a subset (passengers may only use arcs covered by active + lines and subject to capacity), the LP-optimal travel time is at least + this much.""" + adj = defaultdict(list) + for e in edges_data: + u, v = e["endpoints"] + tt_e = float(e["traveling_time_seconds"]) + adj[u].append((v, tt_e)) + adj[v].append((u, tt_e)) + od_by_origin = defaultdict(list) + for od in od_pairs: + od_by_origin[od["origin"]].append((od["destination"], float(od["demand"]))) + total = 0.0 + for s, dest_demand in od_by_origin.items(): + dist = {s: 0.0} + heap = [(0.0, s)] + remaining = {d for d, _ in dest_demand} + while heap and remaining: + du, u = heapq.heappop(heap) + if du > dist.get(u, float('inf')): + continue + if u in remaining: + remaining.discard(u) + for v, w in adj[u]: + nd = du + w + if nd < dist.get(v, float('inf')): + dist[v] = nd + heapq.heappush(heap, (nd, v)) + for d, demand in dest_demand: + sp = dist.get(d, None) + if sp is None: + # Unreachable -- contributes 0 to lower bound (cannot tighten). + continue + total += sp * demand + return total + + +def _check_objective_consistency( + violations, magnitudes, + solution, params, mode_by_name, edge_by_id, lines, + arc_travel_time, arc_cap, num_edges, od_pairs, + edges_data, + arc_total_flow_in, active_paths, +): + """Constraint (8): reported objective_value must be consistent with the + solution variables. See module docstring for the formula and the + full-recompute vs bracketed cases.""" + reported_obj = solution.get("objective_value") + if reported_obj is None: + return + try: + reported = float(reported_obj) + except (TypeError, ValueError): + return + if reported != reported: # NaN + return + + try: + lam = float(params.get("lambda", 0.0)) + except (TypeError, ValueError): + lam = 0.0 + + # === Exact line cost from active_lines + mode/edge data === + line_cost_exact = 0.0 + for line in lines: + mode = mode_by_name.get(line["mode_name"]) + if mode is None: + continue + try: + C_l = float(mode.get("fixed_cost_per_line", 0.0)) + except (TypeError, ValueError): + C_l = 0.0 + c_l_total = 0.0 + for eid in line["edges"]: + edge = edge_by_id.get(eid) + if edge is None: + continue + try: + c_l_total += float(edge.get("operating_cost", 0.0)) + except (TypeError, ValueError): + pass + try: + f_l = float(line["frequency"]) + except (TypeError, ValueError): + f_l = 0.0 + line_cost_exact += C_l + c_l_total * f_l + + # === Travel time component === + tt_actual = None + if arc_total_flow_in is not None: + tt_actual = 0.0 + for aid, f in arc_total_flow_in.items(): + try: + aid_norm = int(aid) + except (ValueError, TypeError): + aid_norm = aid + try: + tt_actual += float(f) * arc_travel_time.get(aid_norm, 0.0) + except (TypeError, ValueError): + pass + elif active_paths is not None: + tt_actual = 0.0 + for ap in active_paths: + try: + fl = float(ap.get("flow", 0.0)) + except (TypeError, ValueError): + fl = 0.0 + path_tt = 0.0 + for aid in ap.get("arcs", []) or []: + try: + aid_norm = int(aid) + except (ValueError, TypeError): + aid_norm = aid + path_tt += arc_travel_time.get(aid_norm, 0.0) + tt_actual += fl * path_tt + + if tt_actual is not None: + true_obj = lam * line_cost_exact + (1.0 - lam) * tt_actual + record_violation( + violations, magnitudes, 8, + f"Objective consistency violated: reported objective_value={reported} " + f"differs from recomputed lambda*line_cost + (1-lambda)*passenger_travel_time" + f"={true_obj} (line_cost={line_cost_exact}, tt={tt_actual}, lambda={lam})", + reported, true_obj, 'eq', + ) + return + + # === Bracketed check (no flow data: e.g. Gurobi reference) === + tt_lb = _shortest_path_demand_sum(edges_data, od_pairs) + tt_ub = 0.0 + num_arcs = 2 * num_edges + for a in range(num_arcs): + tt_ub += arc_cap.get(a, 0.0) * arc_travel_time.get(a, 0.0) + + obj_lb = lam * line_cost_exact + (1.0 - lam) * tt_lb + obj_ub = lam * line_cost_exact + (1.0 - lam) * tt_ub + + record_violation( + violations, magnitudes, 8, + f"Objective below lower bound: reported objective_value={reported} < " + f"lb={obj_lb} = lambda*line_cost + (1-lambda)*sum_(s,t) d_st*shortest_path_tt " + f"(line_cost={line_cost_exact}, tt_lb={tt_lb}, lambda={lam})", + reported, obj_lb, 'ge', + ) + record_violation( + violations, magnitudes, 8, + f"Objective above upper bound: reported objective_value={reported} > " + f"ub={obj_ub} = lambda*line_cost + (1-lambda)*sum_a (cap_a*tau_a) " + f"(line_cost={line_cost_exact}, tt_ub={tt_ub}, lambda={lam})", + reported, obj_ub, 'le', + ) + + +def check_feasibility(instance, solution): + """Check all hard constraints of the LPP formulation.""" + violations = [] # list of (constraint_idx, message) + magnitudes = [] # list of violation magnitude dicts + + # ---- Handle degenerate solutions ---- + if solution.get("objective_value") is None or solution.get("status") in ("no_solution", "infeasible"): + # No actual solution to check -- return null feasibility + return { + "feasible": None, + "violated_constraints": [], + "violations": [f"No solution to check (status={solution.get('status', 'unknown')})"], + "violation_magnitudes": [], + } + + # ---- Extract instance data ---- + params = instance["global_parameters"] + F = params["frequency_upper_bound_F"] + edges_data = instance["network"]["edges"] + num_nodes = instance["network"]["num_nodes"] + num_edges = instance["network"]["num_edges"] + od_pairs = instance["od_matrix"] + modes = instance["modes"] + + # Build mode lookup by name + mode_by_name = {} + for m in modes: + mode_by_name[m["name"]] = m + + # Edge data lookup + edge_by_id = {} + for e in edges_data: + edge_by_id[e["id"]] = e + + # Edge capacity (Lambda_e) + edge_capacity = {} + for e in edges_data: + edge_capacity[e["id"]] = e["edge_capacity"] + + # ---- Extract solution data ---- + active_lines = solution.get("active_lines", []) + + # Build line data: each line has edges, frequency, mode info + lines = [] + for al in active_lines: + mode_name = al["mode"] + mode = mode_by_name[mode_name] + lines.append({ + "edges": al["edges"], + "frequency": al["frequency"], + "mode_name": mode_name, + "kappa": mode["vehicle_capacity"], + "x": 1, # line is active => x_l = 1 + }) + + # ===================================================================== + # Constraint (5): x_l in {0, 1} + # All active lines have x_l = 1 implicitly. Check frequency > 0 lines + # have valid binary x. Since solution only lists active lines, x_l=1 for + # all listed lines, which is trivially binary. + # ===================================================================== + for i, line in enumerate(lines): + x_val = line["x"] + record_violation(violations, magnitudes, 5, + f"Line {i}: x_l = {x_val} is not in {{0, 1}}", + x_val, round(x_val), 'eq') + + # ===================================================================== + # Constraint (6): f_l >= 0 for all l in L + # ===================================================================== + for i, line in enumerate(lines): + f_l = line["frequency"] + record_violation(violations, magnitudes, 6, + f"Line {i}: frequency f_l = {f_l} < 0", + -f_l, 0.0, 'le') # -f_l <= 0 means f_l >= 0 + + # ===================================================================== + # Constraint (4): f_l <= F * x_l for all l in L + # For active lines, x_l = 1, so f_l <= F. + # ===================================================================== + for i, line in enumerate(lines): + f_l = line["frequency"] + x_l = line["x"] + rhs = F * x_l + record_violation(violations, magnitudes, 4, + f"Line {i}: frequency f_l = {f_l:.6f} > F * x_l = {rhs:.6f}", + f_l, rhs, 'le') + + # ===================================================================== + # Constraint (3): f(L_e) <= Lambda_e for all e in E + # Total frequency of all lines using edge e must not exceed edge capacity. + # ===================================================================== + edge_freq_sum = defaultdict(float) + for line in lines: + for eid in line["edges"]: + edge_freq_sum[eid] += line["frequency"] + + for eid in range(num_edges): + Lambda_e = edge_capacity[eid] + freq_sum = edge_freq_sum.get(eid, 0.0) + record_violation(violations, magnitudes, 3, + f"Edge {eid}: total frequency {freq_sum:.6f} > edge capacity Lambda_e = {Lambda_e}", + freq_sum, Lambda_e, 'le') + + # ===================================================================== + # Constraints (1), (2), (7): Passenger flow feasibility + # + # (1) y(P_st) = d_st for all (s,t) in D + # (2) y(P_a) - sum_{l: e(a) in l} kappa_l f_l <= 0 for all a in A + # (7) y_p >= 0 + # + # Since the solution does not include individual path flows y_p, we check + # whether a feasible passenger routing EXISTS by solving an LP: + # Find y >= 0 such that flow conservation (1) and capacity (2) hold. + # + # We formulate this as a multi-commodity flow on the directed arc graph. + # Each OD pair (s,t) is a commodity with demand d_st. + # Arc capacities come from the lines: cap_a = sum_{l: e(a) in l} kappa_l f_l. + # ===================================================================== + + # Build directed arcs from undirected edges + # arc 2*eid: u->v, arc 2*eid+1: v->u + arc_cap = defaultdict(float) # arc_id -> capacity from lines + for line in lines: + kappa = line["kappa"] + f_l = line["frequency"] + for eid in line["edges"]: + arc_cap[2 * eid] += kappa * f_l + arc_cap[2 * eid + 1] += kappa * f_l + + # Build adjacency for directed arcs + arc_adj = defaultdict(list) # node -> list of (neighbor, arc_id) + arc_travel_time = {} + arc_endpoints = {} + for e in edges_data: + eid = e["id"] + u, v = e["endpoints"] + tt_e = e["traveling_time_seconds"] + fwd = 2 * eid + bwd = 2 * eid + 1 + arc_adj[u].append((v, fwd)) + arc_adj[v].append((u, bwd)) + arc_travel_time[fwd] = tt_e + arc_travel_time[bwd] = tt_e + arc_endpoints[fwd] = (u, v) + arc_endpoints[bwd] = (v, u) + + # ===================================================================== + # Fast path A (preferred): solution provides verification aggregates + # `od_served` and `arc_total_flow`. These are formulation-agnostic -- any + # solver (paper's or LLM-generated, path-based or arc-based MCF) can + # aggregate its own flows once at the end without committing to a + # particular formulation. Checker uses these directly to verify (1)(2), + # avoiding the LP slow path entirely. + # ===================================================================== + od_served = solution.get("od_served", None) + arc_total_flow_in = solution.get("arc_total_flow", None) + active_paths = solution.get("active_passenger_paths", None) + if (od_served is not None and arc_total_flow_in is not None + and not active_paths): + flow_per_od = defaultdict(float) + for entry in od_served: + flow_per_od[(entry["origin"], entry["destination"])] += entry["flow"] + # arc_total_flow is dict; keys may be str or int depending on serializer + flow_per_arc = {} + for aid, f in arc_total_flow_in.items(): + try: + aid_norm = int(aid) + except (ValueError, TypeError): + aid_norm = aid + flow_per_arc[aid_norm] = float(f) + + for od in od_pairs: + key = (od["origin"], od["destination"]) + d = od["demand"] + served = flow_per_od.get(key, 0.0) + record_violation(violations, magnitudes, 1, + f"OD ({od['origin']}, {od['destination']}): " + f"served {served:.6f} != demand {d}", + served, d, 'eq') + + for aid, total_flow in flow_per_arc.items(): + cap = arc_cap.get(aid, 0.0) + record_violation(violations, magnitudes, 2, + f"Arc {aid}: total flow {total_flow:.6f} " + f"> capacity {cap:.6f}", + total_flow, cap, 'le') + + # Constraint (8): objective consistency. + _check_objective_consistency( + violations, magnitudes, + solution, params, mode_by_name, edge_by_id, lines, + arc_travel_time, arc_cap, num_edges, od_pairs, + edges_data, arc_total_flow_in, active_paths, + ) + + return { + "feasible": len(violations) == 0, + "violated_constraints": violations, + "violations": [v[1] for v in violations], + "violation_magnitudes": magnitudes, + } + + # ===================================================================== + # Fast path B (fallback): solution has `active_passenger_paths` (path-based + # solvers). Aggregate per-OD and per-arc flows from path list, then verify + # (1)(2). Same constraints, just different input format. + # ===================================================================== + if active_paths: + # Constraint (1): per-OD demand met by sum of path flows + flow_per_od = defaultdict(float) + # Constraint (2): per-arc total flow <= capacity from lines + flow_per_arc = defaultdict(float) + valid_od_keys = { + (od["origin"], od["destination"]) for od in od_pairs + } + for ap in active_paths: + key = (ap["origin"], ap["destination"]) + try: + path_flow = float(ap["flow"]) + except (TypeError, ValueError): + path_flow = -1.0 + arcs = ap.get("arcs", []) + path_valid = key in valid_od_keys and path_flow >= -tol + current = ap["origin"] + if not isinstance(arcs, list) or (not arcs and key[0] != key[1]): + path_valid = False + else: + for raw_aid in arcs: + try: + aid = int(raw_aid) + except (TypeError, ValueError): + path_valid = False + break + endpoints = arc_endpoints.get(aid) + if endpoints is None or endpoints[0] != current: + path_valid = False + break + current = endpoints[1] + if current != ap["destination"]: + path_valid = False + if not path_valid: + record_violation( + violations, magnitudes, 7, + f"Passenger path {key} is not a valid directed path with " + f"nonnegative flow: arcs={arcs}, flow={ap.get('flow')}", + 0.0, 1.0, 'eq', + ) + continue + flow_per_od[key] += path_flow + for aid in arcs: + flow_per_arc[int(aid)] += path_flow + + for od in od_pairs: + key = (od["origin"], od["destination"]) + d = od["demand"] + served = flow_per_od.get(key, 0.0) + record_violation(violations, magnitudes, 1, + f"OD ({od['origin']}, {od['destination']}): " + f"sum y_p = {served:.6f} != demand {d}", + served, d, 'eq') + + for aid, total_flow in flow_per_arc.items(): + cap = arc_cap.get(aid, 0.0) + if total_flow > cap + tol: + record_violation(violations, magnitudes, 2, + f"Arc {aid}: total flow {total_flow:.6f} " + f"> capacity {cap:.6f}", + total_flow, cap, 'le') + + # Constraint (8): objective consistency. + _check_objective_consistency( + violations, magnitudes, + solution, params, mode_by_name, edge_by_id, lines, + arc_travel_time, arc_cap, num_edges, od_pairs, + edges_data, arc_total_flow_in, active_paths, + ) + + return { + "feasible": len(violations) == 0, + "violated_constraints": violations, + "violations": [v[1] for v in violations], + "violation_magnitudes": magnitudes, + } + + # No complete passenger certificate. The old fallback allocated + # |OD|*|arcs| variables (over 21 million on the stored large instances), + # could exhaust evaluator memory, and still used only a broad objective + # envelope. Fail closed and ask the solver to emit the already-supported + # path or aggregate witness; patched gurobi_code.py emits both. + record_violation( + violations, magnitudes, 1, + "Missing passenger-flow certificate: provide nonempty " + "active_passenger_paths, or both od_served and arc_total_flow", + 0.0, 1.0, 'eq', + ) + return { + "feasible": False, + "violated_constraints": sorted(set(c for c, _ in violations)), + "violations": [message for _, message in violations], + "violation_magnitudes": magnitudes, + } + + # Legacy unreachable implementation retained below for provenance. + # Slow path: solve multi-commodity flow LP via scipy linprog + try: + from scipy.optimize import linprog + from scipy.sparse import lil_matrix + _has_scipy = True + except ImportError: + _has_scipy = False + + if _has_scipy and od_pairs: + # Variables: y_{a,k} for each arc a and commodity k + # where k indexes OD pairs + num_od = len(od_pairs) + num_arcs = 2 * num_edges + + # Variable index: k * num_arcs + a + num_vars = num_od * num_arcs + + # Objective: minimize sum of flows (just find feasible) + c_obj = [0.0] * num_vars + + # Equality constraints: flow conservation for each (commodity, node) + # For commodity k with OD (s_k, t_k, d_k): + # sum_{a out of v} y_{a,k} - sum_{a into v} y_{a,k} = d_k if v=s_k + # = -d_k if v=t_k + # = 0 otherwise + + # Build incidence: for each node, list of (arc_id, +1 if outgoing, -1 if incoming) + node_arcs = defaultdict(list) # node -> list of (arc_id, sign) + for e in edges_data: + eid = e["id"] + u, v = e["endpoints"] + fwd = 2 * eid + bwd = 2 * eid + 1 + node_arcs[u].append((fwd, +1)) # u -> v: outgoing from u + node_arcs[v].append((fwd, -1)) # u -> v: incoming to v + node_arcs[v].append((bwd, +1)) # v -> u: outgoing from v + node_arcs[u].append((bwd, -1)) # v -> u: incoming to u + + # Equality constraints + eq_rows = [] + eq_rhs = [] + for k, od in enumerate(od_pairs): + s_k = od["origin"] + t_k = od["destination"] + d_k = od["demand"] + for v in range(num_nodes): + row = {} + for arc_id, sign in node_arcs[v]: + col = k * num_arcs + arc_id + row[col] = row.get(col, 0.0) + sign + if row: # only add if node has arcs + eq_rows.append(row) + if v == s_k: + eq_rhs.append(float(d_k)) + elif v == t_k: + eq_rhs.append(-float(d_k)) + else: + eq_rhs.append(0.0) + + # Inequality constraints: sum_k y_{a,k} <= cap_a for each arc a + ineq_rows = [] + ineq_rhs = [] + for a in range(num_arcs): + cap_a = arc_cap.get(a, 0.0) + row = {} + for k in range(num_od): + col = k * num_arcs + a + row[col] = 1.0 + if row: + ineq_rows.append(row) + ineq_rhs.append(cap_a) + + # Build sparse matrices + n_eq = len(eq_rows) + n_ineq = len(ineq_rows) + + A_eq = lil_matrix((n_eq, num_vars)) + b_eq = eq_rhs + for i, row in enumerate(eq_rows): + for col, val in row.items(): + A_eq[i, col] = val + + A_ub = lil_matrix((n_ineq, num_vars)) + b_ub = ineq_rhs + for i, row in enumerate(ineq_rows): + for col, val in row.items(): + A_ub[i, col] = val + + bounds = [(0.0, None)] * num_vars + + result = linprog( + c_obj, + A_ub=A_ub.tocsc(), b_ub=b_ub, + A_eq=A_eq.tocsc(), b_eq=b_eq, + bounds=bounds, + method='highs', + options={'presolve': True, 'time_limit': 300}, + ) + + if not result.success: + # Passenger flow is infeasible -- determine which constraints are violated. + # Check constraint (1): can demand be routed at all (ignoring capacity)? + # Check constraint (2): is there enough capacity? + + def bfs_reachable(src, adj, n): + visited = set() + queue = [src] + visited.add(src) + while queue: + u = queue.pop(0) + for v, _ in adj[u]: + if v not in visited: + visited.add(v) + queue.append(v) + return visited + + # Re-solve with relaxed capacity to see if it's a capacity issue + # vs connectivity issue + # Try uncapacitated version (only flow conservation) + result_uncp = linprog( + c_obj, + A_eq=A_eq.tocsc(), b_eq=b_eq, + bounds=bounds, + method='highs', + options={'presolve': True, 'time_limit': 60}, + ) + + if not result_uncp.success: + # Even without capacity, flow conservation fails + # This means the network is disconnected for some OD pair + # or the arc graph doesn't allow routing + for k, od in enumerate(od_pairs): + s_k = od["origin"] + t_k = od["destination"] + d_k = od["demand"] + # Check connectivity via arcs that have capacity > 0 + # (i.e., covered by at least one line) + covered_adj = defaultdict(list) + for e in edges_data: + eid = e["id"] + u, v = e["endpoints"] + # Only include arcs with capacity (from active lines) + if arc_cap.get(2 * eid, 0.0) > 0: + covered_adj[u].append((v, 2 * eid)) + if arc_cap.get(2 * eid + 1, 0.0) > 0: + covered_adj[v].append((u, 2 * eid + 1)) + + reachable = bfs_reachable(s_k, covered_adj, num_nodes) + if t_k not in reachable: + record_violation(violations, magnitudes, 1, + f"OD ({s_k},{t_k}): demand {d_k} cannot be routed; " + f"destination not reachable from origin via active lines", + 0.0, float(d_k), 'eq') + else: + # Uncapacitated is feasible but capacitated is not + # => capacity constraint (2) is violated + # Find which arcs are bottlenecks + y_uncp = result_uncp.x + for a in range(num_arcs): + cap_a = arc_cap.get(a, 0.0) + total_flow = sum(y_uncp[k * num_arcs + a] for k in range(num_od)) + if total_flow > cap_a + tol: + eid = a // 2 + e = edge_by_id[eid] + u, v = e["endpoints"] + direction = f"{u}->{v}" if a % 2 == 0 else f"{v}->{u}" + record_violation(violations, magnitudes, 2, + f"Arc {a} ({direction}): passenger flow {total_flow:.4f} " + f"exceeds line capacity {cap_a:.4f}", + total_flow, cap_a, 'le') + + # Also record constraint (1) as violated since demand can't be met + # with capacity limits + for k, od in enumerate(od_pairs): + s_k = od["origin"] + t_k = od["destination"] + d_k = od["demand"] + # Check how much demand could actually be routed + # by solving max-flow per commodity (simplified: use the LP result) + record_violation(violations, magnitudes, 1, + f"OD ({s_k},{t_k}): demand {d_k} may not be fully satisfiable " + f"due to insufficient arc capacity from active lines", + 0.0, float(d_k), 'eq') + # If result.success, constraints (1), (2), (7) are all satisfied + # (y >= 0 is enforced by bounds, flow conservation by A_eq, capacity by A_ub) + + elif not _has_scipy and od_pairs: + # Cannot check passenger flow constraints without scipy + # Skip with a warning -- do not record as violation + pass + + # ===================================================================== + # Constraint (8): objective consistency. See _check_objective_consistency. + # ===================================================================== + _check_objective_consistency( + violations, magnitudes, + solution, params, mode_by_name, edge_by_id, lines, + arc_travel_time, arc_cap, num_edges, od_pairs, + edges_data, arc_total_flow_in, active_paths, + ) + + # ===================================================================== + # Compile results + # ===================================================================== + violated_indices = sorted(set(c for c, _ in violations)) + violation_msgs = [msg for _, msg in violations] + + feasible = len(violated_indices) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": violation_msgs, + "violation_magnitudes": magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the Line Planning Problem (LPP)" + ) + 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(f"FEASIBLE: No constraint violations found.") + else: + print(f"INFEASIBLE: {len(result['violated_constraints'])} constraint(s) violated: " + f"{result['violated_constraints']}") + 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/borndorfer2007/gurobi_code.py b/tasks/borndorfer2007/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a8d741d28257f6ac0d5ecd05a1418d5c3067cc --- /dev/null +++ b/tasks/borndorfer2007/gurobi_code.py @@ -0,0 +1,552 @@ +#!/usr/bin/env python3 +""" +Gurobi MIP implementation for the Line Planning Problem (LPP). + +Paper: "A Column-Generation Approach to Line Planning in Public Transport" +Authors: Borndörfer, Grötschel, Pfetsch (2007), Transportation Science 41(1), pp. 123-132. + +Model (LPP): + min lambda * (C^T x + c^T f) + (1 - lambda) * tau^T y + + subject to: + y(P_st) = d_st for all (s,t) in D (1) + y(P_a) - sum_{l: e(a) in l} kappa_l f_l <= 0 for all a in A (2) + f(L_e) <= Lambda_e for all e in E (3) + f <= F * x (4) + x_l in {0,1} for all l in L (5) + f_l >= 0 for all l in L (6) + y_p >= 0 for all p in P (7) + +Since the sets L (lines) and P (passenger paths) are exponentially large, +we enumerate lines with a time/count budget and use k-shortest paths for passengers. + +INFERRED ASSUMPTION: The paper uses column generation to handle the exponential +number of variables. For the direct MIP, we enumerate a bounded subset of lines +(capped at MAX_LINES to keep the model tractable) and k-shortest passenger paths. +This is necessary because full enumeration is intractable for dense networks. +**NOT SPECIFIED IN PAPER** for a direct MIP approach. +""" + +import argparse +import json +import sys +import time +import heapq +from collections import defaultdict +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 + + +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("ERROR: gurobipy is required. Install Gurobi and its Python interface.") + sys.exit(1) + +# Maximum number of lines to enumerate before stopping +MAX_LINES = 50000 +# Maximum time (seconds) for line enumeration +MAX_ENUM_TIME = 30 + + +def load_instance(path): + with open(path, 'r') as f: + return json.load(f) + + +def build_directed_arcs(edges_data): + """ + Build directed arcs from undirected edges. + Each edge e = (u,v) produces two arcs: + arc a(e): u -> v (arc_id = 2*e_id) + arc a_bar(e): v -> u (arc_id = 2*e_id + 1) + """ + arcs = [] + arc_adj = defaultdict(list) + for e in edges_data: + eid = e["id"] + u, v = e["endpoints"] + tt = e["traveling_time_seconds"] + fwd_id = 2 * eid + arcs.append({"id": fwd_id, "from": u, "to": v, "edge_id": eid, "travel_time": tt}) + arc_adj[u].append((v, fwd_id)) + bwd_id = 2 * eid + 1 + arcs.append({"id": bwd_id, "from": v, "to": u, "edge_id": eid, "travel_time": tt}) + arc_adj[v].append((u, bwd_id)) + return arcs, arc_adj + + +def enumerate_lines_bounded(instance, edges_data, max_length, max_lines=MAX_LINES, + max_time=MAX_ENUM_TIME): + """ + Enumerate feasible lines for each mode with time and count bounds. + A line of mode i is a simple path in G_i between two terminals of T_i, + with at most max_length edges. + + Prioritizes shorter lines first (BFS-like by depth). + """ + lines = [] + modes = instance["modes"] + start_time = time.time() + + for mode_idx, mode in enumerate(modes): + terminals = set(mode["terminals"]) + mode_adj = defaultdict(list) + for eid in mode["edge_indices"]: + e = edges_data[eid] + u, v = e["endpoints"] + mode_adj[u].append((v, eid)) + mode_adj[v].append((u, eid)) + + terminal_list = sorted(terminals) + + # Enumerate using iterative deepening to prioritize shorter lines + for max_depth in range(1, max_length + 1): + if len(lines) >= max_lines or (time.time() - start_time) > max_time: + break + for s in terminal_list: + if len(lines) >= max_lines or (time.time() - start_time) > max_time: + break + # DFS with depth exactly up to max_depth (but only add lines at this depth + # that weren't found at shorter depths) + stack = [(s, frozenset([s]), [], [s])] + while stack: + if len(lines) >= max_lines or (time.time() - start_time) > max_time: + break + curr, visited, edge_path, node_path = stack.pop() + depth = len(edge_path) + + # Record line if at a different terminal and at exactly this depth level + if curr in terminals and curr != s and curr > s and depth == max_depth: + lines.append({ + "mode_idx": mode_idx, + "edges": list(edge_path), + "nodes": list(node_path), + }) + + if depth < max_depth: + for neighbor, eid in mode_adj[curr]: + if neighbor not in visited: + stack.append(( + neighbor, + visited | frozenset([neighbor]), + edge_path + [eid], + node_path + [neighbor], + )) + + # Deduplicate lines (same set of edges) + seen = set() + unique_lines = [] + for line in lines: + key = (line["mode_idx"], tuple(sorted(line["edges"]))) + if key not in seen: + seen.add(key) + unique_lines.append(line) + + # Post-enumeration edge coverage: ensure every edge has ≥1 line. + # The bounded enumeration may truncate before generating a line through + # some edges; the capacity constraint sum y - kappa*f ≤ 0 then has no f + # variable, forcing all paths through that edge to 0 → presolve INFEAS. + covered = set() + for line in unique_lines: + covered.update(line["edges"]) + uncovered_edges = [e for e in edges_data if e["id"] not in covered] + pre_count = len(unique_lines) + from collections import deque + for e in uncovered_edges: + eid = e["id"] + u, v = e["endpoints"] + for mode_idx, mode in enumerate(modes): + if eid not in mode["edge_indices"]: + continue + terminals_set = set(mode["terminals"]) + mode_adj = defaultdict(list) + for meid in mode["edge_indices"]: + me = edges_data[meid] + mu, mv = me["endpoints"] + mode_adj[mu].append((mv, meid)) + mode_adj[mv].append((mu, meid)) + + def bfs_terminal(start, exclude=None): + q = deque([(start, [start], [])]) + vis = {start} + while q: + n, npath, epath = q.popleft() + if n in terminals_set and n != exclude: + return npath, epath + for nb, meid in mode_adj[n]: + if nb not in vis: + vis.add(nb) + q.append((nb, npath + [nb], epath + [meid])) + return None, None + + up, ue = bfs_terminal(u) + if up is None: + continue + s = up[-1] + vp, ve = bfs_terminal(v, exclude=s) + if vp is None: + continue + line_edges = list(reversed(ue)) + [eid] + ve + line_nodes = list(reversed(up)) + vp + if len(line_edges) > max_length: + continue + key = (mode_idx, tuple(sorted(line_edges))) + if key in seen: + continue + seen.add(key) + unique_lines.append({ + "mode_idx": mode_idx, + "edges": line_edges, + "nodes": line_nodes, + }) + break # one line per edge is enough + if uncovered_edges: + added = len(unique_lines) - pre_count + print(f" Edge coverage: added {added} fallback lines for {len(uncovered_edges)} uncovered edges (total: {len(unique_lines)})") + + return unique_lines + + +def dijkstra(source, target, arc_adj, arcs, num_nodes, excluded_arcs=None): + """Dijkstra's shortest path. Returns (dist, arc_path) or None.""" + if excluded_arcs is None: + excluded_arcs = set() + dist = [float('inf')] * num_nodes + prev = [None] * num_nodes + dist[source] = 0.0 + pq = [(0.0, source)] + while pq: + d, u = heapq.heappop(pq) + if d > dist[u]: + continue + if u == target: + path_arcs = [] + node = target + while prev[node] is not None: + pn, aid = prev[node] + path_arcs.append(aid) + node = pn + path_arcs.reverse() + return dist[target], path_arcs + for v, aid in arc_adj[u]: + if aid in excluded_arcs: + continue + nd = d + arcs[aid]["travel_time"] + if nd < dist[v]: + dist[v] = nd + prev[v] = (u, aid) + heapq.heappush(pq, (nd, v)) + return None + + +def k_shortest_paths(source, target, arc_adj, arcs, num_nodes, k): + """Yen's k-shortest simple paths algorithm.""" + result = dijkstra(source, target, arc_adj, arcs, num_nodes) + if result is None: + return [] + _, first_path = result + A = [first_path] + B = [] + + for ki in range(1, k): + if not A: + break + last_path = A[-1] + last_nodes = [source] + for aid in last_path: + last_nodes.append(arcs[aid]["to"]) + + for i in range(len(last_path)): + spur_node = last_nodes[i] + root_path = last_path[:i] + + excluded = set() + for p in A: + if len(p) >= i and p[:i] == root_path and i < len(p): + excluded.add(p[i]) + + root_nodes = set(last_nodes[:i]) + excluded_arcs = set(excluded) + for aid_check in range(len(arcs)): + if arcs[aid_check]["from"] in root_nodes: + excluded_arcs.add(aid_check) + + spur_result = dijkstra(spur_node, target, arc_adj, arcs, num_nodes, excluded_arcs) + if spur_result is not None: + _, spur_path = spur_result + total_path = root_path + spur_path + total_cost = sum(arcs[aid]["travel_time"] for aid in total_path) + path_nodes = [source] + for aid in total_path: + path_nodes.append(arcs[aid]["to"]) + if len(path_nodes) == len(set(path_nodes)): + heapq.heappush(B, (total_cost, total_path)) + + if not B: + break + while B: + cost, candidate = heapq.heappop(B) + if candidate not in A: + A.append(candidate) + break + else: + break + return A + + +def main(): + parser = argparse.ArgumentParser(description="Gurobi MIP solver for Line Planning Problem") + parser.add_argument("--instance_path", type=str, required=True, help="Path to instance JSON") + parser.add_argument("--solution_path", type=str, required=True, help="Path for output solution JSON") + 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) + + total_start = time.time() + print("Loading instance...") + instance = load_instance(args.instance_path) + + lam = instance["global_parameters"]["lambda"] + max_line_length = instance["global_parameters"]["max_line_length_edges"] + F = instance["global_parameters"]["frequency_upper_bound_F"] + modes = instance["modes"] + edges_data = instance["network"]["edges"] + od_pairs = instance["od_matrix"] + num_nodes = instance["network"]["num_nodes"] + + arcs, arc_adj = build_directed_arcs(edges_data) + num_arcs = len(arcs) + + # Step 1: Enumerate lines (bounded) + print("Enumerating lines (bounded)...") + t0 = time.time() + lines = enumerate_lines_bounded(instance, edges_data, max_line_length) + print(f" Enumerated {len(lines)} lines in {time.time()-t0:.1f}s") + + if len(lines) == 0: + print("ERROR: No feasible lines found.") + solution = {"objective_value": None, "status": "infeasible", "error": "No lines enumerated"} + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + return + + # Step 2: Find passenger paths (k-shortest per OD pair) + print("Finding passenger paths...") + t0 = time.time() + # INFERRED ASSUMPTION: k=10 shortest paths per OD pair. **NOT SPECIFIED IN PAPER** + # for a direct MIP. The paper uses column generation for passenger paths. + K_PATHS = 10 + paths_by_od = {} + for od in od_pairs: + s, t = od["origin"], od["destination"] + paths_by_od[(s, t)] = k_shortest_paths(s, t, arc_adj, arcs, num_nodes, K_PATHS) + total_paths = sum(len(v) for v in paths_by_od.values()) + print(f" Found {total_paths} passenger paths in {time.time()-t0:.1f}s") + + # Step 3: Build Gurobi model + print("Building Gurobi model...") + + # Calculate remaining time for solver + elapsed = time.time() - total_start + solver_time = max(10, args.time_limit - int(elapsed)) + + model = gp.Model("LPP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", solver_time) + model.setParam("OutputFlag", 1) + + # Decision variables + x = model.addVars(len(lines), vtype=GRB.BINARY, name="x") + f = model.addVars(len(lines), vtype=GRB.CONTINUOUS, lb=0.0, name="f") + + all_paths = [] + path_idx_by_od = {} + for od in od_pairs: + key = (od["origin"], od["destination"]) + path_idx_by_od[key] = [] + for path_arcs in paths_by_od.get(key, []): + idx = len(all_paths) + all_paths.append((key, path_arcs)) + path_idx_by_od[key].append(idx) + y = model.addVars(len(all_paths), vtype=GRB.CONTINUOUS, lb=0.0, name="y") + + # Objective: min lambda * (C^T x + c^T f) + (1 - lambda) * tau^T y + obj = gp.LinExpr() + for l_idx, line in enumerate(lines): + mode = modes[line["mode_idx"]] + C_l = mode["fixed_cost_per_line"] + c_l = sum(edges_data[eid]["operating_cost"] for eid in line["edges"]) + obj += lam * C_l * x[l_idx] + obj += lam * c_l * f[l_idx] + for p_idx, (od_key, path_arcs) in enumerate(all_paths): + tau_p = sum(arcs[aid]["travel_time"] for aid in path_arcs) + obj += (1 - lam) * tau_p * y[p_idx] + model.setObjective(obj, GRB.MINIMIZE) + + # Constraint (1): Flow conservation + for od in od_pairs: + key = (od["origin"], od["destination"]) + demand = od["demand"] + indices = path_idx_by_od.get(key, []) + if not indices: + print(f" WARNING: No paths for OD pair {key}, demand={demand}") + continue + model.addConstr( + gp.quicksum(y[i] for i in indices) == demand, + name=f"flow_{key[0]}_{key[1]}" + ) + + # Constraint (2): Capacity + arc_to_lines = defaultdict(list) + for l_idx, line in enumerate(lines): + kappa = modes[line["mode_idx"]]["vehicle_capacity"] + for eid in line["edges"]: + arc_to_lines[2 * eid].append((l_idx, kappa)) + arc_to_lines[2 * eid + 1].append((l_idx, kappa)) + + arc_to_paths = defaultdict(list) + for p_idx, (od_key, path_arcs) in enumerate(all_paths): + for aid in path_arcs: + arc_to_paths[aid].append(p_idx) + + for aid in set(arc_to_paths.keys()) | set(arc_to_lines.keys()): + path_ids = arc_to_paths.get(aid, []) + line_entries = arc_to_lines.get(aid, []) + if not path_ids and not line_entries: + continue + lhs = gp.LinExpr() + for p_idx in path_ids: + lhs += y[p_idx] + for l_idx, kappa in line_entries: + lhs -= kappa * f[l_idx] + model.addConstr(lhs <= 0, name=f"cap_a{aid}") + + # Constraint (3): Frequency bounds + edge_to_lines = defaultdict(list) + for l_idx, line in enumerate(lines): + for eid in line["edges"]: + edge_to_lines[eid].append(l_idx) + for e in edges_data: + eid = e["id"] + Lambda_e = e["edge_capacity"] + line_ids = edge_to_lines.get(eid, []) + if line_ids: + model.addConstr( + gp.quicksum(f[l_idx] for l_idx in line_ids) <= Lambda_e, + name=f"freq_e{eid}" + ) + + # Constraint (4): Linking f <= F*x + for l_idx in range(len(lines)): + model.addConstr(f[l_idx] <= F * x[l_idx], name=f"link_{l_idx}") + + print(f"Model: {model.NumVars} vars, {model.NumConstrs} constrs") + print(f"Solving with time limit {solver_time}s...") + model.optimize() + + # Extract solution + solution = {} + if model.SolCount > 0: + obj_val = model.ObjVal + solution["objective_value"] = obj_val + solution["status"] = "optimal" if model.Status == GRB.OPTIMAL else "time_limit" + solution["mip_gap"] = model.MIPGap if hasattr(model, 'MIPGap') else None + solution["solve_time_seconds"] = model.Runtime + + active_lines = [] + total_fixed_cost = 0.0 + total_operating_cost = 0.0 + for l_idx, line in enumerate(lines): + if x[l_idx].X > 0.5: + mode = modes[line["mode_idx"]] + active_lines.append({ + "line_index": l_idx, + "mode": mode["name"], + "nodes": line["nodes"], + "edges": line["edges"], + "frequency": f[l_idx].X, + }) + total_fixed_cost += mode["fixed_cost_per_line"] + total_operating_cost += ( + sum(edges_data[eid]["operating_cost"] for eid in line["edges"]) + * f[l_idx].X + ) + solution["active_lines"] = active_lines + solution["num_active_lines"] = len(active_lines) + + total_travel_time = 0.0 + num_active_paths = 0 + active_paths = [] + # Verification aggregates: per-OD served demand and per-arc total flow. + # These are formulation-agnostic stats (they don't expose the path-based + # decision variables), so any alternative solver can produce them by + # aggregating its own flows once at the end. The checker will prefer + # these over `active_passenger_paths` when both are present. + od_served_agg = defaultdict(float) + arc_total_flow = defaultdict(float) + for p_idx, (od_key, path_arcs) in enumerate(all_paths): + if y[p_idx].X > 1e-6: + tau_p = sum(arcs[aid]["travel_time"] for aid in path_arcs) + total_travel_time += tau_p * y[p_idx].X + num_active_paths += 1 + active_paths.append({ + "origin": od_key[0], + "destination": od_key[1], + "arcs": list(path_arcs), + "flow": y[p_idx].X, + }) + od_served_agg[(od_key[0], od_key[1])] += y[p_idx].X + for aid in path_arcs: + arc_total_flow[aid] += y[p_idx].X + + solution["active_passenger_paths"] = active_paths + solution["od_served"] = [ + {"origin": o, "destination": d, "flow": f} + for (o, d), f in od_served_agg.items() + ] + solution["arc_total_flow"] = {str(aid): f for aid, f in arc_total_flow.items()} + solution["total_travel_time"] = total_travel_time + solution["scaled_travel_time"] = (1 - lam) * total_travel_time + solution["total_fixed_cost"] = total_fixed_cost + solution["total_operating_cost"] = total_operating_cost + solution["scaled_line_cost"] = lam * (total_fixed_cost + total_operating_cost) + solution["num_active_passenger_paths"] = num_active_paths + + print(f"\n=== SOLUTION ===") + print(f"Objective value: {obj_val:.2f}") + print(f"Active lines: {len(active_lines)}") + print(f"Active passenger paths: {num_active_paths}") + print(f"Total travel time: {total_travel_time:.2f}") + print(f"Scaled travel time: {(1-lam)*total_travel_time:.2f}") + print(f"Total fixed cost: {total_fixed_cost:.2f}") + print(f"Total operating cost: {total_operating_cost:.2f}") + print(f"Scaled line cost: {lam*(total_fixed_cost+total_operating_cost):.2f}") + else: + solution["objective_value"] = None + solution["status"] = "infeasible" if model.Status == GRB.INFEASIBLE else "no_solution" + solution["solve_time_seconds"] = model.Runtime + print("No feasible solution found.") + + with open(args.solution_path, 'w') as outf: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, outf, indent=2) + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/borndorfer2007/gurobi_feasi_result/large_feasi_result_1.json b/tasks/borndorfer2007/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/borndorfer2007/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/borndorfer2007/gurobi_feasi_result/large_feasi_result_2.json b/tasks/borndorfer2007/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/borndorfer2007/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/borndorfer2007/gurobi_feasi_result/large_feasi_result_3.json b/tasks/borndorfer2007/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/borndorfer2007/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/borndorfer2007/gurobi_feasi_result/large_feasi_result_4.json b/tasks/borndorfer2007/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/borndorfer2007/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/borndorfer2007/gurobi_feasi_result/large_feasi_result_5.json b/tasks/borndorfer2007/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/borndorfer2007/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/borndorfer2007/gurobi_feasi_result/tiny_feasi_result.json b/tasks/borndorfer2007/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/borndorfer2007/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/borndorfer2007/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/borndorfer2007/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/borndorfer2007/gurobi_solution/large_solution_1.json b/tasks/borndorfer2007/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..afc7c85e69a3bb20cde579def2e9687ce777b6b1 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86147f6b13b2a67c1081333dbe538f31231da1c885014141e830dc5e272185c4 +size 2154186 diff --git a/tasks/borndorfer2007/gurobi_solution/large_solution_2.json b/tasks/borndorfer2007/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..74d7c94886f71f19c002bf712aff9ea773980d11 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5da270d05bc1493c7bc0aa02bf8fc0255ca679dbbd66bb7b904e02164622c952 +size 2025174 diff --git a/tasks/borndorfer2007/gurobi_solution/large_solution_3.json b/tasks/borndorfer2007/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..86b5962faf81207f8091d249024dda2dc9245208 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd84851727da8f35dab05c988e4dd738f9030f8b50cb134f478eca54fcefb8ba +size 2136621 diff --git a/tasks/borndorfer2007/gurobi_solution/large_solution_4.json b/tasks/borndorfer2007/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8edeb0363cb1aa7d36cb543fd584cb83ac3d6a1c --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18df73e9a79bdb4741a88ab4b434d552f0c2ea5c3300c8baf9fcbfa13c47e035 +size 2191855 diff --git a/tasks/borndorfer2007/gurobi_solution/large_solution_5.json b/tasks/borndorfer2007/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..0f022fce52fb711b43c261231701f1c568d2cf46 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2220cc4decd3c1c22127d707a50a69da8de29ce0f1f543cad57414675f1f07f +size 2394735 diff --git a/tasks/borndorfer2007/gurobi_solution/tiny_solution.json b/tasks/borndorfer2007/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..413ccfce7bb6a7bba76063ec4b5a916e06d53518 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc360b7e98b97582f643b388120caf6a8220152c9173039408dbe4f0f9d25cdd +size 4924 diff --git a/tasks/borndorfer2007/gurobi_solution/tiny_solution_2.json b/tasks/borndorfer2007/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e418c9e920199450cee9cb57c6e5b33f583877e8 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4fe10125f149924d5803706d14c4a3b83f302d3404c4f556d3b42303478fe50 +size 4787 diff --git a/tasks/borndorfer2007/gurobi_solution_log/large_log_1.jsonl b/tasks/borndorfer2007/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cf398a42e2b294d900309b7d5696e9d2c7a8e7ff --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ad0ed2026d34e2772fa0983beed90fb87790aa0050ee1504e8c1cd75fc97d8c +size 337 diff --git a/tasks/borndorfer2007/gurobi_solution_log/large_log_2.jsonl b/tasks/borndorfer2007/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..58c51ae26658e9f6b710c7a13d672f128bfac993 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:310aec40cea82e8cc979d8b25a7360f6b4ac9bef7cfbc25eb94d1306110d68fe +size 338 diff --git a/tasks/borndorfer2007/gurobi_solution_log/large_log_3.jsonl b/tasks/borndorfer2007/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8691d8642ec7e6b3c24fcd0e6b06f977afec6c86 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14c2df4a91a2037de447026fb6b3c2c3f82879ed1fb94d5378d52613ab43e123 +size 792 diff --git a/tasks/borndorfer2007/gurobi_solution_log/large_log_4.jsonl b/tasks/borndorfer2007/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1a66ceba3e532ac0829c981114e803b3e2425a81 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0699adeec2f75debe7b56b61753e00c61c6e8f6b60611865f84a95f78115bf87 +size 452 diff --git a/tasks/borndorfer2007/gurobi_solution_log/large_log_5.jsonl b/tasks/borndorfer2007/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ece4b4a3904a7ce4168ce04d1844e152ecfd3281 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7385ab43c92ec6be275efeb41a4bd1e0a293dd3e852e2e7859d7eb1f29a908df +size 2293 diff --git a/tasks/borndorfer2007/gurobi_solution_log/tiny_log.jsonl b/tasks/borndorfer2007/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..299a16ea4fc1c517c11635c6d8e56b6175be8830 --- /dev/null +++ b/tasks/borndorfer2007/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50225a0f4041be9acfcd238202937d1998ac176d373f17264d54d153579a5765 +size 315 diff --git a/tasks/borndorfer2007/instance/large_instance_1.json b/tasks/borndorfer2007/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..dc57ec47fb6807ab80c46ebba144ca5ae16f94f5 --- /dev/null +++ b/tasks/borndorfer2007/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ec468d5dd16eaface08a29e765e470413859e6eb6161007f903dfbbff5bf3dc +size 596971 diff --git a/tasks/borndorfer2007/instance/large_instance_2.json b/tasks/borndorfer2007/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4998d48541930f4214df909bd104fd15e2c4dd5a --- /dev/null +++ b/tasks/borndorfer2007/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed225775acc0a1a45b4cafb4005dd2b9d88dcb863ad2a48e2ffbea37d21d1225 +size 598569 diff --git a/tasks/borndorfer2007/instance/large_instance_3.json b/tasks/borndorfer2007/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..220288c7a96a8533d0d588fe1a11650b406f85a5 --- /dev/null +++ b/tasks/borndorfer2007/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c20ec68318f7f2dd6cab53e06f77c5a361eb009eb2025e3bf118cf579534e29 +size 595313 diff --git a/tasks/borndorfer2007/instance/large_instance_4.json b/tasks/borndorfer2007/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..7a1824e8e212fa041be3073e4cf8c1e5b0d09671 --- /dev/null +++ b/tasks/borndorfer2007/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdb57ae758efcb5b4e4f03b31a9dcf7653b3ca40a44d67890fc6a0f86a1035e5 +size 596578 diff --git a/tasks/borndorfer2007/instance/large_instance_5.json b/tasks/borndorfer2007/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..0efe02e2708ef6d67bc8063f18a6d70a0f7611e4 --- /dev/null +++ b/tasks/borndorfer2007/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9379d4a070104673e81fc7da2c0d5b57a4825ff86aeefa787737afac41dbbdd7 +size 596063 diff --git a/tasks/borndorfer2007/instance/tiny_instance.json b/tasks/borndorfer2007/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..25d3b4dd705be94955eb6050474bc50ad9037ac8 --- /dev/null +++ b/tasks/borndorfer2007/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef0d55a3e5726cd01dfd24d07b4f8e1a6e49cee5a37fb324b52f563d289b70be +size 18357 diff --git a/tasks/borndorfer2007/instance/tiny_instance_2.json b/tasks/borndorfer2007/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..28c12964fe92ffea262fb1aa9431be4456489d28 --- /dev/null +++ b/tasks/borndorfer2007/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e18ba7da7398f6b57daffd614419b49b9207e47213b53fbb91db9f4148a8fc50 +size 18194 diff --git a/tasks/borndorfer2007/instance_schema.json b/tasks/borndorfer2007/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..de9a6ad303ad78bd7a75180ca1c0c8ed22c434b2 --- /dev/null +++ b/tasks/borndorfer2007/instance_schema.json @@ -0,0 +1,60 @@ +{ + "global_parameters": { + "lambda": " Weight applied to total line cost in the objective, with (1 - lambda) applied to total passenger travel time.", + "fixed_cost_per_line": " Fixed cost incurred for establishing any transit line.", + "operating_cost_per_edge": " Cost per unit frequency for operating a line over one edge.", + "max_line_length_edges": " Maximum number of edges allowed in any single transit line.", + "frequency_upper_bound_F": " Global upper bound on the frequency assigned to any individual line.", + "traveling_times_unit": " Unit of measurement for all edge traveling times.", + "coordinates_unit": " Unit of measurement for node coordinates and edge lengths." + }, + "network": { + "num_nodes": " Total number of stations (nodes) in the transit network.", + "num_edges": " Total number of undirected edges connecting stations in the network.", + "num_od_nodes": " Number of stations that serve as origins or destinations for passenger demand.", + "area_km": " Side length of the square area containing the network.", + "nodes": [ + { + "id": " Unique identifier for this station.", + "x": " Horizontal coordinate of this station.", + "y": " Vertical coordinate of this station.", + "is_od_node": " Whether this station can be an origin or destination for passenger trips." + } + ], + "edges": [ + { + "id": " Unique identifier for this edge.", + "endpoints": " Pair of node identifiers connected by this edge.", + "traveling_time_seconds": " Time required to traverse this edge.", + "edge_capacity": " Maximum total frequency of all lines that may use this edge.", + "operating_cost": " Per-unit-frequency cost of operating a line over this edge.", + "length_km": " Physical length of this edge." + } + ] + }, + "modes": [ + { + "name": " Name of this transportation mode.", + "vehicle_capacity": " Number of passengers a single vehicle run of this mode can carry.", + "speed_kmh": " Travel speed of vehicles operating in this mode.", + "fixed_cost_per_line": " Fixed cost for establishing a line of this mode.", + "operating_cost_per_edge": " Per-unit-frequency cost for each edge traversed by a line of this mode.", + "terminals": " Node identifiers where lines of this mode may begin or end.", + "edge_indices": " Indices of edges available to lines of this mode.", + "num_edges": " Number of edges in the subnetwork for this mode.", + "num_terminals": " Number of terminal stations for this mode." + } + ], + "od_matrix": [ + { + "origin": " Node identifier of the trip origin.", + "destination": " Node identifier of the trip destination.", + "demand": " Number of passengers wishing to travel from the origin to the destination." + } + ], + "od_summary": { + "num_od_pairs": " Total number of origin-destination pairs with positive demand.", + "total_demand": " Sum of passenger demand across all origin-destination pairs.", + "num_od_nodes": " Number of distinct stations appearing as origins or destinations." + } +} diff --git a/tasks/borndorfer2007/mathematical_formulation.md b/tasks/borndorfer2007/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..495849ed1fb4864197b5f768837840f1f5e41fc4 --- /dev/null +++ b/tasks/borndorfer2007/mathematical_formulation.md @@ -0,0 +1,68 @@ +# Original Formulation: Line Planning Problem (LPP) + +*Source: A Column-Generation Approach to Line Planning in Public Transport, Ralf Borndörfer, Martin Grötschel, Marc E. Pfetsch, 2007 (Transportation Science 41(1), pp. 123–132).* + +## Sets and Indices + +- $M$ — number of transportation *modes* (bus, tram, subway, etc.), indexed by $i = 1,\dots,M$. + +- $G = (V,E) = (V,\, E_1 \,\dot\cup\, \cdots \,\dot\cup\, E_M)$ — undirected multigraph representing the multimodal transportation network ($V$ nodes, $E$ edges partitioned by mode). + +- $G_i = (V, E_i)$ — subnetwork of $G$ corresponding to mode $i$. + +- $\mathcal{T}_1,\dots,\mathcal{T}_M \subseteq V$ — terminal sets; nodes where lines of each mode can start and end. + +- $\mathcal{L}$ — set of all feasible lines. A *line* of mode $i$ is a (simple) path in $G_i$ connecting two different terminals of $\mathcal{T}_i$. + +- $\mathcal{L}_e := \bigcup\{\, l \in \mathcal{L} : e \in l \,\}$ — set of lines that use edge $e \in E$. + +- $D := \{\, (s,t) \in V \times V : d_{st} > 0 \,\}$ — set of all OD-pairs. + +- $(V, A)$ — directed passenger route graph derived from $G = (V,E)$ by replacing each edge $e \in E$ with two antiparallel arcs $a(e)$ and $\bar a(e)$; $e(a) \in E$ denotes the undirected edge corresponding to $a \in A$. + +- $\mathcal{P}_{st}$ — set of all $(s,t)$-passenger paths (directed $s$–$t$ paths in $(V,A)$), for $(s,t) \in D$. + +- $\mathcal{P} := \bigcup\{\, p \in \mathcal{P}_{st} : (s,t) \in D \,\}$ — set of all passenger paths. + +- $\mathcal{P}_a := \bigcup\{\, p \in \mathcal{P} : a \in p \,\}$ — set of all passenger paths using arc $a \in A$. + +## Parameters + +- $d_{st} \in \mathbb{Q}_+$ — travel demand from $s$ to $t$ (entry of the not-necessarily-symmetric OD-matrix), for $(s,t) \in V \times V$. + +- $\mathbf{c}^i \in \mathbb{Q}_+^{E_i}$ — line operating costs on the edges of mode $i$; $c_l := \sum_{e \in l} c^i_e$ is the operating cost of line $l$ of mode $i$. + +- $C_1,\dots,C_M \in \mathbb{Q}_+$ — fixed cost for setting up a line of each mode; $C_l := C_i$ for a line $l$ of mode $i$. + +- $\kappa_1,\dots,\kappa_M \in \mathbb{Q}_+$ — vehicle capacity for each mode; $\kappa_l := \kappa_i$ for a line $l$ of mode $i$. + +- $\Lambda \in \mathbb{Q}_+^{E}$ — edge (frequency) capacities; $\Lambda_e$ bounds the total frequency of lines using $e \in E$. + +- $\boldsymbol{\tau} \in \mathbb{Q}_+^{A}$ — traveling time on arc $a \in A$; $\tau_p := \sum_{a \in p} \tau_a$ is the traveling time on path $p$. + +- $F$ — global upper bound on the frequency of any single line, assumed $F \ge \Lambda_e$ for all $e \in E$. + +## Decision Variables + +- $y_p \in \mathbb{R}_+$ — flow of passengers traveling from $s$ to $t$ on path $p \in \mathcal{P}_{st}$. + +- $f_l \in \mathbb{R}_+$ — frequency of line $l \in \mathcal{L}$. + +- $x_l \in \{0,1\}$ — decision variable for using line $l \in \mathcal{L}$. + +## Objective + +$$\text{(LPP)}\qquad +\min \ \boldsymbol{\tau}^{\mathsf T}\mathbf{y} + \mathbf{C}^{\mathsf T}\mathbf{x} + \mathbf{c}^{\mathsf T}\mathbf{f}$$ where $\boldsymbol{\tau}^{\mathsf T}\mathbf{y}$ is total passenger traveling time, $\mathbf{C}^{\mathsf T}\mathbf{x}$ is the fixed line set-up cost, and $\mathbf{c}^{\mathsf T}\mathbf{f}$ is the variable operating cost of lines at frequencies $\mathbf{f}$. + +## Constraints + +Using the notation $\mathbf{v}(I) := \sum_{i \in I} v_i$ for a vector $\mathbf{v}$ indexed by a set $I$: $$\begin{align} + \mathbf{y}(\mathcal{P}_{st}) &= d_{st} & &\forall\,(s,t) \in D \tag{1}\\[2pt] + \mathbf{y}(\mathcal{P}_a) - \sum_{l:\, e(a) \in l} \kappa_l f_l &\le 0 & &\forall\, a \in A \tag{2}\\[2pt] + \mathbf{f}(\mathcal{L}_e) &\le \Lambda_e & &\forall\, e \in E \tag{3}\\[2pt] + \mathbf{f} &\le F\mathbf{x} & & \tag{4}\\[2pt] + x_l &\in \{0,1\} & &\forall\, l \in \mathcal{L} \tag{5}\\[2pt] + f_l &\ge 0 & &\forall\, l \in \mathcal{L} \tag{6}\\[2pt] + y_p &\ge 0 & &\forall\, p \in \mathcal{P}. \tag{7} +\end{align}$$ Constraints (1) and (7) model a multicommodity flow problem routing the demand; (2) are the capacity constraints linking passenger paths with line capacity on each arc; (3) are the frequency (edge-capacity) constraints; (4) are the linking constraints forcing $f_l = 0$ whenever line $l$ is not used ($f_l \le F x_l$). diff --git a/tasks/borndorfer2007/problem_description.txt b/tasks/borndorfer2007/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..96908728116042d87c83f19ecfe2433e615f18b1 --- /dev/null +++ b/tasks/borndorfer2007/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A public transit authority operates a multimodal transportation network consisting of a set of nodes connected by undirected edges. The network supports one or more transportation modes such as bus, tram, or subway, and each edge belongs to exactly one mode. For each mode, a designated subset of nodes serves as terminals where lines of that mode may begin and end. A line is a simple path (no repeated nodes) through the subnetwork of its mode, connecting two distinct terminals of that mode. Lines may be subject to a maximum length measured in number of edges. Each undirected edge in the network is associated with a traveling time, an operating cost per unit frequency, and an edge capacity that limits the total frequency of all lines using that edge. Each mode has a fixed cost incurred for establishing any line of that mode and a vehicle capacity specifying how many passengers a single run of a vehicle on that mode can carry. A global upper bound on the frequency of any individual line is also given, and this bound is at least as large as every edge capacity in the network. + +Passenger travel demand is specified by an origin-destination matrix: for each ordered pair of nodes with positive demand, the matrix gives the number of passengers wishing to travel from the origin to the destination within the planning horizon. The network's undirected edges induce a directed passenger route graph in which each undirected edge is replaced by two antiparallel directed arcs, each carrying the same traveling time as the original edge. A passenger path for a given origin-destination pair is any directed path from the origin to the destination in this directed graph, and the travel time of a passenger path is the sum of the arc travel times along it. + +The transit authority must simultaneously choose which lines to operate, at what frequency to run each chosen line, and how to route all passenger demand through the network. Specifically, the authority selects a subset of valid lines to activate, assigns a nonnegative frequency to each active line, and distributes the passengers of every origin-destination pair across directed paths connecting that pair. The frequency of a line that is not activated must be zero. For every origin-destination pair, the total passenger flow across all paths connecting that pair must equal the given demand. On every directed arc, the total passenger flow must not exceed the total transportation capacity provided by the lines covering the corresponding undirected edge, where each line contributes its mode's vehicle capacity multiplied by its frequency. On every undirected edge, the sum of the frequencies of all lines using that edge must not exceed the edge capacity. + +The goal is to minimize a weighted combination of two competing costs. The first component is the total passenger travel time, computed as the sum over all passenger paths of the flow on that path multiplied by the path's travel time. The second component is the total line cost, which itself consists of two parts: the sum of fixed costs over all activated lines, and the sum over all lines of the line's operating cost (the sum of per-edge operating costs along the line) multiplied by its frequency. A weighting parameter between zero and one controls the tradeoff: the quantity to minimize equals the weighting parameter times the total line cost, plus one minus the weighting parameter times the total passenger travel time. diff --git a/tasks/borndorfer2007/solution_logger.py b/tasks/borndorfer2007/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/borndorfer2007/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/borndorfer2007/solution_schema.json b/tasks/borndorfer2007/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3ce24ca513546f9c66e0e8b9fd2fdf76651a2f18 --- /dev/null +++ b/tasks/borndorfer2007/solution_schema.json @@ -0,0 +1,20 @@ +{ + "objective_value": " Weighted combination of total line cost and total passenger travel time achieved by the solution.", + "active_lines": [ + { + "line_index": " Identifier of this line within the enumerated set of candidate lines.", + "mode": " Transportation mode operating this line.", + "nodes": " Ordered sequence of station identifiers visited by this line from one terminal to the other.", + "edges": " Ordered sequence of edge identifiers traversed by this line.", + "frequency": " Number of vehicle runs per planning period operated on this line." + } + ], + "active_passenger_paths": [ + { + "origin": " Origin station identifier of the OD pair carried by this path.", + "destination": " Destination station identifier of the OD pair carried by this path.", + "arcs": " Ordered sequence of directed arc identifiers traversed by this path from origin to destination.", + "flow": " Number of passengers routed along this path. The released certificate requires a non-empty complete path-flow witness so demand, capacity, and passenger travel cost can all be checked exactly." + } + ] +} diff --git a/tasks/bragin2022/feasibility_check.py b/tasks/bragin2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..66ab67e250baf4ad58135e28ad6aef118f627e07 --- /dev/null +++ b/tasks/bragin2022/feasibility_check.py @@ -0,0 +1,376 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Generalized Assignment Problem (GAP) +from Bragin & Tucker (2022). + +Constraints (numbered top-to-bottom from the formulation): + Constraint 1: sum_i x[i][j] = 1 for all j (each job assigned to exactly one machine) + Constraint 2: sum_j a[i][j] * x[i][j] <= b[i] for all i (machine capacity) + Constraint 3: x[i][j] in {0, 1} (binary integrality) + Constraint 4: reported objective_value matches sum_{i,j} c[i][j] * x[i][j] + (Tier C obj-consistency check — full recompute, since the + solution carries every variable the objective depends on) +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', '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 check_feasibility(instance, solution): + num_machines = instance["num_machines"] + num_jobs = instance["num_jobs"] + cost = instance["cost_matrix"] # c[i][j] + resource = instance["resource_matrix"] # a[i][j] + capacity = instance["capacities"] # b[i] + + assignments = solution.get("assignments", {}) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # Build assignment matrix from solution + # assignments maps str(job_index) -> machine_index + x = [[0] * num_jobs for _ in range(num_machines)] + assigned_jobs = set() + for job_str, machine in assignments.items(): + j = int(job_str) + i = int(machine) + if 0 <= i < num_machines and 0 <= j < num_jobs: + x[i][j] = 1 + assigned_jobs.add(j) + + # ------------------------------------------------------------------------- + # Constraint 1: sum_i x[i][j] = 1 for all j (assignment equality) + # ------------------------------------------------------------------------- + unassigned_jobs = [] + multi_assigned_jobs = [] + for j in range(num_jobs): + lhs = sum(x[i][j] for i in range(num_machines)) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(1) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + if lhs == 0: + unassigned_jobs.append(j) + else: + multi_assigned_jobs.append(j) + + if unassigned_jobs: + violations.append( + f"Constraint 1 violated: jobs {unassigned_jobs} are not assigned to any machine" + ) + if multi_assigned_jobs: + violations.append( + f"Constraint 1 violated: jobs {multi_assigned_jobs} are assigned to multiple machines" + ) + + # ------------------------------------------------------------------------- + # Constraint 2: sum_j a[i][j] * x[i][j] <= b[i] for all i (capacity) + # ------------------------------------------------------------------------- + capacity_violated_machines = [] + for i in range(num_machines): + lhs = sum(resource[i][j] * x[i][j] for j in range(num_jobs)) + rhs = float(capacity[i]) + violation_amount = max(lhs - rhs, 0.0) + if violation_amount > TOL: + violated_constraints.add(2) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(lhs), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + capacity_violated_machines.append( + f"machine {i} (usage {lhs} > capacity {rhs})" + ) + + if capacity_violated_machines: + violations.append( + f"Constraint 2 violated: capacity exceeded on {', '.join(capacity_violated_machines)}" + ) + + # ------------------------------------------------------------------------- + # Constraint 3: x[i][j] in {0, 1} (binary integrality) + # ------------------------------------------------------------------------- + non_binary_vars = [] + for job_str, machine in assignments.items(): + j = int(job_str) + i = int(machine) + # Check that machine index is valid + if i < 0 or i >= num_machines: + violated_constraints.add(3) + rhs_val = float(num_machines - 1) + normalizer = max(abs(rhs_val), EPS) + violation_amount = abs(i - max(0, min(i, num_machines - 1))) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(i), + "rhs": rhs_val, + "raw_excess": float(violation_amount), + "normalizer": normalizer, + "ratio": float(violation_amount) / normalizer + }) + non_binary_vars.append(f"x[{i}][{j}] has invalid machine index") + if j < 0 or j >= num_jobs: + violated_constraints.add(3) + rhs_val = float(num_jobs - 1) + normalizer = max(abs(rhs_val), EPS) + violation_amount = abs(j - max(0, min(j, num_jobs - 1))) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(j), + "rhs": rhs_val, + "raw_excess": float(violation_amount), + "normalizer": normalizer, + "ratio": float(violation_amount) / normalizer + }) + non_binary_vars.append(f"x[{i}][{j}] has invalid job index") + + if non_binary_vars: + violations.append( + f"Constraint 3 violated: {', '.join(non_binary_vars)}" + ) + + # ------------------------------------------------------------------------- + # Constraint 4: objective consistency (Tier C defense). + # Recompute true_obj = sum_{i,j} c[i][j] * x[i][j] from the solution + # variables and compare to the reported objective_value. The GAP solution + # carries every obj-determining variable (the full assignment dict), so a + # full recompute applies. Tolerance: max(1e-3 absolute, 1e-3 relative) + # plus a 0.5 integer-floor since cost coefficients are integers in this + # benchmark and any genuine LP/MIP-precision deviation stays well below + # half a unit, while LLM exploits typically lie by orders of magnitude. + # ------------------------------------------------------------------------- + reported_raw = solution.get("objective_value") + if reported_raw is not None: + try: + reported = float(reported_raw) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(sum( + cost[i][j] * x[i][j] + for i in range(num_machines) for j in range(num_jobs) + )) + abs_diff = abs(reported - true_obj) + tol = max(0.5, 1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(4) + normalizer = max(abs(true_obj), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff) / float(normalizer), + }) + violations.append( + f"Constraint 4 violated: reported objective_value={reported} " + f"differs from recomputed sum_(i,j) c[i][j]*x[i][j]={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + + # ------------------------------------------------------------------------- + # 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="Check feasibility of a GAP 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") + 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) + + feasible = result["feasible"] + print(f"Feasibility: {feasible}") + if not 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/bragin2022/gurobi_code.py b/tasks/bragin2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c320572bf11be44b293eb0028ebfb6e2d8c60f49 --- /dev/null +++ b/tasks/bragin2022/gurobi_code.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Generalized Assignment Problem (GAP) +from Bragin & Tucker (2022), "Surrogate 'Level-Based' Lagrangian Relaxation +_GUROBI_CODE_START_TIME = time.time() +for Mixed-Integer Linear Programming," Scientific Reports 12:22417. + +The GAP formulation: + min sum_i sum_j c[i][j] * x[i][j] + s.t. sum_i x[i][j] = 1 for all j (each job assigned to exactly one machine) + sum_j a[i][j] * x[i][j] <= b[i] for all i (machine capacity) + x[i][j] in {0, 1} +""" + +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/). +_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 GAP with Gurobi") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write solution 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) + + # Load instance + with open(args.instance_path, "r") as f: + data = json.load(f) + + num_machines = data["num_machines"] # I + num_jobs = data["num_jobs"] # J + cost = data["cost_matrix"] # c[i][j], shape (I, J) + resource = data["resource_matrix"] # a[i][j], shape (I, J) + capacity = data["capacities"] # b[i], length I + + # Create model + model = gp.Model("GAP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + + # Decision variables: x[i][j] binary + x = {} + for i in range(num_machines): + for j in range(num_jobs): + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + model.update() + + # Objective: minimize sum_i sum_j c[i][j] * x[i][j] + model.setObjective( + gp.quicksum(cost[i][j] * x[i, j] + for i in range(num_machines) + for j in range(num_jobs)), + GRB.MINIMIZE + ) + + # Constraint 1: Each job assigned to exactly one machine + for j in range(num_jobs): + model.addConstr( + gp.quicksum(x[i, j] for i in range(num_machines)) == 1, + name=f"assign_{j}" + ) + + # Constraint 2: Machine capacity + for i in range(num_machines): + model.addConstr( + gp.quicksum(resource[i][j] * x[i, j] for j in range(num_jobs)) <= capacity[i], + name=f"capacity_{i}" + ) + + # Solve + model.optimize() + + # Extract solution + solution = {} + if model.SolCount > 0: + objective_value = model.ObjVal + assignments = {} + for i in range(num_machines): + for j in range(num_jobs): + if x[i, j].X > 0.5: + assignments[str(j)] = i + solution["objective_value"] = objective_value + solution["assignments"] = assignments + solution["status"] = model.Status + solution["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + else: + solution["objective_value"] = None + solution["status"] = model.Status + solution["assignments"] = {} + + # Write solution + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Status: {model.Status}") + if model.SolCount > 0: + print(f"Objective value: {objective_value}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/bragin2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/bragin2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bragin2022/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/bragin2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/bragin2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bragin2022/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/bragin2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/bragin2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bragin2022/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/bragin2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/bragin2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bragin2022/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/bragin2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/bragin2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bragin2022/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/bragin2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/bragin2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bragin2022/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/bragin2022/gurobi_solution/large_solution_1.json b/tasks/bragin2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5090b568ffa24fe968a21dc28ca2b495f4b70723 --- /dev/null +++ b/tasks/bragin2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25463700dd91d549e26854ca8cdfe760d76ae2d39e6c5fb72d171a4f3bcf859e +size 24417 diff --git a/tasks/bragin2022/gurobi_solution/large_solution_2.json b/tasks/bragin2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d04daef7425cd78f85024d6f4b5e5bd3a6915b04 --- /dev/null +++ b/tasks/bragin2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:012981da5e28725b34a6c664a5dbfffdeab4fef3059e7cdfffbd7314215e1b94 +size 24420 diff --git a/tasks/bragin2022/gurobi_solution/large_solution_3.json b/tasks/bragin2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..f2fe36db30eb5d3bc8db489c8622d73d32ad611f --- /dev/null +++ b/tasks/bragin2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ea0c84b4d0b4b7c60614d3733cb49a2653d0efd4cc7f151674bae58507e1ee5 +size 24377 diff --git a/tasks/bragin2022/gurobi_solution/large_solution_4.json b/tasks/bragin2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..65546aa7d4ce975484f0eab642cdb0f22957b8c2 --- /dev/null +++ b/tasks/bragin2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbbcf8ede13badc6fad5cc60260e2557ab8b30ef9812442359b863208cec2ca1 +size 24369 diff --git a/tasks/bragin2022/gurobi_solution/large_solution_5.json b/tasks/bragin2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..b15ed1560462e63f043c2e5b12c63f0400e68171 --- /dev/null +++ b/tasks/bragin2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:508f664b06f2e1645e6b762a8322d634066b6d0742f101810bbf87a1f074f60a +size 24229 diff --git a/tasks/bragin2022/gurobi_solution/tiny_solution.json b/tasks/bragin2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..9315a99ecaff0bc8039ee7e59b15746bd0a7d549 --- /dev/null +++ b/tasks/bragin2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:244c679dde92c19e96f53135aabfe3cd58edc262fa3763b0df199d8405c3f1b2 +size 1397 diff --git a/tasks/bragin2022/gurobi_solution_log/tiny_log.jsonl b/tasks/bragin2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92b237e3a2ddb39fa760f910149ac6d5c604cc31 --- /dev/null +++ b/tasks/bragin2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a37f74466cb14c17484157d95e20d3f526e3769127742836c634ab1b803ea6f7 +size 128 diff --git a/tasks/bragin2022/instance/large_instance_1.json b/tasks/bragin2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..8f17bc8932112b2afbd5d7d80d66b633c10ce838 --- /dev/null +++ b/tasks/bragin2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45ff69b9e8c358e5a16a6b1f914bf8bc0ac7a1e039a160029c0d94e0044dadc0 +size 2533616 diff --git a/tasks/bragin2022/instance/large_instance_2.json b/tasks/bragin2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a383e6f2f36fce35f62578ef52904b997efa1d80 --- /dev/null +++ b/tasks/bragin2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:965957b3fde99f22c1b14c2b4a32f09d58e192bdfbea7533115a67abbf442e09 +size 2545677 diff --git a/tasks/bragin2022/instance/large_instance_3.json b/tasks/bragin2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b82a3c0690a040e4cb4263257dca2108889e907b --- /dev/null +++ b/tasks/bragin2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a61493dacc0c86bade3ebfaa740cee985d0826ec89db900875b47ef67ad92e28 +size 2533022 diff --git a/tasks/bragin2022/instance/large_instance_4.json b/tasks/bragin2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..297ced4dfe8e465f0bceff78673df447ee81217f --- /dev/null +++ b/tasks/bragin2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:986bfe060a640028e5b6b3085992ed137e512a239d2b83f83ff5ca4d8d7d77e1 +size 2532813 diff --git a/tasks/bragin2022/instance/large_instance_5.json b/tasks/bragin2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fa756abb49419411ab5ad4edefb4fa413b0259e8 --- /dev/null +++ b/tasks/bragin2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eeacf78f008c8cbd2ccbc8196d8165f2f89f7d29aa4b18394e4bd65f8d041663 +size 2533065 diff --git a/tasks/bragin2022/instance/tiny_instance.json b/tasks/bragin2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..3e9988ad06c4766b84e42bb62af9fe6c73d36ef0 --- /dev/null +++ b/tasks/bragin2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f8ec9d42b085e93a7e292ecd8bda1902a5336c9237f4e1eb875c1eb5c69dfbf +size 10818 diff --git a/tasks/bragin2022/instance_schema.json b/tasks/bragin2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d638527d39b9bf5e504c77ae1cc476abb658cefa --- /dev/null +++ b/tasks/bragin2022/instance_schema.json @@ -0,0 +1,7 @@ +{ + "num_machines": " Number of machines available to process jobs.", + "num_jobs": " Number of jobs that must be assigned to machines.", + "cost_matrix": " Cost incurred when a specific job is assigned to a specific machine.", + "resource_matrix": " Amount of machine resource consumed when a specific job is assigned to a specific machine.", + "capacities": " Maximum total resource available on each machine." +} diff --git a/tasks/bragin2022/mathematical_formulation.md b/tasks/bragin2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..58f27e0914818de1dbc7ffa3a0dcc3ec02258984 --- /dev/null +++ b/tasks/bragin2022/mathematical_formulation.md @@ -0,0 +1,38 @@ +# Original Formulation: Generalized Assignment Problem (GAP) + +*Source: Surrogate “Level-Based” Lagrangian Relaxation for Mixed-Integer Linear Programming, Mikhail A. Bragin & Emily L. Tucker, Scientific Reports 12:22417, 2022.* + +The MILP that the paper actually benchmarks in its “Generalized Assignment Problems” section is the classical Generalized Assignment Problem. The paper states (p. 8) that “large-scale instances of GAPs are considered (formulation is available in subsection 4.2 of Supplementary Information),” and the experiments (Table 5) report objective (feasible cost) values for this formulation on the OR-library / Yagiura instances of types D and E with 20, 40, and 80 machines and 1600 jobs. The general separable MILP of the main body (eqs. (1)–(2)) and the SLBLR Lagrangian-relaxation machinery (eqs. (3)–(22)) are solution methodology, not the problem definition, and are intentionally excluded below. + +## Sets and Indices + +- $I$ : set of machines, indexed by $i = 1,\dots,|I|$. + +- $J$ : set of jobs, indexed by $j = 1,\dots,|J|$. + +## Parameters + +- $c_{i,j}$ : cost of assigning job $j$ to machine $i$. + +- $a_{i,j}$ : amount of resource consumed when job $j$ is processed on machine $i$. + +- $b_{i}$ : resource capacity of machine $i$. + +## Decision Variables + +- $x_{i,j} \in \{0,1\}$ : equals $1$ if job $j$ is assigned to machine $i$, and $0$ otherwise, for all $i \in I,\ j \in J$. + +## Objective + +$$\begin{equation} + \min_{x}\ \sum_{i \in I} \sum_{j \in J} c_{i,j}\, x_{i,j} + \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} + \sum_{i \in I} x_{i,j} &= 1, && \forall\, j \in J, \tag{2}\\[2pt] + \sum_{j \in J} a_{i,j}\, x_{i,j} &\le b_{i}, && \forall\, i \in I, \tag{3}\\[2pt] + x_{i,j} &\in \{0,1\}, && \forall\, i \in I,\ \forall\, j \in J. \tag{4} +\end{align}$$ diff --git a/tasks/bragin2022/problem_description.txt b/tasks/bragin2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..406b20f678600aca12d2fbefc629b9497adfe2ca --- /dev/null +++ b/tasks/bragin2022/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A finite set of jobs must each be assigned to exactly one machine drawn from a finite set of machines. Assigning a given job to a given machine incurs a known cost, specified for every (machine, job) pair. The total cost of an assignment is the sum, over all jobs, of the cost of the (machine, job) pair selected for that job. The goal is to choose an assignment that minimizes this total cost. + +Processing a given job on a given machine consumes a known amount of that machine's resource, specified for every (machine, job) pair. Each machine has a fixed resource capacity. For every machine, the total resource consumed by all the jobs assigned to that machine must not exceed the resource capacity of that machine. + +The decision for every (machine, job) pair is binary: it equals 1 if the job is assigned to that machine and 0 otherwise. Each job must be assigned to exactly one machine, so for every job exactly one (machine, job) pair takes the value 1. A machine may receive any number of jobs, provided the per-machine capacity requirement is satisfied. diff --git a/tasks/bragin2022/solution_logger.py b/tasks/bragin2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/bragin2022/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/bragin2022/solution_schema.json b/tasks/bragin2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..745df79a9abb1b183620b47e9a376cec56934f97 --- /dev/null +++ b/tasks/bragin2022/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total assignment cost across all jobs.", + "assignments": " Machine to which each job is assigned (0-indexed)." +} diff --git a/tasks/brandao2016/feasibility_check.py b/tasks/brandao2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..88a23955bddc7870720d960f3cf57e376ed35f6d --- /dev/null +++ b/tasks/brandao2016/feasibility_check.py @@ -0,0 +1,406 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Bin Packing Problem (BPP) solutions based on +Brandao and Pedroso's General Arc-flow Formulation (Equations 17-22). + +Constraints numbered top-to-bottom from the formulation: + Constraint 1 (Eq 18): Flow conservation — each bin capacity <= W, num_bins consistent + Constraint 2 (Eq 19): Demand >= b_i for items NOT in J (b_i > 1) + Constraint 3 (Eq 20): Demand = b_i for items in J (b_i = 1) + Constraint 4 (Eq 21): Per-arc flow upper bound f_{uvi} <= b_i (per-bin item count <= b_i) + Constraint 5 (Eq 22): Non-negativity and integrality of flow variables + Constraint 6 (Eq 17): Objective consistency — reported objective_value must + equal the recomputed number of bins z = len(bins). +""" + +import argparse +import json +from collections import Counter + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('bins', 'num_bins', '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 check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + W = instance["parameters"]["W"] + items_by_type = {} + for item in instance["items"]: + items_by_type[item["item_type"]] = { + "weight": item["weight"], + "demand": item["demand"], + } + + # J = {i : b_i = 1} + J = {t for t, info in items_by_type.items() if info["demand"] == 1} + + bins = solution["bins"] + num_bins = solution.get("num_bins", len(bins)) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint 1 (Eq 18): Flow conservation + # ========================================================================= + if abs(num_bins - len(bins)) > tol: + violated_constraints.add(1) + lhs = float(len(bins)) + rhs = float(num_bins) + raw_excess = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Stated num_bins ({num_bins}) does not match actual number of bins ({len(bins)})" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + for b_idx, bin_items in enumerate(bins): + total_weight = 0.0 + for item_type in bin_items: + if item_type in items_by_type: + total_weight += items_by_type[item_type]["weight"] + lhs = total_weight + rhs = float(W) + violation_amount = lhs - rhs + if violation_amount > tol: + violated_constraints.add(1) + normalizer = max(abs(rhs), eps) + violations.append( + f"Bin {b_idx + 1} exceeds capacity: total weight {total_weight} > W={W}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Count item usage across all bins + # ========================================================================= + usage = Counter() + for bin_items in bins: + for item_type in bin_items: + usage[item_type] += 1 + + # ========================================================================= + # Constraint 2 (Eq 19): For items NOT in J (b_i > 1), total usage >= b_i + # ========================================================================= + for item_type, info in items_by_type.items(): + if item_type in J: + continue + demand = info["demand"] + used = usage.get(item_type, 0) + lhs = float(used) + rhs = float(demand) + violation_amount = rhs - lhs + if violation_amount > tol: + violated_constraints.add(2) + normalizer = max(abs(rhs), eps) + violations.append( + f"Item type {item_type} (not in J): assigned {used} < demand {demand}" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 3 (Eq 20): For items in J (b_i = 1), total usage = b_i + # ========================================================================= + for item_type, info in items_by_type.items(): + if item_type not in J: + continue + demand = info["demand"] + used = usage.get(item_type, 0) + lhs = float(used) + rhs = float(demand) + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + violated_constraints.add(3) + normalizer = max(abs(rhs), eps) + violations.append( + f"Item type {item_type} (in J): assigned {used} != demand {demand}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 4 (Eq 21): f_{uvi} <= b_i for each item arc + # ========================================================================= + for b_idx, bin_items in enumerate(bins): + bin_counter = Counter(bin_items) + for item_type, count in bin_counter.items(): + if item_type not in items_by_type: + continue + demand = items_by_type[item_type]["demand"] + lhs = float(count) + rhs = float(demand) + violation_amount = lhs - rhs + if violation_amount > tol: + violated_constraints.add(4) + normalizer = max(abs(rhs), eps) + violations.append( + f"Bin {b_idx + 1}: item type {item_type} appears {count} times > demand {demand}" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 5 (Eq 22): Non-negativity and integrality + # ========================================================================= + for b_idx, bin_items in enumerate(bins): + for item_type in bin_items: + if item_type not in items_by_type: + violated_constraints.add(5) + violations.append( + f"Bin {b_idx + 1}: invalid item type {item_type} not in instance" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(item_type), + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + + # ========================================================================= + # Constraint 6 (Eq 17): Objective consistency + # Reported objective_value must equal z = len(bins). The objective in + # Brandao & Pedroso's arc-flow formulation is simply the total number + # of bins used (an integer count), so we require equality up to 0.5 + # (any integer mismatch fires). + # ========================================================================= + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(len(bins)) + abs_diff = abs(reported - true_obj) + obj_tol = 0.5 # integer count: any mismatch >= 1 fires + if abs_diff > obj_tol: + violated_constraints.add(6) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed z=len(bins)={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol})" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser(description="Feasibility checker for BPP solutions") + parser.add_argument("--instance_path", type=str, required=True) + parser.add_argument("--solution_path", type=str, required=True) + parser.add_argument("--result_path", type=str, required=True) + 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['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/brandao2016/gurobi_code.py b/tasks/brandao2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ffa8559e4abf70197443065133c59b21f9a8e4 --- /dev/null +++ b/tasks/brandao2016/gurobi_code.py @@ -0,0 +1,443 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the General Arc-flow Formulation with Graph Compression +for Bin Packing and Related Problems. + +Based on: Brandao and Pedroso (2016) - "Bin Packing and Related Problems: + General Arc-flow Formulation with Graph Compression" + +This implements the arc-flow MIP formulation (Equations 17-22) over a compressed +graph built via Algorithm 1 (direct Step-3 construction + Step-4 compression). +""" + +import argparse +import json +import sys +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load a BPP instance from JSON.""" + with open(path, "r") as f: + data = json.load(f) + items = [] + for item in data["items"]: + items.append({ + "type": item["item_type"], + "weight": item["weight"], + "demand": item["demand"], + }) + W = data["parameters"]["W"] + return items, W, data + + +def preprocess_items(items, W): + """ + Sort items in decreasing order by normalized weight (alpha_i = w_i / W). + Ties broken by decreasing weight (lexicographic in 1D). + Returns sorted items with original type mapping. + """ + # For 1D: alpha_i = w_i / W + items_sorted = sorted(items, key=lambda it: (-it["weight"] / W, -it["weight"])) + return items_sorted + + +def build_arc_flow_graph(items, W): + """ + Build the compressed arc-flow graph using Algorithm 1 (direct Step-3 construction). + + For 1D bin packing: + - States: (x, i, c) where x = space used, i = current item index, c = copies used + - Lifting: for each state, compute the highest position reachable + - Memoization on (lifted_x, i, c) + + Returns: (arcs, vertices, source_label, target_label) + where arcs is a list of (u, v, item_index) with item_index 0-based (0 = loss arc uses index -1 here, + we use item_index = -1 for loss arcs to distinguish from item 0). + """ + m = len(items) + weights = [it["weight"] for it in items] + demands = [it["demand"] for it in items] + + arcs = [] # list of (u, v, item_idx) where item_idx is 0-based, -1 for loss + vertices = set() + + # Memoization table: (x, i, c) -> node_label + dp = {} + + def highest_position(x, i, c): + """ + Compute the highest position (Step-3 lifting) for 1D case. + Solve: minimize W - sum_{j>=i} w_j * y_j + s.t. sum_{j>=i} w_j * y_j <= W - x + y_j <= b_j for j > i (or b_i - c for j == i) + y_j >= 0, integer + + This is equivalent to: W - maxFill, where maxFill is the max weight + we can pack from items i..m-1 into remaining capacity W - x. + + We solve this greedily / via a simple bounded knapsack approach. + + **INFERRED ASSUMPTION**: The paper says "solving one-dimensional knapsack + problems" for lifting. We use a DP-based bounded knapsack solver for exactness. + """ + remaining = W - x + if remaining <= 0: + return W + + # Simple DP for bounded knapsack to maximize total weight + # Items from index i to m-1, with adjusted bounds + sub_items = [] + for j in range(i, m): + bound = demands[j] - c if j == i else demands[j] + if bound > 0 and weights[j] <= remaining: + sub_items.append((weights[j], bound)) + + if not sub_items: + return W - 0 # can't pack anything more => highest pos = W + + # DP: max weight packable into capacity 'remaining'. + # Always use the exact bounded-knapsack DP (no greedy fallback). + dp_knap = [0] * (remaining + 1) + for (w, b) in sub_items: + if b == 1: + # 0-1 item: iterate backwards + for cap in range(remaining, w - 1, -1): + dp_knap[cap] = max(dp_knap[cap], dp_knap[cap - w] + w) + else: + # Bounded item: binary decomposition + k = 1 + left = b + while left > 0: + take = min(k, left) + tw = take * w + for cap in range(remaining, tw - 1, -1): + dp_knap[cap] = max(dp_knap[cap], dp_knap[cap - tw] + tw) + left -= take + k *= 2 + max_fill = dp_knap[remaining] + + return W - max_fill + + def build(x, i, c): + """ + Recursive graph construction (Algorithm 1). + Returns the node label for state (x, i, c). + """ + # Step 1: Lift state + x = highest_position(x, i, c) + + key = (x, i, c) + if key in dp: + return dp[key] + + # Initialize node label to W (target) + u = W + + up_x = None + # Option 1: Skip current item (move to next item type) + if i < m - 1: + up_x = build(x, i + 1, 0) + u = up_x + + # Option 2: Use one more copy of item i + if c < demands[i] and x + weights[i] <= W: + v = build(x + weights[i], i, c + 1) + u = min(u, v - weights[i]) + # Add item arc + arcs.append((u, v, i)) + vertices.add(u) + vertices.add(v) + # Add loss arc between levels if needed + if i < m - 1 and up_x is not None and u != up_x: + arcs.append((u, up_x, -1)) # loss arc + vertices.add(up_x) + + dp[key] = u + return u + + # Build graph starting from initial state + sys.setrecursionlimit(100000) + source = build(0, 0, 0) + target = W + + vertices.add(source) + vertices.add(target) + + # Add loss arcs from all internal nodes to target + for v in list(vertices): + if v != source and v != target: + arcs.append((v, target, -1)) + + return arcs, vertices, source, target + + +def apply_step4_compression(arcs, vertices, source, target, items): + """ + Step-4 compression: relabel nodes using longest path from source. + + psi(v) = 0 if v = source + psi(v) = max over incoming arcs (u,v,i) of {psi(u) + w_i} otherwise + where w_i = 0 for loss arcs. + """ + weights = [it["weight"] for it in items] + + # Build adjacency list for incoming edges + incoming = defaultdict(list) # node -> list of (from_node, item_idx) + all_nodes = set() + for (u, v, idx) in arcs: + incoming[v].append((u, idx)) + all_nodes.add(u) + all_nodes.add(v) + + # Build adjacency list for outgoing edges (for topological sort) + outgoing = defaultdict(list) + in_degree = defaultdict(int) + for node in all_nodes: + in_degree[node] = 0 + for (u, v, idx) in arcs: + outgoing[u].append(v) + in_degree[v] += 1 + + # Topological sort (Kahn's algorithm) + from collections import deque + queue = deque() + for node in all_nodes: + if in_degree[node] == 0: + queue.append(node) + + topo_order = [] + while queue: + node = queue.popleft() + topo_order.append(node) + for neighbor in outgoing[node]: + in_degree[neighbor] -= 1 + if in_degree[neighbor] == 0: + queue.append(neighbor) + + # Compute psi (longest path from source) via topological order. + psi = {} + psi[source] = 0 + for node in topo_order: + if node not in psi: + psi[node] = 0 + for (u, idx) in incoming[node]: + if u in psi: + w = 0 if idx == -1 else weights[idx] + psi[node] = max(psi[node], psi[u] + w) + + # Relabel: merge nodes with same psi value + new_arcs = set() + for (u, v, idx) in arcs: + nu = psi.get(u, u) + nv = psi.get(v, v) + if nu != nv: # skip self-loops + new_arcs.add((nu, nv, idx)) + + new_source = psi.get(source, 0) + new_target = psi.get(target, target) + new_vertices = set() + for (u, v, idx) in new_arcs: + new_vertices.add(u) + new_vertices.add(v) + new_vertices.add(new_source) + new_vertices.add(new_target) + + return list(new_arcs), new_vertices, new_source, new_target + + +def solve_with_gurobi(arcs, vertices, source, target, items, W, time_limit): + """ + Build and solve the arc-flow MIP formulation (Equations 17-22). + """ + m_items = len(items) + demands = [it["demand"] for it in items] + + # J = {i : b_i = 1} (0-indexed) + J = set(i for i in range(m_items) if demands[i] == 1) + + model = gp.Model("ArcFlowBPP") + + # Solver parameters as specified in the paper (Section 6) + model.setParam("TimeLimit", time_limit) + model.setParam("Threads", 1) + model.setParam("Presolve", 1) + model.setParam("Method", 2) + model.setParam("MIPFocus", 1) + model.setParam("Heuristics", 1.0) + model.setParam("MIPGap", 1e-4) + model.setParam("MIPGapAbs", 1 - 1e-5) + + # Decision variables + # z: number of bins + z = model.addVar(vtype=GRB.INTEGER, name="z", lb=0) + + # f_{uvi}: flow on arc (u, v, i) + f = {} + for idx, (u, v, item_idx) in enumerate(arcs): + ub = GRB.INFINITY + if item_idx >= 0: + ub = demands[item_idx] + f[idx] = model.addVar( + vtype=GRB.INTEGER, name=f"f_{idx}", lb=0, ub=ub + ) + + model.update() + + # Objective (17): minimize z + model.setObjective(z, GRB.MINIMIZE) + + # Constraint (18): Flow conservation + # For each node k: sum(inflow) - sum(outflow) = -z (source), z (target), 0 (other) + node_in = defaultdict(list) # node -> list of arc indices (incoming) + node_out = defaultdict(list) # node -> list of arc indices (outgoing) + for idx, (u, v, item_idx) in enumerate(arcs): + node_out[u].append(idx) + node_in[v].append(idx) + + for node in vertices: + inflow = gp.quicksum(f[idx] for idx in node_in.get(node, [])) + outflow = gp.quicksum(f[idx] for idx in node_out.get(node, [])) + if node == source: + model.addConstr(inflow - outflow == -z, name=f"flow_source") + elif node == target: + model.addConstr(inflow - outflow == z, name=f"flow_target") + else: + model.addConstr(inflow - outflow == 0, name=f"flow_{node}") + + # Constraints (19) and (20): Demand satisfaction + # Group arcs by item type + item_arcs = defaultdict(list) # item_idx -> list of arc indices + for idx, (u, v, item_idx) in enumerate(arcs): + if item_idx >= 0: + item_arcs[item_idx].append(idx) + + for i in range(m_items): + total_flow = gp.quicksum(f[idx] for idx in item_arcs.get(i, [])) + if i in J: + # Constraint (20): equality + model.addConstr(total_flow == demands[i], name=f"demand_eq_{i}") + else: + # Constraint (19): inequality (>=) + model.addConstr(total_flow >= demands[i], name=f"demand_geq_{i}") + + # Solve + model.optimize() + + # Extract solution + obj_val = None + bin_assignments = [] + + if model.SolCount > 0: + obj_val = model.ObjVal + + # Flow decomposition to recover bin assignments + flow_values = {} + for idx, (u, v, item_idx) in enumerate(arcs): + val = round(f[idx].X) + if val > 0: + flow_values[idx] = val + + # Decompose flow into paths from source to target + # Build residual adjacency + residual_out = defaultdict(list) + for idx in flow_values: + u, v, item_idx = arcs[idx] + residual_out[u].append((v, item_idx, idx)) + + total_bins = round(z.X) + for _ in range(total_bins): + path_items = [] + current = source + while current != target: + found = False + for (v, item_idx, arc_idx) in residual_out[current]: + if flow_values.get(arc_idx, 0) > 0: + flow_values[arc_idx] -= 1 + if flow_values[arc_idx] == 0: + del flow_values[arc_idx] + if item_idx >= 0: + path_items.append(items[item_idx]["type"]) + current = v + found = True + break + if not found: + break + # Append every path so len(bin_assignments) == round(z.X); + # paths consisting only of loss arcs yield empty bins. + bin_assignments.append(path_items) + + return obj_val, bin_assignments, model.Status + + +def main(): + parser = argparse.ArgumentParser( + description="Arc-flow formulation for Bin Packing (Gurobi solver)" + ) + 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) + + # Load instance + items, W, instance_data = load_instance(args.instance_path) + + # Preprocess: sort items + items_sorted = preprocess_items(items, W) + + # Build compressed arc-flow graph + arcs, vertices, source, target = build_arc_flow_graph(items_sorted, W) + + # Apply Step-4 compression + arcs, vertices, source, target = apply_step4_compression( + arcs, vertices, source, target, items_sorted + ) + + # Solve MIP + obj_val, bin_assignments, status = solve_with_gurobi( + arcs, vertices, source, target, items_sorted, W, args.time_limit + ) + + # Build solution output + solution = { + "objective_value": obj_val, + "status": "optimal" if status == GRB.OPTIMAL else + "time_limit" if status == GRB.TIME_LIMIT else + "feasible" if obj_val is not None else "infeasible", + "num_bins": int(round(obj_val)) if obj_val is not None else None, + "bins": bin_assignments, + } + + 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 obj_val is not None: + print(f"Objective value (bins used): {obj_val}") + + +if __name__ == "__main__": + main() diff --git a/tasks/brandao2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/brandao2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/brandao2016/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/brandao2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/brandao2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/brandao2016/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/brandao2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/brandao2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/brandao2016/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/brandao2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/brandao2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/brandao2016/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/brandao2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/brandao2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/brandao2016/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/brandao2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/brandao2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/brandao2016/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/brandao2016/gurobi_solution/large_solution_1.json b/tasks/brandao2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ba8c4de3eb751f635825f9274ddc2d7a1c641b7b --- /dev/null +++ b/tasks/brandao2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e51bdec5db32a65ea364529410498efad58d744952d64be4b20da85f02c9c262 +size 2590 diff --git a/tasks/brandao2016/gurobi_solution/large_solution_2.json b/tasks/brandao2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..69c9ffba662b7c4e13ebaba524c85cdf36766ed8 --- /dev/null +++ b/tasks/brandao2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e87e0e7fa98b806acf53709e74a4fae9d8c17f5f1127b1a8b856bdadcbe1b20b +size 2088 diff --git a/tasks/brandao2016/gurobi_solution/large_solution_3.json b/tasks/brandao2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..73dfac80fd4cb769a401213e961db5ca09dc199a --- /dev/null +++ b/tasks/brandao2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6a8965962561b92f9c3def1712577405fd301b5d948716f4fb5a7a994a4b1dd +size 1978 diff --git a/tasks/brandao2016/gurobi_solution/large_solution_4.json b/tasks/brandao2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9bed4e7b645eaf55671e9db20566dd5d08da8378 --- /dev/null +++ b/tasks/brandao2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa8f2ac75c245e3d039734911d8aba726dc819c8eca5d11ebcc1bbc55d5f59a3 +size 2063 diff --git a/tasks/brandao2016/gurobi_solution/large_solution_5.json b/tasks/brandao2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..604d78100fd68f526e15cd832297d512640c6172 --- /dev/null +++ b/tasks/brandao2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0271f9f3252e11fcd22ea16366b68db666fe4b94793e718d3f029f678e3a8d60 +size 926 diff --git a/tasks/brandao2016/gurobi_solution/tiny_solution.json b/tasks/brandao2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..696dfdac504aaa55e9b46531dad8ccf94f9f6d88 --- /dev/null +++ b/tasks/brandao2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:565af2e3ca9a283f98fcd94422eb9b9fb7a0f97fb160432d9adf79f5da6a6c59 +size 988 diff --git a/tasks/brandao2016/gurobi_solution_log/large_log_1.jsonl b/tasks/brandao2016/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e27c70e15adff8da55f3a92ff0a5866ab2b94691 --- /dev/null +++ b/tasks/brandao2016/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:300f1ff91145b5ca26199b0c4b62b26bff6764df1701fec35ff042906eb7ead1 +size 43 diff --git a/tasks/brandao2016/gurobi_solution_log/large_log_2.jsonl b/tasks/brandao2016/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bbbe263f048b93d7797b1309077f7684cfa20e47 --- /dev/null +++ b/tasks/brandao2016/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43865f4956440951bebe6af56f3c7f21d776ced899bfa878eb089735b9eb4df1 +size 43 diff --git a/tasks/brandao2016/gurobi_solution_log/large_log_3.jsonl b/tasks/brandao2016/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..44e57fc26117840284a0829f76f8f776726b9a2d --- /dev/null +++ b/tasks/brandao2016/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57af53090e3b150113a1c9591e677c873d78b1496e45d3c8870bf60c5a4a8352 +size 42 diff --git a/tasks/brandao2016/gurobi_solution_log/large_log_4.jsonl b/tasks/brandao2016/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..859d72e5a3a82704a8509ecd5b3ed27beb1a572e --- /dev/null +++ b/tasks/brandao2016/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f88a01c3453cc7f98b62b168f4f6e0a25fe7db9aed0022e0e37c49b7d5b00ed7 +size 43 diff --git a/tasks/brandao2016/gurobi_solution_log/large_log_5.jsonl b/tasks/brandao2016/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7814c5689abe81fc45923dc430f25b3b4dcd27ae --- /dev/null +++ b/tasks/brandao2016/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e22549d03ca9afa28b99220409e57f620afbdebb87515ee913bd1d6113c7a124 +size 42 diff --git a/tasks/brandao2016/gurobi_solution_log/tiny_log.jsonl b/tasks/brandao2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5caf276888828ff8be62df7c4a34ec7df1f4fa5a --- /dev/null +++ b/tasks/brandao2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fd28c2381df9f9129068d5ada1d3d1b175aa92624e2d772f18c86ea03ebcb11 +size 41 diff --git a/tasks/brandao2016/instance/large_instance_1.json b/tasks/brandao2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..dff8b3845958a7b44366652d8675d431f7124c36 --- /dev/null +++ b/tasks/brandao2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:249ca7f50c8500454940cfb411f82d72ee8f1db9582967ecf04c7f7fe5a7dca8 +size 6720 diff --git a/tasks/brandao2016/instance/large_instance_2.json b/tasks/brandao2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..38ff93eadd7c250994a244d405547f1dfa847736 --- /dev/null +++ b/tasks/brandao2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0369a1b3234c8d2aa21390f223cbd4b5ea24e1e5eef99596c697527de2ff9171 +size 6685 diff --git a/tasks/brandao2016/instance/large_instance_3.json b/tasks/brandao2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..91a29b59dc4c075b6c27d5a38558ec0d5b5ceb50 --- /dev/null +++ b/tasks/brandao2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a384ae9eee2fe3be8916b15942885b5c86c7c7c03df2c1ce10213177bf2d7c5 +size 6780 diff --git a/tasks/brandao2016/instance/large_instance_4.json b/tasks/brandao2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..380b200ab4a9f0ed3553622dc978eada5f7bc545 --- /dev/null +++ b/tasks/brandao2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dff6d1ec11e7083a6a7f4e8eeec72d535bcff77f4e284fc864d0f290ddb46887 +size 6990 diff --git a/tasks/brandao2016/instance/large_instance_5.json b/tasks/brandao2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ff40160c6791a839ebc8156924f0b9864ac2e185 --- /dev/null +++ b/tasks/brandao2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:130151699dd3e6376b5ea61d6d02fa4e0b16526edde5f3fdd5439ff0200d36f6 +size 5115 diff --git a/tasks/brandao2016/instance/tiny_instance.json b/tasks/brandao2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..9a29ba548a10550029447e6e72ba6bc80a0cea1b --- /dev/null +++ b/tasks/brandao2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:709511fd5c03a481962ef364d81505b82df6c1a7272d142026a9e79dfa0eaff6 +size 3223 diff --git a/tasks/brandao2016/instance_schema.json b/tasks/brandao2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..505413d00e5e111240509472e6d257904d332221 --- /dev/null +++ b/tasks/brandao2016/instance_schema.json @@ -0,0 +1,14 @@ +{ + "parameters": { + "n": " Total number of items to be packed across all bins.", + "m": " Number of distinct item types.", + "W": " Maximum weight capacity of each bin." + }, + "items": [ + { + "item_type": " Unique identifier for this item type, starting from 1.", + "weight": " Weight of one copy of this item type.", + "demand": " Number of copies of this item type that must be packed." + } + ] +} diff --git a/tasks/brandao2016/mathematical_formulation.md b/tasks/brandao2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d0418ed6b39e179e7eb96a3c4fbffa1392a9b442 --- /dev/null +++ b/tasks/brandao2016/mathematical_formulation.md @@ -0,0 +1,58 @@ +# Original Formulation: Bin Packing / Cutting Stock via General Arc-flow (AF) + +*Source: Bin Packing and Related Problems: General Arc-flow Formulation with Graph Compression, Filipe Brandão and João Pedro Pedroso, 2013.* + +## Sets and Indices + +- $m$ : number of different item types (weights), indexed $i = 1, \ldots, m$. + +- $V$ : set of vertices of the directed acyclic graph $G = (V, A)$; includes the source vertex $\textsc{s}$ and the target vertex $\textsc{t}$. + +- $A$ : set of arcs. Each arc is a triple $(u, v, i)$ where $u, v \in V$ and $i$ identifies the item type contributing to the arc; arcs with $i = 0$ are the *loss* arcs (representing unused capacity). + +- $J \subseteq \{1, \ldots, m\}$ : subset of items whose demands must be satisfied *exactly* (for efficiency the authors set $J = \{ i = 1, \ldots, m \mid b_i = 1 \}$). + +## Parameters + +- $b_i$ : demand of items of type $i$, for $i = 1, \ldots, m$. + +- $w_i$ : weight (size) of item type $i$. + +- $W$ : bin capacity. + +- $\textsc{s}, \textsc{t}$ : source and target vertices of $G$. + +*The graph $G = (V, A)$ is constructed beforehand so that every path from $\textsc{s}$ to $\textsc{t}$ corresponds to a valid packing pattern for a single bin; $V$ and $A$ are therefore inputs to the MILP below.* + +## Decision Variables + +- $f_{uvi}$ : amount of flow along arc $(u, v, i) \in A$ (non-negative integer). + +- $z$ : number of bins required (total flow from $\textsc{s}$ to $\textsc{t}$). + +## Objective + +$$\begin{align} +\text{minimize} \quad & z \tag{17} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{(u,v,i) \in A:\, v = k} f_{uvi} + \;-\; \sum_{(v,r,i) \in A:\, v = k} f_{vri} + &= + \begin{cases} + -z & \text{if } k = \textsc{s}, \\ + \phantom{-}z & \text{if } k = \textsc{t}, \\ + \phantom{-}0 & \text{for } k \in V \setminus \{\textsc{s}, \textsc{t}\}, + \end{cases} \tag{18} \\[4pt] +\sum_{(u,v,j) \in A:\, j = i} f_{uvj} &\geq b_i, + && i \in \{1, \ldots, m\} \setminus J, \tag{19} \\[4pt] +\sum_{(u,v,j) \in A:\, j = i} f_{uvj} &= b_i, + && i \in J, \tag{20} \\[4pt] +f_{uvi} &\leq b_i, + && \forall (u,v,i) \in A, \text{ if } i \neq 0, \tag{21} \\[4pt] +f_{uvi} &\geq 0, \text{ integer}, + && \forall (u,v,i) \in A. \tag{22} +\end{align}$$ diff --git a/tasks/brandao2016/problem_description.txt b/tasks/brandao2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..58218e690ced2637e409cf0d12fd5f27a0a2f926 --- /dev/null +++ b/tasks/brandao2016/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A facility must pack a collection of items into identical bins of fixed capacity, using as few bins as possible. There are m distinct item types, where each item type has a known integer weight and a known integer demand specifying how many copies of that type must be packed. The bin capacity is a single integer W, and every item weight is strictly positive and does not exceed W. + +The planner decides how many bins to use and how to allocate items to those bins. The total weight of items placed in any single bin must not exceed the capacity W, and for every item type the total number of copies packed across all bins must be at least that type's demand. + +The objective is to minimize the total number of bins used. diff --git a/tasks/brandao2016/solution_logger.py b/tasks/brandao2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/brandao2016/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/brandao2016/solution_schema.json b/tasks/brandao2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1eda629b61863f557bba261c0e9934d1a1df70a9 --- /dev/null +++ b/tasks/brandao2016/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total number of bins used in the packing.", + "num_bins": " Total number of bins used in the packing.", + "bins": " Item types assigned to each bin, where each inner list contains the item_type identifiers of all items packed into that bin." +} diff --git a/tasks/bront2009/feasibility_check.py b/tasks/bront2009/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..71448a0170dd6613f64cafb8e0a49874bd75a545 --- /dev/null +++ b/tasks/bront2009/feasibility_check.py @@ -0,0 +1,486 @@ +""" +Feasibility Checker for CDLP (Choice-Based Deterministic Linear Programming) +============================================================================= +Paper: Bront, Mendez-Diaz, Vulcano (2009) +"A Column Generation Algorithm for Choice-Based Network Revenue Management" +Operations Research 57(3):769-784 + +Checks a candidate CDLP solution against the three hard constraints plus an +objective-consistency check (Tier C defence against self-reported-objective +exploits): + Constraint 1 (Capacity): sum_S lambda * Q_i(S) * t(S) <= c_i for each leg i + Constraint 2 (Time): sum_S t(S) <= T + Constraint 3 (Non-negativity): t(S) >= 0 for all S + Constraint 4 (Obj consistency): + reported objective_value must equal sum_S lambda * R(S) * t(S) + within a small tolerance. Because the solution lists every active + column (offer_set, time_allocated) the objective can be fully + recomputed from the solution + instance data, so a tight equality + check is appropriate. +""" + +import argparse +import json +import numpy as np + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('active_columns', '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 build_problem_data(data): + """Extract problem parameters from instance JSON.""" + n = len(data["products"]) + m = len(data["network"]["legs"]) + L = len(data["segments"]) + T = data["booking_horizon"]["T"] + lam = data["lambda"] + + r = np.array([p["fare"] for p in data["products"]], dtype=float) + + A = np.zeros((m, n), dtype=float) + for j, prod in enumerate(data["products"]): + for leg_id in prod["legs_used"]: + A[leg_id - 1, j] = 1.0 + + c = np.array([leg["capacity"] for leg in data["network"]["legs"]], dtype=float) + + segments = [] + for seg in data["segments"]: + seg_info = { + "lambda_l": seg["lambda_l"], + "consideration_set": [pid - 1 for pid in seg["consideration_set"]], + "v": {}, + "v0": seg["no_purchase_preference"] + } + for idx, pid in enumerate(seg["consideration_set"]): + seg_info["v"][pid - 1] = seg["preference_vector"][idx] + segments.append(seg_info) + + p_l = np.array([seg["lambda_l"] / lam for seg in segments]) + + return { + "n": n, "m": m, "L": L, "T": T, "lam": lam, + "r": r, "A": A, "c": c, + "segments": segments, "p_l": p_l + } + + +def compute_choice_probs(S_set, prob_data): + """Compute P_j(S) for all products j using MNL with overlapping segments.""" + segments = prob_data["segments"] + p_l = prob_data["p_l"] + n = prob_data["n"] + P = np.zeros(n) + for j in S_set: + for l_idx, seg in enumerate(segments): + if j in seg["v"]: + denom = seg["v0"] + for h in S_set: + if h in seg["v"]: + denom += seg["v"][h] + P[j] += p_l[l_idx] * seg["v"][j] / denom + return P + + +def compute_R_and_Q(S_set, prob_data): + """Compute R(S) and Q(S) for an offer set S.""" + r = prob_data["r"] + A = prob_data["A"] + P = compute_choice_probs(S_set, prob_data) + R_S = sum(r[j] * P[j] for j in S_set) + Q_S = A @ P + return R_S, Q_S + + +def extract_columns_and_times(solution): + """ + Extract offer sets and their time allocations from a candidate solution. + Returns list of (S_set_0indexed, t_value) tuples, or None if no primal + variables are present. + """ + if "active_columns" not in solution: + return None + + columns = [] + for col in solution["active_columns"]: + # offer_set is 1-indexed in the solution JSON + S_set = set(pid - 1 for pid in col["offer_set"]) + t_val = col["time_allocated"] + columns.append((S_set, t_val)) + return columns + + +def check_feasibility(instance, solution): + """ + Check all hard constraints of the CDLP formulation plus objective + consistency. + + Constraints: + 1: Capacity -- sum_S lambda * Q_i(S) * t(S) <= c_i for each leg i + 2: Time -- sum_S t(S) <= T + 3: Non-negativity -- t(S) >= 0 for all S + 4: Objective consistency -- reported objective_value == sum_S lambda * R(S) * t(S) + """ + tol = 1e-5 + eps = 1e-5 + + prob_data = build_problem_data(instance) + m = prob_data["m"] + T = prob_data["T"] + lam = prob_data["lam"] + c = prob_data["c"] + + columns = extract_columns_and_times(solution) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + if columns is None: + # Solution has no primal t(S) variables (e.g., simulation-based DCOMP). + # Constraints 1-3 cannot be evaluated, but a reported objective_value + # with no supporting columns is still an obj-consistency violation + # (recomputed obj is 0 in this case). + reported_obj = solution.get("objective_value") + try: + reported = float(reported_obj) if reported_obj is not None else None + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + abs_diff = abs(reported - true_obj) + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(4) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} but no active_columns present so recomputed " + f"sum_S lambda*R(S)*t(S) = 0.0 " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer) + }) + if not violated_constraints: + return { + "feasible": True, + "violated_constraints": [], + "violations": [ + "No primal t(S) variables in solution; CDLP constraints not evaluated" + ], + "violation_magnitudes": [] + } + return { + "feasible": False, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + # ------------------------------------------------------------------ + # Constraint 1: Capacity constraint (one per leg) + # sum_S lambda * Q_i(S) * t(S) <= c_i for i = 1, ..., m + # ------------------------------------------------------------------ + # Compute R(S) and Q(S) for every active column (R(S) reused by constraint 4). + R_per_col = [] + capacity_usage = np.zeros(m) + for S_set, t_val in columns: + R_S, Q_S = compute_R_and_Q(S_set, prob_data) + R_per_col.append(R_S) + capacity_usage += lam * Q_S * t_val + + for i in range(m): + lhs = capacity_usage[i] + rhs = c[i] + violation_amount = lhs - rhs # positive means violated (LHS > RHS) + if violation_amount > tol: + violated_constraints.add(1) + leg_info = instance["network"]["legs"][i] + violations.append( + f"Capacity constraint violated on leg {leg_info['leg_id']} " + f"({leg_info['origin']}->{leg_info['destination']}): " + f"usage {lhs:.6f} > capacity {rhs:.6f}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ------------------------------------------------------------------ + # Constraint 2: Time constraint + # sum_S t(S) <= T + # ------------------------------------------------------------------ + total_time = sum(t_val for _, t_val in columns) + lhs = total_time + rhs = float(T) + violation_amount = lhs - rhs + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Time constraint violated: total time allocated {lhs:.6f} > T = {rhs:.6f}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ------------------------------------------------------------------ + # Constraint 3: Non-negativity + # t(S) >= 0 for all S + # ------------------------------------------------------------------ + for idx, (S_set, t_val) in enumerate(columns): + lhs = 0.0 # RHS of t(S) >= 0 rewritten: 0 <= t(S), so check 0 - t(S) + rhs_val = 0.0 + # For a >= constraint: violation_amount = RHS - LHS = 0 - t_val + violation_amount = rhs_val - t_val # positive means t_val < 0 + if violation_amount > tol: + violated_constraints.add(3) + offer_set_1idx = sorted(j + 1 for j in S_set) + violations.append( + f"Non-negativity violated for offer set {offer_set_1idx}: " + f"t(S) = {t_val:.6f} < 0" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(t_val), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ------------------------------------------------------------------ + # Constraint 4: Objective consistency (Tier C defence) + # reported objective_value == sum_S lambda * R(S) * t(S) + # Full recompute is exact: every variable that determines the obj + # (the active columns and their time allocations) is present in the + # solution. Tolerance: 0.1% relative, with a 1e-3 absolute floor. + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value") + try: + reported = float(reported_obj) if reported_obj is not None else None + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(sum(lam * R_per_col[i] * columns[i][1] for i in range(len(columns)))) + abs_diff = abs(reported - true_obj) + obj_tol = max(1e-3, 1e-3 * 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 sum_S lambda*R(S)*t(S)=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 4, + "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 CDLP (Bront et al. 2009)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Feasibility: {status}") + if result["violated_constraints"]: + 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/bront2009/gurobi_code.py b/tasks/bront2009/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..20eeb1d492d90fc74f914a203a7bd5c776535436 --- /dev/null +++ b/tasks/bront2009/gurobi_code.py @@ -0,0 +1,526 @@ +""" +CDLP (Choice-Based Deterministic Linear Programming) via Column Generation +============================================================================ +Paper: Bront, Mendez-Diaz, Vulcano (2009) +"A Column Generation Algorithm for Choice-Based Network Revenue Management" +Operations Research 57(3):769-784 + +This program solves the CDLP formulation (Equation (3) in the paper) using +column generation (Section 4). The column generation subproblem (Equation (6)) +is solved first by a greedy heuristic (Section 4.2.2), and if that fails, +by an exact MIP reformulation (Section 4.2.1). + +Output: optimal CDLP objective value and the primal/dual solutions. +""" + +import argparse +import json +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): + """Load problem instance from JSON file.""" + with open(path, 'r') as f: + data = json.load(f) + return data + + +def build_problem_data(data): + """ + Extract and precompute all problem parameters from the instance JSON. + Returns a dict with all needed arrays/values. + """ + n = len(data["products"]) # number of products + m = len(data["network"]["legs"]) # number of legs (resources) + L = len(data["segments"]) # number of segments + T = data["booking_horizon"]["T"] + lam = data["lambda"] # overall arrival probability per period + + # Product revenues (0-indexed) + r = np.array([p["fare"] for p in data["products"]], dtype=float) + + # Incidence matrix A: m x n, A[i][j] = 1 if leg i is used by product j + A = np.zeros((m, n), dtype=float) + for j, prod in enumerate(data["products"]): + for leg_id in prod["legs_used"]: + leg_idx = leg_id - 1 # convert 1-indexed to 0-indexed + A[leg_idx, j] = 1.0 + + # Capacities + c = np.array([leg["capacity"] for leg in data["network"]["legs"]], dtype=float) + + # Segment data + segments = [] + for seg in data["segments"]: + seg_info = { + "lambda_l": seg["lambda_l"], + "consideration_set": [pid - 1 for pid in seg["consideration_set"]], # 0-indexed + "v": {}, # preference weights: product_0idx -> weight + "v0": seg["no_purchase_preference"] + } + for idx, pid in enumerate(seg["consideration_set"]): + seg_info["v"][pid - 1] = seg["preference_vector"][idx] + segments.append(seg_info) + + # Compute p_l = lambda_l / lambda + p_l = np.array([seg["lambda_l"] / lam for seg in segments]) + + return { + "n": n, "m": m, "L": L, "T": T, "lam": lam, + "r": r, "A": A, "c": c, + "segments": segments, "p_l": p_l + } + + +def compute_choice_probs(S_set, prob_data): + """ + Compute P_j(S) for all j in S, using the MNL model with overlapping segments. + S_set: set of 0-indexed product indices + Returns: dict {j: P_j(S)} for j in S_set + """ + segments = prob_data["segments"] + p_l = prob_data["p_l"] + n = prob_data["n"] + + P = {} + for j in range(n): + if j not in S_set: + P[j] = 0.0 + continue + total = 0.0 + for l_idx, seg in enumerate(segments): + if j in seg["v"]: + # Compute denominator for this segment + denom = seg["v0"] + for h in S_set: + if h in seg["v"]: + denom += seg["v"][h] + P_lj = seg["v"][j] / denom + total += p_l[l_idx] * P_lj + P[j] = total + return P + + +def compute_R_and_Q(S_set, prob_data): + """ + Compute R(S) = sum_{j in S} r_j * P_j(S) (expected revenue) + and Q(S) = A * P(S) (capacity consumption vector) + """ + r = prob_data["r"] + A = prob_data["A"] + n = prob_data["n"] + + P = compute_choice_probs(S_set, prob_data) + + R_S = sum(r[j] * P[j] for j in S_set) + + P_vec = np.array([P.get(j, 0.0) for j in range(n)]) + Q_S = A @ P_vec + + return R_S, Q_S + + +def greedy_heuristic(pi, sigma, prob_data): + """ + Greedy heuristic for the column generation subproblem (Section 4.2.2). + Returns (S_set, reduced_cost) where S_set is the set of products to offer, + and reduced_cost is the subproblem objective value. + """ + n = prob_data["n"] + r = prob_data["r"] + A = prob_data["A"] + segments = prob_data["segments"] + lam = prob_data["lam"] + + # Step 1: For all products j such that r_j - A_j^T pi <= 0, set y_j = 0 + w = np.array([r[j] - A[:, j] @ pi for j in range(n)]) + S_prime = set() + for j in range(n): + if w[j] > 0: + S_prime.add(j) + + if not S_prime: + return set(), -sigma + + # Step 3: Compute j1* = argmax over S' of sum_l (r_j - A_j^T pi) * v_lj / (v_lj + v_l0) + best_val = -np.inf + best_j = None + for j in S_prime: + val = 0.0 + for seg in segments: + if j in seg["v"]: + vlj = seg["v"][j] + val += w[j] * vlj / (vlj + seg["v0"]) + if val > best_val: + best_val = val + best_j = j + + S = {best_j} + S_prime.discard(best_j) + + # Helper: compute Value(S) = subproblem objective without -sigma + def compute_value(S_set): + val = 0.0 + for j in S_set: + for l_idx, seg in enumerate(segments): + if j in seg["v"]: + denom = seg["v0"] + for h in S_set: + if h in seg["v"]: + denom += seg["v"][h] + val += w[j] * seg["lambda_l"] * seg["v"][j] / denom + return val + + # Step 4: Repeat adding products + changed = True + while changed and S_prime: + changed = False + current_val = compute_value(S) + + # Find best product to add from S' + # Compute for each j in S': the objective of S union {j} + best_new_val = -np.inf + best_new_j = None + for j in S_prime: + # Compute objective: sum_l lambda_l * (sum_{i in C_l cap (S union {j})} w_i * v_li) / (sum_{i in C_l cap (S union {j})} v_li + v_l0) + candidate = S | {j} + new_val = 0.0 + for l_idx, seg in enumerate(segments): + num = 0.0 + denom = seg["v0"] + for h in candidate: + if h in seg["v"]: + num += w[h] * seg["v"][h] + denom += seg["v"][h] + new_val += seg["lambda_l"] * num / denom + if new_val > best_new_val: + best_new_val = new_val + best_new_j = j + + # Following paper step 4(a)-(b): use Value(S union {j*}) + if best_new_j is not None: + candidate_val = compute_value(S | {best_new_j}) + if candidate_val > current_val: + S.add(best_new_j) + S_prime.discard(best_new_j) + changed = True + + reduced_cost = compute_value(S) - sigma + return S, reduced_cost + + +def exact_mip_subproblem(pi, sigma, prob_data, time_limit=300): + """ + Exact MIP reformulation for the column generation subproblem (Section 4.2.1). + Returns (S_set, reduced_cost). + """ + n = prob_data["n"] + r = prob_data["r"] + A = prob_data["A"] + segments = prob_data["segments"] + L = prob_data["L"] + + w = np.array([r[j] - A[:, j] @ pi for j in range(n)]) + + # Compute K >= 1/v_min + all_v = [] + for seg in segments: + all_v.append(seg["v0"]) + for v_val in seg["v"].values(): + if v_val > 0: + all_v.append(v_val) + v_min = min(all_v) + K = 1.0 / v_min + 1.0 # add margin + + model = gp.Model("subproblem_mip") + model.setParam("Threads", 1) + model.setParam("OutputFlag", 0) + model.setParam("TimeLimit", time_limit) + + # Variables + y = model.addVars(n, vtype=GRB.BINARY, name="y") + x = model.addVars(L, lb=0.0, name="x") + + # z[l,j] = x_l * y_j (linearized) + z = {} + for l_idx, seg in enumerate(segments): + for j in seg["consideration_set"]: + z[l_idx, j] = model.addVar(lb=0.0, name=f"z_{l_idx}_{j}") + + model.update() + + # Objective: max sum_l sum_{j in C_l} lambda_l * (r_j - A_j^T pi) * v_lj * z_lj + obj = gp.LinExpr() + for l_idx, seg in enumerate(segments): + for j in seg["consideration_set"]: + coeff = seg["lambda_l"] * w[j] * seg["v"][j] + obj += coeff * z[l_idx, j] + model.setObjective(obj, GRB.MAXIMIZE) + + # Constraints + for l_idx, seg in enumerate(segments): + # x_l * v_l0 + sum_{i in C_l} v_li * z_li = 1 + constr = seg["v0"] * x[l_idx] + for j in seg["consideration_set"]: + constr += seg["v"][j] * z[l_idx, j] + model.addConstr(constr == 1.0, name=f"norm_{l_idx}") + + for j in seg["consideration_set"]: + # x_l - z_lj <= K - K * y_j + model.addConstr(x[l_idx] - z[l_idx, j] <= K - K * y[j], + name=f"lin1_{l_idx}_{j}") + # z_lj <= x_l + model.addConstr(z[l_idx, j] <= x[l_idx], + name=f"lin2_{l_idx}_{j}") + # z_lj <= K * y_j + model.addConstr(z[l_idx, j] <= K * y[j], + name=f"lin3_{l_idx}_{j}") + + model.optimize() + + if model.status in [GRB.OPTIMAL, GRB.SUBOPTIMAL, GRB.TIME_LIMIT]: + if model.SolCount > 0: + S_set = set() + for j in range(n): + if y[j].X > 0.5: + S_set.add(j) + obj_val = model.ObjVal + return S_set, obj_val - sigma + else: + return set(), -sigma + else: + return set(), -sigma + + +def solve_cdlp_column_generation(prob_data, time_limit): + """ + Solve the CDLP via column generation (Section 4 of the paper). + Returns the optimal objective value and dual prices. + """ + n = prob_data["n"] + m = prob_data["m"] + T = prob_data["T"] + lam = prob_data["lam"] + c = prob_data["c"] + segments = prob_data["segments"] + + start_time = time.time() + + # A.2. Initialization: single column containing one product per segment + # Pick the first product of each segment (0-indexed, in labeling order) + init_products = set() + for seg in segments: + first_product = min(seg["consideration_set"]) + init_products.add(first_product) + + columns = [frozenset(init_products)] # list of frozensets + column_set = {columns[0]} # for duplicate checking + + # Precompute R(S) and Q(S) for each column + R_vals = [] + Q_vals = [] + R_S, Q_S = compute_R_and_Q(init_products, prob_data) + R_vals.append(R_S) + Q_vals.append(Q_S) + + iteration = 0 + best_obj = 0.0 + best_pi = np.zeros(m) + best_sigma = 0.0 + best_t_vals = {} + + while True: + elapsed = time.time() - start_time + if elapsed > time_limit: + break + + iteration += 1 + k = len(columns) + + # Solve reduced LP (Equation (4)) + master = gp.Model("CDLP_master") + master.setParam("Threads", 1) + master.setParam("OutputFlag", 0) + remaining_time = max(1, time_limit - (time.time() - start_time)) + master.setParam("TimeLimit", remaining_time) + + t_vars = master.addVars(k, lb=0.0, name="t") + master.update() + + # Objective: max sum_S lambda * R(S) * t(S) + obj = gp.LinExpr() + for idx in range(k): + obj += lam * R_vals[idx] * t_vars[idx] + master.setObjective(obj, GRB.MAXIMIZE) + + # Capacity constraints: sum_S lambda * Q_i(S) * t(S) <= c_i + cap_constrs = [] + for i in range(m): + constr = gp.LinExpr() + for idx in range(k): + constr += lam * Q_vals[idx][i] * t_vars[idx] + cap_constrs.append(master.addConstr(constr <= c[i], name=f"cap_{i}")) + + # Time constraint: sum_S t(S) <= T + time_constr_expr = gp.LinExpr() + for idx in range(k): + time_constr_expr += t_vars[idx] + time_constr = master.addConstr(time_constr_expr <= T, name="time") + + master.optimize() + + if master.status != GRB.OPTIMAL: + break + + best_obj = master.ObjVal + + # Get dual prices + pi = np.array([cap_constrs[i].Pi for i in range(m)]) + sigma = time_constr.Pi + + best_pi = pi.copy() + best_sigma = sigma + best_t_vals = {} + for idx in range(k): + if t_vars[idx].X > 1e-8: + best_t_vals[idx] = t_vars[idx].X + + master.dispose() + + # Check time + elapsed = time.time() - start_time + if elapsed > time_limit: + break + + # Solve column generation subproblem + # First try greedy heuristic + S_greedy, rc_greedy = greedy_heuristic(pi, sigma, prob_data) + + if rc_greedy > 1e-8 and len(S_greedy) > 0: + new_col = frozenset(S_greedy) + if new_col not in column_set: + columns.append(new_col) + column_set.add(new_col) + R_S, Q_S = compute_R_and_Q(S_greedy, prob_data) + R_vals.append(R_S) + Q_vals.append(Q_S) + continue + + # If greedy fails, try exact MIP + elapsed = time.time() - start_time + remaining = max(1, time_limit - elapsed) + S_exact, rc_exact = exact_mip_subproblem(pi, sigma, prob_data, + time_limit=remaining) + + if rc_exact > 1e-8 and len(S_exact) > 0: + new_col = frozenset(S_exact) + if new_col not in column_set: + columns.append(new_col) + column_set.add(new_col) + R_S, Q_S = compute_R_and_Q(S_exact, prob_data) + R_vals.append(R_S) + Q_vals.append(Q_S) + continue + + # No entering column found -> optimal + break + + # Build solution details + solution_columns = [] + for idx, t_val in best_t_vals.items(): + solution_columns.append({ + "offer_set": sorted([j + 1 for j in columns[idx]]), # 1-indexed + "time_allocated": t_val + }) + + return { + "objective_value": best_obj, + "dual_prices_pi": best_pi.tolist(), + "dual_price_sigma": best_sigma, + "num_iterations": iteration, + "num_columns_generated": len(columns), + "active_columns": solution_columns + } + + +def main(): + parser = argparse.ArgumentParser( + description="Solve CDLP via Column Generation (Bront et al. 2009)") + 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) + + # Load instance + data = load_instance(args.instance_path) + + # Build problem data structures + prob_data = build_problem_data(data) + + print(f"Problem: {data.get('description', 'N/A')}") + print(f" Products: {prob_data['n']}, Legs: {prob_data['m']}, " + f"Segments: {prob_data['L']}, T: {prob_data['T']}") + print(f" Capacities: {prob_data['c'].tolist()}") + print(f" Lambda: {prob_data['lam']}") + print(f" Time limit: {args.time_limit}s") + + # Solve CDLP via column generation + start = time.time() + result = solve_cdlp_column_generation(prob_data, args.time_limit) + elapsed = time.time() - start + + print(f"\nResults:") + print(f" CDLP Objective Value: {result['objective_value']:.4f}") + print(f" Dual prices (pi): {result['dual_prices_pi']}") + print(f" Dual price (sigma): {result['dual_price_sigma']:.4f}") + print(f" Column generation iterations: {result['num_iterations']}") + print(f" Total columns generated: {result['num_columns_generated']}") + print(f" Elapsed time: {elapsed:.2f}s") + print(f"\n Active offer sets:") + for col in result["active_columns"]: + print(f" S = {col['offer_set']}, t(S) = {col['time_allocated']:.4f}") + + # Save solution + solution = { + "objective_value": result["objective_value"], + "instance_id": data.get("instance_id", "unknown"), + "solver": "Gurobi (column generation)", + "method": "CDLP", + "elapsed_time_seconds": elapsed, + "dual_prices_pi": result["dual_prices_pi"], + "dual_price_sigma": result["dual_price_sigma"], + "num_iterations": result["num_iterations"], + "num_columns_generated": result["num_columns_generated"], + "active_columns": result["active_columns"] + } + + 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 saved to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/bront2009/gurobi_feasi_result/large_feasi_result_1.json b/tasks/bront2009/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bront2009/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/bront2009/gurobi_feasi_result/large_feasi_result_2.json b/tasks/bront2009/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bront2009/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/bront2009/gurobi_feasi_result/large_feasi_result_3.json b/tasks/bront2009/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bront2009/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/bront2009/gurobi_feasi_result/large_feasi_result_4.json b/tasks/bront2009/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bront2009/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/bront2009/gurobi_feasi_result/large_feasi_result_5.json b/tasks/bront2009/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bront2009/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/bront2009/gurobi_feasi_result/tiny_feasi_result.json b/tasks/bront2009/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bront2009/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/bront2009/gurobi_solution/large_solution_1.json b/tasks/bront2009/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..de5e6e88ca61069d10a6f49cb703599fd1ca2979 --- /dev/null +++ b/tasks/bront2009/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:457c0cbe0cd035c0e49dc9babd05d775c27142aade1aa47df12935ef7305aeeb +size 10213 diff --git a/tasks/bront2009/gurobi_solution/large_solution_2.json b/tasks/bront2009/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4b62a94c78251307d86f8f74bf54a71b040ee133 --- /dev/null +++ b/tasks/bront2009/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e3dc502d84f0e49441e1ddaa2c4f397a3149d8b46fdb91f4e696c0ed3e1b4b3 +size 15606 diff --git a/tasks/bront2009/gurobi_solution/large_solution_3.json b/tasks/bront2009/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..f10a1e83846948579e74b6fa5419a020efbe1ad0 --- /dev/null +++ b/tasks/bront2009/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:881391121c9598c21b1e26ea02b7e7e47a9d7c6b00abd97c7757b37e5baefd33 +size 14210 diff --git a/tasks/bront2009/gurobi_solution/large_solution_4.json b/tasks/bront2009/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ef4917c8adc99b168b00881e4d90a4b796ba15ab --- /dev/null +++ b/tasks/bront2009/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a37adbbe43998ce989c435decb97b9a5c8205aaa6960e5577f8d86ddc928d38 +size 14776 diff --git a/tasks/bront2009/gurobi_solution/large_solution_5.json b/tasks/bront2009/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..986d73307bf5b0a5e3dc4f165c92dc16d128eae6 --- /dev/null +++ b/tasks/bront2009/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a23014727d7dbdd2093bcfd8e9866fb0a81834b346de4135222ee24b7f046418 +size 12443 diff --git a/tasks/bront2009/gurobi_solution/tiny_solution.json b/tasks/bront2009/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..0a107045e8f63cafad9c30bf6505c688a89a3c3c --- /dev/null +++ b/tasks/bront2009/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43fd925e293fe5bae221ce05f10a67436813c298987c144d0636d4cc128b6f91 +size 841 diff --git a/tasks/bront2009/gurobi_solution_log/large_log_1.jsonl b/tasks/bront2009/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ad4b986589ffd7b694e0c96f90bde44ee0bd5034 --- /dev/null +++ b/tasks/bront2009/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8dd61a0c7c6eceff841db8b0ad1f0226ddf0b14e9805493ba80e46efbced7d0a +size 42 diff --git a/tasks/bront2009/gurobi_solution_log/large_log_2.jsonl b/tasks/bront2009/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d7975d7686152ff56b9235a1a4cc9db7a405d893 --- /dev/null +++ b/tasks/bront2009/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f0f61808352b4c4b7522415647ee913d8f4c839ec5da245a58ee543b4ef59da +size 43 diff --git a/tasks/bront2009/gurobi_solution_log/large_log_3.jsonl b/tasks/bront2009/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1e7b9a9c95178fff6e80578585ee0a5f9b1d2357 --- /dev/null +++ b/tasks/bront2009/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6698b5afad084625592d2387f3c6141e7574fce6a4b980e4d56e89d8b999ecd +size 43 diff --git a/tasks/bront2009/gurobi_solution_log/large_log_4.jsonl b/tasks/bront2009/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4c8617b486336ba691f54fc995ca8897115a2c31 --- /dev/null +++ b/tasks/bront2009/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e881d1f04ed2540358d69c29e4736cd4922c95eba4242c29d5fe0957d220a9b +size 43 diff --git a/tasks/bront2009/gurobi_solution_log/large_log_5.jsonl b/tasks/bront2009/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac292c09c669895ef424ce822b0225399ae44515 --- /dev/null +++ b/tasks/bront2009/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8188d54bce13f0dce776b8038899a35a6dfc8ea98f9c67212fea629424f47f7 +size 43 diff --git a/tasks/bront2009/gurobi_solution_log/tiny_log.jsonl b/tasks/bront2009/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dbbc8c0cf515234daca469301bf28144db01b840 --- /dev/null +++ b/tasks/bront2009/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a5b6532f1041d7b4861dc2589e198a412859c8fce45890962b082e786db21e0 +size 54 diff --git a/tasks/bront2009/instance/large_instance_1.json b/tasks/bront2009/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a54c76bc2ab87243f5af28e591f5d0ddabb4442a --- /dev/null +++ b/tasks/bront2009/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa07d275277bd8a612f3ef3a539a35edf365310e2253087382bdf9141d041721 +size 54751 diff --git a/tasks/bront2009/instance/large_instance_2.json b/tasks/bront2009/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b9da8d7408782a8eb92e488fa1a6cec4a1bca82b --- /dev/null +++ b/tasks/bront2009/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9c29ba8b8a315a8e33c869a86c6db4835b9d7adfcc78c509a043552b172dc1c +size 54761 diff --git a/tasks/bront2009/instance/large_instance_3.json b/tasks/bront2009/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..fec0e9c7dfb6d8feb1927c2c24ff5b7c8f144ab8 --- /dev/null +++ b/tasks/bront2009/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40aa7d48f27c87c1c086bd8c0b98ba6d2ad5148a4d82c5e44950f5fe4835f47b +size 54761 diff --git a/tasks/bront2009/instance/large_instance_4.json b/tasks/bront2009/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..37f6cc4c02b1aa1862ff8bc25a3f2be3625a577d --- /dev/null +++ b/tasks/bront2009/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbf44c50be19d10abf7ef13ff75e886042f44cbe3a965fabb63003d60d6864e9 +size 54761 diff --git a/tasks/bront2009/instance/large_instance_5.json b/tasks/bront2009/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e3ec5e4ffa7e835df80c79f3bb6529e902d2c7d9 --- /dev/null +++ b/tasks/bront2009/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f50fff20463bd19b4ebbec45a8374c5f67e3b9a5d13b2097cb7d37a5fbb6acc4 +size 54761 diff --git a/tasks/bront2009/instance/tiny_instance.json b/tasks/bront2009/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..52192059685dab76d278f270568200d79a66eb90 --- /dev/null +++ b/tasks/bront2009/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4abf7ea13410b0fe7471d3af523c6a37e362d903cdfdb1ec2d226427c2a8f206 +size 3509 diff --git a/tasks/bront2009/instance_schema.json b/tasks/bront2009/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..dd4ff00f9c46a403d298de22e4586b18169c753e --- /dev/null +++ b/tasks/bront2009/instance_schema.json @@ -0,0 +1,39 @@ +{ + "network": { + "num_cities": " Number of cities in the airline network.", + "city_names": " Name of each city in the network.", + "num_legs": " Number of flight legs in the network.", + "legs": [ + { + "leg_id": " Unique identifier for this flight leg.", + "origin": " City where this flight leg departs.", + "destination": " City where this flight leg arrives.", + "capacity": " Number of available seats on this flight leg." + } + ] + }, + "products": [ + { + "product_id": " Unique identifier for this product.", + "origin_destination": " Route of the itinerary, with intermediate stops separated by arrows.", + "class": " Fare class of this product.", + "fare": " Revenue earned per unit sold of this product.", + "legs_used": " Leg IDs of the flight legs consumed by one unit of this product." + } + ], + "segments": [ + { + "segment_id": " Unique identifier for this customer segment.", + "lambda_l": " Arrival rate of customers in this segment per period.", + "consideration_set": " Product IDs that customers in this segment would consider purchasing.", + "preference_vector": " Preference weight of each product in the consideration set, in the same order.", + "no_purchase_preference": " Preference weight for the no-purchase option for customers in this segment.", + "description": " Brief label describing the segment's market and price sensitivity." + } + ], + "booking_horizon": { + "T": " Number of discrete time periods in the booking horizon." + }, + "alpha": " Capacity scarcity factor used to scale leg capacities.", + "lambda": " Overall probability that a customer arrives in any single period." +} diff --git a/tasks/bront2009/mathematical_formulation.md b/tasks/bront2009/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3b0691384d4fdad625ed04af245791d06eb2e43b --- /dev/null +++ b/tasks/bront2009/mathematical_formulation.md @@ -0,0 +1,53 @@ +# Original Formulation: Choice-Based Deterministic Linear Program (CDLP) + +*Source: A Column Generation Algorithm for Choice-Based Network Revenue Management, Bront, Méndez-Díaz, and Vulcano, 2009.* + +## Sets and Parameters + +- $N = \{1,\dots,n\}$: set of products (itinerary and fare-class combinations). + +- $m$: number of resources (flight legs), indexed by $i = 1,\dots,m$. + +- $L$: number of customer segments, indexed by $l = 1,\dots,L$. + +- $T$: length of the booking horizon (number of discrete time periods). + +- $S \subseteq N$: an offer set (a subset of products made available to arriving customers). + +- $C_l \subseteq N$: consideration set of segment $l$ (overlap across segments is allowed). + +- $c = (c_1,\dots,c_m)^{\top}$: initial capacity vector of the resources. + +- $A = [a_{ij}] \in \{0,1\}^{m \times n}$: resource-product incidence matrix; $A_j$ denotes the $j$-th column. + +- $r_j$: revenue collected from selling one unit of product $j$. + +- $\lambda$: probability that a customer arrives in a given time period; $p_l$ is the conditional probability of segment $l$ given an arrival, with $\sum_l p_l = 1$; $\lambda_l = \lambda p_l$. + +- $v_{lj} \geq 0$ for $j \in C_l$: preference weight of segment $l$ for product $j$, with $v_{l0} > 0$ the no-purchase weight. + +- Under the MNL choice model, the probability that a segment-$l$ arrival chooses $j \in S$ is $P_{lj}(S) = v_{lj} / \bigl(\sum_{h \in C_l \cap S} v_{lh} + v_{l0}\bigr)$, and the aggregate purchase probability of product $j$ under $S$ is $P_j(S) = \sum_{l=1}^{L} p_l P_{lj}(S)$. + +- Expected per-period revenue from $S$: $R(S) = \sum_{j \in S} r_j P_j(S)$. + +- Resource consumption vector from $S$: $Q(S) = A\, P(S)$ where $P(S) = (P_1(S),\dots,P_n(S))^{\top}$. + +## Decision Variables + +- $t(S) \geq 0$ for every $S \subseteq N$: (continuous) number of time periods during which offer set $S$ is made available. + +## Objective + +$$\begin{equation} +V^{\mathrm{CDLP}} \;=\; \max \; \sum_{S \subseteq N} \lambda\, R(S)\, t(S) \tag{3} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{S \subseteq N} \lambda\, Q(S)\, t(S) & \;\leq\; c, \tag{3a} \\ +\sum_{S \subseteq N} t(S) & \;\leq\; T, \tag{3b} \\ +t(S) & \;\geq\; 0, \qquad \forall S \subseteq N. \tag{3c} +\end{align}$$ + +The formulation has one variable $t(S)$ for each of the $2^{n}-1$ nonempty subsets $S \subseteq N$, i.e. an exponential family of variables; the paper solves it via column generation. diff --git a/tasks/bront2009/problem_description.txt b/tasks/bront2009/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..9feabba1b47ffa2e42e479aaf427c6f4eaef3660 --- /dev/null +++ b/tasks/bront2009/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +An airline operates a network of flight legs connecting several cities. Each leg has a fixed seat capacity. Products sold to customers are itinerary-and-fare-class combinations, where each product is defined by an origin-destination path (possibly spanning multiple legs), a fare class, and a fare (revenue per unit sold). Each product consumes one seat on every leg along its route; for each combination of a leg and a product, it is known whether or not that product uses that leg. + +Customers arrive one at a time over a discrete booking horizon spanning a given number of time periods. In each period, at most one customer arrives. The probability of an arrival in any period is given by a global arrival rate. Customers belong to one of several market segments. Each segment has a known arrival rate equal to the global arrival rate multiplied by the segment's probability share, where the segment probabilities sum to one. Each segment is characterized by a consideration set, which is a subset of the products that customers in that segment would consider purchasing. Consideration sets of different segments may overlap, meaning the same product can appear in the consideration sets of multiple segments. Each segment also has a positive preference weight for every product in its consideration set and a strictly positive no-purchase preference weight. When a customer from a given segment is presented with a set of available products (an offer set), the customer's probability of choosing a particular product in the intersection of the offer set and the segment's consideration set equals that product's preference weight divided by the sum of the preference weights of all products in that intersection plus the no-purchase preference weight. A product outside the intersection is never chosen. The aggregate probability that an arriving customer (whose segment is unknown to the firm) purchases a given product in the offer set equals the sum over all segments of the segment probability times the segment-level choice probability for that product. + +The airline's task is to determine, for every possible nonempty subset of products that could be offered, the total amount of time (measured in number of periods) during which that offer set is made available over the booking horizon. The time allocated to each offer set must be zero or positive. The expected revenue generated when a particular offer set is shown to an arriving customer equals the sum, over all products in that set, of the product's fare times the aggregate purchase probability for that product under that set. The expected consumption of capacity on each leg when an offer set is shown equals the sum of the aggregate purchase probabilities for all products in that set which use that leg. + +The total expected capacity consumption on each leg, summed across all offer sets weighted by the arrival rate and the time allocated to each set, must not exceed the leg's initial seat capacity. The total time allocated across all offer sets must not exceed the length of the booking horizon. The goal is to choose the time allocations for each possible offer set so as to maximize total expected revenue, computed as the sum over all offer sets of the arrival rate times the expected revenue of the set times the time allocated to that set. diff --git a/tasks/bront2009/solution_logger.py b/tasks/bront2009/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/bront2009/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/bront2009/solution_schema.json b/tasks/bront2009/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..48b1a22dc7de70e09088c68e65de4e5bf9699dbe --- /dev/null +++ b/tasks/bront2009/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total expected revenue generated over the booking horizon.", + "active_columns": [ + { + "offer_set": " Subset of product identifiers that is shown to arriving customers during this allocation.", + "time_allocated": " Number of booking periods during which this offer set is made available." + } + ] +} diff --git a/tasks/buchheim2018/feasibility_check.py b/tasks/buchheim2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..da17fa176cc91315188aff1df4a7f2f44df0d393 --- /dev/null +++ b/tasks/buchheim2018/feasibility_check.py @@ -0,0 +1,459 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Quadratic Shortest Path Problem (QSPP) +from Buchheim & Traversi (2018), Problem (19). + +Checks each hard constraint one by one: + Constraint 1: Flow conservation for intermediate nodes + sum_{a in delta+(i)} x_a - sum_{a in delta-(i)} x_a = 0 + for all i in N \\ {s, t} + Constraint 2: Source outflow = 1 + sum_{a in delta+(s)} x_a = 1 + Constraint 3: Sink inflow = 1 + sum_{a in delta-(t)} x_a = 1 + Constraint 4: Binary variables + x_a in {0, 1} for all a in A + Constraint 5: Binary domain check (auto-generated) for solution_x + Constraint 6: Integer domain check (auto-generated) + Constraint 7: Objective consistency -- reported objective_value must + equal the recomputed value + sum_{a,b in A} Q_{ab} x_a x_b + sum_{a in A} L_a x_a +""" + +import argparse +import json +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'solution_arcs') +_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 + + num_nodes = instance["num_nodes"] + num_arcs = instance["num_arcs"] + source = instance["source_node"] + target = instance["target_node"] + arcs = instance["arcs"] + + # Original solution structure is solution_arcs (list of selected arcs); + # derive the binary x vector from it. Accept legacy solution_x dict + # only as a fallback. + x = [0.0] * num_arcs + sol_arcs = solution.get("solution_arcs") + if sol_arcs: + for arc in sol_arcs: + arc_id = int(arc.get("id", -1)) + if 0 <= arc_id < num_arcs: + x[arc_id] = 1.0 + else: + for k, v in solution.get("solution_x", {}).items(): + x[int(k)] = float(v) + solution_x = {str(i): int(round(x[i])) for i in range(num_arcs) if x[i] > 0.5} + + # Build adjacency lists: outgoing and incoming arcs for each node + delta_plus = defaultdict(list) # outgoing arcs + delta_minus = defaultdict(list) # incoming arcs + for arc in arcs: + aid = arc["id"] + delta_plus[arc["from_node"]].append(aid) + delta_minus[arc["to_node"]].append(aid) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------ + # Constraint 1: Flow conservation for intermediate nodes (= 0) + # sum_{a in delta+(i)} x_a - sum_{a in delta-(i)} x_a = 0 + # for all i in N \ {s, t} + # ------------------------------------------------------------------ + for i in range(num_nodes): + if i == source or i == target: + continue + out_flow = sum(x[a] for a in delta_plus.get(i, [])) + in_flow = sum(x[a] for a in delta_minus.get(i, [])) + lhs = out_flow - in_flow + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + violated_constraints.add(1) + violations.append( + f"Constraint 1: Flow conservation violated at node {i}: " + f"outflow={out_flow}, inflow={in_flow}, net={lhs}" + ) + 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: Source outflow = 1 + # sum_{a in delta+(s)} x_a = 1 + # ------------------------------------------------------------------ + lhs_source = sum(x[a] for a in delta_plus.get(source, [])) + rhs_source = 1.0 + violation_amount = abs(lhs_source - rhs_source) + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Constraint 2: Source outflow violated: " + f"sum of outgoing arcs from source = {lhs_source}, expected 1" + ) + normalizer = max(abs(rhs_source), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_source, + "rhs": rhs_source, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 3: Sink inflow = 1 + # sum_{a in delta-(t)} x_a = 1 + # ------------------------------------------------------------------ + lhs_sink = sum(x[a] for a in delta_minus.get(target, [])) + rhs_sink = 1.0 + violation_amount = abs(lhs_sink - rhs_sink) + if violation_amount > tol: + violated_constraints.add(3) + violations.append( + f"Constraint 3: Sink inflow violated: " + f"sum of incoming arcs to target = {lhs_sink}, expected 1" + ) + normalizer = max(abs(rhs_sink), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_sink, + "rhs": rhs_sink, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 4: Binary constraint x_a in {0, 1} for all a in A + # ------------------------------------------------------------------ + for a in range(num_arcs): + dist_to_0 = abs(x[a] - 0.0) + dist_to_1 = abs(x[a] - 1.0) + violation_amount = min(dist_to_0, dist_to_1) + if violation_amount > tol: + # Nearest feasible binary value + nearest_binary = 0.0 if dist_to_0 <= dist_to_1 else 1.0 + violated_constraints.add(4) + violations.append( + f"Constraint 4: Binary constraint violated for arc {a}: " + f"x_{a} = {x[a]}" + ) + normalizer = max(abs(nearest_binary), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": x[a], + "rhs": nearest_binary, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # Build result + _domain_check_vars_binary = [("solution_x", solution_x)] + _domain_check_vars_integer = [] + + # ===================================================================== + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # ===================================================================== + # Constraint 5: 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_constraints.add(5) + violations.append( + f"Constraint 5 (binary domain): {var_name}[{key}] = {v} not in {0, 1}") + violation_magnitudes.append({ + "constraint": 5, + "lhs": v, + "rhs": 1.0, + "raw_excess": float(viol), + "normalizer": 1.0, + "ratio": float(viol), + }) + + # Constraint 6: 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_constraints.add(6) + violations.append( + f"Constraint 6 (integer domain): {var_name}[{key}] = {v} is not integer") + violation_magnitudes.append({ + "constraint": 6, + "lhs": v, + "rhs": round(v), + "raw_excess": float(frac), + "normalizer": max(abs(round(v)), eps), + "ratio": float(frac / max(abs(round(v)), eps)), + }) + + # ------------------------------------------------------------------ + # Constraint 7: Objective consistency + # reported objective_value must equal + # sum_{a,b in A} Q_{ab} x_a x_b + sum_{a in A} L_a x_a + # All variables (selected arcs) are present in the solution, so we + # can fully recompute the true objective. Tolerance is 0.5 because + # the paper states coefficients are purely integer (see math_model.txt + # reproduction-critical comment 6), so an integer mismatch by >=1 + # should fire regardless of relative magnitude. + # ------------------------------------------------------------------ + linear_costs = instance.get("linear_costs") + quadratic_costs = instance.get("quadratic_costs") + reported_obj = solution.get("objective_value") + if linear_costs is not None and quadratic_costs is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + # Selected arcs (treat any x[a] > 0.5 as selected) + selected = [a for a in range(num_arcs) if x[a] > 0.5] + linear_part = sum(float(linear_costs[a]) for a in selected) + quadratic_part = 0.0 + for a in selected: + row = quadratic_costs[a] + for b in selected: + quadratic_part += float(row[b]) + true_obj = linear_part + quadratic_part + abs_diff = abs(reported - true_obj) + # Integer coefficients per paper -- tighten to 0.5 so any + # off-by-1 (or worse) fires regardless of magnitude. + obj_tol = max(0.5, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(7) + violations.append( + f"Constraint 7: Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed sum_a,b Q_ab x_a x_b + sum_a L_a x_a=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + 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 QSPP (Buchheim & Traversi 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() + + 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"]: + 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/buchheim2018/gurobi_code.py b/tasks/buchheim2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..1c1a7abda9050d52a24cec1a5d8151708722c667 --- /dev/null +++ b/tasks/buchheim2018/gurobi_code.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Quadratic Shortest Path Problem (QSPP) +from Buchheim & Traversi (2018), "Quadratic Combinatorial Optimization +_GUROBI_CODE_START_TIME = time.time() +Using Separable Underestimators", INFORMS J. Computing 30(3):424-437. + +Model (19): + min sum_(a,b in A) Q_ab x_a x_b + sum_(a in A) L_a x_a + s.t. flow conservation for all intermediate nodes + source outflow = 1 + sink inflow = 1 + x_a in (0,1) for all a in A +""" + +import argparse +import json +import os +import sys +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_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 QSPP instance from JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(data, time_limit): + """Build and solve the QSPP model using Gurobi.""" + num_arcs = data["num_arcs"] + num_nodes = data["num_nodes"] + source = data["source_node"] + target = data["target_node"] + arcs = data["arcs"] + linear_costs = data["linear_costs"] + Q = data["quadratic_costs"] + + # Build adjacency: outgoing and incoming arcs for each node + delta_plus = defaultdict(list) # outgoing arcs + delta_minus = defaultdict(list) # incoming arcs + for arc in arcs: + aid = arc["id"] + delta_plus[arc["from_node"]].append(aid) + delta_minus[arc["to_node"]].append(aid) + + # Create model + model = gp.Model("QSPP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + # Suppress output for cleaner runs; remove if debugging is needed + model.setParam("OutputFlag", 1) + + # Decision variables: x_a in {0,1} for each arc a + x = model.addVars(num_arcs, vtype=GRB.BINARY, name="x") + + # Objective: min sum_{a,b} Q_{ab} x_a x_b + sum_a L_a x_a + obj = gp.QuadExpr() + # Linear part + for a in range(num_arcs): + obj += linear_costs[a] * x[a] + # Quadratic part + for a in range(num_arcs): + for b in range(a, num_arcs): + if Q[a][b] != 0: + if a == b: + # x_a^2 = x_a for binary, so diagonal contributes Q[a][a]*x_a + # But Q diagonal is 0 per the instance data. Include for generality. + obj += Q[a][a] * x[a] + else: + # Q is symmetric: Q[a][b]*x_a*x_b + Q[b][a]*x_b*x_a = 2*Q[a][b]*x_a*x_b + # Gurobi expects the combined coefficient for x_a*x_b when a != b + obj += (Q[a][b] + Q[b][a]) * x[a] * x[b] + + model.setObjective(obj, GRB.MINIMIZE) + + # Flow conservation constraints + all_nodes = set(range(num_nodes)) + for i in all_nodes: + out_arcs = delta_plus.get(i, []) + in_arcs = delta_minus.get(i, []) + if i == source: + # sum_{a in delta+(s)} x_a = 1 + model.addConstr( + gp.quicksum(x[a] for a in out_arcs) == 1, + name=f"source_{i}" + ) + elif i == target: + # sum_{a in delta-(t)} x_a = 1 + model.addConstr( + gp.quicksum(x[a] for a in in_arcs) == 1, + name=f"sink_{i}" + ) + else: + # Flow conservation: out - in = 0 + model.addConstr( + gp.quicksum(x[a] for a in out_arcs) + - gp.quicksum(x[a] for a in in_arcs) == 0, + name=f"flow_{i}" + ) + + # Optimize + model.optimize() + + # Extract solution + result = {} + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = model.Status + result["status_str"] = { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + }.get(model.Status, str(model.Status)) + result["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + # Record active arcs in the solution + sol_arcs = [] + for a in range(num_arcs): + if x[a].X > 0.5: + sol_arcs.append(arcs[a]) + result["solution_arcs"] = sol_arcs + else: + result["objective_value"] = None + result["status"] = model.Status + result["status_str"] = "NO_SOLUTION_FOUND" + result["solution_arcs"] = [] + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve QSPP using Gurobi (Buchheim & Traversi 2018)" + ) + 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) + + data = load_instance(args.instance_path) + result = build_and_solve(data, args.time_limit) + + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status_str']}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/buchheim2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/buchheim2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/buchheim2018/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/buchheim2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/buchheim2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/buchheim2018/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/buchheim2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/buchheim2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/buchheim2018/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/buchheim2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/buchheim2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/buchheim2018/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/buchheim2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/buchheim2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/buchheim2018/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/buchheim2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/buchheim2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/buchheim2018/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/buchheim2018/gurobi_solution/large_solution_1.json b/tasks/buchheim2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c285bd75d76c57b116c1ac6aab5bcea77d5814c3 --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:533102ddb1daf7b90e1ddf27cd1553ff5b032defddfe525f88de097cf92f5e32 +size 2223 diff --git a/tasks/buchheim2018/gurobi_solution/large_solution_2.json b/tasks/buchheim2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4561a71674382efbc415b898bb5ba995a9c7e100 --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b466d3b9954afb642636fc737b5f792dd92c90d441160b554e769abc96e8e383 +size 2215 diff --git a/tasks/buchheim2018/gurobi_solution/large_solution_3.json b/tasks/buchheim2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8014b733517f7e9c0b722c20ea2f2d1f56bce848 --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e788817a9ed89fe53b73795cba33f2e53e7491c29c976111518701aee18fd36a +size 2226 diff --git a/tasks/buchheim2018/gurobi_solution/large_solution_4.json b/tasks/buchheim2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..64f6f2db11c7307825415ade507a156e49cd9b5d --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4fb9f936c8105b19e83368c7f86eb69b1f579afd88f3be5f3dfdfab7162f8d1 +size 2235 diff --git a/tasks/buchheim2018/gurobi_solution/large_solution_5.json b/tasks/buchheim2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..2a343443b551d40259279970e6a22f01f551f4d1 --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03fdd3868dcf695a40438f33937c6b93706ed81955f6e7681838640951b4c03b +size 2214 diff --git a/tasks/buchheim2018/gurobi_solution/tiny_solution.json b/tasks/buchheim2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..c61b442b358b3950587592e9f4a7f91ddba38d9c --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ddd6bdc6bd3778523aa62b56959b221c2f4f80b2a721d64fd79fd69e8f91e7bc +size 1435 diff --git a/tasks/buchheim2018/gurobi_solution_log/large_log_1.jsonl b/tasks/buchheim2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fa430a3f0df8f97b3d1393569e8a4d80c3d46b40 --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22fb38b5e2db53b4d9754e831c2a5f669db227ab0bcaac4040ec432bee6451ac +size 343 diff --git a/tasks/buchheim2018/gurobi_solution_log/large_log_2.jsonl b/tasks/buchheim2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f51a1b80662569c28ab1987c29a39e2e26ccda5b --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6dd184d4840950839bdc0829ef2eeb11f84f9a6379d8e0f4915d8dc28b401b7c +size 216 diff --git a/tasks/buchheim2018/gurobi_solution_log/large_log_3.jsonl b/tasks/buchheim2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..71c7643049df433e1f65226c0df6813ca2ad00ae --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7aeeacbceeb07484da6cfdf39e02e980eb800e879e28745ef69555faebf4f17b +size 387 diff --git a/tasks/buchheim2018/gurobi_solution_log/large_log_4.jsonl b/tasks/buchheim2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cf603a83f117359420fbbf5cca1b9fa6b0000e3d --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67ffa59eed72fa257f279d9c0f3525e1f378af899ad7009c5170b8c679203078 +size 303 diff --git a/tasks/buchheim2018/gurobi_solution_log/large_log_5.jsonl b/tasks/buchheim2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2bd92c0e23891b46118688413df97a521f30bbba --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a5c6f00670fd8b8100a5bbbc4963b07ed194ad8040ad8495d700d7d6b858fc7 +size 43 diff --git a/tasks/buchheim2018/gurobi_solution_log/tiny_log.jsonl b/tasks/buchheim2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..884ba60f11af55244a0695f96f6c070f09233684 --- /dev/null +++ b/tasks/buchheim2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92e2f99b113721264283403eaed5bee82945fc055d4d0b0a417b2bd25009c0b6 +size 42 diff --git a/tasks/buchheim2018/instance/large_instance_1.json b/tasks/buchheim2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..8082b1d999367640158bfd4479f23218e84d02c9 --- /dev/null +++ b/tasks/buchheim2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a742fbe3d62134d23ea6e684f3a7091eb0de3d5f6928c07c7553653c81a75185 +size 576281 diff --git a/tasks/buchheim2018/instance/large_instance_2.json b/tasks/buchheim2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..3208ef199f74dd7806f166cf9a3403af836a6efa --- /dev/null +++ b/tasks/buchheim2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d7de13fd051c0e73f245619bf417f2902e934036533f37a483b1087ae7599d0 +size 563348 diff --git a/tasks/buchheim2018/instance/large_instance_3.json b/tasks/buchheim2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9eb7e32a26492286230e62afac445e0a8b70d71a --- /dev/null +++ b/tasks/buchheim2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e03f68665136c410965a4e8e675e1c74147bd9ce315fcb725e299f22b24067e +size 567803 diff --git a/tasks/buchheim2018/instance/large_instance_4.json b/tasks/buchheim2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4b6d8334cf1d8f92bae04ce44035ac8da1ceee3c --- /dev/null +++ b/tasks/buchheim2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2eb7039092fcf77a9ae0d528b18b9b000171e3dbd6e86ff28299a2d284492d1 +size 571902 diff --git a/tasks/buchheim2018/instance/large_instance_5.json b/tasks/buchheim2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3740a39f02d138e17fa709c89dbac1acae6fbb44 --- /dev/null +++ b/tasks/buchheim2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d369c602e5f95732232f6d819c98914f4f5e9105b3d73ef49876b813048fcab5 +size 565775 diff --git a/tasks/buchheim2018/instance/tiny_instance.json b/tasks/buchheim2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..9dac67296171769b558d148b44d1abfc2f893926 --- /dev/null +++ b/tasks/buchheim2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46f65d015c59fbcb0f7927457164dc01149104f7551ab73524bb787fc83d840a +size 112902 diff --git a/tasks/buchheim2018/instance_schema.json b/tasks/buchheim2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ea72c1b3d9b75506f6143cf893bf79998343be11 --- /dev/null +++ b/tasks/buchheim2018/instance_schema.json @@ -0,0 +1,23 @@ +{ + "grid_size_k": " Side length of the square grid network.", + "num_nodes": " Total number of nodes in the grid network.", + "num_arcs": " Total number of directed arcs in the grid network.", + "source_node": " Identifier of the origin node where the path must start.", + "target_node": " Identifier of the destination node where the path must end.", + "nodes": [ + { + "id": " Unique identifier of this node in row-major order.", + "row": " Row position of this node in the grid.", + "col": " Column position of this node in the grid." + } + ], + "arcs": [ + { + "id": " Unique identifier of this arc.", + "from_node": " Identifier of the node where this arc originates.", + "to_node": " Identifier of the node where this arc terminates." + } + ], + "linear_costs": " Traversal cost incurred for using each arc in the path.", + "quadratic_costs": " Symmetric interaction cost incurred when each pair of arcs both appear in the chosen path, with zero diagonal entries." +} diff --git a/tasks/buchheim2018/mathematical_formulation.md b/tasks/buchheim2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..90ddc89bcc965fa7640ad4c876eb45f7cdfa5863 --- /dev/null +++ b/tasks/buchheim2018/mathematical_formulation.md @@ -0,0 +1,41 @@ +# Original Formulation: Quadratic Shortest Path Problem (QSPP) + +*Source: Quadratic Combinatorial Optimization Using Separable Underestimators, Christoph Buchheim and Emiliano Traversi, 2018 (INFORMS Journal on Computing 30(3):424–437).* + +## Sets and Indices + +- $G = (N, A)$: directed graph with node set $N$ and arc set $A$. + +- $s \in N$: origin (source) node of the path. + +- $t \in N$: destination (sink) node of the path. + +- $\delta^+(i)$: set of outgoing arcs of node $i$. + +- $\delta^-(i)$: set of ingoing arcs of node $i$. + +## Parameters + +- $Q_{ab} \in \mathbb{R}$: quadratic cost coefficient incurred when arcs $a$ and $b$ are used together, $\forall\, a, b \in A$. The matrix $Q$ is symmetric. + +- $L_a \in \mathbb{R}$: linear traversal cost of arc $a$, $\forall\, a \in A$. + +## Decision Variables + +- $x_a \in \{0,1\}$: equals $1$ if arc $a$ is used in the path, $0$ otherwise, $\forall\, a \in A$. + +## Objective + +$$\begin{align} +\min \quad & \sum_{a,b \in A} Q_{ab}\, x_a x_b + \sum_{a \in A} L_a\, x_a \tag{19} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.} \quad +& \sum_{a \in \delta^+(i)} x_a - \sum_{a \in \delta^-(i)} x_a = 0 && \forall\, i \in N \setminus \{s, t\} \tag{19}\\ +& \sum_{a \in \delta^+(s)} x_a = 1 \tag{19}\\ +& \sum_{a \in \delta^-(t)} x_a = 1 \tag{19}\\ +& x_a \in \{0,1\} && \forall\, a \in A \tag{19} +\end{align}$$ diff --git a/tasks/buchheim2018/problem_description.txt b/tasks/buchheim2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c7ec2e933579fe9947f0d4d47614ae5663ca56ef --- /dev/null +++ b/tasks/buchheim2018/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A logistics planner must find a least-cost path through a directed network. The network consists of a set of nodes and a set of directed arcs, where each arc points from one node to another. Two specific nodes are designated in advance: one as the origin (the source) and one as the destination (the sink) of the path. + +Each arc carries a linear traversal cost, and every ordered pair of arcs (including a pair that refers to the same arc twice) carries a quadratic interaction cost that is incurred whenever both arcs in the pair appear together in the chosen path. The quadratic cost matrix is symmetric, meaning the interaction cost for using any first arc together with any second arc equals the interaction cost for using that second arc together with that first arc. The input data specifies the number of nodes, the identifier of the origin node, the identifier of the destination node, a list of arcs with their endpoint nodes, a vector of linear costs (one per arc), and a full symmetric matrix of quadratic costs (one entry per ordered pair of arcs). + +The planner must select a subset of arcs forming a single directed path from the origin to the destination. For every intermediate node (every node other than the origin and the destination), the number of selected arcs entering that node must equal the number of selected arcs leaving it, so that flow is conserved. Exactly one selected arc must leave the origin, and exactly one selected arc must enter the destination. Each arc is either used or not used; fractional usage is not permitted. + +The goal is to minimize the total path cost, which is the sum of two components: the sum of the linear costs of all selected arcs, plus the sum over all ordered pairs of selected arcs (including the case where both indices of the pair refer to the same selected arc) of their quadratic interaction cost. Because the quadratic cost matrix is symmetric, each unordered pair of two distinct selected arcs contributes twice its matrix entry (once for each ordering) to the total quadratic cost. diff --git a/tasks/buchheim2018/solution_logger.py b/tasks/buchheim2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/buchheim2018/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/buchheim2018/solution_schema.json b/tasks/buchheim2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8d95ff28f1416114dc21c52af06d2a530a118ac0 --- /dev/null +++ b/tasks/buchheim2018/solution_schema.json @@ -0,0 +1,10 @@ +{ + "objective_value": " Total path cost, combining linear traversal costs and quadratic interaction costs of all selected arcs.", + "solution_arcs": [ + { + "id": " Unique identifier of this arc selected in the path.", + "from_node": " Identifier of the node where this selected arc originates.", + "to_node": " Identifier of the node where this selected arc terminates." + } + ] +} diff --git a/tasks/byeon2022/feasibility_check.py b/tasks/byeon2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f7606bb2bd55b4e970eb63920835f9193710a6a5 --- /dev/null +++ b/tasks/byeon2022/feasibility_check.py @@ -0,0 +1,1175 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the released integrated-primal UCGNA variant. + +Based on: Byeon & Van Hentenryck (2022), "Benders Subproblem Decomposition + for Bilevel Problems with Convex Follower" + +Checks the complete primary witness against the released commitment, dispatch, +electricity-network, and gas-network primal constraints. The original +source-paper dual/Benders rows below are numbering context only and are not +part of this executable release. + + Constraint 1 (1b): G_x x + G_y y >= h (upper-level coupling) + Constraint 2 (1c): x in X (leader variable domain) + Constraint 3 (1d): y in argmin{...} (follower feasibility) + Constraint 4 (4b): t >= f(x) (bilevel objective bound) + Constraint 5 (7b): G_y y >= h_y - G_xy x (same as 1 in MISOCP) + Constraint 6 (7c): By >= b - Ax (same as follower in 3) + Constraint 7 (7d): dual feasibility (requires dual vars) + Constraint 8 (7e): strong duality gap (requires dual vars) + Constraint 9 (7f): McCormick (requires dual vars) + Constraint 10 (14a): optimality cuts (Benders-specific) + Constraint 11 (14b): feasibility cuts (Benders-specific) + Constraint 12 (10b): subproblem (requires subproblem vars) + Constraint 13 (10c): subproblem (requires subproblem vars) + Constraint 14 (10d): subproblem domain (requires subproblem vars) + Constraint 15 (11b): subproblem (requires subproblem vars) + Constraint 16 (11c): subproblem domain (requires subproblem vars) + Constraint 17 (24b): equivalent to 1/5 (extended formulation) + Constraint 18 (24c): dual constraint (requires dual vars) + Constraint 19 (24d): equivalent to 2 (extended formulation) + Constraint 20 (24e): equivalent to 3 (extended formulation) + Constraint 21 (40a): objective consistency (recomputed vs reported) + +Constraints 1, 2, 3 and 21 are checked from the required complete primary +witness. Legacy constraints 4-20 are outside the declared release variant. + +The public Gurobi format is a flat complete `primary_variables` dictionary; +explicit zeros are required. + +Time convention: internally uses 0-based decision periods (t = 0..T-1). + - efficient_algorithm.py already uses this convention. + - gurobi_code.py uses t=0 as pre-horizon; its t=1..T map to our t=0..T-1. +""" + +import argparse +import json +import sys + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ( + 'objective_value', 'objective_weight_beta', 'primary_variables', + 'released_problem_variant', +) +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('primary_variables',) +_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 + + +# MISOCP barrier solver (used in the single-level reformulation here) leaves +# equality slacks at ~1e-5 even with tightened BarConvTol; the prior 1e-5 +# TOL was rejecting numerically-valid solutions on GenDecomp etc. Loosen to +# 1e-4 to accept normal solver imprecision while still catching real +# constraint violations. +TOL = 1e-4 +EPS = 1e-5 + +# ====================================================================== +# I/O helpers +# ====================================================================== + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def expected_primary_variable_names(inst): + """Return the exact complete flat witness key set for the release model.""" + T = int(inst["time_periods"]) + periods = range(1, T + 1) + generators = inst["generators"]["generators"] + buses = inst["electricity_network"]["buses"] + lines = inst["electricity_network"]["lines"] + gas = inst["gas_network"] + junctions = gas["junctions"] + connections = gas["connections"] + + names = set() + for generator in generators: + uid = generator["id"] + names.add(f"o_{uid}_0") + names.add(f"p_{uid}_0") + for t in periods: + names.update({ + f"o_{uid}_{t}", f"vp_{uid}_{t}", f"vm_{uid}_{t}", + f"r_{uid}_{t}", f"p_{uid}_{t}", + }) + if generator["is_gfpp"]: + names.add(f"phimax_{uid}_{t}") + for bid in generator["bids"]: + names.add(f"w_{uid}_{bid['id']}_{t}") + names.add(f"se_{uid}_{bid['id']}_{t}") + for line in lines: + for t in periods: + names.add(f"f_{line['id']}_{t}") + for bus in buses: + for t in periods: + names.add(f"theta_{bus['id']}_{t}") + for junction in junctions: + jid = junction["id"] + for t in periods: + names.update({ + f"sg_{jid}_{t}", f"pisq_{jid}_{t}", f"lg_{jid}_{t}", + f"qg_{jid}_{t}", f"gamma_{jid}_{t}", + }) + if junction["is_source"]: + for interval in junction["supply_intervals"]: + names.add(f"sgs_{jid}_{interval['id']}_{t}") + for connection in connections: + for t in periods: + names.add(f"phig_{connection['id']}_{t}") + for zone in gas["pricing_zones"]: + for t in periods: + names.add(f"psi_{zone['id']}_{t}") + return names + + +# ====================================================================== +# Solution format detection and parsing +# ====================================================================== + +def detect_format(sol): + """Return 'efficient', 'gurobi', or None.""" + if "leader_variables" in sol: + return "efficient" + if "status_name" in sol or "primary_variables" in sol or "nonzero_variables" in sol: + return "gurobi" + return None + + +def has_solution(sol, fmt): + """True if the solution contains actual variable values.""" + if fmt == "efficient": + lv = sol.get("leader_variables", {}) + fv = sol.get("follower_variables", {}) + return bool(lv) and bool(fv) + if fmt == "gurobi": + return bool(sol.get("primary_variables") or sol.get("nonzero_variables")) + return False + + +def _parse_key2(d): + """Parse dict with keys 'id1_id2' -> {(int,int): float}.""" + out = {} + for key, val in d.items(): + parts = key.split("_") + out[(int(parts[0]), int(parts[1]))] = float(val) + return out + + +def _parse_key3(d): + """Parse dict with keys 'id1_id2_id3' -> {(int,int,int): float}.""" + out = {} + for key, val in d.items(): + parts = key.split("_") + out[(int(parts[0]), int(parts[1]), int(parts[2]))] = float(val) + return out + + +def parse_efficient(sol): + """Parse efficient_solution format into unified variable dict.""" + lv = sol["leader_variables"] + fv = sol["follower_variables"] + v = {} + v["o"] = _parse_key2(lv.get("o", {})) + v["v_plus"] = _parse_key2(lv.get("v_plus", {})) + v["v_minus"] = _parse_key2(lv.get("v_minus", {})) + v["w"] = _parse_key3(lv.get("w", {})) + v["r"] = _parse_key2(lv.get("r", {})) + v["p"] = _parse_key2(fv.get("p", {})) + v["s_e"] = _parse_key3(fv.get("s_e", {})) + v["f"] = _parse_key2(fv.get("f", {})) + v["theta"] = _parse_key2(fv.get("theta", {})) + v["s_g"] = _parse_key2(fv.get("s_g", {})) + v["q_gas"] = _parse_key2(fv.get("q_gas", {})) + # Variables not in efficient solution output + v["l_gas"] = {} + v["gamma_gas"] = {} + v["pi_sq"] = {} + v["phi_gas"] = {} + v["s_g_s"] = {} + v["psi"] = {} + v["phi_max"] = {} + return v + + +def parse_gurobi(sol): + """Parse gurobi_solution nonzero_variables into unified variable dict. + + Gurobi uses t=0 as pre-horizon. Decision periods t=1..T are mapped to + our t=0..T-1. + """ + nz = sol.get("primary_variables") or sol.get("nonzero_variables") or {} + v = {k: {} for k in [ + "o", "v_plus", "v_minus", "w", "r", + "p", "s_e", "f", "theta", + "s_g", "q_gas", "l_gas", "gamma_gas", + "pi_sq", "phi_gas", "s_g_s", "psi", "phi_max", + ]} + + for name, val in nz.items(): + parts = name.split("_") + prefix = parts[0] + try: + if prefix == "o" and len(parts) == 3: + uid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["o"][(uid, t - 1)] = float(val) + elif prefix == "vp" and len(parts) == 3: + uid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["v_plus"][(uid, t - 1)] = float(val) + elif prefix == "vm" and len(parts) == 3: + uid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["v_minus"][(uid, t - 1)] = float(val) + elif prefix == "w" and len(parts) == 4: + uid, bid, t = int(parts[1]), int(parts[2]), int(parts[3]) + if t >= 1: + v["w"][(uid, bid, t - 1)] = float(val) + elif prefix == "r" and len(parts) == 3: + uid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["r"][(uid, t - 1)] = float(val) + elif prefix == "p" and len(parts) == 3: + uid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["p"][(uid, t - 1)] = float(val) + elif prefix == "se" and len(parts) == 4: + uid, bid, t = int(parts[1]), int(parts[2]), int(parts[3]) + if t >= 1: + v["s_e"][(uid, bid, t - 1)] = float(val) + elif prefix == "f" and len(parts) == 3: + lid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["f"][(lid, t - 1)] = float(val) + elif prefix == "theta" and len(parts) == 3: + bus, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["theta"][(bus, t - 1)] = float(val) + elif prefix == "sg" and len(parts) == 3: + jid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["s_g"][(jid, t - 1)] = float(val) + elif prefix == "qg" and len(parts) == 3: + jid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["q_gas"][(jid, t - 1)] = float(val) + elif prefix == "lg" and len(parts) == 3: + jid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["l_gas"][(jid, t - 1)] = float(val) + elif prefix == "gamma" and len(parts) == 3: + jid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["gamma_gas"][(jid, t - 1)] = float(val) + elif prefix == "pisq" and len(parts) == 3: + jid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["pi_sq"][(jid, t - 1)] = float(val) + elif prefix == "phig" and len(parts) == 3: + cid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["phi_gas"][(cid, t - 1)] = float(val) + elif prefix == "sgs" and len(parts) == 4: + jid, sid, t = int(parts[1]), int(parts[2]), int(parts[3]) + if t >= 1: + v["s_g_s"][(jid, sid, t - 1)] = float(val) + elif prefix == "psi" and len(parts) == 3: + k, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["psi"][(k, t - 1)] = float(val) + elif prefix == "phimax" and len(parts) == 3: + uid, t = int(parts[1]), int(parts[2]) + if t >= 1: + v["phi_max"][(uid, t - 1)] = float(val) + except (ValueError, IndexError): + continue + return v + + +def parse_vars(sol, fmt): + if fmt == "efficient": + return parse_efficient(sol) + return parse_gurobi(sol) + + +# ====================================================================== +# Variable accessor (returns default 0.0 for missing / zero variables) +# ====================================================================== + +def g(v, var_name, key, default=0.0): + return v.get(var_name, {}).get(key, default) + + +# ====================================================================== +# Objective recomputation (constraint 21) +# ====================================================================== + +def recompute_objective(inst, v): + """Recompute the obj (40a) from solution variables. + + Returns (obj_value, mode) where mode is "full" when every variable + referenced by the objective is present in the parsed solution, or + "lower_bound" when the supply-interval allocation s_g_s is missing + (e.g. efficient format). In the lower-bound mode, the gas supply + cost is replaced by the minimum-cost greedy allocation of the + observed total junction supply s_g[j,t] to its supply intervals + sorted by ascending slope -- this is a true lower bound on the + actual supply cost. + """ + T = inst["time_periods"] + gens = inst["generators"]["generators"] + junctions = inst["gas_network"]["junctions"] + + # ----- Electricity component (40a, first term) ----- + obj_elec = 0.0 + for gen in gens: + uid = gen["id"] + no_load = gen["no_load_cost"] + for t in range(T): + obj_elec += no_load * g(v, "o", (uid, t)) + obj_elec += g(v, "r", (uid, t)) + for bid in gen["bids"]: + b = bid["id"] + obj_elec += bid["price"] * g(v, "s_e", (uid, b, t)) + + # ----- Gas component (40a, second term) ----- + s_g_s_present = bool(v.get("s_g_s")) + obj_gas = 0.0 + for j in junctions: + jid = j["id"] + for t in range(T): + obj_gas += j["demand_shedding_cost"] * g(v, "q_gas", (jid, t)) + if j["is_source"] and j.get("supply_intervals"): + intervals = j["supply_intervals"] + if s_g_s_present: + for t in range(T): + for si in intervals: + obj_gas += si["slope"] * g(v, "s_g_s", (jid, si["id"], t)) + else: + # Greedy fill -> minimum supply cost given observed s_g[j,t]. + sorted_si = sorted(intervals, key=lambda x: x["slope"]) + for t in range(T): + remaining = g(v, "s_g", (jid, t)) + for si in sorted_si: + cap = si["interval_ub"] - si["interval_lb"] + take = min(cap, max(0.0, remaining)) + obj_gas += si["slope"] * take + remaining -= take + if remaining <= 1e-12: + break + + mode = "full" if s_g_s_present else "lower_bound" + beta = float(inst["objective_weight_beta"]) + return beta * obj_elec + (1.0 - beta) * obj_gas, mode + + +# ====================================================================== +# Constraint checking +# ====================================================================== + +def check_feasibility(inst, v, fmt, reported_obj=None): + """Check all verifiable hard constraints. + + Returns list of (constraint_index, message, lhs, rhs, violation_amount). + + The optional reported_obj enables constraint 21 (objective + consistency): the obj (40a) is recomputed from the variables and + compared to reported_obj. The check uses full-equality comparison + when every obj-determining variable is present in the solution + (gurobi format), or a lower-bound comparison otherwise (efficient + format, where s_g_s is missing). + """ + T = inst["time_periods"] + gens = inst["generators"]["generators"] + buses = inst["electricity_network"]["buses"] + lines = inst["electricity_network"]["lines"] + junctions = inst["gas_network"]["junctions"] + connections = inst["gas_network"]["connections"] + + gen_map = {gen["id"]: gen for gen in gens} + bus_map = {b["id"]: b for b in buses} + line_map = {l["id"]: l for l in lines} + junc_map = {j["id"]: j for j in junctions} + + bus_gens = {b["id"]: [] for b in buses} + for gen in gens: + bus_gens[gen["bus"]].append(gen["id"]) + + junc_gfpps = {j["id"]: [] for j in junctions} + for gen in gens: + if gen["is_gfpp"] and gen["gas_junction"] is not None: + junc_gfpps[gen["gas_junction"]].append(gen["id"]) + + viols = [] # (constraint_idx, msg, lhs, rhs, violation_amount) + + REL_TOL = 1e-4 # 0.01% relative slack — accommodates Weymouth-style + # nonlinear quadratic constraints under SOCP relaxation + def chk(ci, msg, lhs, rhs, op): + """Record violation if constraint is violated beyond both absolute + and relative tolerance.""" + if op == "<=": + va = lhs - rhs + elif op == ">=": + va = rhs - lhs + else: # "=" + va = abs(lhs - rhs) + # Effective tolerance: max of absolute TOL and relative tolerance + # scaled to the magnitude of the right-hand side. Catches genuine + # violations while accepting solver numerical noise on large values. + eff_tol = max(TOL, REL_TOL * max(abs(lhs), abs(rhs))) + if va > eff_tol: + viols.append((ci, msg, float(lhs), float(rhs), float(va))) + + # ================================================================== + # Constraint 2 (1c): Leader variable domain x in X + # ================================================================== + + # --- Binary checks: o, v+, v-, w must be 0 or 1 --- + for gen in gens: + uid = gen["id"] + for t in range(T): + for vn, label in [("o", "o"), ("v_plus", "v+"), ("v_minus", "v-")]: + val = g(v, vn, (uid, t)) + rd = round(val) + if abs(val - rd) > TOL: + chk(2, f"{label}[{uid},{t}]={val:.6f} not binary", val, float(rd), "=") + for bid in gen["bids"]: + b = bid["id"] + val = g(v, "w", (uid, b, t)) + rd = round(val) + if abs(val - rd) > TOL: + chk(2, f"w[{uid},{b},{t}]={val:.6f} not binary", val, float(rd), "=") + + # --- (40d) Initial status: o[u,0] = initial_status (efficient only) --- + if fmt == "efficient": + for gen in gens: + uid = gen["id"] + chk(2, f"InitStatus: o[{uid},0]={g(v,'o',(uid,0)):.0f} " + f"!= {gen['initial_status']}", + g(v, "o", (uid, 0)), float(gen["initial_status"]), "=") + + # --- (40g) Startup/shutdown logic: v+[t] - v-[t] = o[t] - o_prev --- + for gen in gens: + uid = gen["id"] + for t in range(T): + vp = g(v, "v_plus", (uid, t)) + vm = g(v, "v_minus", (uid, t)) + o_t = g(v, "o", (uid, t)) + o_prev = float(gen["initial_status"]) if t == 0 else g(v, "o", (uid, t - 1)) + lhs = vp - vm + rhs = o_t - o_prev + chk(2, f"Logic: v+[{uid},{t}]-v-[{uid},{t}]={lhs:.4f} " + f"!= o[{uid},{t}]-o_prev={rhs:.4f}", + lhs, rhs, "=") + + # --- v+ + v- <= 1 --- + for gen in gens: + uid = gen["id"] + for t in range(T): + vp = g(v, "v_plus", (uid, t)) + vm = g(v, "v_minus", (uid, t)) + chk(2, f"Excl: v+[{uid},{t}]+v-[{uid},{t}]={vp+vm:.4f} > 1", + vp + vm, 1.0, "<=") + + # --- (40e) Min up time --- + for gen in gens: + uid = gen["id"] + tau = gen["min_up_time"] + for t in range(T): + lhs = sum(g(v, "v_plus", (uid, n)) for n in range(max(0, t - tau + 1), t + 1)) + rhs = g(v, "o", (uid, t)) + chk(2, f"MinUp[{uid},{t}]: sum_vp={lhs:.4f} > o={rhs:.4f}", lhs, rhs, "<=") + + # --- (40f) Min down time --- + for gen in gens: + uid = gen["id"] + tau = gen["min_down_time"] + for t in range(T): + lhs = sum(g(v, "v_minus", (uid, n)) for n in range(max(0, t - tau + 1), t + 1)) + rhs = 1.0 - g(v, "o", (uid, t)) + chk(2, f"MinDown[{uid},{t}]: sum_vm={lhs:.4f} > 1-o={rhs:.4f}", lhs, rhs, "<=") + + # --- (40b) Startup cost: r >= 0 and r >= C*(o[t] - sum o[t-n]) --- + for gen in gens: + uid = gen["id"] + for t in range(T): + r_val = g(v, "r", (uid, t)) + chk(2, f"r[{uid},{t}]={r_val:.6f} < 0", r_val, 0.0, ">=") + for h_cost, cost in gen["startup_cost_params"]: + expr = g(v, "o", (uid, t)) + for n in range(1, h_cost + 1): + tn = t - n + if tn >= 0: + expr -= g(v, "o", (uid, tn)) + else: + expr -= float(gen["initial_status"]) + rhs = cost * expr + chk(2, f"StartupCost[{uid},{t}]: r={r_val:.4f} < {rhs:.4f}", + r_val, rhs, ">=") + + # --- (40h) Bid on: w[u,b,t] <= o[u,t] --- + for gen in gens: + uid = gen["id"] + for bid in gen["bids"]: + b = bid["id"] + for t in range(T): + chk(2, f"BidOn: w[{uid},{b},{t}]={g(v,'w',(uid,b,t)):.4f} " + f"> o[{uid},{t}]={g(v,'o',(uid,t)):.4f}", + g(v, "w", (uid, b, t)), g(v, "o", (uid, t)), "<=") + + # ================================================================== + # Constraint 1 (1b): Upper-level coupling G_x x + G_y y >= h + # ================================================================== + + # --- (40l) Bid bounds: s_e[u,b,t] <= max_amount * w[u,b,t] --- + for gen in gens: + uid = gen["id"] + for bid in gen["bids"]: + b = bid["id"] + s_bar = bid["max_amount"] + for t in range(T): + se = g(v, "s_e", (uid, b, t)) + w_val = g(v, "w", (uid, b, t)) + rhs = s_bar * w_val + chk(1, f"BidBound: s_e[{uid},{b},{t}]={se:.6f} > " + f"{s_bar}*w={rhs:.6f}", se, rhs, "<=") + + # --- (40m) Bid ordering: s_e[u,b,t] >= max_amount[b] * w[u,b+1,t] --- + for gen in gens: + uid = gen["id"] + bids_list = gen["bids"] + for idx in range(len(bids_list) - 1): + b = bids_list[idx]["id"] + b_next = bids_list[idx + 1]["id"] + s_bar = bids_list[idx]["max_amount"] + for t in range(T): + se = g(v, "s_e", (uid, b, t)) + w_next = g(v, "w", (uid, b_next, t)) + rhs = s_bar * w_next + chk(1, f"BidOrder: s_e[{uid},{b},{t}]={se:.6f} < " + f"{s_bar}*w_next={rhs:.6f}", se, rhs, ">=") + + # ================================================================== + # Constraint 3 (1d): Follower feasibility Ax + By >= b + # ================================================================== + + # --- Non-negativity: s_e >= 0, p >= 0 --- + for gen in gens: + uid = gen["id"] + for bid in gen["bids"]: + b = bid["id"] + for t in range(T): + se = g(v, "s_e", (uid, b, t)) + chk(3, f"s_e[{uid},{b},{t}]={se:.6f} < 0", se, 0.0, ">=") + for t in range(T): + p_val = g(v, "p", (uid, t)) + chk(3, f"p[{uid},{t}]={p_val:.6f} < 0", p_val, 0.0, ">=") + + # --- (42c) Generation decomposition: p[u,t] = sum_b s_e[u,b,t] --- + for gen in gens: + uid = gen["id"] + for t in range(T): + p_val = g(v, "p", (uid, t)) + se_sum = sum(g(v, "s_e", (uid, bid["id"], t)) for bid in gen["bids"]) + chk(3, f"GenDecomp: p[{uid},{t}]={p_val:.6f} != sum_se={se_sum:.6f}", + p_val, se_sum, "=") + + # --- (42e) Power bounds: p_min * o <= p <= p_max * o --- + for gen in gens: + uid = gen["id"] + for t in range(T): + p_val = g(v, "p", (uid, t)) + o_val = g(v, "o", (uid, t)) + lb = gen["min_power"] * o_val + ub = gen["max_power"] * o_val + chk(3, f"PowLB: p[{uid},{t}]={p_val:.6f} < p_min*o={lb:.6f}", + p_val, lb, ">=") + chk(3, f"PowUB: p[{uid},{t}]={p_val:.6f} > p_max*o={ub:.6f}", + p_val, ub, "<=") + + # --- (42f) Initial generation (efficient format only) --- + if fmt == "efficient": + for gen in gens: + uid = gen["id"] + p_val = g(v, "p", (uid, 0)) + init_gen = gen["initial_gen"] + chk(3, f"InitGen: p[{uid},0]={p_val:.6f} != {init_gen:.6f}", + p_val, init_gen, "=") + + # --- (42g) Ramp up: p[t] - p_prev <= ramp_up*o_prev + p_max*v+[t] --- + for gen in gens: + uid = gen["id"] + for t in range(T): + p_val = g(v, "p", (uid, t)) + if t == 0: + p_prev = gen["initial_gen"] + o_prev = float(gen["initial_status"]) + else: + p_prev = g(v, "p", (uid, t - 1)) + o_prev = g(v, "o", (uid, t - 1)) + vp = g(v, "v_plus", (uid, t)) + lhs = p_val - p_prev + rhs = gen["ramp_up"] * o_prev + gen["max_power"] * vp + chk(3, f"RampUp[{uid},{t}]: delta_p={lhs:.6f} > {rhs:.6f}", + lhs, rhs, "<=") + + # --- (42h) Ramp down: p_prev - p[t] <= ramp_down*o[t] + p_min*v-[t] --- + for gen in gens: + uid = gen["id"] + for t in range(T): + p_val = g(v, "p", (uid, t)) + p_prev = gen["initial_gen"] if t == 0 else g(v, "p", (uid, t - 1)) + o_val = g(v, "o", (uid, t)) + vm = g(v, "v_minus", (uid, t)) + lhs = p_prev - p_val + rhs = gen["ramp_down"] * o_val + gen["min_power"] * vm + chk(3, f"RampDown[{uid},{t}]: delta_p={lhs:.6f} > {rhs:.6f}", + lhs, rhs, "<=") + + # --- (42i) DC power flow definition --- + # Compute expected f from theta using the solution's sign convention: + # efficient: f = -B*(theta_from - theta_to) + # gurobi: f = B*(theta_from - theta_to) + sign = -1.0 if fmt == "efficient" else 1.0 + computed_f = {} + for l in lines: + lid = l["id"] + B_l = l["susceptance"] + for t in range(T): + tf = g(v, "theta", (l["from_bus"], t)) + tt = g(v, "theta", (l["to_bus"], t)) + expected = sign * B_l * (tf - tt) + computed_f[(lid, t)] = expected + # Check stored f against expected (if stored) + if (lid, t) in v["f"]: + actual = v["f"][(lid, t)] + chk(3, f"DCflow[{lid},{t}]: f={actual:.6f} != expected={expected:.6f}", + actual, expected, "=") + + # --- (42j) Thermal limits: |f| <= f_bar --- + for l in lines: + lid = l["id"] + f_bar = l["thermal_limit"] + for t in range(T): + f_val = computed_f.get((lid, t), g(v, "f", (lid, t))) + chk(3, f"ThermUB[{lid},{t}]: |f|={abs(f_val):.6f} > {f_bar:.6f}", + abs(f_val), f_bar, "<=") + + # --- (42l) Angle difference limits --- + for l in lines: + delta = l["angle_diff_limit"] + for t in range(T): + tf = g(v, "theta", (l["from_bus"], t)) + tt = g(v, "theta", (l["to_bus"], t)) + diff = abs(tf - tt) + chk(3, f"AngleDiff[{l['id']},{t}]: |diff|={diff:.6f} > {delta:.6f}", + diff, delta, "<=") + + # --- Voltage angle bounds --- + for bus in buses: + i = bus["id"] + for t in range(T): + th = g(v, "theta", (i, t)) + chk(3, f"ThetaLB[{i},{t}]: theta={th:.6f} < {bus['voltage_angle_lb']:.6f}", + th, bus["voltage_angle_lb"], ">=") + chk(3, f"ThetaUB[{i},{t}]: theta={th:.6f} > {bus['voltage_angle_ub']:.6f}", + th, bus["voltage_angle_ub"], "<=") + + # --- (42b) Power balance at each bus --- + # Balance equation (same in both conventions when using computed_f): + # gen_sum + flow_in - flow_out = demand + for bus in buses: + i = bus["id"] + for t in range(T): + gen_sum = sum(g(v, "p", (uid, t)) for uid in bus_gens[i]) + demand = bus["demand_profile"][t] + flow_in = 0.0 + flow_out = 0.0 + for l in lines: + lid = l["id"] + fv = computed_f.get((lid, t), g(v, "f", (lid, t))) + if l["from_bus"] == i: + flow_out += fv + if l["to_bus"] == i: + flow_in += fv + lhs = gen_sum + flow_in - flow_out + chk(3, f"PowBal[{i},{t}]: gen+flow_in-flow_out={lhs:.6f} != demand={demand:.6f}", + lhs, demand, "=") + + # ================================================================== + # Gas network constraints (Constraint 3 continued) + # ================================================================== + + # --- (42p) Shedding bounds: 0 <= q_gas[j,t] <= d_g[j,t] --- + for j in junctions: + jid = j["id"] + for t in range(T): + qg = g(v, "q_gas", (jid, t)) + d_g = j["gas_demand_profile"][t] + chk(3, f"q_gas[{jid},{t}]={qg:.6f} < 0", qg, 0.0, ">=") + chk(3, f"ShedBound[{jid},{t}]: q_gas={qg:.6f} > d_g={d_g:.6f}", + qg, d_g, "<=") + + # --- s_g >= 0 --- + for j in junctions: + jid = j["id"] + for t in range(T): + sg = g(v, "s_g", (jid, t)) + chk(3, f"s_g[{jid},{t}]={sg:.6f} < 0", sg, 0.0, ">=") + + # --- Non-source junctions: s_g = 0 --- + for j in junctions: + jid = j["id"] + if not j["is_source"]: + for t in range(T): + sg = g(v, "s_g", (jid, t)) + chk(3, f"NoSupply[{jid},{t}]: s_g={sg:.6f} != 0", sg, 0.0, "=") + + # --- (42o) Demand satisfaction: l_gas + q_gas = d_g --- + if v.get("l_gas"): + for j in junctions: + jid = j["id"] + for t in range(T): + lg = g(v, "l_gas", (jid, t)) + qg = g(v, "q_gas", (jid, t)) + d_g = j["gas_demand_profile"][t] + chk(3, f"DemSat[{jid},{t}]: l_gas+q_gas={lg+qg:.6f} != d_g={d_g:.6f}", + lg + qg, d_g, "=") + + # --- (42n) Supply decomposition: s_g = sum s_g_s (source junctions) --- + if v.get("s_g_s"): + for j in junctions: + jid = j["id"] + if j["is_source"] and j["supply_intervals"]: + for t in range(T): + sg = g(v, "s_g", (jid, t)) + sg_sum = sum(g(v, "s_g_s", (jid, si["id"], t)) + for si in j["supply_intervals"]) + chk(3, f"SupplyDecomp[{jid},{t}]: s_g={sg:.6f} != sum={sg_sum:.6f}", + sg, sg_sum, "=") + + # --- (42m) Gas flow conservation --- + if v.get("phi_gas") and v.get("gamma_gas"): + for j in junctions: + jid = j["id"] + for t in range(T): + sg = g(v, "s_g", (jid, t)) + d_g = j["gas_demand_profile"][t] + qg = g(v, "q_gas", (jid, t)) + lg = g(v, "l_gas", (jid, t)) if v.get("l_gas") else (d_g - qg) + gamma = g(v, "gamma_gas", (jid, t)) + flow_in = sum(g(v, "phi_gas", (c["id"], t)) + for c in connections if c["to_junction"] == jid) + flow_out = sum(g(v, "phi_gas", (c["id"], t)) + for c in connections if c["from_junction"] == jid) + lhs = sg + flow_in - flow_out + rhs = lg + gamma + chk(3, f"GasBal[{jid},{t}]: LHS={lhs:.6f} != RHS={rhs:.6f}", + lhs, rhs, "=") + + # --- phi_gas >= 0 --- + if v.get("phi_gas"): + for c in connections: + cid = c["id"] + for t in range(T): + phi = g(v, "phi_gas", (cid, t)) + chk(3, f"phi_gas[{cid},{t}]={phi:.6f} < 0", phi, 0.0, ">=") + + # --- Pressure bounds --- + if v.get("pi_sq"): + for j in junctions: + jid = j["id"] + for t in range(T): + pi = g(v, "pi_sq", (jid, t)) + chk(3, f"PressLB[{jid},{t}]: pi_sq={pi:.6f} < {j['pressure_lb_squared']:.6f}", + pi, j["pressure_lb_squared"], ">=") + chk(3, f"PressUB[{jid},{t}]: pi_sq={pi:.6f} > {j['pressure_ub_squared']:.6f}", + pi, j["pressure_ub_squared"], "<=") + + # --- (42s) Compressor bounds --- + if v.get("pi_sq"): + for c in connections: + if c["type"] == "compressor": + cid = c["id"] + fj = c["from_junction"] + tj = c["to_junction"] + rlb2 = c["compression_ratio_lb"] ** 2 + rub2 = c["compression_ratio_ub"] ** 2 + for t in range(T): + pi_to = g(v, "pi_sq", (tj, t)) + pi_from = g(v, "pi_sq", (fj, t)) + chk(3, f"CompLB[{cid},{t}]: pi_to={pi_to:.6f} < " + f"ratio_lb^2*pi_from={rlb2 * pi_from:.6f}", + pi_to, rlb2 * pi_from, ">=") + chk(3, f"CompUB[{cid},{t}]: pi_to={pi_to:.6f} > " + f"ratio_ub^2*pi_from={rub2 * pi_from:.6f}", + pi_to, rub2 * pi_from, "<=") + + # --- (42u) Weymouth equation (SOC relaxation): pi_from - pi_to >= W*phi^2 --- + if v.get("pi_sq") and v.get("phi_gas"): + for c in connections: + if c["type"] == "pipeline": + cid = c["id"] + fj = c["from_junction"] + tj = c["to_junction"] + W = c["weymouth_factor"] + for t in range(T): + pi_from = g(v, "pi_sq", (fj, t)) + pi_to = g(v, "pi_sq", (tj, t)) + phi = g(v, "phi_gas", (cid, t)) + lhs = pi_from - pi_to + rhs = W * phi * phi + chk(3, f"Weymouth[{cid},{t}]: pi_diff={lhs:.6f} < W*phi^2={rhs:.6f}", + lhs, rhs, ">=") + + # --- (42w) Heat rate: gamma >= sum(H2*p^2 + H1*p + H0*o) --- + if v.get("gamma_gas"): + for j in junctions: + jid = j["id"] + gfpp_ids = junc_gfpps.get(jid, []) + if gfpp_ids: + for t in range(T): + gamma = g(v, "gamma_gas", (jid, t)) + heat_sum = 0.0 + for uid in gfpp_ids: + hr = gen_map[uid]["heat_rate_coefficients"] + p_val = g(v, "p", (uid, t)) + o_val = g(v, "o", (uid, t)) + heat_sum += (hr["H_u2"] * p_val ** 2 + + hr["H_u1"] * p_val + + hr["H_u0"] * o_val) + chk(3, f"HeatRate[{jid},{t}]: gamma={gamma:.6f} < " + f"heat_sum={heat_sum:.6f}", gamma, heat_sum, ">=") + + # ================================================================== + # Constraint 21 (40a): Objective consistency + # ================================================================== + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj, mode = recompute_objective(inst, v) + # 0.1% relative tolerance with 1e-3 absolute floor. Generous + # enough to absorb barrier-solver noise (~1e-6 absolute on a + # 1e5-magnitude objective for this paper) yet tight enough to + # catch obj=0 / obj=MAX_FLOAT exploits on any realistic + # instance. + tol = max(1e-3, 1e-3 * max(abs(true_obj), abs(reported))) + if mode == "full": + diff = abs(reported - true_obj) + if diff > tol: + msg = (f"ObjConsistency(full): reported objective_value=" + f"{reported} differs from recomputed obj (40a)=" + f"{true_obj} (|diff|={diff:.6g}, tol={tol:.6g})") + viols.append((21, msg, float(reported), float(true_obj), float(diff))) + else: # lower_bound + shortfall = true_obj - reported + if shortfall > tol: + msg = (f"ObjConsistency(lower_bound): reported objective_value=" + f"{reported} is below recomputed lower bound=" + f"{true_obj} (shortfall={shortfall:.6g}, tol={tol:.6g})") + viols.append((21, msg, float(reported), float(true_obj), float(shortfall))) + + return viols + + +# ====================================================================== +# Output formatting +# ====================================================================== + +def format_output(viols): + """Convert raw violation list into the required JSON structure.""" + if not viols: + return { + "feasible": True, + "violated_constraints": [], + "violations": [], + "violation_magnitudes": [], + } + + # Build per-constraint message groups + constraint_msgs = {} + magnitudes = [] + + for ci, msg, lhs, rhs, va in viols: + constraint_msgs.setdefault(ci, []).append(msg) + normalizer = max(abs(rhs), EPS) + magnitudes.append({ + "constraint": ci, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(va, 10), + "normalizer": round(normalizer, 10), + "ratio": round(va / normalizer, 10), + }) + + violated_constraints = sorted(constraint_msgs.keys()) + + # Aggregate violation messages per constraint index + violations = [] + for ci in violated_constraints: + msgs = constraint_msgs[ci] + if len(msgs) <= 3: + violations.extend(msgs) + else: + violations.append( + f"{msgs[0]} (and {len(msgs) - 1} more violations of constraint {ci})") + + return { + "feasible": False, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": magnitudes, + } + + +# ====================================================================== +# Main +# ====================================================================== + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the integrated-primal UCGNA " + "release variant (Byeon & Van Hentenryck data)") + 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 to write feasibility result JSON") + 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 + + contract_violations = [] + if inst.get("released_problem_variant") != "integrated_primal_ucgna": + contract_violations.append("instance has unsupported released_problem_variant") + if sol.get("released_problem_variant") != inst.get("released_problem_variant"): + contract_violations.append( + "solution released_problem_variant does not match instance" + ) + try: + solution_beta = float(sol.get("objective_weight_beta")) + instance_beta = float(inst["objective_weight_beta"]) + except (TypeError, ValueError, KeyError, OverflowError): + contract_violations.append("objective_weight_beta is missing or nonnumeric") + else: + if not 0.0 <= instance_beta <= 1.0 or abs(solution_beta - instance_beta) > 1e-12: + contract_violations.append( + "solution objective_weight_beta does not match the instance" + ) + + primary = sol.get("primary_variables") + if isinstance(primary, dict): + expected_names = expected_primary_variable_names(inst) + actual_names = set(primary) + if actual_names != expected_names: + contract_violations.append( + "primary_variables must contain the exact complete witness; " + f"missing={len(expected_names - actual_names)}, " + f"unexpected={len(actual_names - expected_names)}" + ) + if contract_violations: + with open(args.result_path, "w") as result_handle: + json.dump( + { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": contract_violations, + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + return + + fmt = detect_format(sol) + + if fmt is None: + result = { + "feasible": False, + "violated_constraints": [], + "violations": ["Unknown solution format"], + "violation_magnitudes": [], + } + elif not has_solution(sol, fmt): + status = sol.get("status", sol.get("status_name", "unknown")) + result = { + "feasible": False, + "violated_constraints": [], + "violations": [f"No solution available (status: {status})"], + "violation_magnitudes": [], + } + else: + v = parse_vars(sol, fmt) + viols = check_feasibility(inst, v, fmt, sol.get("objective_value")) + result = format_output(viols) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Result written to {args.result_path}") + print(f" Feasible: {result['feasible']}") + if result["violated_constraints"]: + print(f" Violated constraints: {result['violated_constraints']}") + print(f" Total violation instances: {len(result['violation_magnitudes'])}") + elif not result["violation_magnitudes"] and not result["feasible"]: + print(f" Note: {result['violations'][0]}") + + +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/byeon2022/gurobi_code.py b/tasks/byeon2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..f8189c3830389aab873e4495b4f96401d31c2bff --- /dev/null +++ b/tasks/byeon2022/gurobi_code.py @@ -0,0 +1,1239 @@ +#!/usr/bin/env python3 +""" +Executable integrated-primal UCGNA release variant based on the network and +unit-commitment data of Byeon & Van Hentenryck (2022). + +The original repository attempted an incomplete conic bilevel dual (its SOC +dual terms were absent). The public data now identifies the executable task +honestly as ``integrated_primal_ucgna``: commitment, dispatch, gas price, and +network decisions are optimized jointly under the primal constraints. + +Time indexing: t=0 is pre-horizon (fixed from initial conditions). + t=1..T are decision periods. Demand profiles are indexed + 0..T-1 in the JSON, corresponding to periods t=1..T. + +RELEASED DATA CONVENTIONS: + - beta is supplied by each instance (0.5 in the bundled data) + - Compression ratios are on pressure (squared for pressure-squared constraints) + - Ramp-up rate used for (42g), ramp-down rate for (42h) +""" + +import argparse +import json +import sys +import math +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("ERROR: gurobipy not installed. Install with: pip install gurobipy") + sys.exit(1) + + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- +BETA = 0.5 # only used in legacy dual rows removed from release model +DUAL_UB = 10000.0 # INFERRED: upper bound on dual variables for McCormick +EPS = 1e-8 + + +def load_instance(path): + with open(path, "r") as f: + return json.load(f) + + +def build_model(inst, time_limit=3600): + """Build and return the Gurobi model for the single-level MISOCP. + + Time convention: t=0 is pre-horizon (initial state, fixed). + t=1..T are decision periods. JSON demand_profile[k] corresponds to t=k+1. + """ + + if inst.get("released_problem_variant") != "integrated_primal_ucgna": + raise ValueError("unsupported or missing released_problem_variant") + beta = float(inst["objective_weight_beta"]) + if not 0.0 <= beta <= 1.0: + raise ValueError("objective_weight_beta must lie in [0, 1]") + + T = inst["time_periods"] # number of decision periods + periods = range(1, T + 1) # decision periods: 1..T + + # --- Shorthand accessors --- + e_net = inst["electricity_network"] + buses = {b["id"]: b for b in e_net["buses"]} + lines = {l["id"]: l for l in e_net["lines"]} + bus_ids = sorted(buses.keys()) + line_ids = sorted(lines.keys()) + + gen_data = inst["generators"] + gens = {g["id"]: g for g in gen_data["generators"]} + gen_ids = sorted(gens.keys()) + gfpp_ids = [uid for uid in gen_ids if gens[uid]["is_gfpp"]] + + g_net = inst["gas_network"] + junctions = {j["id"]: j for j in g_net["junctions"]} + connections = {c["id"]: c for c in g_net["connections"]} + junc_ids = sorted(junctions.keys()) + conn_ids = sorted(connections.keys()) + source_junc_ids = [j for j in junc_ids if junctions[j]["is_source"]] + pipeline_ids = [a for a in conn_ids if connections[a]["type"] == "pipeline"] + compressor_ids = [a for a in conn_ids if connections[a]["type"] == "compressor"] + + pricing_zones = g_net["pricing_zones"] + psi_ub = g_net["max_gas_price_mmBtu"] # 200 + psi_lb = g_net["min_gas_price_mmBtu"] # 0 + + # Map junction -> zone + junc_to_zone = {} + for zone in pricing_zones: + for j in zone["junctions"]: + junc_to_zone[j] = zone["id"] + zone_ids = [z["id"] for z in pricing_zones] + + # Map bus -> generators at that bus + bus_to_gens = {i: [] for i in bus_ids} + for uid in gen_ids: + bus_to_gens[gens[uid]["bus"]].append(uid) + + # Map junction -> GFPPs at that junction + junc_to_gfpps = {j: [] for j in junc_ids} + for uid in gfpp_ids: + gj = gens[uid]["gas_junction"] + if gj is not None: + junc_to_gfpps[gj].append(uid) + + # Helper: get demand at bus i for decision period t (1-indexed) + def elec_demand(i, t): + return buses[i]["demand_profile"][t - 1] + + def gas_demand(j, t): + return junctions[j]["gas_demand_profile"][t - 1] + + # ----------------------------------------------------------------------- + # Create model + # ----------------------------------------------------------------------- + m = gp.Model("UCGNA_MISOCP") + m.setParam("Threads", 1) + + # ----------------------------------------------------------------------- + # LEADER VARIABLES (Table 4) + # ----------------------------------------------------------------------- + # o[u,t] for t=0..T (t=0 is pre-horizon, fixed) + o = {} + v_plus = {} # t=1..T + v_minus = {} # t=1..T + w = {} # t=1..T + r = {} # t=1..T + phi_max = {} # t=1..T, GFPPs only + + for u in gen_ids: + g = gens[u] + # Pre-horizon on/off status (fixed) + o[u, 0] = m.addVar(vtype=GRB.BINARY, name=f"o_{u}_0") + for t in periods: + o[u, t] = m.addVar(vtype=GRB.BINARY, name=f"o_{u}_{t}") + v_plus[u, t] = m.addVar(vtype=GRB.BINARY, name=f"vp_{u}_{t}") + v_minus[u, t] = m.addVar(vtype=GRB.BINARY, name=f"vm_{u}_{t}") + r[u, t] = m.addVar(lb=0.0, name=f"r_{u}_{t}") + for bid in g["bids"]: + b = bid["id"] + w[u, b, t] = m.addVar(vtype=GRB.BINARY, name=f"w_{u}_{b}_{t}") + + for u in gfpp_ids: + for t in periods: + phi_max[u, t] = m.addVar(lb=0.0, name=f"phimax_{u}_{t}") + + # ----------------------------------------------------------------------- + # FOLLOWER PRIMAL VARIABLES (Table 5) - only for t=1..T + # ----------------------------------------------------------------------- + s_e = {} # power from bid + p = {} # total power (also need p[u,0] = initial_gen for ramp) + f_line = {} # power flow on line + theta = {} # voltage angle + s_g = {} # gas supply at junction + s_g_s = {} # gas supply from interval + pi_sq = {} # pressure squared + phi_gas = {} # gas flow on connection + l_gas = {} # satisfied gas demand + q_gas = {} # shed gas demand + gamma = {} # total GFPP gas consumption at junction + + for u in gen_ids: + g = gens[u] + # Pre-horizon generation (fixed) + p[u, 0] = m.addVar(lb=0.0, name=f"p_{u}_0") + for t in periods: + p[u, t] = m.addVar(lb=0.0, name=f"p_{u}_{t}") + for bid in g["bids"]: + b = bid["id"] + s_e[u, b, t] = m.addVar(lb=0.0, name=f"se_{u}_{b}_{t}") + + for l in line_ids: + for t in periods: + f_line[l, t] = m.addVar(lb=-GRB.INFINITY, name=f"f_{l}_{t}") + + for i in bus_ids: + for t in periods: + theta[i, t] = m.addVar( + lb=buses[i]["voltage_angle_lb"], + ub=buses[i]["voltage_angle_ub"], + name=f"theta_{i}_{t}") + + for j in junc_ids: + for t in periods: + s_g[j, t] = m.addVar(lb=0.0, name=f"sg_{j}_{t}") + l_gas[j, t] = m.addVar(lb=0.0, name=f"lg_{j}_{t}") + q_gas[j, t] = m.addVar(lb=0.0, name=f"qg_{j}_{t}") + gamma[j, t] = m.addVar(lb=0.0, name=f"gamma_{j}_{t}") + pi_sq[j, t] = m.addVar( + lb=junctions[j]["pressure_lb_squared"], + ub=junctions[j]["pressure_ub_squared"], + name=f"pisq_{j}_{t}") + + for j in source_junc_ids: + junc = junctions[j] + for si in junc["supply_intervals"]: + sid = si["id"] + cap = si["interval_ub"] - si["interval_lb"] + for t in periods: + s_g_s[j, sid, t] = m.addVar(lb=0.0, ub=cap, + name=f"sgs_{j}_{sid}_{t}") + + for a in conn_ids: + for t in periods: + phi_gas[a, t] = m.addVar(lb=0.0, name=f"phig_{a}_{t}") + + # Gas zonal price variables + psi = {} + for k in zone_ids: + for t in periods: + psi[k, t] = m.addVar(lb=psi_lb, ub=psi_ub, name=f"psi_{k}_{t}") + + # ----------------------------------------------------------------------- + # FOLLOWER DUAL VARIABLES (for linear constraints, t=1..T) + # ----------------------------------------------------------------------- + # (42b) power balance: lambda_b[i,t] free + lambda_b = {} + for i in bus_ids: + for t in periods: + lambda_b[i, t] = m.addVar(lb=-DUAL_UB, ub=DUAL_UB, + name=f"lam_b_{i}_{t}") + + # (42c) p = sum s_e: lambda_c[u,t] free + lambda_c = {} + for u in gen_ids: + for t in periods: + lambda_c[u, t] = m.addVar(lb=-DUAL_UB, ub=DUAL_UB, + name=f"lam_c_{u}_{t}") + + # (42d upper) s_e <= s_bar * w: rho_d_upper[u,b,t] >= 0 + rho_d_upper = {} + for u in gen_ids: + for bid in gens[u]["bids"]: + b = bid["id"] + for t in periods: + rho_d_upper[u, b, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"rho_du_{u}_{b}_{t}") + + # (42e lower) p >= p_min * o: alpha_lower[u,t] >= 0 + alpha_lower = {} + for u in gen_ids: + for t in periods: + alpha_lower[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"al_{u}_{t}") + + # (42e upper) p <= p_max * o: alpha_upper[u,t] >= 0 + alpha_upper = {} + for u in gen_ids: + for t in periods: + alpha_upper[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"au_{u}_{t}") + + # (42g) ramp up: delta_up[u,t] >= 0, for t >= 1 (all decision periods) + delta_up = {} + for u in gen_ids: + for t in periods: + delta_up[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"du_{u}_{t}") + + # (42h) ramp down: delta_down[u,t] >= 0 + delta_down = {} + for u in gen_ids: + for t in periods: + delta_down[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"dd_{u}_{t}") + + # (42i) DC flow: lambda_i[l,t] free + lambda_i = {} + for l in line_ids: + for t in periods: + lambda_i[l, t] = m.addVar(lb=-DUAL_UB, ub=DUAL_UB, + name=f"lam_i_{l}_{t}") + + # (42j) thermal limit: rho_j_upper[l,t], rho_j_lower[l,t] >= 0 + rho_j_upper = {} + rho_j_lower = {} + for l in line_ids: + for t in periods: + rho_j_upper[l, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"rho_ju_{l}_{t}") + rho_j_lower[l, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"rho_jl_{l}_{t}") + + # (42l) angle diff: rho_l_upper[l,t], rho_l_lower[l,t] >= 0 + rho_l_upper = {} + rho_l_lower = {} + for l in line_ids: + for t in periods: + rho_l_upper[l, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"rho_lu_{l}_{t}") + rho_l_lower[l, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"rho_ll_{l}_{t}") + + # (42m) gas flow conservation: lambda_m[j,t] free + lambda_m = {} + for j in junc_ids: + for t in periods: + lambda_m[j, t] = m.addVar(lb=-DUAL_UB, ub=DUAL_UB, + name=f"lam_m_{j}_{t}") + + # (42n) supply decomposition: lambda_n[j,t] free (source only) + lambda_n = {} + for j in source_junc_ids: + for t in periods: + lambda_n[j, t] = m.addVar(lb=-DUAL_UB, ub=DUAL_UB, + name=f"lam_n_{j}_{t}") + + # (42o) demand satisfaction: lambda_o[j,t] free + lambda_o = {} + for j in junc_ids: + for t in periods: + lambda_o[j, t] = m.addVar(lb=-DUAL_UB, ub=DUAL_UB, + name=f"lam_o_{j}_{t}") + + # (42p) shedding bound: rho_p[j,t] >= 0 + rho_p = {} + for j in junc_ids: + for t in periods: + rho_p[j, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"rho_p_{j}_{t}") + + # (42r) supply interval upper: rho_r[j,s,t] >= 0 + rho_r = {} + for j in source_junc_ids: + for si in junctions[j]["supply_intervals"]: + sid = si["id"] + for t in periods: + rho_r[j, sid, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"rho_r_{j}_{sid}_{t}") + + # (42s) compressor bounds duals + comp_lower_dual = {} + comp_upper_dual = {} + for a in compressor_ids: + for t in periods: + comp_lower_dual[a, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"cl_{a}_{t}") + comp_upper_dual[a, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"cu_{a}_{t}") + + # Non-source supply zero: lambda_ns[j,t] free + lambda_ns = {} + for j in junc_ids: + if not junctions[j]["is_source"]: + for t in periods: + lambda_ns[j, t] = m.addVar(lb=-DUAL_UB, ub=DUAL_UB, + name=f"lam_ns_{j}_{t}") + + # ----------------------------------------------------------------------- + # McCormick auxiliary variables for strong duality bilinear terms + # ----------------------------------------------------------------------- + # mu_d[u,b,t] = rho_d_upper[u,b,t] * w[u,b,t] + mu_d = {} + for u in gen_ids: + for bid in gens[u]["bids"]: + b = bid["id"] + for t in periods: + mu_d[u, b, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"mu_d_{u}_{b}_{t}") + + # mu_el[u,t] = alpha_lower[u,t] * o[u,t] + mu_el = {} + for u in gen_ids: + for t in periods: + mu_el[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"mu_el_{u}_{t}") + + # mu_eu[u,t] = alpha_upper[u,t] * o[u,t] + mu_eu = {} + for u in gen_ids: + for t in periods: + mu_eu[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"mu_eu_{u}_{t}") + + # mu_go[u,t] = delta_up[u,t] * o[u,t-1], for t in 1..T + mu_go = {} + for u in gen_ids: + for t in periods: + mu_go[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"mu_go_{u}_{t}") + + # mu_gv[u,t] = delta_up[u,t] * v_plus[u,t], for t in 1..T + mu_gv = {} + for u in gen_ids: + for t in periods: + mu_gv[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"mu_gv_{u}_{t}") + + # mu_ho[u,t] = delta_down[u,t] * o[u,t], for t in 1..T + mu_ho = {} + for u in gen_ids: + for t in periods: + mu_ho[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"mu_ho_{u}_{t}") + + # mu_hv[u,t] = delta_down[u,t] * v_minus[u,t], for t in 1..T + mu_hv = {} + for u in gen_ids: + for t in periods: + mu_hv[u, t] = m.addVar(lb=0.0, ub=DUAL_UB, + name=f"mu_hv_{u}_{t}") + + # McCormick for bid-validity (41a-41e): v_bid[u,k,t] = psi[k,t] * o[u,t] + v_bid = {} + for u in gfpp_ids: + gj = gens[u]["gas_junction"] + k = junc_to_zone[gj] + for t in periods: + v_bid[u, k, t] = m.addVar(lb=0.0, ub=psi_ub, + name=f"vbid_{u}_{k}_{t}") + + m.update() + + # ----------------------------------------------------------------------- + # OBJECTIVE (40a) + # ----------------------------------------------------------------------- + obj_elec = gp.LinExpr() + obj_gas = gp.LinExpr() + + for t in periods: + for u in gen_ids: + g = gens[u] + obj_elec.add(g["no_load_cost"] * o[u, t]) + obj_elec.add(r[u, t]) + for bid in g["bids"]: + b = bid["id"] + obj_elec.add(bid["price"] * s_e[u, b, t]) + + for j in junc_ids: + junc = junctions[j] + obj_gas.add(junc["demand_shedding_cost"] * q_gas[j, t]) + if junc["is_source"]: + for si in junc["supply_intervals"]: + sid = si["id"] + obj_gas.add(si["slope"] * s_g_s[j, sid, t]) + + m.setObjective(beta * obj_elec + (1 - beta) * obj_gas, GRB.MINIMIZE) + + # ----------------------------------------------------------------------- + # FIX PRE-HORIZON STATE (t=0) + # ----------------------------------------------------------------------- + for u in gen_ids: + g = gens[u] + m.addConstr(o[u, 0] == g["initial_status"], name=f"fix_o0_{u}") + m.addConstr(p[u, 0] == g["initial_gen"], name=f"fix_p0_{u}") + + # ----------------------------------------------------------------------- + # LEADER CONSTRAINTS + # ----------------------------------------------------------------------- + + # (40d) Initial status fixing for must-stay periods + # Fix o[u,t] = initial_status for t = 1, ..., min(T, remaining_periods) + for u in gen_ids: + g = gens[u] + init_status = g["initial_status"] + remaining = g["initial_active_periods"] + g["initial_inactive_periods"] + for t in range(1, min(T + 1, remaining + 1)): + m.addConstr(o[u, t] == init_status, name=f"init_fix_{u}_{t}") + + # (40g) Startup/shutdown logic: v+[t] - v-[t] = o[t] - o[t-1], t=1..T + for u in gen_ids: + for t in periods: + m.addConstr(v_plus[u, t] - v_minus[u, t] == o[u, t] - o[u, t - 1], + name=f"logic_{u}_{t}") + for t in periods: + m.addConstr(v_plus[u, t] + v_minus[u, t] <= 1, + name=f"vpm_excl_{u}_{t}") + + # (40b) Startup cost + for u in gen_ids: + g = gens[u] + for h_idx, (h, C_uh) in enumerate(g["startup_cost_params"]): + for t in periods: + # r[u,t] >= C_uh * (o[u,t] - sum_{n=1..h} o[u,t-n]) + expr = C_uh * o[u, t] + for n in range(1, h + 1): + tn = t - n + if tn >= 0: + # tn=0 is the pre-horizon state (fixed) + expr -= C_uh * o[u, tn] + else: + # Before pre-horizon: use initial_status + expr -= C_uh * g["initial_status"] + m.addConstr(r[u, t] >= expr, + name=f"startup_cost_{u}_{h_idx}_{t}") + + # (40e) Min up time + for u in gen_ids: + g = gens[u] + tau_bar = g["min_up_time"] + for t in periods: + lhs = gp.LinExpr() + for tp in range(max(1, t - tau_bar + 1), t + 1): + lhs.add(v_plus[u, tp]) + m.addConstr(lhs <= o[u, t], name=f"min_up_{u}_{t}") + + # (40f) Min down time + for u in gen_ids: + g = gens[u] + tau = g["min_down_time"] + for t in periods: + lhs = gp.LinExpr() + for tp in range(max(1, t - tau + 1), t + 1): + lhs.add(v_minus[u, tp]) + m.addConstr(lhs <= 1 - o[u, t], name=f"min_down_{u}_{t}") + + # (40h) Bid selection requires generator on (for GFPPs) + for u in gfpp_ids: + g = gens[u] + for bid in g["bids"]: + b = bid["id"] + for t in periods: + m.addConstr(w[u, b, t] <= o[u, t], + name=f"bid_on_{u}_{b}_{t}") + + # (40i) phi_max definition for GFPPs + # phi_max[u,t] = max_gas_price_fraction * psi_ub * o[u,t] + for u in gfpp_ids: + g = gens[u] + frac = g["max_gas_price_fraction"] + for t in periods: + m.addConstr(phi_max[u, t] == frac * psi_ub * o[u, t], + name=f"phi_max_def_{u}_{t}") + + # (40l) Bid bounds: 0 <= s_e[u,b,t] <= s_bar_b * w[u,b,t] + for u in gen_ids: + g = gens[u] + for bid in g["bids"]: + b = bid["id"] + s_bar = bid["max_amount"] + for t in periods: + m.addConstr(s_e[u, b, t] <= s_bar * w[u, b, t], + name=f"bid_ub_{u}_{b}_{t}") + + # (40m) Sequential bid activation + for u in gen_ids: + g = gens[u] + bids_list = g["bids"] + for idx in range(len(bids_list) - 1): + b = bids_list[idx]["id"] + b_next = bids_list[idx + 1]["id"] + s_bar = bids_list[idx]["max_amount"] + for t in periods: + m.addConstr(s_e[u, b, t] >= s_bar * w[u, b_next, t], + name=f"bid_seq_{u}_{b}_{t}") + + # (40n) + McCormick (41a-41e): Bid-validity for GFPPs + for u in gfpp_ids: + gj = gens[u]["gas_junction"] + k = junc_to_zone[gj] + for t in periods: + # (41a) phi_max >= v_bid (= psi * o linearized) + m.addConstr(phi_max[u, t] >= v_bid[u, k, t], + name=f"bidval_{u}_{t}") + # (41b) + m.addConstr(v_bid[u, k, t] >= psi[k, t] - psi_ub * (1 - o[u, t]), + name=f"mc_bid_lb1_{u}_{t}") + # (41c) + m.addConstr(v_bid[u, k, t] <= psi[k, t] - psi_lb * (1 - o[u, t]), + name=f"mc_bid_ub1_{u}_{t}") + # (41d) + m.addConstr(v_bid[u, k, t] <= psi_ub * o[u, t], + name=f"mc_bid_ub2_{u}_{t}") + # (41e) + m.addConstr(v_bid[u, k, t] >= psi_lb * o[u, t], + name=f"mc_bid_lb2_{u}_{t}") + + # ----------------------------------------------------------------------- + # FOLLOWER PRIMAL CONSTRAINTS (t=1..T) + # ----------------------------------------------------------------------- + + # (42b) Power balance at each bus + for i in bus_ids: + for t in periods: + gen_sum = gp.LinExpr() + for u in bus_to_gens[i]: + gen_sum.add(p[u, t]) + demand = elec_demand(i, t) + + flow_out = gp.LinExpr() + flow_in = gp.LinExpr() + for l in line_ids: + ln = lines[l] + if ln["from_bus"] == i: + flow_out.add(f_line[l, t]) + if ln["to_bus"] == i: + flow_in.add(f_line[l, t]) + + m.addConstr(gen_sum - demand == flow_out - flow_in, + name=f"pbal_{i}_{t}") + + # (42c) Generation = sum of bids + for u in gen_ids: + for t in periods: + bid_sum = gp.LinExpr() + for bid in gens[u]["bids"]: + bid_sum.add(s_e[u, bid["id"], t]) + m.addConstr(p[u, t] == bid_sum, name=f"gen_bid_{u}_{t}") + + # (42e) Power bounds + for u in gen_ids: + g = gens[u] + for t in periods: + m.addConstr(p[u, t] >= g["min_power"] * o[u, t], + name=f"pmin_{u}_{t}") + m.addConstr(p[u, t] <= g["max_power"] * o[u, t], + name=f"pmax_{u}_{t}") + + # (42g) Ramp up: p[t] - p[t-1] <= ramp_up * o[t-1] + max_power * v+[t] + for u in gen_ids: + g = gens[u] + for t in periods: + m.addConstr(p[u, t] - p[u, t - 1] <= + g["ramp_up"] * o[u, t - 1] + g["max_power"] * v_plus[u, t], + name=f"ramp_up_{u}_{t}") + + # (42h) Ramp down: p[t-1] - p[t] <= ramp_down * o[t] + min_power * v-[t] + for u in gen_ids: + g = gens[u] + for t in periods: + m.addConstr(p[u, t - 1] - p[u, t] <= + g["ramp_down"] * o[u, t] + g["min_power"] * v_minus[u, t], + name=f"ramp_down_{u}_{t}") + + # (42i) DC power flow: f = b * (theta_from - theta_to) + for l in line_ids: + ln = lines[l] + for t in periods: + m.addConstr(f_line[l, t] == ln["susceptance"] * + (theta[ln["from_bus"], t] - theta[ln["to_bus"], t]), + name=f"dcflow_{l}_{t}") + + # (42j) Thermal limits + for l in line_ids: + ln = lines[l] + for t in periods: + m.addConstr(f_line[l, t] <= ln["thermal_limit"], + name=f"therm_ub_{l}_{t}") + m.addConstr(f_line[l, t] >= -ln["thermal_limit"], + name=f"therm_lb_{l}_{t}") + + # (42l) Angle difference limits + for l in line_ids: + ln = lines[l] + for t in periods: + m.addConstr(theta[ln["from_bus"], t] - theta[ln["to_bus"], t] <= + ln["angle_diff_limit"], + name=f"angdiff_ub_{l}_{t}") + m.addConstr(theta[ln["from_bus"], t] - theta[ln["to_bus"], t] >= + -ln["angle_diff_limit"], + name=f"angdiff_lb_{l}_{t}") + + # (42m) Gas flow conservation + for j in junc_ids: + for t in periods: + flow_out = gp.LinExpr() + flow_in = gp.LinExpr() + for a in conn_ids: + cn = connections[a] + if cn["from_junction"] == j: + flow_out.add(phi_gas[a, t]) + if cn["to_junction"] == j: + flow_in.add(phi_gas[a, t]) + m.addConstr(s_g[j, t] - l_gas[j, t] - gamma[j, t] == + flow_out - flow_in, + name=f"gasbal_{j}_{t}") + + # (42n) Supply decomposition (source junctions) + for j in source_junc_ids: + for t in periods: + supply_sum = gp.LinExpr() + for si in junctions[j]["supply_intervals"]: + supply_sum.add(s_g_s[j, si["id"], t]) + m.addConstr(s_g[j, t] == supply_sum, name=f"supply_dec_{j}_{t}") + + # Non-source junctions: s_g = 0 + for j in junc_ids: + if not junctions[j]["is_source"]: + for t in periods: + m.addConstr(s_g[j, t] == 0, name=f"no_supply_{j}_{t}") + + # (42o) Demand satisfaction + for j in junc_ids: + for t in periods: + d_g = gas_demand(j, t) + m.addConstr(l_gas[j, t] == d_g - q_gas[j, t], + name=f"gas_demand_{j}_{t}") + + # (42p) Shedding bounds + for j in junc_ids: + for t in periods: + d_g = gas_demand(j, t) + m.addConstr(q_gas[j, t] <= d_g, name=f"shed_ub_{j}_{t}") + + # (42s) Compressor constraints + for a in compressor_ids: + cn = connections[a] + ratio_lb_sq = cn["compression_ratio_lb"] ** 2 + ratio_ub_sq = cn["compression_ratio_ub"] ** 2 + fj = cn["from_junction"] + tj = cn["to_junction"] + for t in periods: + m.addConstr(pi_sq[tj, t] >= ratio_lb_sq * pi_sq[fj, t], + name=f"comp_lb_{a}_{t}") + m.addConstr(pi_sq[tj, t] <= ratio_ub_sq * pi_sq[fj, t], + name=f"comp_ub_{a}_{t}") + + # (42u) Weymouth equation (SOC relaxation) for pipelines + # pi_sq[from] - pi_sq[to] >= W * phi_gas^2 + for a in pipeline_ids: + cn = connections[a] + W = cn["weymouth_factor"] + fj = cn["from_junction"] + tj = cn["to_junction"] + for t in periods: + m.addQConstr( + pi_sq[fj, t] - pi_sq[tj, t] >= W * phi_gas[a, t] * phi_gas[a, t], + name=f"weymouth_{a}_{t}") + + # (42w) Heat rate constraint (SOC) + # gamma[j,t] >= sum_{u at j} (H_u2 * p[u,t]^2 + H_u1 * p[u,t] + H_u0 * o[u,t]) + for j in junc_ids: + gfpps_at_j = junc_to_gfpps[j] + if gfpps_at_j: + for t in periods: + quad_expr = gp.QuadExpr() + for u in gfpps_at_j: + g = gens[u] + hr = g["heat_rate_coefficients"] + quad_expr.add(hr["H_u2"] * p[u, t] * p[u, t]) + quad_expr.add(hr["H_u1"] * p[u, t]) + quad_expr.add(hr["H_u0"] * o[u, t]) + m.addQConstr(gamma[j, t] >= quad_expr, + name=f"heatrate_{j}_{t}") + + # ----------------------------------------------------------------------- + # DUAL FEASIBILITY CONSTRAINTS + # ----------------------------------------------------------------------- + + # --- Dual for s_e[u,b,t] (>= 0) --- + # (42c): coeff +1 -> lambda_c + # (42d upper): s_bar*w - s_e >= 0 -> coeff -1 -> rho_d_upper * (-1) + # Cost: BETA * price + # Condition: lambda_c - rho_d_upper <= BETA * price + for u in gen_ids: + for bid in gens[u]["bids"]: + b = bid["id"] + for t in periods: + m.addConstr(lambda_c[u, t] - rho_d_upper[u, b, t] <= BETA * bid["price"], + name=f"df_se_{u}_{b}_{t}") + + # --- Dual for p[u,t] (>= 0) --- + # (42b): coeff +1 at bus -> lambda_b[bus,t] + # (42c): coeff -1 -> -lambda_c[u,t] + # (42e lower): p >= p_min*o -> coeff +1 -> alpha_lower + # (42e upper): p_max*o - p >= 0 -> coeff -1 -> -alpha_upper + # (42g) at t: ramp_up*o[t-1]+p_max*v+[t]-p[t]+p[t-1] >= 0 -> p[t] coeff -1 -> -delta_up[t] + # (42g) at t+1: ... +p[t] ... -> p[t] coeff +1 -> +delta_up[t+1] + # (42h) at t: ramp_down*o[t]+p_min*v-[t]+p[t]-p[t-1] >= 0 -> p[t] coeff +1 -> +delta_down[t] + # (42h) at t+1: ... -p[t] ... -> p[t] coeff -1 -> -delta_down[t+1] + # Cost: 0 + for u in gen_ids: + g = gens[u] + bus_u = g["bus"] + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_b[bus_u, t], 1.0) + expr.add(lambda_c[u, t], -1.0) + expr.add(alpha_lower[u, t], 1.0) + expr.add(alpha_upper[u, t], -1.0) + # (42g) at t + expr.add(delta_up[u, t], -1.0) + # (42g) at t+1 (if exists) + if t + 1 <= T: + expr.add(delta_up[u, t + 1], 1.0) + # (42h) at t + expr.add(delta_down[u, t], 1.0) + # (42h) at t+1 (if exists) + if t + 1 <= T: + expr.add(delta_down[u, t + 1], -1.0) + m.addConstr(expr <= 0, name=f"df_p_{u}_{t}") + + # --- Dual for f_line[l,t] (free) --- + # (42b): from_bus coeff -1, to_bus coeff +1 + # (42i): f - b*theta_from + b*theta_to = 0 -> f coeff +1 -> lambda_i + # (42j upper): f_bar - f >= 0 -> coeff -1 -> -rho_j_upper + # (42j lower): f + f_bar >= 0 -> coeff +1 -> +rho_j_lower + # Cost: 0 (free -> equality) + for l in line_ids: + ln = lines[l] + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_b[ln["from_bus"], t], -1.0) + expr.add(lambda_b[ln["to_bus"], t], 1.0) + expr.add(lambda_i[l, t], 1.0) + expr.add(rho_j_upper[l, t], -1.0) + expr.add(rho_j_lower[l, t], 1.0) + m.addConstr(expr == 0, name=f"df_f_{l}_{t}") + + # --- Dual for theta[i,t] (bounded, treat as free for simplicity) --- + # (42i): f = b*(theta_from - theta_to) rewritten as f - b*theta_from + b*theta_to = 0 + # from_bus: coeff -b -> lambda_i * (-b) + # to_bus: coeff +b -> lambda_i * (+b) + # (42l upper): Delta - (theta_from - theta_to) >= 0 + # from_bus: coeff -1 -> -rho_l_upper + # to_bus: coeff +1 -> +rho_l_upper + # (42l lower): (theta_from - theta_to) + Delta >= 0 + # from_bus: coeff +1 -> +rho_l_lower + # to_bus: coeff -1 -> -rho_l_lower + # Cost: 0 (equality for free) + for i in bus_ids: + for t in periods: + expr = gp.LinExpr() + for l in line_ids: + ln = lines[l] + b_l = ln["susceptance"] + if ln["from_bus"] == i: + expr.add(lambda_i[l, t], -b_l) + expr.add(rho_l_upper[l, t], -1.0) + expr.add(rho_l_lower[l, t], 1.0) + if ln["to_bus"] == i: + expr.add(lambda_i[l, t], b_l) + expr.add(rho_l_upper[l, t], 1.0) + expr.add(rho_l_lower[l, t], -1.0) + m.addConstr(expr == 0, name=f"df_theta_{i}_{t}") + + # --- Dual for s_g[j,t] (>= 0) --- + # (42m): coeff +1 -> lambda_m + # (42n)/(no_supply): coeff -1 -> -lambda_n or -lambda_ns + # Cost: 0 + for j in junc_ids: + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_m[j, t], 1.0) + if junctions[j]["is_source"]: + expr.add(lambda_n[j, t], -1.0) + else: + expr.add(lambda_ns[j, t], -1.0) + m.addConstr(expr <= 0, name=f"df_sg_{j}_{t}") + + # --- Dual for s_g_s[j,s,t] (>= 0, <= cap) --- + # (42n): coeff +1 -> lambda_n + # (42r): cap - s_g_s >= 0 -> coeff -1 -> -rho_r + # Cost: (1-BETA) * slope + for j in source_junc_ids: + for si in junctions[j]["supply_intervals"]: + sid = si["id"] + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_n[j, t], 1.0) + expr.add(rho_r[j, sid, t], -1.0) + m.addConstr(expr <= (1 - BETA) * si["slope"], + name=f"df_sgs_{j}_{sid}_{t}") + + # --- Dual for pi_sq[j,t] (bounded, treat as free) --- + # (42s) compressor: + # lower: pi_sq[to] - ratio_lb^2*pi_sq[from] >= 0 + # from: coeff -ratio_lb^2 -> comp_lower_dual * (-ratio_lb^2) + # to: coeff +1 -> comp_lower_dual + # upper: ratio_ub^2*pi_sq[from] - pi_sq[to] >= 0 + # from: coeff +ratio_ub^2 -> comp_upper_dual * ratio_ub^2 + # to: coeff -1 -> -comp_upper_dual + # Cost: 0 + for j in junc_ids: + for t in periods: + expr = gp.LinExpr() + for a in compressor_ids: + cn = connections[a] + ratio_lb_sq = cn["compression_ratio_lb"] ** 2 + ratio_ub_sq = cn["compression_ratio_ub"] ** 2 + if cn["from_junction"] == j: + expr.add(comp_lower_dual[a, t], -ratio_lb_sq) + expr.add(comp_upper_dual[a, t], ratio_ub_sq) + if cn["to_junction"] == j: + expr.add(comp_lower_dual[a, t], 1.0) + expr.add(comp_upper_dual[a, t], -1.0) + m.addConstr(expr == 0, name=f"df_pisq_{j}_{t}") + + # --- Dual for phi_gas[a,t] (>= 0) --- + # (42m): from_junction flow_out coeff -1, to_junction flow_in coeff +1 + # (gasbal: s_g - l_gas - gamma - flow_out + flow_in = 0) + # at from_junction: coeff -1 -> lambda_m[from] * (-1) + # at to_junction: coeff +1 -> lambda_m[to] * (+1) + # Cost: 0 + for a in conn_ids: + cn = connections[a] + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_m[cn["from_junction"], t], -1.0) + expr.add(lambda_m[cn["to_junction"], t], 1.0) + m.addConstr(expr <= 0, name=f"df_phig_{a}_{t}") + + # --- Dual for l_gas[j,t] (>= 0) --- + # (42m): coeff -1 -> -lambda_m + # (42o): l_gas = d_g - q_gas -> coeff +1 -> lambda_o + # Cost: 0 + for j in junc_ids: + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_m[j, t], -1.0) + expr.add(lambda_o[j, t], 1.0) + m.addConstr(expr <= 0, name=f"df_lg_{j}_{t}") + + # --- Dual for q_gas[j,t] (>= 0) --- + # (42o): coeff -1 -> -lambda_o + # (42p): d_g - q >= 0 -> coeff -1 -> -rho_p + # Cost: (1-BETA) * kappa_j + for j in junc_ids: + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_o[j, t], -1.0) + expr.add(rho_p[j, t], -1.0) + m.addConstr(expr <= (1 - BETA) * junctions[j]["demand_shedding_cost"], + name=f"df_qg_{j}_{t}") + + # --- Dual for gamma[j,t] (>= 0) --- + # (42m): coeff -1 -> -lambda_m + # Cost: 0 + for j in junc_ids: + for t in periods: + expr = gp.LinExpr() + expr.add(lambda_m[j, t], -1.0) + m.addConstr(expr <= 0, name=f"df_gamma_{j}_{t}") + + # ----------------------------------------------------------------------- + # McCORMICK CONSTRAINTS for strong duality bilinear terms + # ----------------------------------------------------------------------- + def add_mccormick(model, mu, dual, binary, dual_ub, name_prefix): + """mu = dual * binary, dual in [0, dual_ub], binary in {0,1}.""" + model.addConstr(mu >= 0, name=f"{name_prefix}_lb1") + model.addConstr(mu <= dual_ub * binary, name=f"{name_prefix}_ub1") + model.addConstr(mu >= dual - dual_ub * (1 - binary), name=f"{name_prefix}_lb2") + model.addConstr(mu <= dual, name=f"{name_prefix}_ub2") + + # mu_d[u,b,t] = rho_d_upper[u,b,t] * w[u,b,t] + for u in gen_ids: + for bid in gens[u]["bids"]: + b = bid["id"] + for t in periods: + add_mccormick(m, mu_d[u, b, t], rho_d_upper[u, b, t], + w[u, b, t], DUAL_UB, f"mc_d_{u}_{b}_{t}") + + # mu_el[u,t] = alpha_lower[u,t] * o[u,t] + for u in gen_ids: + for t in periods: + add_mccormick(m, mu_el[u, t], alpha_lower[u, t], + o[u, t], DUAL_UB, f"mc_el_{u}_{t}") + + # mu_eu[u,t] = alpha_upper[u,t] * o[u,t] + for u in gen_ids: + for t in periods: + add_mccormick(m, mu_eu[u, t], alpha_upper[u, t], + o[u, t], DUAL_UB, f"mc_eu_{u}_{t}") + + # mu_go[u,t] = delta_up[u,t] * o[u,t-1] + for u in gen_ids: + for t in periods: + add_mccormick(m, mu_go[u, t], delta_up[u, t], + o[u, t - 1], DUAL_UB, f"mc_go_{u}_{t}") + + # mu_gv[u,t] = delta_up[u,t] * v_plus[u,t] + for u in gen_ids: + for t in periods: + add_mccormick(m, mu_gv[u, t], delta_up[u, t], + v_plus[u, t], DUAL_UB, f"mc_gv_{u}_{t}") + + # mu_ho[u,t] = delta_down[u,t] * o[u,t] + for u in gen_ids: + for t in periods: + add_mccormick(m, mu_ho[u, t], delta_down[u, t], + o[u, t], DUAL_UB, f"mc_ho_{u}_{t}") + + # mu_hv[u,t] = delta_down[u,t] * v_minus[u,t] + for u in gen_ids: + for t in periods: + add_mccormick(m, mu_hv[u, t], delta_down[u, t], + v_minus[u, t], DUAL_UB, f"mc_hv_{u}_{t}") + + # ----------------------------------------------------------------------- + # STRONG DUALITY CONSTRAINT + # ----------------------------------------------------------------------- + # Follower primal objective <= dual objective + # LHS: sum of follower cost * follower variable + # RHS: sum of (dual * RHS), where RHS may involve leader variables (linearized) + + primal_cost = gp.LinExpr() + dual_cost = gp.LinExpr() + + for t in periods: + # --- Primal cost --- + for u in gen_ids: + for bid in gens[u]["bids"]: + b = bid["id"] + primal_cost.add(BETA * bid["price"] * s_e[u, b, t]) + for j in junc_ids: + junc = junctions[j] + primal_cost.add((1 - BETA) * junc["demand_shedding_cost"] * q_gas[j, t]) + if junc["is_source"]: + for si in junc["supply_intervals"]: + primal_cost.add((1 - BETA) * si["slope"] * s_g_s[j, si["id"], t]) + + # --- Dual cost (RHS * dual) --- + + # (42b) power balance: RHS = demand (constant) + for i in bus_ids: + dual_cost.add(lambda_b[i, t], elec_demand(i, t)) + + # (42c) p = sum s_e: RHS = 0 + + # (42d upper) s_bar * w - s_e >= 0: RHS = s_bar * w (parametric) + # -> s_bar * mu_d (McCormick for rho_d_upper * w) + for u in gen_ids: + for bid in gens[u]["bids"]: + b = bid["id"] + dual_cost.add(mu_d[u, b, t], bid["max_amount"]) + + # (42e lower) p >= p_min * o: RHS = p_min * o + # -> p_min * mu_el + for u in gen_ids: + dual_cost.add(mu_el[u, t], gens[u]["min_power"]) + + # (42e upper) p_max * o - p >= 0: RHS = p_max * o + # -> p_max * mu_eu + for u in gen_ids: + dual_cost.add(mu_eu[u, t], gens[u]["max_power"]) + + # (42g) ramp up: ramp_up*o[t-1] + p_max*v+[t] - p[t] + p[t-1] >= 0 + # RHS = ramp_up * o[t-1] + p_max * v+[t] (parametric) + # -> ramp_up * mu_go + p_max * mu_gv + for u in gen_ids: + g = gens[u] + dual_cost.add(mu_go[u, t], g["ramp_up"]) + dual_cost.add(mu_gv[u, t], g["max_power"]) + + # (42h) ramp down: ramp_down*o[t] + p_min*v-[t] + p[t] - p[t-1] >= 0 + # RHS = ramp_down * o[t] + p_min * v-[t] (parametric) + # -> ramp_down * mu_ho + p_min * mu_hv + for u in gen_ids: + g = gens[u] + dual_cost.add(mu_ho[u, t], g["ramp_down"]) + dual_cost.add(mu_hv[u, t], g["min_power"]) + + # (42i) DC flow: RHS = 0 + + # (42j upper) f_bar - f >= 0: RHS = f_bar (constant) + for l in line_ids: + dual_cost.add(rho_j_upper[l, t], lines[l]["thermal_limit"]) + + # (42j lower) f + f_bar >= 0: RHS = f_bar (constant) + for l in line_ids: + dual_cost.add(rho_j_lower[l, t], lines[l]["thermal_limit"]) + + # (42l upper) Delta - angle_diff >= 0: RHS = Delta + for l in line_ids: + dual_cost.add(rho_l_upper[l, t], lines[l]["angle_diff_limit"]) + + # (42l lower) angle_diff + Delta >= 0: RHS = Delta + for l in line_ids: + dual_cost.add(rho_l_lower[l, t], lines[l]["angle_diff_limit"]) + + # (42m) gas balance: RHS = 0 + + # (42n) supply decomposition: RHS = 0 + + # (42o) demand: l_gas + q_gas = d_g -> RHS = d_g + for j in junc_ids: + dual_cost.add(lambda_o[j, t], gas_demand(j, t)) + + # (42p) shed: d_g - q >= 0 -> RHS = d_g + for j in junc_ids: + dual_cost.add(rho_p[j, t], gas_demand(j, t)) + + # (42r) supply interval: cap - s_g_s >= 0 -> RHS = cap + for j in source_junc_ids: + for si in junctions[j]["supply_intervals"]: + sid = si["id"] + cap = si["interval_ub"] - si["interval_lb"] + dual_cost.add(rho_r[j, sid, t], cap) + + # (42s) compressor: RHS = 0 + # non-source s_g=0: RHS = 0 + + # Strong duality: primal_cost == dual_cost + m.addConstr(primal_cost == dual_cost, name="strong_duality") + + # Remove the legacy incomplete follower-dual block. Keeping it would + # silently impose a system that is not the dual of the SOC follower. The + # remaining named constraints are exactly the integrated-primal release. + m.update() + legacy_dual_constraints = [ + constraint + for constraint in m.getConstrs() + if constraint.ConstrName.startswith(("df_", "mc_")) + or constraint.ConstrName == "strong_duality" + ] + m.remove(legacy_dual_constraints) + m.update() + m._frontieror_release_variant = inst["released_problem_variant"] + m._frontieror_objective_weight_beta = beta + + # ----------------------------------------------------------------------- + # GUROBI PARAMETERS + # ----------------------------------------------------------------------- + m.Params.NumericFocus = 3 + m.Params.DualReductions = 0 + m.Params.ScaleFlag = 0 + m.Params.BarQCPConvTol = 1e-7 + m.Params.Aggregate = 0 + m.Params.TimeLimit = time_limit + + return m + + +def solve_and_output(m, solution_path): + """Solve the model and write solution JSON.""" + m.optimize() + + result = { + "status": m.Status, + "status_name": { + 1: "LOADED", + 2: "OPTIMAL", + 3: "INFEASIBLE", + 4: "INF_OR_UNBD", + 5: "UNBOUNDED", + 6: "CUTOFF", + 7: "ITERATION_LIMIT", + 8: "NODE_LIMIT", + 9: "TIME_LIMIT", + 10: "SOLUTION_LIMIT", + 11: "INTERRUPTED", + 12: "NUMERIC", + 13: "SUBOPTIMAL", + 14: "INPROGRESS", + 15: "USER_OBJ_LIMIT", + }.get(m.Status, "UNKNOWN"), + "objective_value": None, + "best_bound": None, + "gap": None, + "runtime": m.Runtime, + "node_count": m.NodeCount, + "released_problem_variant": m._frontieror_release_variant, + "objective_weight_beta": m._frontieror_objective_weight_beta, + } + + if m.SolCount > 0: + result["objective_value"] = m.ObjVal + try: + result["best_bound"] = m.ObjBound + result["gap"] = m.MIPGap + except Exception: + pass + + # Export every primary variable, including explicit zeros. Complete + # key coverage lets the checker distinguish a zero decision from an + # omitted decision. + primary_prefixes = ( + "o_", "vp_", "vm_", "r_", "w_", "phimax_", + "p_", "se_", "f_", "theta_", + "sg_", "sgs_", "pisq_", "phig_", + "lg_", "qg_", "gamma_", "psi_", + ) + primary_vars = {} + for v in m.getVars(): + if v.VarName.startswith(primary_prefixes): + primary_vars[v.VarName] = v.X + result["primary_variables"] = primary_vars + else: + print("WARNING: No feasible solution found.") + + 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']:.6f}") + print(f"Status: {result['status_name']}") + print(f"Runtime: {result['runtime']:.2f}s") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="MISOCP single-level reformulation (Approach G) for UCGNA bilevel problem " + "(Byeon & Van Hentenryck, 2022)") + 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 (default: gurobi_solution_1.json)") + parser.add_argument("--time_limit", type=int, default=3600, + help="Gurobi time limit in seconds (default: 3600)") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print(f"Loading instance from {args.instance_path}") + inst = load_instance(args.instance_path) + print(f"Instance: {inst.get('instance_id', 'unknown')}, " + f"T={inst['time_periods']}, " + f"generators={inst['generators']['num_generators']}, " + f"GFPPs={inst['generators']['num_gfpp']}") + + print("Building MISOCP model...") + model = build_model(inst, time_limit=args.time_limit) + print(f"Model has {model.NumVars} variables, {model.NumConstrs} linear constraints, " + f"{model.NumQConstrs} quadratic constraints") + + print("Solving...") + result = solve_and_output(model, args.solution_path) + + # Always exit 0: even when Gurobi proved INFEASIBLE or no incumbent + # was found, the wrapper has produced a valid solution JSON (with + # objective_value=None) and the orchestration layer's classifier + # interprets that correctly. Returning a non-zero exit code here + # would have run_program_solutions.py record exit_code=1 which the + # tag classifier promotes to tag G/H — falsely flagging a genuine + # INFEAS result as a Python crash. + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/byeon2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/byeon2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/byeon2022/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/byeon2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/byeon2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/byeon2022/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/byeon2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/byeon2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/byeon2022/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/byeon2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/byeon2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/byeon2022/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/byeon2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/byeon2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/byeon2022/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/byeon2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/byeon2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/byeon2022/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/byeon2022/gurobi_solution/large_solution_1.json b/tasks/byeon2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..24d3af79214c8a1c56cd3f4b5778c384c883c9dd --- /dev/null +++ b/tasks/byeon2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40cf7461e446d2b23482c0be3a235d0669cac9ac31456efe9559caf901217345 +size 71744 diff --git a/tasks/byeon2022/gurobi_solution/large_solution_2.json b/tasks/byeon2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a318a6dbd42ac47df3678039aa0245dccbeabf71 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8313d18ea074870773a5de9c2291f8c4cd95eaf511ccd23e6a65fc578ad44d72 +size 68668 diff --git a/tasks/byeon2022/gurobi_solution/large_solution_3.json b/tasks/byeon2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6c4c28c4fe5802fe6101895862aa235058668906 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f43ef8fef468a9306a36088d1cf782af2c6b9c2492f4c44bfe9b1eb8052fd607 +size 70291 diff --git a/tasks/byeon2022/gurobi_solution/large_solution_4.json b/tasks/byeon2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..6a5f9c724b806dacb5023366ff5f56e11a5cad87 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5117d933976c43bbed9c0f8130daeb1986e133f778c11946254f64f8ba8e91f7 +size 71691 diff --git a/tasks/byeon2022/gurobi_solution/large_solution_5.json b/tasks/byeon2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..27dadccef876c96231def18fcdae193429304909 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90f82042534ce7d1dcf9c48b9f20f6edd7e1c07163e1085e6bbd44176554b218 +size 75535 diff --git a/tasks/byeon2022/gurobi_solution/tiny_solution.json b/tasks/byeon2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..e03836730eca893aa398fe09880913fd7eb00f26 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83cbeab7e6de2050bc10940ebd5f3d0f0a8e1a08240d756e12bb36a7433ad826 +size 6425 diff --git a/tasks/byeon2022/gurobi_solution_log/large_log_1.jsonl b/tasks/byeon2022/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..df6e953a07dd82fa6d5b39cb302e3636419d517e --- /dev/null +++ b/tasks/byeon2022/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cce03dc3ce108e94e6d61869de8fa388a9135179ad336f011785453be2a33bc1 +size 222 diff --git a/tasks/byeon2022/gurobi_solution_log/large_log_2.jsonl b/tasks/byeon2022/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ec5a3743bbc0ec182261d3582505d149f8ad1a4 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2809fc2d8077b0b660c979070c540e4f85f8f46640e8e4858d053573fb3ee32b +size 168 diff --git a/tasks/byeon2022/gurobi_solution_log/large_log_3.jsonl b/tasks/byeon2022/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cdf0add1a4e7efcb902a345e3e7f0f6fed6f1f1d --- /dev/null +++ b/tasks/byeon2022/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34cefb4ba0fd316406a8df8ea370cc949e39182b13f62ac352b35af7e0346875 +size 55 diff --git a/tasks/byeon2022/gurobi_solution_log/large_log_4.jsonl b/tasks/byeon2022/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ed110ba3659b3f801dabd69784847933da37d67 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9dccd814ab997003a8f11b9135659208333e5d83b1224144c7b7e24e5fda7f57 +size 217 diff --git a/tasks/byeon2022/gurobi_solution_log/large_log_5.jsonl b/tasks/byeon2022/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5588e928cbb767bc9c83b928af81b638d3b274e7 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4af4497c0178dee648038cc6cf935605723da851e1654d453768e566eb9c426c +size 218 diff --git a/tasks/byeon2022/gurobi_solution_log/tiny_log.jsonl b/tasks/byeon2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d3a7a753e81c3e45cca56d9304bdbfb98d0d3831 --- /dev/null +++ b/tasks/byeon2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:002ba2066e4d644bb05596c3773219354df32cd0e093736225d00c32fe2d5c55 +size 55 diff --git a/tasks/byeon2022/instance/large_instance_1.json b/tasks/byeon2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a2cd24e9184902ed107f5a4ea1e21cbe31146442 --- /dev/null +++ b/tasks/byeon2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0377eaa6149ed0747e4ea4467e209d9d0d021958e6e77c6253ba45cdd71b9f5d +size 18715 diff --git a/tasks/byeon2022/instance/large_instance_2.json b/tasks/byeon2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..feb307a14edad039d84780eea5cdfcf2d9e288da --- /dev/null +++ b/tasks/byeon2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c9ac5f3c6c1899ff6bed53326c9c8c58670ad277ba519d38d0cadf8f08cb4ec +size 19201 diff --git a/tasks/byeon2022/instance/large_instance_3.json b/tasks/byeon2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d35e4d901ec40d02bf8b5f405517a3f2ac98a221 --- /dev/null +++ b/tasks/byeon2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19deb995f4f0e9cbae570150bd084452176f2f3e5b66763762ea0cbd2258eafd +size 18817 diff --git a/tasks/byeon2022/instance/large_instance_4.json b/tasks/byeon2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a7093a05d907ed620dba5e760ac0e4e111186dc4 --- /dev/null +++ b/tasks/byeon2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:274a23092ced4fb3dda2b1e5b9513e9ab8e75a74278087fa47573c1c243116f9 +size 19190 diff --git a/tasks/byeon2022/instance/large_instance_5.json b/tasks/byeon2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8670f477d07f5fe5a5aa9f081bd8f5a207c12a58 --- /dev/null +++ b/tasks/byeon2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:684002d6b393ecef3a6b317dc741c732acc3de26fb62b642d20898f33f95a6fb +size 19179 diff --git a/tasks/byeon2022/instance/tiny_instance.json b/tasks/byeon2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..783a2d5beabbdbbc6b5b90a1576c239f3683c56c --- /dev/null +++ b/tasks/byeon2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:982b4c6d4533c6f280730368d2435a93c77b1509720bfbad9d62f4391136de47 +size 8700 diff --git a/tasks/byeon2022/instance_schema.json b/tasks/byeon2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0327b5dd3565e8d29d44e4106b82bea24f5d26ad --- /dev/null +++ b/tasks/byeon2022/instance_schema.json @@ -0,0 +1,117 @@ +{ + "instance_id": " Unique identifier for this problem instance.", + "scale": " Size category of the instance (small, medium, or large).", + "problem_type": " Type of optimization problem formulation.", + "released_problem_variant": " Executable release contract: commitment, dispatch, gas-price, and network variables are optimized jointly under the primal constraints.", + "objective_weight_beta": " Weight on electricity cost; one minus this value weights gas cost.", + "stress_parameters": { + "eta_p": " Multiplier applied to base electricity demand across all buses.", + "eta_g": " Multiplier applied to base gas demand across all junctions." + }, + "time_periods": " Number of time periods in the planning horizon.", + "electricity_network": { + "num_buses": " Number of buses in the electricity transmission grid.", + "num_lines": " Number of transmission lines connecting buses.", + "buses": [ + { + "id": " Unique identifier for this bus.", + "demand_profile": " Electricity demand at this bus in each time period (MW).", + "voltage_angle_lb": " Lower bound on the voltage phase angle at this bus (radians).", + "voltage_angle_ub": " Upper bound on the voltage phase angle at this bus (radians)." + } + ], + "lines": [ + { + "id": " Unique identifier for this transmission line.", + "from_bus": " Bus at one endpoint of the line.", + "to_bus": " Bus at the other endpoint of the line.", + "susceptance": " Electrical susceptance of the line relating power flow to voltage angle difference (MW/rad).", + "thermal_limit": " Maximum allowable power flow on the line (MW).", + "angle_diff_limit": " Maximum allowable voltage angle difference between the two endpoint buses (radians)." + } + ] + }, + "generators": { + "num_generators": " Total number of generators in the system.", + "num_gfpp": " Number of gas-fired power plants among the generators.", + "generators": [ + { + "id": " Unique identifier for this generator.", + "bus": " Bus where this generator is located.", + "is_gfpp": " Whether this generator is a gas-fired power plant that consumes natural gas.", + "gas_junction": " Gas network junction from which this GFPP draws fuel, or null for non-GFPP generators.", + "min_power": " Minimum real power output when the generator is on (MW).", + "max_power": " Maximum real power output (MW).", + "ramp_down": " Maximum decrease in power output between consecutive time periods (MW).", + "ramp_up": " Maximum increase in power output between consecutive time periods (MW).", + "no_load_cost": " Fixed operating cost incurred each period the generator is on ($).", + "min_up_time": " Minimum number of consecutive periods the generator must remain on after starting up.", + "min_down_time": " Minimum number of consecutive periods the generator must remain off after shutting down.", + "initial_status": " On/off status of the generator at the start of the horizon (1 = on, 0 = off).", + "initial_gen": " Power output of the generator in the pre-horizon period (MW).", + "initial_active_periods": " Number of consecutive periods the generator has been on at the start of the horizon.", + "initial_inactive_periods": " Number of consecutive periods the generator has been off at the start of the horizon.", + "startup_cost_params": " Startup cost tiers, each a pair of lookback window length (periods) and associated startup cost ($).", + "num_bids": " Number of supply bid segments for this generator.", + "bids": [ + { + "id": " Unique identifier for this bid segment.", + "price": " Marginal price of electricity offered in this bid segment ($/MWh).", + "max_amount": " Maximum generation quantity available in this bid segment (MW)." + } + ], + "heat_rate_coefficients": { + "H_u2": " Quadratic coefficient of the heat rate curve relating power output to gas consumption (mmBtu/MW^2h).", + "H_u1": " Linear coefficient of the heat rate curve (mmBtu/MWh).", + "H_u0": " Constant coefficient of the heat rate curve (mmBtu/h)." + }, + "max_gas_price_fraction": " Maximum fraction of the global gas price upper bound at which this GFPP's bids remain profitable, or null for non-GFPP generators." + } + ] + }, + "gas_network": { + "num_junctions": " Number of junctions in the gas transmission network.", + "num_connections": " Total number of connections (pipelines and compressors) in the gas network.", + "num_compressors": " Number of compressor connections in the gas network.", + "num_pricing_zones": " Number of gas pricing zones partitioning the junctions.", + "max_gas_price_mmBtu": " Global upper bound on the gas price ($/mmBtu).", + "min_gas_price_mmBtu": " Global lower bound on the gas price ($/mmBtu).", + "pricing_zones": [ + { + "id": " Unique identifier for this pricing zone.", + "junctions": " Gas junctions belonging to this pricing zone." + } + ], + "junctions": [ + { + "id": " Unique identifier for this gas junction.", + "is_source": " Whether this junction is a gas supply source.", + "pressure_lb_squared": " Lower bound on the squared pressure at this junction.", + "pressure_ub_squared": " Upper bound on the squared pressure at this junction.", + "demand_shedding_cost": " Penalty cost per unit of unmet gas demand at this junction ($/unit).", + "gas_demand_profile": " Exogenous gas demand at this junction in each time period.", + "supply_intervals": [ + { + "id": " Unique identifier for this supply interval.", + "interval_lb": " Lower bound on gas production in this interval.", + "interval_ub": " Upper bound on gas production in this interval.", + "slope": " Marginal cost of gas supply within this interval ($/unit)." + } + ] + } + ], + "connections": [ + { + "id": " Unique identifier for this gas network connection.", + "from_junction": " Junction at the upstream end of the connection.", + "to_junction": " Junction at the downstream end of the connection.", + "type": " Type of connection (pipeline or compressor).", + "weymouth_factor": " Resistance factor relating pressure drop to squared gas flow for pipelines, or null for compressors.", + "compression_ratio_lb": " Lower bound on the pressure compression ratio for compressors, or null for pipelines.", + "compression_ratio_ub": " Upper bound on the pressure compression ratio for compressors, or null for pipelines.", + "control_ratio_lb": " Lower bound on the control valve ratio, or null if not applicable.", + "control_ratio_ub": " Upper bound on the control valve ratio, or null if not applicable." + } + ] + } +} diff --git a/tasks/byeon2022/mathematical_formulation.md b/tasks/byeon2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..9300bf511081633d198c23ac3ff3928d26dbcc89 --- /dev/null +++ b/tasks/byeon2022/mathematical_formulation.md @@ -0,0 +1,73 @@ +# Released Formulation: Integrated-Primal UCGNA MISOCP + +*Source: Benders Subproblem Decomposition for Bilevel Problems with Convex Follower, Byeon and Van Hentenryck, 2022.* + +The source paper studies a bilevel second-order-cone model. The executable +FrontierOR release is deliberately narrower and every instance declares +`released_problem_variant = integrated_primal_ucgna`. It jointly optimizes +all commitment, dispatch, gas-network, gas-price, and electricity-network +variables under the leader constraints (40b--41e) and follower **primal** +constraints (42b--42w): + +$$ +\min\; \beta C_{\mathrm{electricity}} + +(1-\beta)C_{\mathrm{gas}}, +$$ + +where $\beta$ is the instance field `objective_weight_beta`. The electricity +term contains no-load, startup, and bid-dispatch costs; the gas term contains +gas-demand shedding and interval supply costs. The conic Weymouth and heat +rate inequalities are retained. Zonal gas prices are bounded primal decisions +linked to commitment by the released bid-validity constraints. + +There is no follower `argmin`, dual-feasibility system, or strong-duality +constraint in this executable variant. In particular, the former incomplete +SOC dual is not part of the released feasible set. A valid solution reports +the complete primary-variable key set, including explicit zeros, and the +checker recomputes this objective and every released primal constraint. + +## Source-paper bilevel context (not the executable release contract) + +## Sets and Parameters + +- $n_x, n_y$: dimensions of the leader and follower variable vectors. + +- $m_x, m_y$: numbers of leader and follower constraints. + +- $\mathcal{I} \subseteq \{1,\dots,n_x\}$: index set of integer leader variables. + +- $\mathcal{J} \subseteq \mathcal{I}$: indices $i$ such that column $i$ of $A$ is nonzero (leader variables that appear in the follower problem). + +- $c_x \in \mathbb{R}^{n_x}$, $c_y \in \mathbb{R}^{n_y}$: leader objective coefficients. + +- $G_x \in \mathbb{R}^{m_x \times n_x}$, $G_y \in \mathbb{R}^{m_x \times n_y}$, $h \in \mathbb{R}^{m_x}$: leader constraint data. + +- $A \in \mathbb{R}^{m_y \times n_x}$, $B \in \mathbb{R}^{m_y \times n_y}$, $b \in \mathbb{R}^{m_y}$, $d \in \mathbb{R}^{n_y}$: follower constraint and objective data. + +- $\underline{x}_i, \overline{x}_i$: lower and upper bounds on $x_i$ (finite for $i \in \mathcal{J}$). + +- $\mathcal{K}_x, \mathcal{K}_y$: Cartesian products of second-order cones and nonnegative orthants (the ambient cones for $x$ and $y$). + +## Decision Variables + +- $x \in \mathbb{R}^{n_x}$: leader (upper-level) decision variables. + +- $y \in \mathbb{R}^{n_y}$: follower (lower-level) decision variables. + +## Objective + +$$\begin{equation} +\min_{x,\,y} \quad c_x^{\top} x + c_y^{\top} y \tag{1a} +\end{equation}$$ + +## Constraints (Bilevel) + +$$\begin{align} +G_x x + G_y y & \;\geq\; h, \tag{1b} \\[2pt] +x & \;\in\; \mathcal{X} \;:=\; \Bigl\{ x \in \mathcal{K}_x \;:\; + x_i \in [\underline{x}_i,\overline{x}_i] \cap \mathbb{Z},\;\forall i \in \mathcal{I} \Bigr\}, \tag{1c} \\[2pt] +y & \;\in\; \arg\min_{y' \in \mathcal{K}_y} + \Bigl\{\, d^{\top} y' \;:\; A x + B y' \geq b \,\Bigr\}. \tag{1d} +\end{align}$$ + +Constraint (1d) enforces that $y$ is an optimal response of the follower to the leader decision $x$ (optimistic bilevel); the problem is an MISOCP-follower bilevel program. Under Assumption 2(b) integer bounded $x_i$ for $i \in \mathcal{J}$ may be encoded as binary without loss of generality. diff --git a/tasks/byeon2022/problem_description.txt b/tasks/byeon2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..1b88da68f1f83332df40dfc181e9c023574d7a5e --- /dev/null +++ b/tasks/byeon2022/problem_description.txt @@ -0,0 +1,19 @@ +# Problem Description + +This released benchmark concerns Unit Commitment with Gas Network Awareness (UCGNA) and coordinates interdependent electricity and natural gas systems over a finite planning horizon. It is explicitly identified in every JSON instance as the `integrated_primal_ucgna` variant: commitment, dispatch, gas-price, and network variables are optimized jointly. It does not claim to be the exact bilevel-conic reformulation from the source paper. The electricity transmission grid is an undirected graph of buses connected by transmission lines, and the natural gas transmission system is a directed graph of junctions connected by pipelines, compressors, and control valves. A set of time periods spans the planning horizon. Some generators are conventional, while others are gas-fired power plants (GFPPs) that consume natural gas from the gas network at specified junctions. Gas junctions are partitioned into pricing zones, each of which has a single zonal gas-price decision. + +The input data for the electricity network specifies, for each bus, the electricity demand profile over all time periods, and lower and upper bounds on the voltage angle. For each transmission line, the data provides the susceptance, the thermal flow limit, and the maximum allowable voltage angle difference between its two endpoint buses. For each generator, the data specifies which bus it is located at, whether it is a GFPP (and if so, which gas junction it draws fuel from), its minimum and maximum real power output, its ramp-up and ramp-down rates, its no-load cost, its minimum up-time and minimum down-time, its initial on/off status, its initial power output, the number of time periods it has been active or inactive at the start of the horizon, and a list of startup cost tiers each defined by a lookback window in periods and an associated cost. Each generator submits a set of supply bids, where each bid has a price and a maximum generation amount. Each GFPP additionally has heat-rate curve coefficients (a quadratic, linear, and constant term) relating power output to gas consumption, a maximum allowable fraction of the gas price at which its bids remain profitable, and a per-bid profitability threshold representing the maximum gas price at which that particular bid remains profitable. + +The input data for the gas network specifies, for each junction, whether it is a gas source, the lower and upper bounds on squared pressure, a cost of shedding gas demand, and a gas demand profile over all time periods. Source junctions provide a set of non-overlapping gas supply intervals, each defined by lower and upper production limits and a marginal supply cost (slope), with slopes ordered from cheapest to most expensive across successive intervals. For each pipeline connection, the data provides a Weymouth resistance factor relating pressure drop to the square of gas flow. For each compressor, the data provides lower and upper bounds on the compression ratio. For each control valve, the data provides lower and upper bounds on the control ratio. A global maximum and minimum gas price per unit of energy (mmBtu) are given. + +The joint decision vector contains, for each generator and period, on/off, startup/shutdown, bid-selection, startup-cost, and dispatch decisions. For every GFPP it also contains the maximum allowable gas price at its scheduled output. Network decisions comprise bid-level generation, power flows, voltage angles, gas supply and its interval decomposition, gas flows, squared pressures, satisfied and shed gas demand, GFPP gas consumption, and zonal gas prices. In this executable variant zonal prices are bounded primal decisions coupled to commitment through the bid-validity rules; they are not asserted to be conic-dual equilibrium multipliers. + +The leader's choices must satisfy several rules. Each generator's initial on/off status is fixed for the first period and must remain unchanged for any remaining periods dictated by the initial active or inactive duration. The startup cost in each period must be at least as large as the applicable startup cost tier, determined by comparing the current on status against the on/off history over the lookback window. The startup cost must also be nonnegative. The minimum up-time rule requires that the sum of startup indicators over any window of consecutive periods equal in length to the minimum up-time must not exceed the on/off indicator of the last period in that window. The minimum down-time rule requires that the sum of startup indicators over any window of consecutive periods equal in length to the minimum down-time must not exceed one minus the on/off indicator of the period immediately before that window. The startup and shutdown indicators relate to the on/off indicators by the rule that the startup indicator minus the shutdown indicator equals the change in on/off status from the previous period to the current period. A bid of a GFPP can only be selected if that generator is on. For GFPPs, the generation from each bid is bounded above by the bid's maximum amount times the bid selection indicator. GFPP bids are activated sequentially: the next bid can be selected only if the current bid is fully utilized. For each GFPP in each period, the maximum allowable gas price is determined by the per-bid profitability thresholds and the bid selection pattern: for each bid except the last, the bid's profitability threshold is multiplied by the difference between that bid's selection indicator and the next bid's selection indicator, and the last bid's threshold is multiplied by its own selection indicator, with the sum of these products giving the maximum allowable gas price. For each committed GFPP at a junction in a given pricing zone, this maximum allowable gas price must be at least as large as the zonal gas price when the generator is on (that is, at least the product of the zonal gas price and the on/off indicator). This nonlinear relationship is represented exactly through linear inequalities that introduce auxiliary quantities and use the global gas price bounds. + +The dispatch must satisfy the following rules. At each bus and each time period, the total power generated by all generators at that bus minus the bus demand equals the net outgoing power flow (outgoing minus incoming flows on lines incident to that bus). Each generator's total output equals the sum of its bid amounts. Each bid's generation amount is bounded between zero and the bid's maximum capacity. Each generator's output is bounded between its minimum and maximum power times the on/off indicator. For ramp-up, the increase in output from one period to the next is limited by the ramp-up rate times the prior on/off indicator plus the maximum power times the startup indicator. For ramp-down, the decrease is limited by the ramp-down rate times the current on/off indicator plus the minimum power times the shutdown indicator. The initial output in the pre-horizon period is fixed. Power flow on each line equals line susceptance times the endpoint voltage-angle difference, and flow and angle differences obey their stated bounds. + +For the gas network, at each junction and each time period, the gas supply minus the satisfied demand minus the total GFPP gas consumption equals the net outgoing gas flow. At source junctions the total supply equals the sum of supply-interval amounts, and each interval amount is bounded by the interval's capacity. At non-source junctions the supply is zero. The satisfied demand plus the shed demand equals the exogenous gas demand, and shed demand cannot exceed the gas demand. Gas flows on all connections are nonnegative. For pipelines, the Weymouth equation is enforced as a convex relaxation: the squared pressure at the from-junction minus the squared pressure at the to-junction is at least the Weymouth factor times the square of the gas flow. For compressors, the squared pressure at the to-junction divided by the squared pressure at the from-junction lies between the square of the lower compression ratio and the square of the upper compression ratio (equivalently, the to-junction squared pressure is bounded between these ratio-squared values times the from-junction squared pressure). For control valves, the to-junction squared pressure is similarly bounded between the square of the lower control ratio and the square of the upper control ratio times the from-junction squared pressure. Squared pressures at all junctions are bounded within their specified lower and upper limits. The total gas consumed by GFPPs at each junction that is also a bus in the electricity network is at least the sum, over all GFPPs located at that junction, of the quadratic heat-rate function of that generator's power output: the quadratic coefficient times the square of the output plus the linear coefficient times the output plus the constant coefficient times the on/off indicator. This is also enforced as a convex relaxation. + +There is no separate lower-level optimality condition in the released executable variant. All submitted primary variables form one complete primal witness. The checker requires every expected key, verifies the joint feasibility constraints, and recomputes the objective from that witness. + +The goal is to minimize total integrated system cost. The instance field `objective_weight_beta` weights electricity cost, and one minus that value weights gas cost. The electricity component sums no-load cost, startup cost, and bid-price times bid generation. The gas component sums demand-shedding cost and supply-interval cost. Zonal gas-price decisions and commitment decisions must jointly satisfy the bid-validity rules above. diff --git a/tasks/byeon2022/solution_logger.py b/tasks/byeon2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/byeon2022/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/byeon2022/solution_schema.json b/tasks/byeon2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..53bbe8e7f911d59829b9bed3a3c954a95e3da98b --- /dev/null +++ b/tasks/byeon2022/solution_schema.json @@ -0,0 +1,25 @@ +{ + "objective_value": " Total weighted system cost combining electricity commitment-plus-dispatch cost and gas dispatch cost.", + "released_problem_variant": " Must match the instance release contract.", + "objective_weight_beta": " Electricity-cost weight copied from the instance.", + "primary_variables": { + "o_{generator}_{period}": " Whether the generator is on (1) or off (0) in each period, with period 0 being the fixed pre-horizon state.", + "vp_{generator}_{period}": " Whether the generator starts up at the beginning of each period.", + "vm_{generator}_{period}": " Whether the generator shuts down at the beginning of each period.", + "w_{generator}_{bid}_{period}": " Whether the given supply bid of the generator is selected in each period.", + "r_{generator}_{period}": " Startup cost incurred by the generator in each period.", + "phimax_{generator}_{period}": " Maximum allowable gas price at which the committed gas-fired power plant's scheduled output remains profitable in each period.", + "p_{generator}_{period}": " Real power output of the generator in each period, with period 0 being the fixed pre-horizon output.", + "se_{generator}_{bid}_{period}": " Real power output supplied by the given bid of the generator in each period.", + "f_{line}_{period}": " Real power flow on the transmission line from its from-bus to its to-bus in each period.", + "theta_{bus}_{period}": " Voltage angle at the bus in each period.", + "sg_{junction}_{period}": " Total gas supply provided at the junction in each period.", + "sgs_{junction}_{supply_interval}_{period}": " Gas supply provided from the given supply interval of the source junction in each period.", + "pisq_{junction}_{period}": " Squared pressure at the gas junction in each period.", + "phig_{connection}_{period}": " Gas flow on the gas-network connection from its from-junction to its to-junction in each period.", + "lg_{junction}_{period}": " Satisfied gas demand at the junction in each period.", + "qg_{junction}_{period}": " Shed gas demand at the junction in each period.", + "gamma_{junction}_{period}": " Total gas consumed by gas-fired power plants at the junction in each period.", + "psi_{pricing_zone}_{period}": " Zonal gas price for the pricing zone in each period." + } +} diff --git a/tasks/caprara1999/feasibility_check.py b/tasks/caprara1999/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c357916129980e701ba759a8d20d0909e6180be8 --- /dev/null +++ b/tasks/caprara1999/feasibility_check.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Quadratic Knapsack Problem (QKP). + +Checks hard constraints from Caprara, Pisinger, and Toth (1999): + Constraint 1: sum_{j in N} w_j x_j <= c (capacity) + Constraint 2: x_j in {0, 1} for all j in N (binary / integrality) + Constraint 3: objective consistency + reported objective_value must equal recomputed + sum_{i in N} sum_{j in N} p_{ij} x_i x_j + within a small tolerance (Tier C defence against + self-reported-objective exploits). All variables determining + the objective (the selected_items vector x) are present in + the solution, so a full recompute is exact. +""" + +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 + + n = instance["n"] + weights = instance["weights"] + capacity = instance["capacity"] + profit_matrix = instance["profit_matrix"] + + # Parse selected_items: could be a binary vector [0,1,0,...] or a list of indices [3,4,7,...] + raw_items = solution["selected_items"] + if len(raw_items) == n and all(v in (0, 1, 0.0, 1.0) for v in raw_items): + # Binary vector format + x = [float(v) for v in raw_items] + else: + # List of selected indices format + x = [0.0] * n + for idx in raw_items: + x[idx] = 1.0 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ---- Constraint 1: capacity constraint ---- + # sum_{j in N} w_j x_j <= c + lhs_cap = sum(weights[j] * x[j] for j in range(n)) + rhs_cap = float(capacity) + violation_amount_cap = max(lhs_cap - rhs_cap, 0.0) + + if violation_amount_cap > tol: + violated_constraints.add(1) + violations.append( + f"Capacity constraint violated: total weight {lhs_cap} exceeds capacity {rhs_cap}" + ) + normalizer = max(abs(rhs_cap), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_cap, + "rhs": rhs_cap, + "raw_excess": violation_amount_cap, + "normalizer": normalizer, + "ratio": violation_amount_cap / normalizer, + }) + + # ---- Constraint 2: binary / integrality constraint ---- + # x_j in {0, 1} for all j in N + for j in range(n): + diff = min(abs(x[j] - 0.0), abs(x[j] - 1.0)) + if diff > tol: + violated_constraints.add(2) + rhs_val = round(x[j]) # nearest integer + violation_amount = diff + violations.append( + f"Integrality violated for item {j}: x[{j}] = {x[j]} is not binary" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": x[j], + "rhs": float(rhs_val), + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ---- Constraint 3: objective consistency (Tier C) ---- + # reported objective_value == sum_i sum_j p_{ij} x_i x_j + # Full recompute is exact: selected_items contains every variable that + # determines the objective. Tolerance: 0.1% relative with a 0.5 absolute + # floor, since profit_matrix entries are integers and any honest mismatch + # is at least 1. + reported_obj = solution.get("objective_value") + try: + reported = float(reported_obj) if reported_obj is not None else None + except (TypeError, ValueError): + reported = None + if reported is not None: + # Iterate only over the selected items for efficiency (n can be 300+). + selected = [j for j in range(n) if x[j] > 0.5] + true_obj = 0.0 + for i in selected: + row = profit_matrix[i] + for j in selected: + true_obj += row[j] + true_obj = float(true_obj) + abs_diff = abs(reported - true_obj) + obj_tol = max(0.5, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(3) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum_i sum_j p_ij x_i x_j=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 3, + "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 QKP (Caprara et al. 1999)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to instance JSON file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to solution JSON file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write feasibility result JSON file") + args = parser.parse_args() + + 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"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/caprara1999/gurobi_code.py b/tasks/caprara1999/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..06190174dc381c8d26fbb942f9cecc2a1bbf18b5 --- /dev/null +++ b/tasks/caprara1999/gurobi_code.py @@ -0,0 +1,146 @@ +""" +Quadratic Knapsack Problem (QKP) solver using Gurobi. + +Implements the linearized ILP formulation from: + Caprara, Pisinger, and Toth (1999), + "Exact Solution of the Quadratic Knapsack Problem" + +Linearized ILP: + maximize sum_{j in N} sum_{i in N\{j}} p_{ij} y_{ij} + sum_{j in N} q_j x_j + subject to: + sum_{j in N} w_j x_j <= c + sum_{i in N\{j}} w_i y_{ij} <= (c - w_j) x_j, for all j in N + 0 <= y_{ij} <= x_j, for all i,j in N, j != i + y_{ij} = y_{ji}, for all i,j in N, j > i + x_j, y_{ij} in {0,1} +""" + +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 solve_qkp(instance_path: str, solution_path: str, time_limit: float) -> None: + # Load instance + with open(instance_path, "r") as f: + data = json.load(f) + + n = data["n"] + capacity = data["capacity"] + weights = data["weights"] + P = data["profit_matrix"] + + N = range(n) + + # Diagonal entries are the individual item profits q_j + q = [P[j][j] for j in N] + + # Build model + model = gp.Model("QKP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + + # Decision variables + x = model.addVars(N, vtype=GRB.BINARY, name="x") + + # y_{ij} for i != j + y = {} + for i in N: + for j in N: + if i != j: + y[i, j] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}_{j}") + + model.update() + + # Objective (2): sum_{j} sum_{i != j} p_{ij} y_{ij} + sum_{j} q_j x_j + obj = gp.quicksum(P[i][j] * y[i, j] for i in N for j in N if i != j) + obj += gp.quicksum(q[j] * x[j] for j in N) + model.setObjective(obj, GRB.MAXIMIZE) + + # Constraint (3): capacity constraint + model.addConstr( + gp.quicksum(weights[j] * x[j] for j in N) <= capacity, + name="capacity" + ) + + # Constraint (4): surrogate knapsack constraints for each j + for j in N: + model.addConstr( + gp.quicksum(weights[i] * y[i, j] for i in N if i != j) + <= (capacity - weights[j]) * x[j], + name=f"surrogate_{j}" + ) + + # Constraint (5): y_{ij} <= x_j + for i in N: + for j in N: + if i != j: + model.addConstr(y[i, j] <= x[j], name=f"link_{i}_{j}") + + # Constraint (6): symmetry y_{ij} = y_{ji} for j > i + for i in N: + for j in N: + if j > i: + model.addConstr(y[i, j] == y[j, i], name=f"sym_{i}_{j}") + + # Solve + model.optimize() + + # Extract solution + if model.SolCount > 0: + objective_value = model.ObjVal + selected_items = [int(x[j].X > 0.5) for j in N] + else: + objective_value = None + selected_items = [0] * n + + # Write solution + solution = { + "objective_value": objective_value, + "selected_items": selected_items, + } + + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + +def main(): + parser = argparse.ArgumentParser( + description="Solve QKP using Gurobi (Caprara et al. 1999 linearization)" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to instance JSON file" + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to write solution JSON file" + ) + parser.add_argument( + "--time_limit", type=int, default=300, + help="Gurobi 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) + solve_qkp(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/caprara1999/gurobi_feasi_result/large_feasi_result_1.json b/tasks/caprara1999/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/caprara1999/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/caprara1999/gurobi_feasi_result/large_feasi_result_2.json b/tasks/caprara1999/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/caprara1999/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/caprara1999/gurobi_feasi_result/large_feasi_result_3.json b/tasks/caprara1999/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/caprara1999/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/caprara1999/gurobi_feasi_result/large_feasi_result_4.json b/tasks/caprara1999/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/caprara1999/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/caprara1999/gurobi_feasi_result/large_feasi_result_5.json b/tasks/caprara1999/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/caprara1999/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/caprara1999/gurobi_feasi_result/tiny_feasi_result.json b/tasks/caprara1999/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/caprara1999/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/caprara1999/gurobi_solution/large_solution_1.json b/tasks/caprara1999/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3d4535148700de5a36fd80ec3b09f52e075408f9 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2682afba3221cb16991360e6434053ce7f8f1485479bac8859cc4f198833a729 +size 2180 diff --git a/tasks/caprara1999/gurobi_solution/large_solution_2.json b/tasks/caprara1999/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f32ed3eb18cb5fa89b8f9a17ac72260a4245efbc --- /dev/null +++ b/tasks/caprara1999/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:662be2b591eec244ea17f745c23eeeae0e6795571f1db9a6bb66124cea805aa5 +size 2181 diff --git a/tasks/caprara1999/gurobi_solution/large_solution_3.json b/tasks/caprara1999/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..52dee3c7a6f023b540890f85a8a31f526337c503 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f33e0dcddcc180a6260c52b6d1e95fc1e95944717308d22eace042e623523f6d +size 2180 diff --git a/tasks/caprara1999/gurobi_solution/large_solution_4.json b/tasks/caprara1999/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c82e7606ffc8a09a39e9ce527a7f6741790e85ba --- /dev/null +++ b/tasks/caprara1999/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec982a066655bda62d2e6a50aafc8b5625640fe1a7d72cc39af74e1e5fe43aeb +size 2180 diff --git a/tasks/caprara1999/gurobi_solution/large_solution_5.json b/tasks/caprara1999/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3a908a4dc9536f40a99742fd3a9c9d81e39ceb4c --- /dev/null +++ b/tasks/caprara1999/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0c7131c4bfc7f1d5ab19b806a9528442aed7b3ff3f5c175e0a4ab85a2792391 +size 2182 diff --git a/tasks/caprara1999/gurobi_solution/tiny_solution.json b/tasks/caprara1999/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..630f4df1e34e94814e2b55d0c47478fc82a25930 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93a2c487af461d545aecde22c94c47724b796510dd529dda89dab2cd61bd892f +size 216 diff --git a/tasks/caprara1999/gurobi_solution_log/large_log_1.jsonl b/tasks/caprara1999/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c52f91ea765d94974b18779291b75efa87091d3a --- /dev/null +++ b/tasks/caprara1999/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:374b2fe7d0f56890a9295c1628f5bbaf87519e135d563679b8d5973faf5d8c31 +size 42 diff --git a/tasks/caprara1999/gurobi_solution_log/large_log_2.jsonl b/tasks/caprara1999/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6447f82305f717a20a7ae6855a8518a3a3414746 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6fd166e0ad03b19addafadbd381428919b44d047028487e1c4e43b829d5798a4 +size 43 diff --git a/tasks/caprara1999/gurobi_solution_log/large_log_3.jsonl b/tasks/caprara1999/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a361d08567660e4d13d922cf59d179c5472692b8 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbadfd710f72b85eb0fcd28a15ebd8462ddae738631f54b57850b795ffbd32d6 +size 42 diff --git a/tasks/caprara1999/gurobi_solution_log/large_log_4.jsonl b/tasks/caprara1999/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d63af7c69bb1893f258f8de2ae7de7a3114588a2 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6caaf59b269be1a5ae732d504d9aa4a273c839835fae6d19e75391d082327c27 +size 43 diff --git a/tasks/caprara1999/gurobi_solution_log/large_log_5.jsonl b/tasks/caprara1999/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c5bb05cf5fda6d5a873a5298fc22582d0a6a55f8 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6abe5dea27310d68d55ed286dd168b10119bc3230ffee31aac103d99e7237d84 +size 43 diff --git a/tasks/caprara1999/gurobi_solution_log/tiny_log.jsonl b/tasks/caprara1999/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e1ec12c34c01bda701914b294ef5fe750ba7ebf8 --- /dev/null +++ b/tasks/caprara1999/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4dd4eea488ddfbece2445e191b5cb7c853dc90d612ec48eb3a1e64beddd2adb4 +size 41 diff --git a/tasks/caprara1999/instance/large_instance_1.json b/tasks/caprara1999/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..7dfdd3574ab1e6b7d410fefdde3444d49983cda2 --- /dev/null +++ b/tasks/caprara1999/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41577d380b4b011fce80b92bc95d1ceacb6efee0771cd2b1b1b40ad09baa5ea6 +size 898862 diff --git a/tasks/caprara1999/instance/large_instance_2.json b/tasks/caprara1999/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..62beebd48cf684d4253de9e72041dad648ea5fba --- /dev/null +++ b/tasks/caprara1999/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89c9c47e514419671feaaafca350724f07f09a3b84b1530403adaee20bcf2e9d +size 878310 diff --git a/tasks/caprara1999/instance/large_instance_3.json b/tasks/caprara1999/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e9b24a95cb0097bd93e5d099ebf59d38e7c79b52 --- /dev/null +++ b/tasks/caprara1999/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6d2f22e9b35b8578d439a6a9b256f1f955e9cc6bd48e4e6303d91fd592c9a8a +size 857382 diff --git a/tasks/caprara1999/instance/large_instance_4.json b/tasks/caprara1999/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f528d1aeec2af46e0bc8c858780ba956a93d8825 --- /dev/null +++ b/tasks/caprara1999/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:928b19126a377818e4c1fce47fb77573e640fea4fbef49892c5f744f0225c0d3 +size 836220 diff --git a/tasks/caprara1999/instance/large_instance_5.json b/tasks/caprara1999/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..081c7ce59b60be21ad9063dc8f23c5885c8e650c --- /dev/null +++ b/tasks/caprara1999/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73b2a4a4669d04835a3835dcf0d4a33e001354b6a7b3474d565bcd19cc43966e +size 906043 diff --git a/tasks/caprara1999/instance/tiny_instance.json b/tasks/caprara1999/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b32ed5cb06b09914d05e840c0a6626e1d1df0191 --- /dev/null +++ b/tasks/caprara1999/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:329f1c1d3b16cfb404868efd9c35d58b1b4b5c76c28bb832684b250f63b21b3e +size 4184 diff --git a/tasks/caprara1999/instance_schema.json b/tasks/caprara1999/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e737999ed84ce6c091585e9f38110d18732d40af --- /dev/null +++ b/tasks/caprara1999/instance_schema.json @@ -0,0 +1,7 @@ +{ + "n": " Number of items available for packing into the knapsack.", + "density_percent": " Percentage of entries in the profit matrix that are nonzero.", + "capacity": " Maximum total weight the knapsack can hold.", + "weights": " Weight of each item.", + "profit_matrix": " Symmetric matrix where each diagonal entry gives the individual profit for selecting that item and each off-diagonal entry gives the additional joint profit earned when both items in the pair are selected together." +} \ No newline at end of file diff --git a/tasks/caprara1999/mathematical_formulation.md b/tasks/caprara1999/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..825c56f2316614b8efcab17795a210b892c6c4b5 --- /dev/null +++ b/tasks/caprara1999/mathematical_formulation.md @@ -0,0 +1,34 @@ +# Original Formulation: Quadratic Knapsack Problem (QKP) + +*Source: Exact Solution of the Quadratic Knapsack Problem, Alberto Caprara, David Pisinger, Paolo Toth, 1999 (INFORMS Journal on Computing 11(2):125–137).* + +## Sets and Parameters + +- $N := \{1, \dots, n\}$ — set of items; $i, j \in N$ are item indices. + +- $n$ — number of items. + +- $w_j$ — positive integer weight of item $j$, for $j \in N$. + +- $c$ — positive integer knapsack capacity. + +- $P = (p_{ij})$ — $n \times n$ nonnegative integer profit matrix, assumed symmetric, i.e. $p_{ij} = p_{ji}$ for all $i, j \in N,\ j > i$. The diagonal element $q_j := p_{jj}$ is the profit achieved if item $j$ is selected; for $j > i$, the quantity $p_{ij} + p_{ji}$ is the profit achieved if both items $i$ and $j$ are selected. + +It is assumed without loss of generality that $\max_{j \in N} w_j \leq c < \sum_{j \in N} w_j$. + +## Decision Variables + +- $x_j \in \{0, 1\}$ — equal to $1$ if item $j$ is selected, $0$ otherwise, for $j \in N$. + +## Objective + +$$\begin{align} +\text{maximize} \quad & z(\text{QKP}) = \sum_{i \in N} \sum_{j \in N} p_{ij}\, x_i x_j \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{subject to} \quad & \sum_{j \in N} w_j x_j \leq c \tag{1} \\ + & x_j \in \{0, 1\}, \quad j \in N. \tag{1} +\end{align}$$ diff --git a/tasks/caprara1999/problem_description.txt b/tasks/caprara1999/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8c1a91fe44d8a2314b6f27e99eacc65dad446ef --- /dev/null +++ b/tasks/caprara1999/problem_description.txt @@ -0,0 +1,3 @@ +# Problem Description + +A collection of items is available for packing into a single knapsack. Each item has a known positive integer weight, and the knapsack has a known positive integer capacity. The capacity is at least as large as the heaviest single item but strictly less than the total weight of all items combined, so that some items must be left out. A symmetric profit matrix, with as many rows and columns as there are items and with nonnegative integer entries, specifies two kinds of profit: the diagonal entry for each item gives the individual profit earned simply by selecting that item, while each off-diagonal entry for a pair of distinct items records an additional profit earned only when both items in the pair are selected together. The profit matrix is symmetric, meaning the entry for any two distinct items is the same regardless of which item indexes the row and which indexes the column. The task is to choose a subset of the items to place in the knapsack such that the total weight of the chosen items does not exceed the knapsack capacity. The goal is to maximize the total profit, which equals the sum of all entries in the profit matrix for which both the row item and the column item are selected. Because diagonal entries have the same item in both the row and column position, each diagonal entry contributes when its item is selected. Because the matrix is symmetric and every off-diagonal entry appears in both orderings, the profit contribution from each pair of distinct selected items equals twice the value of a single off-diagonal entry for that pair. diff --git a/tasks/caprara1999/solution_logger.py b/tasks/caprara1999/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/caprara1999/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/caprara1999/solution_schema.json b/tasks/caprara1999/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..4dffeebb921b261fe12956a828dac6beca6f5ded --- /dev/null +++ b/tasks/caprara1999/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total profit from individual item profits and joint profits of all selected item pairs.", + "selected_items": " Whether each item is placed in the knapsack (1 = selected, 0 = not selected)." +} \ No newline at end of file diff --git a/tasks/carosi2019/feasibility_check.py b/tasks/carosi2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..539880bf41d4f5533086c6cc72cc95b3612cfea8 --- /dev/null +++ b/tasks/carosi2019/feasibility_check.py @@ -0,0 +1,890 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for ITTVS (Integrated Timetabling and Vehicle Scheduling) solutions. + +Checks hard constraints from the MILP formulation (equations 2-6) in: + Carosi, Frangioni, Galli, Girardi, Vallese (2019) + "A matheuristic for integrated timetabling and vehicle scheduling" + Transportation Research Part B 127, 99-124. + +Constraint numbering (top to bottom in formulation section, skipping objective): + Constraint 1 = eq(2): TT flow conservation + Constraint 2 = eq(3): y binary integrality + Constraint 3 = eq(4): VS flow conservation (circulation) + Constraint 4 = eq(5): VS capacity bounds (0 <= x <= u) + Constraint 5 = eq(6): Linking (TT selection = VS selection) + Constraint 6 = eq(1): Objective-value consistency (Tier C anti-exploit) - + the program's reported objective_value must equal the recomputed + alpha * (VS arc costs) + sum_d (TT arc costs) evaluated on the + provided vs_flows and the selected-trip chain in each direction + (within a 0.1% relative tolerance). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('num_vehicles', 'objective_value', 'selected_trips', 'tt_arcs_used', 'vs_flows') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('num_vehicles', 'tt_arcs_used') +_FRONTIEROR_DERIVED_FIELD_RULES = (('num_vehicles', 'mapping_value', 'vs_flows', 'VS_O_plus-->VS_O_minus'),) +_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 + + + +# ============================================================ +# Tolerance constants +# ============================================================ +TOL = 1e-5 +EPS = 1e-5 + + +# ============================================================ +# Instance helpers +# ============================================================ + +def get_headway_params_minutes(instance, tw_index): + """Return (ideal, min, max) headway in minutes for a time window.""" + for tw in instance['time_windows']: + if tw['index'] == tw_index: + return ( + tw['ideal_headway_seconds'] / 60.0, + tw['min_headway_seconds'] / 60.0, + tw['max_headway_seconds'] / 60.0, + ) + return None + + +def get_stopping_params(instance, terminal, tw_index): + """Return (min_dwell, max_dwell) in minutes for terminal at time window.""" + for entry in instance.get('stopping_times', {}).get(terminal, []): + if entry['time_window_index'] == tw_index: + return entry['min_stopping_time_minutes'], entry['max_stopping_time_minutes'] + return 0, 999999 + + +def get_pull_params(instance, terminal, tw_index): + """Return (pull_out, pull_in) times in minutes for terminal at time window.""" + for entry in instance.get('pull_in_out_times', {}).get(terminal, []): + if entry['time_window_index'] == tw_index: + return entry['pull_out_time_minutes'], entry['pull_in_time_minutes'] + return 0, 0 + + +def get_depot_min_dwell(instance, tw_index): + """Return minimum depot dwell time in minutes for time window.""" + for entry in instance.get('stopping_times', {}).get('O', []): + if entry['time_window_index'] == tw_index: + return entry['min_stopping_time_minutes'] + return 0 + + +def add_violation(violated_set, violations, violation_magnitudes, + constraint_idx, message, lhs, rhs, operator='eq'): + """Record a constraint violation with normalized magnitude.""" + if operator == 'geq': + # LHS >= RHS required; violation if LHS < RHS + violation_amount = rhs - lhs + elif operator == 'leq': + # LHS <= RHS required; violation if LHS > RHS + violation_amount = lhs - rhs + else: + # Equality + violation_amount = abs(lhs - rhs) + + if violation_amount <= TOL: + return # Not actually violated + + violated_set.add(constraint_idx) + violations.append(message) + 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), + }) + + +# ============================================================ +# Main feasibility check +# ============================================================ + +def check_feasibility(instance, solution): + violations = [] + violation_magnitudes = [] + violated_set = set() + + # --- Parse instance --- + all_trips = instance['potential_trips'] + trip_map = {t['id']: t for t in all_trips} + selected_ids = solution.get('selected_trips', []) + selected_set = set(selected_ids) + + dir_infos = instance['directions'] + dir_ids = [d['pattern_id'] for d in dir_infos] + + # Group potential trips by direction + trips_by_dir = {} + for t in all_trips: + trips_by_dir.setdefault(t['pattern_id'], []).append(t) + + # Selected trips per direction, sorted by main-stop arrival time + sel_by_dir = {} + for d in dir_ids: + sel_by_dir[d] = sorted( + [t for t in trips_by_dir.get(d, []) if t['id'] in selected_set], + key=lambda t: t['main_stop_arrival_time_minutes'] + ) + + # Determine initial / final trip sets + init_tws = instance.get('initial_trip_time_windows', {}) + final_tws = instance.get('final_trip_time_windows', {}) + + def is_initial(trip, direction): + if direction not in init_tws: + return True # all trips admissible if not specified + return trip['time_window_index'] == init_tws[direction] + + def is_final(trip, direction): + if direction not in final_tws: + return True + return trip['time_window_index'] == final_tws[direction] + + # ========================================================== + # Constraint 1 (eq 2): TT flow conservation + # For each direction d, the selected trips must form a + # valid unit-flow path source -> t1 -> ... -> tk -> sink + # in the TT compatibility graph G_d^TT. + # ========================================================== + for d in dir_ids: + sel = sel_by_dir[d] + + # (a) At least one trip must be selected per direction + # (source deficit = -1, sink deficit = +1; need a path) + if len(sel) == 0: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=1, + message=(f"Constraint 1 (TT flow conservation): No trips selected " + f"for direction {d}; cannot route unit flow from source to sink"), + lhs=0.0, rhs=-1.0, operator='eq' + ) + continue + + # (b) First selected trip must be an admissible initial trip + # (source arc must exist) + first_trip = sel[0] + if not is_initial(first_trip, d): + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=1, + message=(f"Constraint 1 (TT flow conservation): First selected trip " + f"{first_trip['id']} in direction {d} is in time window " + f"{first_trip['time_window_index']}, not in initial window " + f"{init_tws.get(d)}; no source arc exists"), + lhs=0.0, rhs=1.0, operator='eq' + ) + + # (c) Last selected trip must be an admissible final trip + # (sink arc must exist) + last_trip = sel[-1] + if not is_final(last_trip, d): + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=1, + message=(f"Constraint 1 (TT flow conservation): Last selected trip " + f"{last_trip['id']} in direction {d} is in time window " + f"{last_trip['time_window_index']}, not in final window " + f"{final_tws.get(d)}; no sink arc exists"), + lhs=0.0, rhs=1.0, operator='eq' + ) + + # (d) Consecutive selected trips must have feasible headway + # Arc (i, j) exists iff l_min <= a(j)-a(i) <= l_max + for idx in range(1, len(sel)): + ti = sel[idx - 1] + tj = sel[idx] + hw = (tj['main_stop_arrival_time_minutes'] + - ti['main_stop_arrival_time_minutes']) + hw_params = get_headway_params_minutes(instance, ti['time_window_index']) + if hw_params is None: + continue + _, l_min, l_max = hw_params + + if hw < l_min - TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=1, + message=(f"Constraint 1 (TT flow conservation): Direction {d}, " + f"headway between trip {ti['id']} and {tj['id']} is " + f"{hw:.4f} min, below minimum {l_min:.4f} min; " + f"no TT arc exists"), + lhs=hw, rhs=l_min, operator='geq' + ) + elif hw > l_max + TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=1, + message=(f"Constraint 1 (TT flow conservation): Direction {d}, " + f"headway between trip {ti['id']} and {tj['id']} is " + f"{hw:.4f} min, above maximum {l_max:.4f} min; " + f"no TT arc exists"), + lhs=hw, rhs=l_max, operator='leq' + ) + + # ========================================================== + # Constraint 2 (eq 3): y binary integrality + # y_{n,m}^d in {0, 1} + # Automatically satisfied when solution is a list of + # selected trip IDs. Check that IDs are valid. + # ========================================================== + for tid in selected_ids: + if tid not in trip_map: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=2, + message=(f"Constraint 2 (binary integrality): Selected trip ID {tid} " + f"does not exist in the set of potential trips"), + lhs=1.0, rhs=0.0, operator='eq' + ) + + # Check for duplicates (each trip arc can carry at most flow 1) + if len(selected_ids) != len(selected_set): + dup_counts = {} + for tid in selected_ids: + dup_counts[tid] = dup_counts.get(tid, 0) + 1 + for tid, cnt in dup_counts.items(): + if cnt > 1: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=2, + message=(f"Constraint 2 (binary integrality): Trip {tid} appears " + f"{cnt} times in selected_trips (must be 0 or 1)"), + lhs=float(cnt), rhs=1.0, operator='leq' + ) + + # ========================================================== + # Constraint 3 (eq 4): VS flow conservation (circulation) + # Constraint 4 (eq 5): VS capacity bounds 0 <= x <= u + # + # Per project rule, the checker rigorously verifies the original + # math-model VS variables `vs_flows` provided in the solution + # (paper Eq 4-5) rather than running a heuristic re-assignment. + # If `vs_flows` is missing, rigorous verification cannot be + # performed and constraint 3 is flagged as unverifiable. + # ========================================================== + import ast as _ast + from collections import defaultdict + valid_selected = [trip_map[tid] for tid in selected_ids + if tid in trip_map] + + def _parse_node(s): + s = s.strip() + if s.startswith('(') and s.endswith(')'): + try: + return _ast.literal_eval(s) + except (ValueError, SyntaxError): + return s + return s + + raw_flows = solution.get('vs_flows', None) + O_minus = 'VS_O_minus' + O_plus = 'VS_O_plus' + max_fleet = instance.get('max_fleet') + if max_fleet is None: + max_fleet = instance.get('objective_function', {}).get('max_fleet') + + parsed_arcs = None # populated below; reused for objective recomputation + + if not raw_flows: + # Required field missing — rigorous verification impossible. + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=3, + message=("Constraint 3 (VS flow conservation): solution is " + "missing the required `vs_flows` field; cannot " + "rigorously verify the vehicle schedule (paper " + "Eq 4-5) without it."), + lhs=0.0, rhs=1.0, operator='eq' + ) + else: + # Parse arcs and accumulate per-node in/out flows. + flow_in = defaultdict(float) + flow_out = defaultdict(float) + arcs_used = [] # (from_node, to_node, flow) + for key, val in raw_flows.items(): + try: + f_str, t_str = key.split('-->') + except ValueError: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=3, + message=f"Malformed vs_flows key {key!r} (expected 'from-->to')", + lhs=0.0, rhs=1.0, operator='eq' + ) + continue + try: + v = float(val) + except (TypeError, ValueError): + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=4, + message=f"Non-numeric vs_flows value for {key!r}: {val!r}", + lhs=0.0, rhs=1.0, operator='eq' + ) + continue + f_node = _parse_node(f_str) + t_node = _parse_node(t_str) + arcs_used.append((f_node, t_node, v)) + flow_in[t_node] += v + flow_out[f_node] += v + + parsed_arcs = arcs_used # share with the objective-recompute block + + # ---- Constraint 3 (Eq 4): flow conservation at each non-depot node ---- + all_nodes = set(flow_in) | set(flow_out) + for node in all_nodes: + if node == O_minus or node == O_plus: + continue # depot circulation closes via the return arc + in_v = flow_in[node] + out_v = flow_out[node] + if abs(in_v - out_v) > TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=3, + message=(f"Constraint 3 (VS flow conservation, Eq 4): " + f"node {node!r} has incoming flow {in_v:.6g} " + f"!= outgoing flow {out_v:.6g}"), + lhs=float(in_v), rhs=float(out_v), operator='eq' + ) + + # ---- Constraint 4 (Eq 5): per-arc capacity ---- + for f_node, t_node, v in arcs_used: + if v < -TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=4, + message=(f"Constraint 4 (VS capacity, Eq 5): arc " + f"{f_node!r}->{t_node!r} has negative flow {v:.6g}"), + lhs=float(v), rhs=0.0, operator='geq' + ) + if f_node == O_plus and t_node == O_minus: + # Return arc capacity = max_fleet + if max_fleet is not None and v > max_fleet + TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=4, + message=(f"Constraint 4 (VS capacity, Eq 5): return arc " + f"{O_plus}->{O_minus} flow {v:.6g} exceeds " + f"max_fleet {max_fleet}"), + lhs=float(v), rhs=float(max_fleet), operator='leq' + ) + else: + # All other arcs have unit capacity + if v > 1.0 + TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=4, + message=(f"Constraint 4 (VS capacity, Eq 5): arc " + f"{f_node!r}->{t_node!r} flow {v:.6g} > 1"), + lhs=float(v), rhs=1.0, operator='leq' + ) + + # ---- Selected-trip ↔ trip-arc flow consistency ---- + # Each selected trip i must have its trip arc (i, 'start') -> (i, 'end') + # carry exactly 1 unit of flow. + flow_pair = {(f, t): v for f, t, v in arcs_used} + for tid in selected_ids: + if tid not in trip_map: + continue + trip_arc_flow = flow_pair.get(((tid, 'start'), (tid, 'end')), 0.0) + if abs(trip_arc_flow - 1.0) > TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=4, + message=(f"Constraint 4 (VS trip-arc binding): selected " + f"trip {tid} has trip arc flow {trip_arc_flow:.6g} " + f"!= 1"), + lhs=float(trip_arc_flow), rhs=1.0, operator='eq' + ) + + # ---- Fleet-size bound (Eq 5 / max_fleet) ---- + if max_fleet is not None: + fleet_size = flow_out.get(O_minus, 0.0) + if fleet_size > max_fleet + TOL: + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=4, + message=(f"Constraint 4 (VS capacity, Eq 5): fleet size " + f"{fleet_size:.6g} (out of {O_minus}) exceeds " + f"max_fleet {max_fleet}"), + lhs=float(fleet_size), rhs=float(max_fleet), operator='leq' + ) + + # ========================================================== + # Constraint 5 (eq 6): Linking constraints + # sum_{(n,m) in B(i)} y_{n,m}^{d(i)} = x_{i^-, i^+} + # for all i in T. + # + # A selected trip must be reachable in the TT graph + # (have a valid incoming arc from source or a predecessor). + # If not, y_entering_i = 0 but x_trip_i = 1 → violation. + # ========================================================== + for d in dir_ids: + sel = sel_by_dir[d] + if len(sel) == 0: + continue + + for idx, tj in enumerate(sel): + # Check if tj has a valid TT predecessor among earlier selected + # trips, OR if tj is reachable from source (initial trip). + has_valid_incoming = False + + # Source arc: exists if tj is an initial trip + if is_initial(tj, d): + has_valid_incoming = True + + # Predecessor arcs: (ti, tj) exists if l_min <= hw <= l_max + if not has_valid_incoming: + for k in range(idx): + ti = sel[k] + hw = (tj['main_stop_arrival_time_minutes'] + - ti['main_stop_arrival_time_minutes']) + hw_params = get_headway_params_minutes( + instance, ti['time_window_index'] + ) + if hw_params is None: + continue + _, l_min, l_max = hw_params + if l_min - TOL <= hw <= l_max + TOL: + has_valid_incoming = True + break + + if not has_valid_incoming: + # y entering tj = 0 (no valid TT arc) but x trip = 1 + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=5, + message=(f"Constraint 5 (linking): Trip {tj['id']} in direction " + f"{d} is selected (x=1) but has no valid incoming TT " + f"arc (y=0); linking constraint violated"), + lhs=0.0, rhs=1.0, operator='eq' + ) + + # Also check: last selected trip must have a valid outgoing arc + # (to sink if final, or to a successor) + last = sel[-1] + if not is_final(last, d): + # Check if there's a valid successor among selected trips + # that leads eventually to a final trip + has_valid_outgoing = False + # Since last is the last selected trip by arrival time, + # it cannot have a successor. It must be final. + add_violation( + violated_set, violations, violation_magnitudes, + constraint_idx=5, + message=(f"Constraint 5 (linking): Last selected trip {last['id']} " + f"in direction {d} is not a final trip and has no " + f"successor; flow cannot reach sink"), + lhs=0.0, rhs=1.0, operator='eq' + ) + + # ========================================================== + # Constraint 6 (eq 1): Objective-value consistency (Tier C anti-exploit) + # reported_obj == alpha * VS_cost + sum_d TT_cost_d + # + # Full recompute is possible because the solution carries every + # variable the objective depends on: + # - x_{u,v} appears in `vs_flows` (arc-by-arc flow values) + # - y_{d,u,v} is implicit in the sorted selected_trips chain + # per direction (the TT path source -> t1 -> ... -> tk -> sink, + # which is the path the constraint checks above validate) + # + # Arc costs come directly from the math model: + # VS trip arc (i^-, i^+) cost 0 + # VS in-line arc (i^+, j^-) cost = st(j) - et(i) - min_dwell_en(i) + # VS out-line arc (i^+, j^-) cost = pullin_en(i) + pullout_sn(j) + # VS start arc (O^-, i^-) cost = pullout_sn(i) + # VS end arc (i^+, O^+) cost = pullin_en(i) + # VS return arc (O^+, O^-) cost = M (fleet-size proxy) + # TT trip-pair arc (i, j) cost = (a(j) - a(i) - ideal_hw)^2 (quadratic) + # TT source/sink arcs cost 0 + # + # We skip this check (silent, no extra violation) when the data + # needed to recompute is unavailable: missing `vs_flows` + # (constraint 3 already fires above) or missing/non-numeric + # `objective_value`. In every other case we recompute exactly + # and reject if the reported value disagrees by more than the + # 0.1% relative + 1e-3 absolute tolerance. + # ========================================================== + reported_obj_raw = solution.get('objective_value') + reported_obj = None + if reported_obj_raw is not None: + try: + reported_obj = float(reported_obj_raw) + except (TypeError, ValueError): + reported_obj = None + + if parsed_arcs is not None and reported_obj is not None: + alpha = instance.get('objective_function', {}).get('alpha', 1.0) + try: + alpha = float(alpha) + except (TypeError, ValueError): + alpha = 1.0 + M_param = instance.get('M') + if M_param is None: + M_param = instance.get('objective_function', {}).get('M') + if M_param is None: + M_param = 10000 # default used by gurobi_code.py:148 + try: + M_param = float(M_param) + except (TypeError, ValueError): + M_param = 10000.0 + + # ---- VS cost from parsed_arcs ---- + vs_cost = 0.0 + for f_node, t_node, v in parsed_arcs: + try: + cost = _vs_arc_cost(instance, trip_map, f_node, t_node, + O_minus, O_plus, M_param) + except Exception: + cost = None + if cost is None: + # Unknown arc shape — skip cost contribution for it. + continue + vs_cost += cost * v + + # ---- TT cost from the sorted-selected-trip chain ---- + # Per the constraint checks above, the chain source -> t1 -> ... -> tk + # -> sink IS the TT path, so its cost is the sum of (i, j) arc penalties + # for consecutive (ti, tj). Source/sink arcs have cost 0. + tt_cost = 0.0 + for d in dir_ids: + sel = sel_by_dir[d] + for idx in range(1, len(sel)): + ti = sel[idx - 1] + tj = sel[idx] + hw_params = get_headway_params_minutes( + instance, ti['time_window_index'] + ) + if hw_params is None: + continue + ideal, _, _ = hw_params + actual = (tj['main_stop_arrival_time_minutes'] + - ti['main_stop_arrival_time_minutes']) + tt_cost += float((actual - ideal) ** 2) + + recomputed_obj = alpha * vs_cost + tt_cost + abs_diff = abs(reported_obj - recomputed_obj) + tol_obj = max(1e-3, 1e-3 * abs(recomputed_obj)) + + if abs_diff > tol_obj: + # Inline recording (not via add_violation) so we can apply a + # 0.1% relative tolerance rather than the helper's hard 1e-5 + # absolute floor. + violated_set.add(6) + msg = (f"Constraint 6 (objective consistency, Eq 1): reported " + f"objective_value={reported_obj!r} differs from " + f"recomputed alpha*VS_cost + TT_cost = " + f"{alpha}*{vs_cost} + {tt_cost} = {recomputed_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol_obj:.6g})") + violations.append(msg) + normalizer = max(abs(recomputed_obj), EPS) + violation_magnitudes.append({ + 'constraint': 6, + 'lhs': float(reported_obj), + 'rhs': float(recomputed_obj), + 'raw_excess': float(abs_diff), + 'normalizer': float(normalizer), + 'ratio': float(abs_diff / normalizer), + }) + + # ========================================================== + # Build result + # ========================================================== + feasible = len(violated_set) == 0 + # Deduplicate violated_constraints and aggregate violation messages + unique_violated = sorted(violated_set) + # Aggregate violation messages per constraint index + aggregated_msgs = [] + seen_msgs = set() + for msg in violations: + if msg not in seen_msgs: + aggregated_msgs.append(msg) + seen_msgs.add(msg) + + return { + 'feasible': feasible, + 'violated_constraints': unique_violated, + 'violations': aggregated_msgs, + 'violation_magnitudes': violation_magnitudes if not feasible else [], + } + + +# ============================================================ +# VS arc-cost helper for objective recomputation +# ============================================================ + +def _vs_arc_cost(instance, trip_map, f_node, t_node, + O_minus, O_plus, M_param): + """Return the math-model arc cost for a VS arc, or None if the + arc shape is unrecognized (in which case the cost is omitted + from the recomputed objective; the constraint check fires the + appropriate violation separately if the arc is illegal). + """ + # Return arc (O^+ -> O^-) + if f_node == O_plus and t_node == O_minus: + return float(M_param) + # Start arc (O^- -> (i, 'start')) + if f_node == O_minus and isinstance(t_node, tuple) \ + and len(t_node) == 2 and t_node[1] == 'start': + tid = t_node[0] + tr = trip_map.get(tid) + if tr is None: + return None + _, _, pullout, _ = _terminal_params( + instance, tr['start_terminal'], tr['time_window_index'] + ) + return float(pullout) + # End arc ((i, 'end') -> O^+) + if t_node == O_plus and isinstance(f_node, tuple) \ + and len(f_node) == 2 and f_node[1] == 'end': + tid = f_node[0] + tr = trip_map.get(tid) + if tr is None: + return None + _, _, _, pullin = _terminal_params( + instance, tr['end_terminal'], tr['time_window_index'] + ) + return float(pullin) + # Trip arc ((i, 'start') -> (i, 'end')) + if (isinstance(f_node, tuple) and isinstance(t_node, tuple) + and len(f_node) == 2 and len(t_node) == 2 + and f_node[1] == 'start' and t_node[1] == 'end' + and f_node[0] == t_node[0]): + return 0.0 + # In-line / out-line compatibility arcs ((i, 'end') -> (j, 'start')) + if (isinstance(f_node, tuple) and isinstance(t_node, tuple) + and len(f_node) == 2 and len(t_node) == 2 + and f_node[1] == 'end' and t_node[1] == 'start'): + i_tid, j_tid = f_node[0], t_node[0] + ti = trip_map.get(i_tid) + tj = trip_map.get(j_tid) + if ti is None or tj is None: + return None + en_i = ti['end_terminal'] + sn_j = tj['start_terminal'] + wait = tj['departure_time_minutes'] - ti['arrival_time_minutes'] + if en_i == sn_j: + # In-line compatibility: cost = wait - min_dwell_en(i) + min_dwell, _, _, _ = _terminal_params( + instance, en_i, ti['time_window_index'] + ) + return float(wait - min_dwell) + # Out-line compatibility: cost = pullin_en(i) + pullout_sn(j) + _, _, _, pullin_en_i = _terminal_params( + instance, en_i, ti['time_window_index'] + ) + _, _, pullout_sn_j, _ = _terminal_params( + instance, sn_j, tj['time_window_index'] + ) + return float(pullin_en_i + pullout_sn_j) + return None + + +def _terminal_params(instance, terminal, tw_index): + """Return (min_dwell, max_dwell, pull_out, pull_in) for a terminal + in a given time window, matching gurobi_code.build_vs_graph_pure's + parameter lookup. Missing entries default to zero (consistent with + gurobi_code's fallback).""" + min_dwell, max_dwell = 0, 9999 + for entry in instance.get('stopping_times', {}).get(terminal, []): + if entry['time_window_index'] == tw_index: + min_dwell = entry['min_stopping_time_minutes'] + max_dwell = entry['max_stopping_time_minutes'] + break + pull_out, pull_in = 0, 0 + for entry in instance.get('pull_in_out_times', {}).get(terminal, []): + if entry['time_window_index'] == tw_index: + pull_out = entry['pull_out_time_minutes'] + pull_in = entry['pull_in_time_minutes'] + break + return min_dwell, max_dwell, pull_out, pull_in + + +# ============================================================ +# Entry point +# ============================================================ + +def main(): + parser = argparse.ArgumentParser( + description='Feasibility checker for ITTVS solutions (Carosi et al. 2019)' + ) + 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() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result['feasible'] else "INFEASIBLE" + print(f"Feasibility: {status}") + if not result['feasible']: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result['violations']: + print(f" - {v}") + + +if __name__ == '__main__': + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/carosi2019/gurobi_code.py b/tasks/carosi2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..895f88dfdfb89677f8e8784b3f7164b99c8e7527 --- /dev/null +++ b/tasks/carosi2019/gurobi_code.py @@ -0,0 +1,614 @@ +""" +Gurobi MILP implementation of the ITTVS (Integrated Timetabling and Vehicle Scheduling) model. + +Source: Carosi, Frangioni, Galli, Girardi, Vallese (2019) + "A matheuristic for integrated timetabling and vehicle scheduling" + Transportation Research Part B 127 (2019) 99-124 + +Mathematical model (1)-(6) as described in Section 4 of the paper. + +Uses the "pure" VS compatibility graph (Section 4.2.1) for simplicity. +""" + +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# ============================================================ +# INSTANCE LOADING +# ============================================================ + +def load_instance(path): + with open(path) as f: + raw = json.load(f) + return convert_instance(raw) + + +def convert_instance(raw): + """Convert raw instance JSON to the format expected by the solver. + + Raw instance keys: + potential_trips[i]: id, pattern_id, direction, start_terminal, end_terminal, + departure_time_minutes, arrival_time_minutes, time_window_index + time_windows[i]: index, ideal_headway_seconds, min_headway_seconds, max_headway_seconds + stopping_times[terminal][i]: time_window_index, min_stopping_time_minutes, max_stopping_time_minutes + pull_in_out_times[terminal][i]: time_window_index, pull_out_time_minutes, pull_in_time_minutes + directions[i]: pattern_id (used as direction identifier) + objective_function: alpha + + Solver expects: + trips[i]: id, direction (=pattern_id), a (=departure minutes), st (=departure), + et (=arrival), sn (=start_terminal), en (=end_terminal), time_window (=tw index) + time_windows[i]: id (=index), headway_params[direction]->{ideal,min,max} (in minutes), + terminal_params[terminal]->{min_dwell,max_dwell,pullout_time,pullin_time}, + depot_params->{min_dwell} + directions: list of pattern_id strings + alpha: from objective_function + """ + # Build direction list (pattern_id strings) + directions = [d['pattern_id'] for d in raw['directions']] + + # Build stopping_times and pull_in_out lookup: (terminal, tw_index) -> values + stop_lookup = {} # (terminal, tw_index) -> (min_stop, max_stop) + for terminal, entries in raw['stopping_times'].items(): + for entry in entries: + stop_lookup[(terminal, entry['time_window_index'])] = ( + entry['min_stopping_time_minutes'], + entry['max_stopping_time_minutes'], + ) + + pull_lookup = {} # (terminal, tw_index) -> (pull_out, pull_in) + for terminal, entries in raw['pull_in_out_times'].items(): + for entry in entries: + pull_lookup[(terminal, entry['time_window_index'])] = ( + entry['pull_out_time_minutes'], + entry['pull_in_time_minutes'], + ) + + # Depot stopping times + depot_stop_lookup = {} # tw_index -> min_stop + for entry in raw['stopping_times'].get('O', []): + depot_stop_lookup[entry['time_window_index']] = entry['min_stopping_time_minutes'] + + # All terminals (exclude depot 'O') + terminals = [d['start_terminal'] for d in raw['directions']] + terminals += [d['end_terminal'] for d in raw['directions']] + terminals = list(set(t for t in terminals if t != 'O')) + + # Build converted time_windows + time_windows = [] + for tw in raw['time_windows']: + idx = tw['index'] + # Headway: same for all directions (seconds -> minutes) + hw_ideal = tw['ideal_headway_seconds'] / 60.0 + hw_min = tw['min_headway_seconds'] / 60.0 + hw_max = tw['max_headway_seconds'] / 60.0 + headway_params = {d: {'ideal': hw_ideal, 'min': hw_min, 'max': hw_max} for d in directions} + + # Terminal params + terminal_params = {} + for t in terminals: + min_dwell, max_dwell = stop_lookup.get((t, idx), (0, 9999)) + pullout, pullin = pull_lookup.get((t, idx), (0, 0)) + terminal_params[t] = { + 'min_dwell': min_dwell, + 'max_dwell': max_dwell, + 'pullout_time': pullout, + 'pullin_time': pullin, + } + + depot_params = {'min_dwell': depot_stop_lookup.get(idx, 0)} + + time_windows.append({ + 'id': idx, + 'headway_params': headway_params, + 'terminal_params': terminal_params, + 'depot_params': depot_params, + }) + + # Build trips from potential_trips + trips = [] + for pt in raw['potential_trips']: + trips.append({ + 'id': pt['id'], + 'direction': pt['pattern_id'], + 'a': pt['main_stop_arrival_time_minutes'], # arrival at main stop (for headway calc per paper) + 'st': pt['departure_time_minutes'], # start time + 'et': pt['arrival_time_minutes'], # end time + 'sn': pt['start_terminal'], # start node (terminal) + 'en': pt['end_terminal'], # end node (terminal) + 'time_window': pt['time_window_index'], + }) + + # Determine initial/final trips per direction based on time window indices + initial_trips = {} + final_trips = {} + init_tw = raw.get('initial_trip_time_windows', {}) + final_tw = raw.get('final_trip_time_windows', {}) + for d in directions: + if d in init_tw: + initial_trips[d] = [t['id'] for t in trips if t['direction'] == d and t['time_window'] == init_tw[d]] + if d in final_tw: + final_trips[d] = [t['id'] for t in trips if t['direction'] == d and t['time_window'] == final_tw[d]] + + alpha = raw.get('objective_function', {}).get('alpha', 1.0) + M = raw.get('M', 10000) + max_fleet = raw.get('max_fleet', None) + + return { + 'trips': trips, + 'directions': directions, + 'time_windows': time_windows, + 'initial_trips': initial_trips, + 'final_trips': final_trips, + 'alpha': alpha, + 'M': M, + 'max_fleet': max_fleet, + } + + +# ============================================================ +# PARAMETER HELPERS +# ============================================================ + +def get_hw_params(instance, direction, tw_id): + """Return (ideal, min, max) headway for given direction and time window.""" + for tw in instance['time_windows']: + if tw['id'] == tw_id: + p = tw['headway_params'][direction] + return p['ideal'], p['min'], p['max'] + raise ValueError(f"Time window {tw_id} not found") + + +def get_terminal_params(instance, terminal, tw_id): + """Return (min_dwell, max_dwell, pullout_time, pullin_time) for terminal and time window.""" + for tw in instance['time_windows']: + if tw['id'] == tw_id: + p = tw['terminal_params'][terminal] + return p['min_dwell'], p['max_dwell'], p['pullout_time'], p['pullin_time'] + raise ValueError(f"Time window {tw_id} not found") + + +def get_depot_min_dwell(instance, tw_id): + """Return minimum depot dwell time for time window.""" + for tw in instance['time_windows']: + if tw['id'] == tw_id: + return tw['depot_params'].get('min_dwell', 0) + return 0 + + +# ============================================================ +# PENALTY FUNCTION +# ============================================================ + +def headway_penalty(actual_hw, ideal_hw): + """ + Quadratic penalty for headway deviation from ideal. + + NOT SPECIFIED IN PAPER: exact closed-form formula of the quadratic penalty. + INFERRED ASSUMPTION: penalty = (actual_hw - ideal_hw)^2 (squared deviation in minutes^2). + Properties: zero if actual_hw == ideal_hw; positive and nondecreasing in |actual_hw - ideal_hw|. + """ + return float((actual_hw - ideal_hw) ** 2) + + +# ============================================================ +# TT GRAPH CONSTRUCTION (Section 4.1) +# ============================================================ + +def build_tt_graph(direction, trips, instance): + """ + Build TT compatibility graph G_d^TT for direction d. + + Nodes: N_d^TT = T_d ∪ {source_d, sink_d} + Arcs: + - (source_d, i) for i in T_d^ini: cost 0 + - (i, j) for i,j in T_d s.t. l_d^{h(i)} <= a(j)-a(i) <= l_bar_d^{h(i)}: cost = penalty + - (i, sink_d) for i in T_d^fin: cost 0 + + Returns: + source, sink : node identifiers for source/sink + nodes : list of all nodes + arcs : dict (u,v) -> cost + backward_star: dict trip_id -> list of arcs entering that node + """ + source = ('source', direction) + sink = ('sink', direction) + + initial_ids = set( + instance.get('initial_trips', {}).get(direction, [t['id'] for t in trips]) + ) + final_ids = set( + instance.get('final_trips', {}).get(direction, [t['id'] for t in trips]) + ) + + arcs = {} # (u, v) -> cost + + # Source arcs to initial trips (cost 0) + for t in trips: + if t['id'] in initial_ids: + arcs[(source, t['id'])] = 0.0 + + # Trip-to-trip arcs: arc (i, j) iff l_d^{h(i)} <= a(j)-a(i) <= l_bar_d^{h(i)} + # Arc cost = penalty(a(j)-a(i), l_hat_d^{h(i)}) + sorted_trips = sorted(trips, key=lambda x: x['a']) + for idx_i, ti in enumerate(sorted_trips): + l_hat, l_min, l_max = get_hw_params(instance, direction, ti['time_window']) + for idx_j in range(idx_i + 1, len(sorted_trips)): + tj = sorted_trips[idx_j] + hw = tj['a'] - ti['a'] + if hw > l_max: + break # sorted by a; all further trips exceed max headway + if hw >= l_min: + cost = headway_penalty(hw, l_hat) + arcs[(ti['id'], tj['id'])] = cost + + # Final arcs from final trips to sink (cost 0) + for t in trips: + if t['id'] in final_ids: + arcs[(t['id'], sink)] = 0.0 + + # Backward star B(i): set of arcs entering trip node i + # Used in linking constraint (6) + backward_star = {t['id']: [] for t in trips} + for (u, v), cost in arcs.items(): + if v in backward_star: + backward_star[v].append((u, v)) + + all_nodes = [source, sink] + [t['id'] for t in trips] + return source, sink, all_nodes, arcs, backward_star + + +# ============================================================ +# VS GRAPH CONSTRUCTION — "Pure" version (Section 4.2.1) +# ============================================================ + +def build_vs_graph_pure(trips, instance): + """ + Build the "pure" VS compatibility graph G^VS (Section 4.2.1). + + Nodes: N^VS = {(i,'start'), (i,'end') : i in T} ∪ {O^-, O^+} + + Arc types: + 1. Trip arcs (i^-, i^+): cost 0, capacity 1 + 2. In-line compatibility arcs (i^+, j^-) where en(i)=sn(j), + feasible dwell: delta_n^{h(i)} <= st(j)-et(i) <= delta_bar_n^{h(i)} + cost = st(j)-et(i)-delta_n^{h(i)} (extra waiting), capacity 1 + 3. Out-line compatibility arcs (i^+, j^-) where en(i)!=sn(j), + feasible: st(j)-et(i) >= t_{en(i),-}^{h(i)} + delta_O^{h(i)} + t_{sn(j),+}^{h(j)} + cost = t_{en(i),-}^{h(i)} + t_{sn(j),+}^{h(j)}, capacity 1 + 4. Start arcs (O^-, i^-): cost = t_{sn(i),+}^{h(i)}, capacity 1 + 5. End arcs (i^+, O^+): cost = t_{en(i),-}^{h(i)}, capacity 1 + 6. Return arc (O^+, O^-): cost = M (fleet size proxy), capacity = max_fleet + + Returns: + O_minus, O_plus : node identifiers + all_nodes : set of all nodes + arcs : dict (u,v) -> (cost, capacity) + """ + O_minus = 'VS_O_minus' + O_plus = 'VS_O_plus' + + M = instance.get('M', 10000) + max_fleet = instance.get('max_fleet', None) + cap_K = max_fleet if (max_fleet is not None and max_fleet > 0) else 100000 + + alpha = instance.get('alpha', 1.0) + + arcs = {} # (u, v) -> (cost, capacity) + + for t in trips: + i = t['id'] + i_start = (i, 'start') # i^- + i_end = (i, 'end') # i^+ + tw_id = t['time_window'] + sn, en = t['sn'], t['en'] + + _, _, pullout_sn, _ = get_terminal_params(instance, sn, tw_id) + _, _, _, pullin_en = get_terminal_params(instance, en, tw_id) + + # 1. Trip arc (i^-, i^+): cost 0, capacity 1 + arcs[(i_start, i_end)] = (0.0, 1) + + # 4. Start arc (O^-, i^-): cost = t_{sn(i),+}^{h(i)}, capacity 1 + arcs[(O_minus, i_start)] = (float(pullout_sn), 1) + + # 5. End arc (i^+, O^+): cost = t_{en(i),-}^{h(i)}, capacity 1 + arcs[(i_end, O_plus)] = (float(pullin_en), 1) + + # 2 & 3. Compatibility arcs between trips + # Optimized: sort trips by start time and use early termination. + # Pre-compute terminal params to avoid repeated lookups. + tp_cache = {} + def get_tp_cached(terminal, tw_id): + key = (terminal, tw_id) + if key not in tp_cache: + tp_cache[key] = get_terminal_params(instance, terminal, tw_id) + return tp_cache[key] + + dd_cache = {} + def get_dd_cached(tw_id): + if tw_id not in dd_cache: + dd_cache[tw_id] = get_depot_min_dwell(instance, tw_id) + return dd_cache[tw_id] + + sorted_by_st = sorted(trips, key=lambda t: t['st']) + + for idx_i, ti in enumerate(sorted_by_st): + i = ti['id'] + tw_i = ti['time_window'] + en_i = ti['en'] + _, _, _, pullin_en_i = get_tp_cached(en_i, tw_i) + min_dwell_i, max_dwell_i, _, _ = get_tp_cached(en_i, tw_i) + depot_dwell_i = get_dd_cached(tw_i) + + # Only consider trips j where st(j) > et(i) (j starts after i ends) + # and wait = st(j) - et(i) is within a reasonable window. + # Max useful wait: max_dwell at any terminal, or large deadhead time + max_useful_wait = max(max_dwell_i, pullin_en_i + depot_dwell_i + 60) + + for idx_j in range(idx_i + 1, len(sorted_by_st)): + tj = sorted_by_st[idx_j] + wait = tj['st'] - ti['et'] + + if wait < 0: + continue # j starts before i ends + if wait > max_useful_wait: + break # sorted by st; all further trips have even larger wait + + j = tj['id'] + tw_j = tj['time_window'] + sn_j = tj['sn'] + _, _, pullout_sn_j, _ = get_tp_cached(sn_j, tw_j) + + if en_i == sn_j: + # 2. In-line compatibility: en(i) = sn(j) + # Condition: delta_{en(i)}^{h(i)} <= st(j)-et(i) <= delta_bar_{en(i)}^{h(i)} + if min_dwell_i <= wait <= max_dwell_i: + extra_wait = float(wait - min_dwell_i) + arc_key = ((i, 'end'), (j, 'start')) + arcs[arc_key] = (extra_wait, 1) + else: + # 3. Out-line compatibility: en(i) != sn(j) + # Condition: st(j)-et(i) >= t_{en(i),-}^{h(i)} + delta_O^{h(i)} + t_{sn(j),+}^{h(j)} + min_time = pullin_en_i + depot_dwell_i + pullout_sn_j + if wait >= min_time: + cost = float(pullin_en_i + pullout_sn_j) + arc_key = ((i, 'end'), (j, 'start')) + arcs[arc_key] = (cost, 1) + + # 6. Return arc (O^+, O^-): cost = M (fleet size proxy), capacity = K + arcs[(O_plus, O_minus)] = (float(M), cap_K) + + all_nodes = set() + for (u, v) in arcs: + all_nodes.add(u) + all_nodes.add(v) + + return O_minus, O_plus, all_nodes, arcs + + +# ============================================================ +# MAIN SOLVER +# ============================================================ + +def solve_ittvs(instance, time_limit): + """ + Solve the ITTVS MILP (1)-(6) using Gurobi. + + Decision variables: + y_{d,u,v} in {0,1}: TT arc selection (constraint 3) + x_{u,v} >= 0 (continuous): VS arc flow (automatically integer at optimum + due to total unimodularity, as noted in paper) + + Returns solution dict with objective_value and other info. + """ + trips = instance['trips'] + directions = instance['directions'] + trips_by_dir = {d: [t for t in trips if t['direction'] == d] for d in directions} + alpha = instance.get('alpha', 1.0) + + # ---- Build graphs ---- + tt_data = {} + for d in directions: + src, snk, nodes, arcs, bstar = build_tt_graph(d, trips_by_dir[d], instance) + tt_data[d] = { + 'source': src, 'sink': snk, + 'nodes': nodes, 'arcs': arcs, 'backward_star': bstar + } + + vs_ominus, vs_oplus, vs_nodes, vs_arcs = build_vs_graph_pure(trips, instance) + + # ---- Create Gurobi model ---- + model = gp.Model("ITTVS") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("MIPFocus", 1) # CPXPARAM_Emphasis_MIP=1 analogue (from paper Section 7.2) + model.setParam("RINS", 0) # CPXPARAM_MIP_Strategy_LBHeur=1 analogue + + # ---- Decision variables ---- + + # y_{d,u,v} in {0,1} for TT arcs (constraint 3) + y = {} + for d in directions: + for (u, v) in tt_data[d]['arcs']: + y[(d, u, v)] = model.addVar( + vtype=GRB.BINARY, name=f"y_{d}_{u}_{v}" + ) + + # x_{u,v} >= 0 continuous for VS arcs (constraint 5) + # Note: x need not be declared integer due to total unimodularity (paper Note 1) + x = {} + for (u, v), (cost, cap) in vs_arcs.items(): + x[(u, v)] = model.addVar( + lb=0.0, ub=float(cap), vtype=GRB.CONTINUOUS, name=f"x_{u}_{v}" + ) + + model.update() + + # ---- Objective (1): min alpha*c*x + sum_d c^d*y^d ---- + obj = gp.LinExpr() + for (u, v), (cost, cap) in vs_arcs.items(): + obj += alpha * cost * x[(u, v)] + for d in directions: + for (u, v), cost in tt_data[d]['arcs'].items(): + obj += cost * y[(d, u, v)] + model.setObjective(obj, GRB.MINIMIZE) + + # ---- Constraint (2): TT flow conservation ---- + # sum_{(m,n) in A_d^TT} y_{m,n}^d - sum_{(n,m) in A_d^TT} y_{n,m}^d = b_n^d + # b_{source} = -1, b_{sink} = +1, b_{trip} = 0 + for d in directions: + src = tt_data[d]['source'] + snk = tt_data[d]['sink'] + arcs_d = tt_data[d]['arcs'] + nodes_d = tt_data[d]['nodes'] + + # Pre-build adjacency lists for efficiency + tt_in_arcs = {} # node -> list of (u, v) + tt_out_arcs = {} # node -> list of (u, v) + for node in nodes_d: + tt_in_arcs[node] = [] + tt_out_arcs[node] = [] + for (u, v) in arcs_d: + if v in tt_in_arcs: + tt_in_arcs[v].append((u, v)) + if u in tt_out_arcs: + tt_out_arcs[u].append((u, v)) + + for node in nodes_d: + b = -1 if node == src else (1 if node == snk else 0) + in_flow = gp.quicksum(y[(d, u, v)] for (u, v) in tt_in_arcs[node]) + out_flow = gp.quicksum(y[(d, u, v)] for (u, v) in tt_out_arcs[node]) + model.addConstr(in_flow - out_flow == b, name=f"tt_flow_{d}_{node}") + + # ---- Constraint (4): VS flow conservation (circulation) ---- + # sum_{(m,n) in A^VS} x_{m,n} - sum_{(n,m) in A^VS} x_{n,m} = 0 for all n + # Pre-build adjacency lists for VS graph + vs_in_arcs = {node: [] for node in vs_nodes} + vs_out_arcs = {node: [] for node in vs_nodes} + for (u, v) in vs_arcs: + if v in vs_in_arcs: + vs_in_arcs[v].append((u, v)) + if u in vs_out_arcs: + vs_out_arcs[u].append((u, v)) + + for node in vs_nodes: + in_flow = gp.quicksum(x[(u, v)] for (u, v) in vs_in_arcs[node]) + out_flow = gp.quicksum(x[(u, v)] for (u, v) in vs_out_arcs[node]) + model.addConstr(in_flow - out_flow == 0, name=f"vs_flow_{node}") + + # ---- Constraint (6): Linking constraints ---- + # sum_{(n,m) in B(i)} y_{n,m}^{d(i)} = x_{i^-, i^+} for all i in T + for trip in trips: + i = trip['id'] + d = trip['direction'] + bstar = tt_data[d]['backward_star'].get(i, []) + + tt_in = gp.LinExpr() + for (u, v) in bstar: + tt_in += y[(d, u, v)] + + vs_trip_key = ((i, 'start'), (i, 'end')) + if vs_trip_key in x: + model.addConstr(tt_in == x[vs_trip_key], name=f"link_{i}") + + # ---- Solve ---- + model.optimize() + + # ---- Extract solution ---- + solution = {} + + if model.SolCount > 0: + solution['objective_value'] = float(model.ObjVal) + solution['status'] = 'optimal' if model.Status == GRB.OPTIMAL else 'feasible_time_limit' + solution['mip_gap'] = float(model.MIPGap) if model.SolCount > 0 else None + + # Selected trips (those whose trip arc carries flow) + selected_trips = [] + for trip in trips: + key = ((trip['id'], 'start'), (trip['id'], 'end')) + if key in x and x[key].X > 0.5: + selected_trips.append(trip['id']) + solution['selected_trips'] = selected_trips + + # Number of vehicles (flow on return arc) + ret_key = (vs_oplus, vs_ominus) + if ret_key in x: + solution['num_vehicles'] = int(round(x[ret_key].X)) + + # TT: arcs used per direction (for timetable reconstruction) + tt_arcs_used = {} + for d in directions: + tt_arcs_used[d] = [] + for (u, v) in tt_data[d]['arcs']: + if y[(d, u, v)].X > 0.5: + tt_arcs_used[d].append([str(u), str(v)]) + solution['tt_arcs_used'] = tt_arcs_used + + # VS: arc flows (for vehicle schedule reconstruction) + vs_flows = {} + for (u, v), (cost, cap) in vs_arcs.items(): + val = x[(u, v)].X + if val > 1e-4: + vs_flows[f"{u}-->{v}"] = round(val, 4) + solution['vs_flows'] = vs_flows + + else: + solution['objective_value'] = float('inf') + solution['status'] = 'no_feasible_solution' + solution['selected_trips'] = [] + solution['num_vehicles'] = None + + return solution + + +# ============================================================ +# ENTRY POINT +# ============================================================ + +def main(): + parser = argparse.ArgumentParser( + description='Gurobi MILP solver for ITTVS (Carosi et al. 2019)' + ) + parser.add_argument('--instance_path', required=True, + help='Path to instance JSON file') + parser.add_argument('--solution_path', required=True, + help='Path where solution JSON will be written') + parser.add_argument('--time_limit', type=int, default=3600, + help='Maximum solver runtime in seconds') + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + solution = solve_ittvs(instance, args.time_limit) + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2, default=str) + + print(f"Solution written to: {args.solution_path}") + print(f"Status: {solution.get('status')}") + print(f"Objective value: {solution.get('objective_value')}") + print(f"Selected trips: {solution.get('selected_trips')}") + print(f"Num vehicles: {solution.get('num_vehicles')}") + + +if __name__ == '__main__': + main() diff --git a/tasks/carosi2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/carosi2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carosi2019/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/carosi2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/carosi2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carosi2019/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/carosi2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/carosi2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carosi2019/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/carosi2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/carosi2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carosi2019/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/carosi2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/carosi2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carosi2019/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/carosi2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/carosi2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carosi2019/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/carosi2019/gurobi_solution/large_solution_1.json b/tasks/carosi2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..53d7f744300da07d7593229fc3ef255205128def --- /dev/null +++ b/tasks/carosi2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d2b37491e9c14fb6bfc19d9148bd869851dd88f24bf84ac15a2c628dc397873 +size 67171 diff --git a/tasks/carosi2019/gurobi_solution/large_solution_2.json b/tasks/carosi2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..0dd91ab7d131df7340f14d8097f699d26ae9a120 --- /dev/null +++ b/tasks/carosi2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e97bc1e7224b35843638c552ff37150dc59050108ce5f26a4701591142368bb3 +size 54357 diff --git a/tasks/carosi2019/gurobi_solution/large_solution_3.json b/tasks/carosi2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b2ae17a1fcde6e87303b1caa921ef9bf574e8497 --- /dev/null +++ b/tasks/carosi2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8bdf2e1437f77176637f09c058b0754103aba01957c9c692925da38c447670d +size 72863 diff --git a/tasks/carosi2019/gurobi_solution/large_solution_4.json b/tasks/carosi2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..81a1697cf8517642557b882c70657dc57b594f4e --- /dev/null +++ b/tasks/carosi2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:179ab0cb75ea21b73b3adcf0a9be2e74b0714d40e38dc016ae2da84d32a276e2 +size 66195 diff --git a/tasks/carosi2019/gurobi_solution/large_solution_5.json b/tasks/carosi2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..590928cdd5075d44e5884da384f971ae8d32d5ab --- /dev/null +++ b/tasks/carosi2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c5a02385e266f76c901e36dfae13a8d5d9578ec19d4883c362a3998cc070a00 +size 75699 diff --git a/tasks/carosi2019/gurobi_solution/tiny_solution.json b/tasks/carosi2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2790f8260870d713fbd6efab32a4859cf81814f1 --- /dev/null +++ b/tasks/carosi2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebbc981958af9212882927640fe3aeea3ce8344613bb245c5664c53bf12c6efb +size 3773 diff --git a/tasks/carosi2019/gurobi_solution_log/large_log_1.jsonl b/tasks/carosi2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..62a761eb4bcde950ee6f07b28a4a99e97474c66a --- /dev/null +++ b/tasks/carosi2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d730a19007264da3bd641762215b52e80f1abc4c4e33d2647facd3a3d27d7b0f +size 482 diff --git a/tasks/carosi2019/gurobi_solution_log/large_log_2.jsonl b/tasks/carosi2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1cbc3913af6040ab3c9e0376d3d23c3037d0ebb9 --- /dev/null +++ b/tasks/carosi2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:91ff7cf32fa37448463165d0f8236ba5675af2343fddefe22190b961d0f98fe8 +size 426 diff --git a/tasks/carosi2019/gurobi_solution_log/large_log_3.jsonl b/tasks/carosi2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4241614d0d2288267a2e93118002411299f2470d --- /dev/null +++ b/tasks/carosi2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fc7e9d27bfa80d50dbd04134b47448630039cce98034d8466b74288b90afa41 +size 862 diff --git a/tasks/carosi2019/gurobi_solution_log/large_log_4.jsonl b/tasks/carosi2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b3e66ddd78835ff78df76ab850b1da4e6e868385 --- /dev/null +++ b/tasks/carosi2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04cfd07a8991ced4dd409608ccf7bcf13dfb59c1c3099cbe4c2a225bb2fbc76b +size 512 diff --git a/tasks/carosi2019/gurobi_solution_log/large_log_5.jsonl b/tasks/carosi2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dbc7f053b3401f25c7bee8749133f98dfb8765fd --- /dev/null +++ b/tasks/carosi2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbb6fa25f79d4cdc7a98f524bf56264320f6c54df3caa034ac7cf2c71bba18a5 +size 193 diff --git a/tasks/carosi2019/gurobi_solution_log/tiny_log.jsonl b/tasks/carosi2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d35d4bc5de7ec3638dcea9a2916b569bb543dc7a --- /dev/null +++ b/tasks/carosi2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6be13612361ffbe2c147895d3dd6f137b099f998f71e9f03fa29377d6d34757e +size 87 diff --git a/tasks/carosi2019/instance/large_instance_1.json b/tasks/carosi2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..be849b8ed71fff8f3f912dd0c29bedd3b1e660e5 --- /dev/null +++ b/tasks/carosi2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af12047b3f9e3ca5bb18034d43903850c06a0ef3ceb2f3cc76b52c2ef02b749d +size 1498679 diff --git a/tasks/carosi2019/instance/large_instance_2.json b/tasks/carosi2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..59675d43987eebdaab9b197760d560c6c72b60b0 --- /dev/null +++ b/tasks/carosi2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d9698ff671555c6b213b7d760f01acdfbf45c8a2471c7e895705c5379ce2c84 +size 1498839 diff --git a/tasks/carosi2019/instance/large_instance_3.json b/tasks/carosi2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d3279485a2bccc2c116cc97384eabda5e0d7db2f --- /dev/null +++ b/tasks/carosi2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcaec6b821c49d3a668be8ddb42fa12d12cd4c044e5512183729bc4d3cf9e8f2 +size 1157281 diff --git a/tasks/carosi2019/instance/large_instance_4.json b/tasks/carosi2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..075b758b29a4b0b6bc3fe35bc65d4e9f3ff74523 --- /dev/null +++ b/tasks/carosi2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f141c8f4417154cf1e7522df293d0e8cb845ec44686f269b0f32bda85be239e +size 841206 diff --git a/tasks/carosi2019/instance/large_instance_5.json b/tasks/carosi2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..df8a575e8b81982d645b152cc2dcee37c4898b4b --- /dev/null +++ b/tasks/carosi2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:931fc4ad4740eb1d1298dbe5a92ab118ed7c79c4dbde26552735b26f92a4e173 +size 1498828 diff --git a/tasks/carosi2019/instance/tiny_instance.json b/tasks/carosi2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..0b7565445190f8ff994a8cb9ac2d9f1e6d036f20 --- /dev/null +++ b/tasks/carosi2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d028c61e9423c97854cd6784c8644556f67d45c591d1f85349c4c21176c37a88 +size 127545 diff --git a/tasks/carosi2019/instance_schema.json b/tasks/carosi2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..07c961c5c3c2a0ca7e303271afac9e46b567b4ce --- /dev/null +++ b/tasks/carosi2019/instance_schema.json @@ -0,0 +1,80 @@ +{ + "topology": { + "terminals": " Named terminals served by the bus line.", + "depot": " Identifier for the central depot where all vehicles are stored.", + "num_terminals": " Number of terminals on the bus line.", + "scheme_length": " Number of departure/arrival patterns per direction in the service scheme." + }, + "planning_horizon": { + "start_minutes": " Start of the service day in minutes from midnight.", + "end_minutes": " End of the service day in minutes from midnight.", + "duration_minutes": " Total length of the service day in minutes." + }, + "directions": [ + { + "pattern_id": " Unique identifier for this service pattern.", + "direction": " Whether this pattern runs outbound or inbound.", + "start_terminal": " Terminal where trips of this pattern depart.", + "end_terminal": " Terminal where trips of this pattern arrive.", + "trip_duration_minutes": " Travel time in minutes for a single trip on this pattern." + } + ], + "time_windows": [ + { + "index": " Zero-based index identifying this time window within the planning horizon.", + "start_minutes": " Start of this time window in minutes from midnight.", + "end_minutes": " End of this time window in minutes from midnight.", + "ideal_headway_seconds": " Target time separation in seconds between consecutive trips passing the main stop.", + "min_headway_seconds": " Shortest allowable time separation in seconds between consecutive trips at the main stop.", + "max_headway_seconds": " Longest allowable time separation in seconds between consecutive trips at the main stop." + } + ], + "stopping_times": { + "{terminal}": [ + { + "time_window_index": " Index of the time window to which these stopping limits apply.", + "min_stopping_time_minutes": " Minimum dwell time in minutes a vehicle must wait at this terminal between consecutive trips.", + "max_stopping_time_minutes": " Maximum dwell time in minutes a vehicle may wait at this terminal between consecutive trips." + } + ] + }, + "pull_in_out_times": { + "{terminal}": [ + { + "time_window_index": " Index of the time window to which these travel times apply.", + "pull_out_time_minutes": " Travel time in minutes from the depot to this terminal when starting service.", + "pull_in_time_minutes": " Travel time in minutes from this terminal back to the depot when ending service." + } + ] + }, + "initial_trip_time_windows": { + "{pattern_id}": " Time window index from which the first trip of the timetable must be selected for this pattern." + }, + "final_trip_time_windows": { + "{pattern_id}": " Time window index from which the last trip of the timetable must be selected for this pattern." + }, + "penalty_function": { + "type": " Form of the penalty applied to headway deviations.", + "description": " Formula describing how the penalty grows as actual headway deviates from the ideal." + }, + "objective_function": { + "type": " Structure of the overall objective being minimized.", + "description": " Formula combining vehicle scheduling costs and timetable quality costs.", + "alpha": " Weight applied to vehicle scheduling costs relative to timetable quality costs.", + "vs_cost_components": " Named components contributing to the vehicle scheduling cost.", + "tt_cost_components": " Named components contributing to the timetable quality cost." + }, + "potential_trips": [ + { + "id": " Unique identifier for this candidate trip.", + "pattern_id": " Service pattern to which this trip belongs.", + "direction": " Whether this trip runs outbound or inbound.", + "start_terminal": " Terminal where this trip departs.", + "end_terminal": " Terminal where this trip arrives.", + "departure_time_minutes": " Scheduled departure time from the start terminal in minutes from midnight.", + "arrival_time_minutes": " Scheduled arrival time at the end terminal in minutes from midnight.", + "main_stop_arrival_time_minutes": " Scheduled arrival time at the main headway-measurement stop in minutes from midnight.", + "time_window_index": " Index of the time window in which this trip falls." + } + ] +} diff --git a/tasks/carosi2019/mathematical_formulation.md b/tasks/carosi2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d4f26725e1da7057ca8c519ba4ac11a30bbc52a4 --- /dev/null +++ b/tasks/carosi2019/mathematical_formulation.md @@ -0,0 +1,71 @@ +# Original Formulation: Integrated Timetabling and Vehicle Scheduling (ITTVS) + +*Source: A matheuristic for integrated timetabling and vehicle scheduling, S. Carosi, A. Frangioni, L. Galli, L. Girardi, G. Vallese, Transportation Research Part B 127 (2019) 99–124.* + +The model below is the integrated MILP presented in Section 4.3 (“TT–VS integrated model”), equations (1)–(6), whose notation is carried into the solution approach (Section 6) and the computational results (Section 7). The TT sub-problem (graph $G_d^{TT}$, Section 4.1) and the VS sub-problem (graph $G^{VS}$, Section 4.2) are coupled by the linking constraints (6). + +## Sets and Indices + +- $\mathcal{D}$ : set of directions $d$ (e.g. $\mathcal{D}=\{\overrightarrow{AB},\overrightarrow{BA}\}$ for a simple single line). + +- $\mathcal{T}=[\mathcal{T}_d]_{d\in\mathcal{D}}$ : set of all potential trips; $\mathcal{T}_d\subset\mathcal{T}$ is the subset of potential trips of direction $d$. + +- $\mathcal{T}_d^{ini},\,\mathcal{T}_d^{fin}\subseteq\mathcal{T}_d$ : admissible initial / final trips for direction $d$. + +- $G_d^{TT}=(N_d^{TT},A_d^{TT})$ : (acyclic) TT compatibility graph of direction $d$, with $N_d^{TT}=\mathcal{T}_d\cup\{O_d^-,O_d^+\}$, where $O_d^-$ is a dummy source and $O_d^+$ a dummy sink. An arc $(i,j)\in A_d^{TT}$ exists iff the headway $a(j)-a(i)$ is feasible (Section 4.1). + +- $G^{VS}=(N^{VS},A^{VS})$ : (single) VS compatibility graph, with two nodes $i^-,i^+$ per trip $i\in\mathcal{T}$ plus depot nodes $O^-,O^+$ (“pure” version, Section 4.2.1; see *Variants* for the time-space version). + +- $B(i)$ : backward star of trip node $i$ in $N_{d(i)}^{TT}$, i.e. the set of TT arcs entering node $i$. + +- $N=\{A,B\}$ : terminals of the line; $N^+=N\cup\{O\}$ : terminals plus the single depot $O$. + +- $d(i)$ : direction of trip $i$; $h(i)$ : time window in which trip $i$ falls. + +## Parameters + +- $b_n^d$ : node deficit in $G_d^{TT}$; $b_{O_d^-}^d=-1$, $b_{O_d^+}^d=+1$, and $b_n^d=0$ otherwise. + +- $c^d$ : (row) cost vector of TT arcs in $A_d^{TT}$; the cost of arc $(i,j)$ is the headway-deviation penalty of $a(j)-a(i)$ from the ideal headway $\hat{l}_d^{\,h(i)}$ (zero at the ideal headway; a quadratic penalty in the experiments). + +- $c$ : (row) cost vector of VS arcs in $A^{VS}$: trip arcs $(i^-,i^+)$ cost $0$; in-line arcs $(i^+,j^-)$ cost $st(j)-et(i)-\underline{\delta}_{en(i)}^{\,h(i)}$ (extra waiting); out-line arcs $(i^+,j^-)$ cost $t_{en(i),-}^{\,h(i)}+t_{sn(j),+}^{\,h(j)}$; start arcs $(O^-,i^-)$ cost $t_{sn(i),+}^{\,h(i)}$; end arcs $(i^+,O^+)$ cost $t_{en(i),-}^{\,h(i)}$; the return arc $(O^+,O^-)$ has a large cost $M$ (per-vehicle deployment cost). + +- $u_{n,m}$ : capacity of VS arc $(n,m)\in A^{VS}$; $u_{n,m}=1$ for trip, in-line/out-line, start and end arcs; $u_{O^+,O^-}=K$ (maximum fleet cardinality, or $+\infty$ if unconstrained). + +- $\alpha$ : weighting parameter balancing VS cost against TT quality (primary trade-off parameter). + +- $\hat{l}_d^{\,h},\ \underline{l}_d^{\,h},\ \bar{l}_d^{\,h}$ : ideal, minimum and maximum headway of direction $d$ in window $h$. + +- $a(i)$ : arrival time of trip $i$ at its main stop; $st(i),et(i)$ : departure / arrival time of trip $i$ at $sn(i),en(i)$. + +- $sn(i),en(i)$ : start and end terminal of trip $i$. + +- $\underline{\delta}_n^{\,h},\ \bar{\delta}_n^{\,h}$ : minimum / maximum stopping time at terminal $n\in N^+$ in window $h$ ($\bar{\delta}_O^{\,h}=+\infty$). + +- $t_{n,+}^{\,h},\ t_{n,-}^{\,h}$ : pull-out (depot$\to n$) and pull-in ($n\to$depot) travel times of terminal $n$ in window $h$. + +## Decision Variables + +- $y_{n,m}^d\in\{0,1\}$ : TT arc-selection variable, $(n,m)\in A_d^{TT}$, $d\in\mathcal{D}$; equals $1$ iff arc $(n,m)$ belongs to the chosen timetable path $\pi_d$ (i.e. the $O_d^-$–$O_d^+$ path). + +- $x_{n,m}\ge 0$ : VS arc-flow variable, $(n,m)\in A^{VS}$ (the flow defining the vehicle schedule $\Omega$). It need not be declared integer: by total unimodularity of (4)–(5) it is automatically integral once $y$ is integral. + +## Objective + +$$\begin{equation} +\min \quad \alpha\, c\,x + \sum_{d\in\mathcal{D}} c^d y^d \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +& \sum_{(m,n)\in A_d^{TT}} y_{m,n}^d \;-\; \sum_{(n,m)\in A_d^{TT}} y_{n,m}^d \;=\; b_n^d, + && n\in N_d^{TT},\ d\in\mathcal{D} \tag{2}\\[2pt] +& y_{n,m}^d \in \{0,1\}, && (n,m)\in A_d^{TT},\ d\in\mathcal{D} \tag{3}\\[2pt] +& \sum_{(m,n)\in A^{VS}} x_{m,n} \;-\; \sum_{(n,m)\in A^{VS}} x_{n,m} \;=\; 0, + && n\in N^{VS} \tag{4}\\[2pt] +& 0 \le x_{n,m} \le u_{n,m}, && (n,m)\in A^{VS} \tag{5}\\[2pt] +& \sum_{(n,m)\in B(i)} y_{n,m}^{\,d(i)} \;=\; x_{i^-,\,i^+}, && i\in\mathcal{T} \tag{6} +\end{align}$$ + +Constraints (2)–(3) are the flow-conservation/integrality constraints of the $|\mathcal{D}|$ TT sub-problems (one $O_d^-$–$O_d^+$ path per direction, i.e. timetable $\pi_d$). Constraints (4)–(5) are the flow-conservation and capacity constraints of the VS sub-problem (a circulation on $G^{VS}$). Constraints (6) are the linking constraints: trip $i$ is selected in the timetable (flow on a TT arc entering node $i$) iff its trip arc $(i^-,i^+)$ carries flow in the vehicle schedule. diff --git a/tasks/carosi2019/problem_description.txt b/tasks/carosi2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..4ede46febf87f425147837db06f819faa14f7b20 --- /dev/null +++ b/tasks/carosi2019/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A public transit agency operates a single bus line between two terminals, A and B, served from a single depot O. The line runs in two directions: outbound (A to B) and inbound (B to A). For each direction, a main stop along the route is designated for measuring headways, which are the time separations between consecutive trips passing that point. The planning horizon spans a full service day and is partitioned into several time windows. For each time window and each direction, the input specifies an ideal headway, a minimum allowed headway, and a maximum allowed headway. A large pool of potential trips is given as input, where each trip has a fixed direction, a departure time from its start terminal, an arrival time at its end terminal, an arrival time at the main stop, and the time window to which it belongs. Within each direction, specified subsets of trips are admissible as the first trip and as the last trip of the timetable. + +For each terminal and each time window, the input provides a minimum and a maximum stopping time that a vehicle must observe when dwelling at that terminal between consecutive trips. The depot has a minimum stopping time (which may be zero) but no effective maximum stopping time. For each terminal and each time window, the input also specifies a pull-out travel time (depot to terminal) and a pull-in travel time (terminal to depot). A trade-off weight governs the balance between vehicle scheduling costs and timetable quality costs, and a large per-vehicle deployment cost is also given as input. + +The agency must simultaneously select a timetable and a vehicle schedule. A timetable for one direction is an ordered chain of trips drawn from the potential trips for that direction that starts at an admissible initial trip, ends at an admissible final trip, and is built so that every two consecutive trips in the chain have a headway (measured at the main stop) falling between the minimum and maximum allowed headways for the time window of the earlier trip. A timetable for the full line consists of one such ordered chain per direction; although the headway feasibility rules above apply within each direction separately, the two direction-specific chains are not chosen independently of the vehicle schedule but are jointly optimized with it, because every trip selected in either direction must be covered by exactly one vehicle in the schedule described below. The quality of the timetable is measured by a quadratic penalty applied to each pair of consecutively selected trips within a direction: the penalty is zero when the actual headway equals the ideal headway for the time window of the earlier trip and increases as the squared deviation from that ideal headway. + +A vehicle schedule assigns the selected trips to vehicles. Each vehicle begins its service day with a pull-out trip from the depot to the start terminal of its first service trip, then performs a sequence of service trips, and ends with a pull-in trip from the end terminal of its last service trip back to the depot, so that each vehicle's service day forms a closed depot-to-depot loop and the overall vehicle schedule is a collection of such depot-to-depot loops that together cover every selected trip exactly once. Two consecutively assigned trips for the same vehicle must be compatible. Two trips are in-line compatible if the second trip starts at the same terminal where the first trip ends and the gap between the end of the first trip and the start of the second falls between the minimum and maximum stopping times at that terminal for the time window of the first trip. Two trips are out-line compatible if the second trip starts at a different terminal than where the first trip ends and the gap between the two trips is at least the pull-in travel time from the first trip's end terminal to the depot for the time window of the first trip, plus the minimum depot stopping time for the time window of the first trip, plus the pull-out travel time from the depot to the second trip's start terminal for the time window of the second trip. Each selected trip must be covered by exactly one vehicle. + +The vehicle scheduling cost has three components: a primary component equal to the per-vehicle deployment cost multiplied by the number of vehicles used, a secondary component equal to the total extra waiting time at terminals beyond the minimum stopping time for the time window of the preceding trip across all in-line compatible consecutive trip pairs, and a secondary component equal to the total pull-in and pull-out travel times across all out-line compatible consecutive trip pairs (using the pull-in travel time for the time window of the preceding trip and the pull-out travel time for the time window of the following trip), plus the pull-out travel time for the first trip of each vehicle in that trip's time window and the pull-in travel time for the last trip of each vehicle in that trip's time window. The timetable cost is the sum over both directions of all quadratic headway-deviation penalties for consecutively selected trips. + +The goal is to minimize the weighted sum of the vehicle scheduling cost (scaled by the trade-off weight) and the timetable cost, simultaneously choosing which trips to include in the timetable and how to assign them to vehicles, subject to all headway, trip sequencing, terminal stopping time, and trip coverage requirements described above. diff --git a/tasks/carosi2019/solution_logger.py b/tasks/carosi2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/carosi2019/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")