diff --git a/tasks/armbruster2012/instance_schema.json b/tasks/armbruster2012/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0adc2a5014d1fa87522ea9f5290d616e11ad7054 --- /dev/null +++ b/tasks/armbruster2012/instance_schema.json @@ -0,0 +1,9 @@ +{ + "num_nodes": " Total number of nodes in the undirected graph.", + "num_edges": " Total number of edges in the undirected graph.", + "bisection_capacity_F": " Maximum allowable sum of node weights in each partition group.", + "total_node_weight": " Sum of all node weights across the graph.", + "node_weights": " Weight of each node, indexed by node identifier.", + "edges": " Pair of endpoint node identifiers for each edge.", + "edge_weights": " Cost associated with cutting each edge, in the same order as edges." +} \ No newline at end of file diff --git a/tasks/armbruster2012/mathematical_formulation.md b/tasks/armbruster2012/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..ee184e1e432006cb9d6b82e75195edf0df6d4234 --- /dev/null +++ b/tasks/armbruster2012/mathematical_formulation.md @@ -0,0 +1,50 @@ +# Original Formulation: Minimum Graph Bisection (MB) + +*Source: LP and SDP branch-and-cut algorithms for the minimum graph bisection problem: a computational comparison, Michael Armbruster, Marzena Fügenschuh, Christoph Helmberg, Alexander Martin, 2012.* + +## Sets and Indices + +$$\begin{align*} +G = (V,E) \quad & \text{undirected graph with node set } V=\{1,\ldots,n\}\\ + & \text{and edge set } E \subseteq \{\{i,j\}:i,j\in V,\; i= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/armbruster2012/solution_schema.json b/tasks/armbruster2012/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7e692b5e9794ba59897313bb2840c77ac950a57f --- /dev/null +++ b/tasks/armbruster2012/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total cost of all edges whose endpoints are assigned to different groups.", + "partition_S": " Node identifiers assigned to the group containing the reference node (node 0).", + "partition_complement": " Node identifiers assigned to the group not containing the reference node." +} \ No newline at end of file diff --git a/tasks/arslan2021/feasibility_check.py b/tasks/arslan2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b1f2273df6c4d24452320d2c8b2b455fb8da88f1 --- /dev/null +++ b/tasks/arslan2021/feasibility_check.py @@ -0,0 +1,392 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the benchmark's LP-relaxed Two-Stage Robust Knapsack. + +Based on: Arslan & Detienne (2022), "Decomposition-based approaches for a class of +two-stage robust binary optimization problems", INFORMS Journal on Computing 34(2). + +The benchmark evaluates the LP-relaxed recourse variant of the min-max-min problem: + min_{x in {0,1}^I} sum_i (f_i - p_bar_i) x_i + + max_{xi in Xi} min_{(y,r) in Y(x)} sum_i [(p_hat_i xi_i - f_i) y_i - p_hat_i xi_i r_i] + +The ONLY first-stage decision variable is x in {0,1}^I. The second-stage +(y, r) and the dual variables (u0, v) from the deterministic-equivalent +single-level reformulation (Eq. 10-14) are NOT part of the original +decision space. Any binary x is feasible (relatively complete recourse: +Y(x) always contains (y=0, r=0)). + +Checked constraints: + Constraint 1: x_i in {0,1} for all i [original domain] + Constraint 2: reported objective_value equals the exact fixed-x value of + the deterministic-equivalent LP relaxation. +""" + +import json +import math +import argparse + + +def compute_relaxed_fixed_x_objective(instance, x): + """Solve the benchmark's LP-relaxed recourse problem for fixed x.""" + import numpy as np + from scipy.optimize import linprog + from scipy.sparse import coo_matrix + + items = instance["items"] + item_count = len(items) + params = instance["problem_parameters"] + capacity = float(params["knapsack_capacity"]) + gamma = float(params["uncertainty_budget"]) + r_offset = item_count + u_index = 2 * item_count + v_offset = u_index + 1 + variable_count = 3 * item_count + 1 + + objective = np.zeros(variable_count, dtype=float) + first_stage = 0.0 + for i, item in enumerate(items): + outsource = float(item["outsource_penalty"]) + nominal = float(item["nominal_profit"]) + first_stage += (outsource - nominal) * x[i] + objective[i] = -outsource + objective[v_offset + i] = 1.0 + objective[u_index] = gamma + + rows = [] + columns = [] + values = [] + rhs = [] + + def add_constraint(coefficients, upper): + row = len(rhs) + for column, value in coefficients.items(): + rows.append(row) + columns.append(column) + values.append(value) + rhs.append(float(upper)) + + for i, item in enumerate(items): + degradation = float(item["max_degradation"]) + add_constraint({ + i: degradation, + r_offset + i: -degradation, + u_index: -1.0, + v_offset + i: -1.0, + }, 0.0) + add_constraint({r_offset + i: 1.0, i: -1.0}, 0.0) + capacity_coefficients = {} + for i, item in enumerate(items): + capacity_coefficients[i] = float(item["weight"]) + capacity_coefficients[r_offset + i] = float(item["repair_capacity"]) + add_constraint(capacity_coefficients, capacity) + + matrix = coo_matrix( + (values, (rows, columns)), + shape=(len(rhs), variable_count), + ).tocsr() + bounds = ( + [(0.0, float(x[i])) for i in range(item_count)] + + [(0.0, 1.0) for _ in range(item_count)] + + [(0.0, None)] + + [(0.0, None) for _ in range(item_count)] + ) + result = linprog( + objective, + A_ub=matrix, + b_ub=np.asarray(rhs), + bounds=bounds, + method="highs", + options={"presolve": True}, + ) + if not result.success: + raise RuntimeError( + f"fixed-x relaxed recourse LP failed: {result.message}" + ) + return first_stage + float(result.fun) + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'x') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance, solution): + """Check x and the exact objective of the LP-relaxed benchmark. + + The only decision variable in the original problem is the first-stage + x in {0,1}^I. Relatively complete recourse holds (Y(x) contains + (y=0, r=0) for any x), so any binary x is feasible. + + Additionally, the reported objective_value is checked against an + analytic envelope [L_Z, U_Z] computed from x and the instance data + to defend against fabricated/lying objective reports (Tier C + obj-consistency check). + """ + tol = 1e-5 + eps = 1e-5 + + items = instance["items"] + num_items = len(items) + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # ---- Parse x (list or dict format) ---- + raw_x = solution.get("x") + if isinstance(raw_x, list): + try: + x = [float(v) for v in raw_x] + except (TypeError, ValueError): + x = None + elif isinstance(raw_x, dict): + try: + x = [float(raw_x[str(i)]) for i in range(num_items)] + except (KeyError, TypeError, ValueError): + x = None + else: + x = None + + # ================================================================== + # Constraint 1: First-stage binary domain x_i in {0,1} for all i + # ================================================================== + if x is None: + violated_constraints.add(1) + violations.append("Solution missing first-stage decision variable 'x'.") + else: + for i in range(num_items): + val = x[i] + nearest = round(val) + if nearest not in (0, 1) or abs(val - nearest) > tol: + violated_constraints.add(1) + nearest_binary = 0.0 if val < 0.5 else 1.0 + va = abs(val - nearest_binary) + violations.append( + f"Binary constraint violated for x_{i}: x_{i} = {val}" + ) + normalizer = max(abs(nearest_binary), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": val, + "rhs": nearest_binary, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + }) + + # ================================================================== + # Constraint 2: exact objective for the benchmark's LP-relaxed recourse. + # ================================================================== + if x is not None and 1 not in violated_constraints: + expected = compute_relaxed_fixed_x_objective(instance, x) + reported = float(solution["objective_value"]) + difference = abs(reported - expected) + tol_obj = max(1e-4, 1e-8 * abs(expected)) + if difference > tol_obj: + violated_constraints.add(2) + violations.append( + f"Objective consistency violated: objective_value={reported} " + f"does not match the exact fixed-x LP-relaxation value " + f"{expected} (|diff|={difference:.4g}, tol={tol_obj:.4g})" + ) + normalizer = max(abs(expected), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": reported, + "rhs": expected, + "raw_excess": difference, + "normalizer": normalizer, + "ratio": difference / normalizer, + }) + + return { + "feasible": len(violated_constraints) == 0, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Two-Stage Robust Knapsack" + ) + 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 JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write JSON feasibility result") + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is feasible.") + else: + print(f"Solution is INFEASIBLE. " + f"Violated constraints: {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/arslan2021/gurobi_code.py b/tasks/arslan2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ca7433804d29383ccb43fa9646c01d8c018559 --- /dev/null +++ b/tasks/arslan2021/gurobi_code.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +""" +Gurobi MILP implementation of the benchmark's LP-relaxed recourse variant of +the Two-Stage Robust Knapsack Problem. + +Based on: Arslan & Detienne (2022), "Decomposition-based approaches for a class of +two-stage robust binary optimization problems", INFORMS Journal on Computing 34(2). + +Implements formulation (42) / deterministic equivalent (10)-(14) applied to the +knapsack application (Section 4.1, Equation 43). + +Problem (43): + min_{x in {0,1}^I} sum_i (f_i - p_bar_i) x_i + + max_{xi in Xi} min_{(y,r) in Y(x)} sum_i [(p_hat_i xi_i - f_i) y_i - p_hat_i xi_i r_i] + +where: + Y_LP(x) = {(y,r) in [0,1]^{2I} | sum c_i y_i + t_i r_i <= C, y_i <= x_i, r_i <= y_i} + Xi = {xi in R^I_+ | sum xi_i <= Gamma, 0 <= xi_i <= 1} + +Deterministic equivalent approach: + By Proposition 2.1, the inner min over Y(x) = min over conv(Y(x)). + By Proposition 2.4, since linking is y_i <= x_i (H=I, T=-I, d=0), + conv(Y(x)) = Y_bar(x) = conv(Y) intersect {y <= x}. + By minimax theorem: max_xi min_y = min_y max_xi (both sets compact convex, bilinear). + Dualizing max_xi gives the MILP below. + +Benchmark convention: the second-stage binary set is replaced by its elementary +LP relaxation. This is an approximation of the paper's Eq. (43), not a claim +that the elementary relaxation equals the binary knapsack polytope's convex hull. +""" + +import json +import argparse +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load the knapsack instance from JSON.""" + with open(path) as f: + return json.load(f) + + +def build_and_solve(data, time_limit): + """ + Build and solve the deterministic equivalent MILP. + + The formulation dualizes the inner max over the uncertainty set Xi: + max_{xi >= 0, sum xi <= Gamma, xi <= 1} sum_i p_hat_i (y_i - r_i) xi_i + Dual: min u0 * Gamma + sum v_i s.t. u0 + v_i >= p_hat_i (y_i - r_i), u0, v_i >= 0 + + Full MILP: + min sum_i (f_i - p_bar_i) x_i - sum_i f_i y_i + Gamma u0 + sum_i v_i + s.t. u0 + v_i >= p_hat_i (y_i - r_i) for all i [dual feasibility] + sum_i c_i y_i + t_i r_i <= C [knapsack capacity] + r_i <= y_i for all i [repair requires production] + y_i <= x_i for all i [linking first/second stage] + x_i in {0,1} for all i + 0 <= y_i <= 1, 0 <= r_i <= 1 for all i [LP relaxation of conv(Y)] + u0 >= 0, v_i >= 0 for all i + """ + items = data['items'] + I = len(items) + C = data['problem_parameters']['knapsack_capacity'] + Gamma = data['problem_parameters']['uncertainty_budget'] + + # Extract parameters + weight = [item['weight'] for item in items] + p_bar = [item['nominal_profit'] for item in items] + p_hat = [item['max_degradation'] for item in items] + f_out = [item['outsource_penalty'] for item in items] + t_rep = [item['repair_capacity'] for item in items] + + model = gp.Model("TwoStageRobustKnapsack") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + + # --- Decision variables --- + # First-stage: x_i = 1 if item i is selected for production + x = model.addVars(I, vtype=GRB.BINARY, name="x") + + # Second-stage (LP relaxation of conv(Y)): + # y_i: fraction of item i produced as-is + # r_i: fraction of item i repaired + y = model.addVars(I, lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name="y") + r = model.addVars(I, lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name="r") + + # Dual variables for uncertainty set + # u0: dual for sum_i xi_i <= Gamma + # v_i: dual for xi_i <= 1 + u0 = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, name="u0") + v = model.addVars(I, lb=0.0, vtype=GRB.CONTINUOUS, name="v") + + # --- Objective --- + # min sum_i (f_i - p_bar_i) x_i [first-stage cost] + # + sum_i (-f_i) y_i [nominal second-stage cost] + # + Gamma * u0 + sum_i v_i [worst-case uncertainty premium via LP duality] + model.setObjective( + gp.quicksum((f_out[i] - p_bar[i]) * x[i] for i in range(I)) + + gp.quicksum(-f_out[i] * y[i] for i in range(I)) + + Gamma * u0 + + gp.quicksum(v[i] for i in range(I)), + GRB.MINIMIZE + ) + + # --- Constraints --- + + # Dual feasibility: u0 + v_i >= p_hat_i (y_i - r_i) for all i + # From LP duality of: max_{xi in Xi} sum_i p_hat_i xi_i (y_i - r_i) + for i in range(I): + model.addConstr(u0 + v[i] >= p_hat[i] * (y[i] - r[i]), + name=f"dual_feas_{i}") + + # Knapsack capacity constraint (from Y): + # sum_i c_i y_i + t_i r_i <= C + model.addConstr( + gp.quicksum(weight[i] * y[i] + t_rep[i] * r[i] for i in range(I)) <= C, + name="knapsack_cap" + ) + + # Repair requires production: r_i <= y_i for all i (from Y) + for i in range(I): + model.addConstr(r[i] <= y[i], name=f"repair_req_{i}") + + # Linking constraint: y_i <= x_i for all i (from Y(x)) + # This couples first-stage selection with second-stage production + for i in range(I): + model.addConstr(y[i] <= x[i], name=f"linking_{i}") + + # --- Solve --- + model.optimize() + + # --- Extract solution --- + solution = {"solver_status": model.Status} + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + # Original formulation (Eq. 43) has first-stage binary x only; the + # second-stage (y, r) and dual variables (u0, v) are artifacts of the + # deterministic-equivalent single-level reformulation with LP duality. + # They are NOT part of the original problem's decision space, so they + # are not exported. + solution["x"] = {str(i): int(round(x[i].X)) for i in range(I)} + + if model.Status == GRB.OPTIMAL: + solution["optimality_gap"] = 0.0 + else: + solution["optimality_gap"] = model.MIPGap + + # Interpret solution + selected_items = [i for i in range(I) if round(x[i].X) == 1] + solution["selected_items"] = selected_items + else: + solution["objective_value"] = None + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Two-Stage Robust Knapsack - Gurobi deterministic equivalent MILP" + ) + 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 for output 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) + + data = load_instance(args.instance_path) + solution = build_and_solve(data, 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) + + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']:.6f}") + print(f"Status: {solution['solver_status']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/arslan2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/arslan2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/arslan2021/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/arslan2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/arslan2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/arslan2021/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/arslan2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/arslan2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/arslan2021/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/arslan2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/arslan2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/arslan2021/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/arslan2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/arslan2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/arslan2021/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/arslan2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/arslan2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/arslan2021/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/arslan2021/gurobi_solution/large_solution_1.json b/tasks/arslan2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0d3ccd017b746f6e0f74038588ce6a504560b10a --- /dev/null +++ b/tasks/arslan2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb568b4643cbd60927c0c1dd651b3adbcc992b6c6ba820debb94171f3ebaef85 +size 5605 diff --git a/tasks/arslan2021/gurobi_solution/large_solution_2.json b/tasks/arslan2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d4c7d39015f22b72ebe531953737e49a3bbb8483 --- /dev/null +++ b/tasks/arslan2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90b3dfbd254a9a92f679a2c162c6fd5b786253fdeaf57b84128cbb57f84e3b44 +size 5560 diff --git a/tasks/arslan2021/gurobi_solution/large_solution_3.json b/tasks/arslan2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ea89737b2c0af856a709ab3329882e6198da6829 --- /dev/null +++ b/tasks/arslan2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c91e506ed8035a73e861c574819376c5b4dfd16562879fdb6274fc372684421c +size 5857 diff --git a/tasks/arslan2021/gurobi_solution/large_solution_4.json b/tasks/arslan2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f300fa97bac654031ee4b6d54c2fedca54c1d505 --- /dev/null +++ b/tasks/arslan2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30566aaddcf7fe499676f1a5b3812dd4245971b5166280b117b422a463be6c28 +size 5896 diff --git a/tasks/arslan2021/gurobi_solution/large_solution_5.json b/tasks/arslan2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..733b51b410815b01bfcdc039ec3b69033e1a4a88 --- /dev/null +++ b/tasks/arslan2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de266324a1c2ab24520cbfdb3c37c5d63f393a11764b6e7986647dfca8937961 +size 4856 diff --git a/tasks/arslan2021/gurobi_solution/tiny_solution.json b/tasks/arslan2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..cfe77ed660d37732055409de2830456cfc3d2380 --- /dev/null +++ b/tasks/arslan2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b56dd0d8d5b76792d3b52f70ebbcc431dc951a1934869acbd36197ac92cc7e3 +size 504 diff --git a/tasks/arslan2021/gurobi_solution_log/large_log_1.jsonl b/tasks/arslan2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ef5d555ae41601f2d6e58fa7dcea1b93260fbcc --- /dev/null +++ b/tasks/arslan2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1c66a1dfff0258d48da66c84e06bc7b76eb299ef4224f40f8c0804f313596f3 +size 1475 diff --git a/tasks/arslan2021/gurobi_solution_log/large_log_2.jsonl b/tasks/arslan2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..daeccb576d99f02ec2fdc281d59b380cac2ab395 --- /dev/null +++ b/tasks/arslan2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e739536e494a1d8429703d15a12b4ce160ba591f172f2a13354ed0167d0ede5f +size 95 diff --git a/tasks/arslan2021/gurobi_solution_log/large_log_3.jsonl b/tasks/arslan2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a933ceae72fedf4fcf53a85fbe379a8dc08fb5bb --- /dev/null +++ b/tasks/arslan2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab1b16a11b7e6da409301ee1e41bacc4b958b27a32d19e8b6bd8e5483573ac7d +size 769 diff --git a/tasks/arslan2021/gurobi_solution_log/large_log_4.jsonl b/tasks/arslan2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d9decc807aef64b52730f8726b3575201c460b6d --- /dev/null +++ b/tasks/arslan2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f65afd1ac4f116bf64bf6200754839600f8a87ce0a73610bf8bed8bf2eb5780 +size 324 diff --git a/tasks/arslan2021/gurobi_solution_log/large_log_5.jsonl b/tasks/arslan2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..58e067c700160f8dd1c5c97456cad73657592f73 --- /dev/null +++ b/tasks/arslan2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:888672926021ac7f212ef267acb5bdeb9c9b61bf7b796a9750cab92aaecdb048 +size 796 diff --git a/tasks/arslan2021/gurobi_solution_log/tiny_log.jsonl b/tasks/arslan2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1b21c90ff71a594f3901a836d5a71575007b215c --- /dev/null +++ b/tasks/arslan2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ccb0da32fbe2c3ce076ebd93f29c571192ba4011eefa56889b6f517679c0bd2 +size 40 diff --git a/tasks/arslan2021/instance/large_instance_1.json b/tasks/arslan2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4a39ceaa0271e1db7551d27c438b6ae00b72e26d --- /dev/null +++ b/tasks/arslan2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13fd266f85b6d7c13f22d37329a2e60f1e59b9a1eacd7e21bf3bc38de9a6a126 +size 53939 diff --git a/tasks/arslan2021/instance/large_instance_2.json b/tasks/arslan2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..fdd81f7db4d719e065501a2161810e7adbfdf212 --- /dev/null +++ b/tasks/arslan2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99c13785a447a40b756955cd455636ce7bb3133bfc62a5bf922f19b362554096 +size 53984 diff --git a/tasks/arslan2021/instance/large_instance_3.json b/tasks/arslan2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c41be0ee7b1e40c4aea4a67c9d0dc89ff4a40031 --- /dev/null +++ b/tasks/arslan2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43bdc4f16f99732d74eda48ede64a582a5c77592444f6e8506e679b888623560 +size 54214 diff --git a/tasks/arslan2021/instance/large_instance_4.json b/tasks/arslan2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a5253ed2fb3723953ce7e7ef1ab52ede569751d6 --- /dev/null +++ b/tasks/arslan2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eff2d3fda7dfb49f536d09921eed7e0598aa3e057a1ea2adea03ba4cf7b64b05 +size 52850 diff --git a/tasks/arslan2021/instance/large_instance_5.json b/tasks/arslan2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5bac2152fed7f74e3a7ba635e8ce33340f1e2c56 --- /dev/null +++ b/tasks/arslan2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c23b77564b9fbe0e958f62476f96ebf4e0f7210e81a3e44102c67713c6f1e88 +size 53955 diff --git a/tasks/arslan2021/instance/tiny_instance.json b/tasks/arslan2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a951a75897ac73acf8a416c42c915d13d806121a --- /dev/null +++ b/tasks/arslan2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87a071e6441fac9539b9b6dc057589e6323e786ef61fc10c7b6aa8c343c6faa3 +size 4596 diff --git a/tasks/arslan2021/instance_schema.json b/tasks/arslan2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ee85319248ebe2b49284da1376fa1736a08ba298 --- /dev/null +++ b/tasks/arslan2021/instance_schema.json @@ -0,0 +1,16 @@ +{ + "problem_parameters": { + "knapsack_capacity": " Total capacity of the knapsack available for production and repair activities.", + "uncertainty_budget": " Maximum total degradation the adversary can impose across all items." + }, + "items": [ + { + "id": " Unique identifier for the item.", + "weight": " Capacity consumed when the item is produced.", + "nominal_profit": " Profit earned from the item when there is no degradation.", + "max_degradation": " Worst-case profit reduction for the item when its degradation factor equals one.", + "outsource_penalty": " Cost penalty incurred when the item is outsourced instead of produced in-house.", + "repair_capacity": " Additional capacity consumed when the item is repaired to recover its full nominal profit." + } + ] +} diff --git a/tasks/arslan2021/mathematical_formulation.md b/tasks/arslan2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..8824b307f2f524d36295db27daa16e4f5dcdff95 --- /dev/null +++ b/tasks/arslan2021/mathematical_formulation.md @@ -0,0 +1,75 @@ +# Original Formulation (General Min-Max-Min, Eq. 1) + +## Sets, Dimensions, and Parameters + +- Dimensions: $N = p + p'$ first-stage vars; $N_1$ binary first-stage; $M = q + q'$ second-stage vars; $M_1$ binary second-stage; $S$ dimension of uncertainty vector $\xi$; $S'$ rows of $A$. + +- First-stage data: $G \in \mathbb{Z}^{N' \times N}$, $g \in \mathbb{Z}^{N'}$, $c \in \mathbb{Z}^N$. + +- Second-stage data: $E \in \mathbb{Z}^{M'' \times M}$, $e \in \mathbb{Z}^{M''}$, $f \in \mathbb{Z}^M$, $Q \in \mathbb{Z}^{M \times S}$. + +- Linking-constraint data: $H \in \mathbb{Z}^{M' \times M}$, $T \in \mathbb{Z}^{M' \times N_1}$, $d \in \mathbb{Z}^{M'}$. + +- Uncertainty-set data: $A \in \mathbb{Z}^{S' \times S}$, $b \in \mathbb{Z}^{S'}$. + +## Feasible Regions + +$$\begin{align*} +X & = \{\, x \in \{0,1\}^{N_1} \times \mathbb{R}^{N - N_1}_+ \;:\; G x \leq g \,\}, \\ +Y & = \{\, y \in \{0,1\}^{M_1} \times \mathbb{R}^{M - M_1}_+ \;:\; E y \leq e \,\}, \\ +Y(x) & = \{\, y \in Y \;:\; H y \leq d - T x_1 \,\}, \\ +\Xi & = \{\, \xi \in \mathbb{R}^{S} \;:\; A \xi \leq b \,\}. +\end{align*}$$ + +## Original Problem + +$$\begin{align} +\min_{x \in X} \; c^\top x \;+\; \max_{\xi \in \Xi} \; \min_{y \in Y(x)} \; (f + Q\xi)^\top y + \tag{1} +\end{align}$$ + +At the first stage, $x$ is chosen before $\xi$ is observed. An adversary then picks $\xi \in \Xi$ to maximize the second-stage cost. Finally, the decision maker reacts by choosing $y \in Y(x)$ that minimizes $(f + Q\xi)^\top y$. Both $X$ and $Y$ are bounded mixed-binary sets. + +# Benchmark Application: LP-Relaxed Two-Stage Robust Knapsack + +The original paper's Eq. (43) has binary recourse. The released benchmark +uses the explicit LP relaxation below, replacing the binary domains of +$(y,r)$ by their unit intervals. This distinction is material and defines the +objective values in the bundled references. + +## Sets and Parameters + +- $I = \{1, \ldots, I\}$: set of items. + +- $c_i$: weight (capacity requirement) of item $i$. + +- $\bar{p}_i$: expected profit of item $i$; $\hat{p}_i$: maximum profit degradation. + +- $f_i$: outsourcing cost/penalty; $t_i$: additional repair capacity for item $i$. + +- $C$: total knapsack capacity; $\Gamma$: uncertainty budget. + +## Uncertainty Set + +$$\begin{align*} +\Xi \;=\; \Big\{\, \xi \in \mathbb{R}^{I}_+ \;:\; \sum_{i \in I} \xi_i \leq \Gamma,\; 0 \leq \xi_i \leq 1 \ \forall i \in I \,\Big\}. +\end{align*}$$ + +## Decision Variables + +First-stage: $x_i \in \{0,1\}$, $x_i = 1$ iff item $i$ is selected for production. +Second-stage (in $Y_{LP}(x)$): $0\le y_i\le1$ (fraction produced as-is), $0\le r_i\le1$ (fraction repaired). $$\begin{align*} +Y_{LP}(x) \;=\; \Big\{ (y, r) \in [0,1]^I \times [0,1]^I \;:\; + & \sum_{i \in I} (c_i y_i + t_i r_i) \leq C,\; + y_i \leq x_i\ \forall i,\; + r_i \leq y_i\ \forall i \Big\}. +\end{align*}$$ + +## LP-Relaxed Min-Max-Min Problem + +$$\begin{align} +\min_{x \in \{0,1\}^I}\; \sum_{i \in I} (f_i - \bar{p}_i)\, x_i + \;+\; \max_{\xi \in \Xi}\; \min_{(y,r) \in Y_{LP}(x)}\; + \sum_{i \in I} \Big[\, (\hat{p}_i\, \xi_i - f_i)\, y_i \;-\; \hat{p}_i\, \xi_i\, r_i \,\Big] + \tag{43-LP} +\end{align}$$ diff --git a/tasks/arslan2021/problem_description.txt b/tasks/arslan2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..dee7f22a90908b0100269d4089eab179f1b32c61 --- /dev/null +++ b/tasks/arslan2021/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A company manages a collection of items, each characterized by a weight, a nominal profit, a maximum profit degradation, an outsourcing penalty cost, and a repair capacity requirement. The company has a knapsack with a fixed total capacity. In a first planning phase, before any uncertainty is revealed, the company must decide which items to select for potential in-house production. This benchmark then uses the LP-relaxed recourse approximation of the binary model: after an adversarial degradation is revealed, the fractions produced as-is and repaired may take any value between zero and one. Items not selected in the first phase cannot be produced or repaired. This relaxation is the problem evaluated by the supplied model, checker, and reference objectives; it should not be interpreted as the original binary-recourse Eq. (43). + +The uncertainty in profit degradation is governed by a vector of degradation factors, one per item, each ranging from zero to one. The total sum of all degradation factors across items is limited by an uncertainty budget. The actual profit of an item produced as-is equals its nominal profit minus the product of its maximum degradation and the corresponding degradation factor. An item that is repaired recovers its full nominal profit regardless of the degradation factor. An item that is outsourced yields its nominal profit minus its outsourcing penalty, regardless of degradation. The adversary chooses the degradation factors to inflict the worst possible outcome on the company, subject to the budget and per-item bounds. + +The input data specifies the number of items, and for each item: its weight (consumption of knapsack capacity when produced), its nominal profit, its maximum profit degradation (the worst-case profit reduction when the degradation factor equals one), its outsourcing penalty cost, and the additional capacity consumed when that item is repaired instead of produced as-is. The data also specifies the total knapsack capacity and the uncertainty budget controlling the total allowable degradation across all items. + +The company must choose which items to select in the first phase. The second-stage production and repair variables are continuous fractions in [0,1]. A repaired fraction cannot exceed the produced fraction. The total capacity consumed by production and repair together must not exceed the knapsack capacity: each produced fraction consumes its proportional item weight, and each repaired fraction consumes its proportional additional repair capacity. Only items selected in the first phase may receive a positive production or repair fraction. + +The goal is to minimize the total worst-case cost. This cost is the sum of two components. The first component, determined before uncertainty is revealed, equals the sum over all selected items of the difference between each item's outsourcing penalty and its nominal profit. The second component, determined after the adversary reveals the degradation, equals the sum over all produced items of that item's maximum degradation multiplied by its degradation factor minus that item's outsourcing penalty, minus the sum over all repaired items of that item's maximum degradation multiplied by its degradation factor. Equivalently, selecting an item incurs a baseline cost of outsourcing penalty minus nominal profit; producing that item as-is then offsets the outsourcing penalty but exposes it to degradation; repairing it further offsets the degradation exposure. The adversary maximizes this second-stage cost over the uncertainty set, and the company minimizes against the adversary's worst case. diff --git a/tasks/arslan2021/solution_logger.py b/tasks/arslan2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/arslan2021/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/arslan2021/solution_schema.json b/tasks/arslan2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..639877a8409c0a46d09ab4d8967dfbb4caad1f14 --- /dev/null +++ b/tasks/arslan2021/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total worst-case cost combining first-stage selection costs and the adversarial worst-case second-stage production/repair/outsourcing costs.", + "x": " Whether each item is selected for potential in-house production in the first stage (1 = selected, 0 = not selected)." +} diff --git a/tasks/bard2002/feasibility_check.py b/tasks/bard2002/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..981b8b4188bd9447904f985276c1502bf01f8e5f --- /dev/null +++ b/tasks/bard2002/feasibility_check.py @@ -0,0 +1,673 @@ +""" +Feasibility checker for the VRPTW formulation from: +Bard, Kontoravdis, and Yu (2002), +"A Branch-and-Cut Procedure for the Vehicle Routing Problem with Time Windows", +Transportation Science, 36(2), 250-269. + +Checks all hard constraints (2)-(8) from the mathematical formulation, +plus constraint (9): objective consistency (Tier C anti-gaming defense). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('departure_times', 'loads', 'num_vehicles', 'objective_value', 'routes', 'total_distance') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('departure_times', 'loads', 'num_vehicles', 'total_distance') +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def build_distance_matrix(data): + """Build or load distance matrix from instance data.""" + depot = data["depot"] + customers = data["customers"] + n = len(customers) + num = n + 1 + nodes = [depot] + customers + + if "distance_matrix" in data and data["distance_matrix"]: + return data["distance_matrix"] + + x_c = [nodes[i]["x"] for i in range(num)] + y_c = [nodes[i]["y"] for i in range(num)] + raw_dist = [[0.0] * num for _ in range(num)] + for i in range(num): + for j in range(num): + if i != j: + d = math.sqrt((x_c[i] - x_c[j]) ** 2 + (y_c[i] - y_c[j]) ** 2) + raw_dist[i][j] = math.floor(d * 10) / 10.0 + return raw_dist + + +def build_tau(data, raw_dist): + """Build travel time matrix with service time folded in, per paper preprocessing.""" + depot = data["depot"] + customers = data["customers"] + n = len(customers) + num = n + 1 + nodes = [depot] + customers + + ready = [nodes[i]["ready_time"] for i in range(num)] + due = [nodes[i]["due_date"] for i in range(num)] + service = [nodes[i]["service_time"] for i in range(num)] + + fold = data.get("travel_time_includes_service_time", False) + + tau = [[0.0] * num for _ in range(num)] + for i in range(num): + for j in range(num): + if i == j: + continue + t = raw_dist[i][j] + if not fold: + t += service[i] + if (ready[j] - due[i]) > t: + t = ready[j] - due[i] + tau[i][j] = t + return tau + + +def extract_x_from_routes(routes, num): + """Extract binary x_{ij} variables from routes.""" + x = {} + for route in routes: + for k in range(len(route) - 1): + i, j = route[k], route[k + 1] + x[i, j] = 1 + return x + + +def compute_departure_times_and_loads(routes, tau, ready, demand): + """ + Compute departure times (t_i) and loads (y_i) from routes. + t_i = departure time from customer i (max of arrival, ready_time). + y_i = accumulated load at departure from customer i. + """ + t = {} + y = {} + for route in routes: + current_time = 0.0 + current_load = 0 + for k in range(len(route) - 1): + i = route[k] + j = route[k + 1] + arr = current_time + tau[i][j] + if j != 0: + dep = max(arr, ready[j]) + current_time = dep + current_load += demand[j] + t[j] = dep + y[j] = current_load + return t, y + + +def check_feasibility(data, solution): + """ + Check all hard constraints (2)-(8) from the VRPTW formulation, + plus constraint (9) objective-consistency check. + Returns feasibility result dictionary. + """ + tol = 1e-5 + eps = 1e-5 + + depot = data["depot"] + customers = data["customers"] + n = len(customers) + num = n + 1 # depot + customers + nodes = [depot] + customers + + Q = data["vehicle_capacity"] + demand = [nodes[i]["demand"] for i in range(num)] + ready = [nodes[i]["ready_time"] for i in range(num)] + due = [nodes[i]["due_date"] for i in range(num)] + + raw_dist = build_distance_matrix(data) + tau = build_tau(data, raw_dist) + + routes = solution.get("routes", []) + x = extract_x_from_routes(routes, num) + + # Use provided departure_times and loads if available, otherwise compute + if "departure_times" in solution and solution["departure_times"]: + t = {int(k): v for k, v in solution["departure_times"].items()} + else: + t, _ = compute_departure_times_and_loads(routes, tau, ready, demand) + + if "loads" in solution and solution["loads"]: + y = {int(k): v for k, v in solution["loads"].items()} + else: + _, y = compute_departure_times_and_loads(routes, tau, ready, demand) + + I = list(range(1, num)) # customer indices + I0 = list(range(num)) # depot + customer indices + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint (2): Each customer served exactly once + # sum_{j in I_0} x_{ij} = 1, for all i in I + # ========================================================================= + for i in I: + lhs_val = sum(x.get((i, j), 0) for j in I0 if j != i) + rhs_val = 1.0 + violation_amount = abs(lhs_val - rhs_val) + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Constraint (2): Customer {i} is visited {int(lhs_val)} time(s) " + f"instead of exactly 1" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (3): Flow conservation + # sum_{j in I_0} x_{ij} - sum_{j in I_0} x_{ji} = 0, for all i in I_0 + # ========================================================================= + for i in I0: + out_flow = sum(x.get((i, j), 0) for j in I0 if j != i) + in_flow = sum(x.get((j, i), 0) for j in I0 if j != i) + lhs_val = out_flow - in_flow + rhs_val = 0.0 + violation_amount = abs(lhs_val - rhs_val) + if violation_amount > tol: + violated_constraints.add(3) + node_label = f"depot (node 0)" if i == 0 else f"customer {i}" + violations.append( + f"Constraint (3): Flow conservation violated at {node_label}: " + f"out_flow={out_flow}, in_flow={in_flow}, difference={lhs_val}" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (4): Time linking + # t_j >= t_i + tau_{ij} * x_{ij} - T_{ij} * (1 - x_{ij}), for i,j in I + # where T_{ij} = b_i - a_j + # Only active (binding) when x_{ij} = 1, so we check: t_j >= t_i + tau_{ij} + # ========================================================================= + for i in I: + for j in I: + if i == j: + continue + x_ij = x.get((i, j), 0) + T_ij = due[i] - ready[j] + rhs_val = t.get(i, 0.0) + tau[i][j] * x_ij - T_ij * (1 - x_ij) + lhs_val = t.get(j, 0.0) + # This is a >= constraint: lhs >= rhs, so violation = rhs - lhs + violation_amount = rhs_val - lhs_val + if violation_amount > tol: + violated_constraints.add(4) + violations.append( + f"Constraint (4): Time linking violated for arc ({i},{j}): " + f"t_{j}={lhs_val:.2f} < t_{i} + tau*x - T*(1-x) = {rhs_val:.2f}" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (5): Load linking + # y_j >= y_i + q_j - Q_j * (1 - x_{ij}), for i,j in I + # where Q_j = Q - q_j + # ========================================================================= + for i in I: + for j in I: + if i == j: + continue + x_ij = x.get((i, j), 0) + Q_j = Q - demand[j] + rhs_val = y.get(i, 0.0) + demand[j] - Q_j * (1 - x_ij) + lhs_val = y.get(j, 0.0) + # >= constraint: violation = rhs - lhs + violation_amount = rhs_val - lhs_val + if violation_amount > tol: + violated_constraints.add(5) + violations.append( + f"Constraint (5): Load linking violated for arc ({i},{j}): " + f"y_{j}={lhs_val:.2f} < y_{i} + q_{j} - Q_{j}*(1-x) = {rhs_val:.2f}" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (6): Vehicle capacity + # q_i <= y_i <= Q, for all i in I + # Two parts: (a) y_i >= q_i and (b) y_i <= Q + # ========================================================================= + for i in I: + y_i = y.get(i, 0.0) + # (a) y_i >= q_i + lhs_val_a = y_i + rhs_val_a = float(demand[i]) + violation_amount_a = rhs_val_a - lhs_val_a # >= constraint + if violation_amount_a > tol: + violated_constraints.add(6) + violations.append( + f"Constraint (6): Load at customer {i} too low: " + f"y_{i}={lhs_val_a:.2f} < q_{i}={rhs_val_a:.2f}" + ) + normalizer = max(abs(rhs_val_a), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs_val_a, + "rhs": rhs_val_a, + "raw_excess": violation_amount_a, + "normalizer": normalizer, + "ratio": violation_amount_a / normalizer, + }) + + # (b) y_i <= Q + lhs_val_b = y_i + rhs_val_b = float(Q) + violation_amount_b = lhs_val_b - rhs_val_b # <= constraint + if violation_amount_b > tol: + violated_constraints.add(6) + violations.append( + f"Constraint (6): Load at customer {i} exceeds capacity: " + f"y_{i}={lhs_val_b:.2f} > Q={rhs_val_b:.2f}" + ) + normalizer = max(abs(rhs_val_b), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs_val_b, + "rhs": rhs_val_b, + "raw_excess": violation_amount_b, + "normalizer": normalizer, + "ratio": violation_amount_b / normalizer, + }) + + # ========================================================================= + # Constraint (7): Time window + # a_i <= t_i <= b_i, for all i in I + # Two parts: (a) t_i >= a_i and (b) t_i <= b_i + # ========================================================================= + for i in I: + t_i = t.get(i, 0.0) + # (a) t_i >= a_i + lhs_val_a = t_i + rhs_val_a = float(ready[i]) + violation_amount_a = rhs_val_a - lhs_val_a # >= constraint + if violation_amount_a > tol: + violated_constraints.add(7) + violations.append( + f"Constraint (7): Departure time at customer {i} too early: " + f"t_{i}={lhs_val_a:.2f} < a_{i}={rhs_val_a:.2f}" + ) + normalizer = max(abs(rhs_val_a), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": lhs_val_a, + "rhs": rhs_val_a, + "raw_excess": violation_amount_a, + "normalizer": normalizer, + "ratio": violation_amount_a / normalizer, + }) + + # (b) t_i <= b_i + lhs_val_b = t_i + rhs_val_b = float(due[i]) + violation_amount_b = lhs_val_b - rhs_val_b # <= constraint + if violation_amount_b > tol: + violated_constraints.add(7) + violations.append( + f"Constraint (7): Departure time at customer {i} too late: " + f"t_{i}={lhs_val_b:.2f} > b_{i}={rhs_val_b:.2f}" + ) + normalizer = max(abs(rhs_val_b), eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": lhs_val_b, + "rhs": rhs_val_b, + "raw_excess": violation_amount_b, + "normalizer": normalizer, + "ratio": violation_amount_b / normalizer, + }) + + # ========================================================================= + # Constraint (8): Binary constraint + # x_{ij} in {0, 1}, for all i,j in I_0 + # ========================================================================= + for i in I0: + for j in I0: + if i == j: + continue + x_ij = x.get((i, j), 0) + if x_ij not in (0, 1): + violation_amount = min(abs(x_ij - 0), abs(x_ij - 1)) + if violation_amount > tol: + violated_constraints.add(8) + violations.append( + f"Constraint (8): x_{{{i},{j}}} = {x_ij} is not binary" + ) + normalizer = max(1.0, eps) + violation_magnitudes.append({ + "constraint": 8, + "lhs": float(x_ij), + "rhs": round(x_ij), + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint (9): Objective-consistency (Tier C anti-gaming) + # Recompute the VRPTW objective from the solution routes and compare to + # the reported objective_value. The math model defines the objective as + # min sum_{i=1..n} x_{0i} = number of vehicles dispatched from depot + # which equals the number of (0, j) arcs with j in I, i.e., the count + # of routes that actually leave the depot to visit a customer. + # Since the objective is an integer count, use tol=0.5 (any integer + # mismatch by >= 1 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(sum(x.get((0, j), 0) for j in I)) + abs_diff = abs(reported - true_obj) + obj_tol = 0.5 + if abs_diff > obj_tol: + violated_constraints.add(9) + violations.append( + f"Constraint (9): Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed sum_{{j in I}} x_{{0,j}}={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 9, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + # Bind serialized summary fields to the route witness. They are useful to + # consumers, but are not independent decisions and must not be accepted + # after being corrupted while the routes remain unchanged. + derived_num_vehicles = len(routes) + reported_num_vehicles = solution.get("num_vehicles") + if (isinstance(reported_num_vehicles, bool) + or not isinstance(reported_num_vehicles, (int, float)) + or abs(float(reported_num_vehicles) - derived_num_vehicles) > tol): + violated_constraints.add(9) + violations.append( + f"Constraint (9): num_vehicles={reported_num_vehicles!r} does not " + f"equal len(routes)={derived_num_vehicles}" + ) + violation_magnitudes.append({ + "constraint": 9, + "lhs": float(reported_num_vehicles) + if isinstance(reported_num_vehicles, (int, float)) + and not isinstance(reported_num_vehicles, bool) else 0.0, + "rhs": float(derived_num_vehicles), + "raw_excess": 1.0, + "normalizer": max(float(derived_num_vehicles), eps), + "ratio": 1.0 / max(float(derived_num_vehicles), eps), + }) + + derived_total_distance = round(sum( + float(raw_dist[route[pos]][route[pos + 1]]) + for route in routes + for pos in range(len(route) - 1) + ), 1) + reported_total_distance = solution.get("total_distance") + distance_ok = ( + not isinstance(reported_total_distance, bool) + and isinstance(reported_total_distance, (int, float)) + and abs(float(reported_total_distance) - derived_total_distance) <= 0.05 + ) + if not distance_ok: + violated_constraints.add(9) + violations.append( + f"Constraint (9): total_distance={reported_total_distance!r} does " + f"not equal the route-derived distance={derived_total_distance}" + ) + violation_magnitudes.append({ + "constraint": 9, + "lhs": float(reported_total_distance) + if isinstance(reported_total_distance, (int, float)) + and not isinstance(reported_total_distance, bool) else 0.0, + "rhs": float(derived_total_distance), + "raw_excess": abs(float(reported_total_distance) + - derived_total_distance) + if isinstance(reported_total_distance, (int, float)) + and not isinstance(reported_total_distance, bool) else 1.0, + "normalizer": max(abs(float(derived_total_distance)), eps), + "ratio": (abs(float(reported_total_distance) + - derived_total_distance) + / max(abs(float(derived_total_distance)), eps)) + if isinstance(reported_total_distance, (int, float)) + and not isinstance(reported_total_distance, bool) else 1.0, + }) + + # Build result + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for VRPTW (Bard et al. 2002)") + 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() + + data = 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(data, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"FEASIBLE - no constraints violated") + else: + print(f"INFEASIBLE - violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/bard2002/gurobi_code.py b/tasks/bard2002/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..67e1251377e6fa054cb929db69abe6f9d6e82a52 --- /dev/null +++ b/tasks/bard2002/gurobi_code.py @@ -0,0 +1,354 @@ +""" +Gurobi implementation of the VRPTW formulation from: +Bard, Kontoravdis, and Yu (2002), +"A Branch-and-Cut Procedure for the Vehicle Routing Problem with Time Windows", +Transportation Science, 36(2), 250-269. + +The model minimizes the number of vehicles (primary objective). +""" + +import argparse +import json +import math +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load a VRPTW instance from JSON.""" + with open(path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(instance_path, solution_path, time_limit): + data = load_instance(instance_path) + + depot = data["depot"] + customers = data["customers"] + n = len(customers) + Q = data["vehicle_capacity"] + + # Build node list: 0 = depot, 1..n = customers (using their original ids) + # Map customer id -> index in our arrays (1-based) + # We assume customers are listed in order with ids 1..n + nodes = [depot] + customers # index 0 = depot, 1..n = customers + num_nodes = n + 1 # 0..n + + # Extract coordinates, demands, time windows, service times + x_coord = [nodes[i]["x"] for i in range(num_nodes)] + y_coord = [nodes[i]["y"] for i in range(num_nodes)] + demand = [nodes[i]["demand"] for i in range(num_nodes)] + ready = [nodes[i]["ready_time"] for i in range(num_nodes)] + due = [nodes[i]["due_date"] for i in range(num_nodes)] + service = [nodes[i]["service_time"] for i in range(num_nodes)] + + # ------------------------------------------------------------------------- + # Use the distance matrix from the instance if provided, otherwise compute + # ------------------------------------------------------------------------- + if "distance_matrix" in data and data["distance_matrix"]: + raw_dist = data["distance_matrix"] + else: + # Compute Euclidean distances truncated to 1 decimal + raw_dist = [[0.0] * num_nodes for _ in range(num_nodes)] + for i in range(num_nodes): + for j in range(num_nodes): + if i != j: + d = math.sqrt((x_coord[i] - x_coord[j]) ** 2 + + (y_coord[i] - y_coord[j]) ** 2) + raw_dist[i][j] = math.floor(d * 10) / 10.0 + + # ------------------------------------------------------------------------- + # Preprocessing: compute travel times tau[i][j] + # Paper convention: + # 1) tau[i][j] = distance[i][j] (velocity = 1) + # 2) Fold service time into travel time: tau[i][j] += sigma_i + # 3) If (a_j - b_i) > tau[i][j], set tau[i][j] = a_j - b_i + # ------------------------------------------------------------------------- + # NOTE: The instance JSON may already indicate travel_time_includes_service_time. + # We check and only fold service time if needed. + fold_service = data.get("travel_time_includes_service_time", False) + + tau = [[0.0] * num_nodes for _ in range(num_nodes)] + for i in range(num_nodes): + for j in range(num_nodes): + if i == j: + tau[i][j] = 0.0 + continue + t = raw_dist[i][j] + # Fold in service time of node i (departure node) + if not fold_service: + t += service[i] + # If (a_j - b_i) > t, replace t + if (ready[j] - due[i]) > t: + t = ready[j] - due[i] + tau[i][j] = t + + # NOTE: When travel_time_includes_service_time is True, the distance_matrix + # already includes service time. The paper says tau_{ij} <- tau_{ij} + sigma_i. + # If the instance says it's already included, we skip that step. + # However, looking at the instance data, the distance matrix appears to be + # raw Euclidean distances (not including service time). Let's re-check: + # The flag says True but the distances look like raw Euclidean. + # ASSUMPTION: We trust the flag. If distances seem raw, we still respect the flag. + + # ------------------------------------------------------------------------- + # Determine infeasible arcs + # Arc (i,j) is infeasible if: + # - Visiting i then j violates time windows: a_i + tau[i][j] > b_j + # (earliest departure from i + travel time exceeds latest arrival at j) + # - Or capacity: demand[i] + demand[j] > Q (for i,j both customers) + # ------------------------------------------------------------------------- + I = list(range(1, num_nodes)) # customer indices 1..n + I0 = list(range(num_nodes)) # all nodes 0..n + + feasible_arc = [[False] * num_nodes for _ in range(num_nodes)] + for i in I0: + for j in I0: + if i == j: + continue + # Check time feasibility + # Earliest departure from i: ready[i] (+ service time if not folded) + earliest_dep_i = ready[i] + if not fold_service and i > 0: + earliest_dep_i += service[i] + # Actually, with service time folded into tau, departure from i at + # time ready[i] means arrival at j at ready[i] + tau[i][j]. + # For feasibility: ready[i] + tau[i][j] <= due[j] + # But we also need: the arrival time at j >= ready[j] (wait is ok) + # The binding constraint is: ready[i] + tau[i][j] <= due[j] + if ready[i] + tau[i][j] > due[j]: + continue + # Check capacity feasibility (only for customer-customer arcs) + if i > 0 and j > 0: + if demand[i] + demand[j] > Q: + continue + feasible_arc[i][j] = True + + # ------------------------------------------------------------------------- + # Build Gurobi model + # ------------------------------------------------------------------------- + model = gp.Model("VRPTW") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i][j]: binary, 1 if vehicle travels from i to j + x = {} + for i in I0: + for j in I0: + if i != j and feasible_arc[i][j]: + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + # t[i]: departure time from customer i (continuous) + t = {} + for i in I: + t[i] = model.addVar(lb=ready[i], ub=due[i], vtype=GRB.CONTINUOUS, + name=f"t_{i}") + + # y[i]: vehicle load at departure from customer i (continuous) + y = {} + for i in I: + y[i] = model.addVar(lb=demand[i], ub=Q, vtype=GRB.CONTINUOUS, + name=f"y_{i}") + + model.update() + + # ------------------------------------------------------------------------- + # Objective: minimize number of vehicles = sum of x[0][j] for j in I + # ------------------------------------------------------------------------- + model.setObjective( + gp.quicksum(x[0, j] for j in I if (0, j) in x), + GRB.MINIMIZE + ) + + # ------------------------------------------------------------------------- + # Constraint (2): Each customer served by exactly one vehicle + # sum_j x[i][j] = 1 for all i in I + # ------------------------------------------------------------------------- + for i in I: + model.addConstr( + gp.quicksum(x[i, j] for j in I0 if (i, j) in x) == 1, + name=f"serve_{i}" + ) + + # ------------------------------------------------------------------------- + # Constraint (3): Flow conservation + # sum_j x[i][j] - sum_j x[j][i] = 0 for all i in I_0 + # ------------------------------------------------------------------------- + for i in I0: + model.addConstr( + gp.quicksum(x[i, j] for j in I0 if (i, j) in x) - + gp.quicksum(x[j, i] for j in I0 if (j, i) in x) == 0, + name=f"flow_{i}" + ) + + # ------------------------------------------------------------------------- + # Constraint (4): Time linking constraints + # t[j] >= t[i] + tau[i][j] * x[i][j] - T[i][j] * (1 - x[i][j]) + # where T[i][j] = b_i - a_j + # For i, j in I (customers only) + # ------------------------------------------------------------------------- + for i in I: + for j in I: + if i != j and (i, j) in x: + T_ij = due[i] - ready[j] + model.addConstr( + t[j] >= t[i] + tau[i][j] * x[i, j] - T_ij * (1 - x[i, j]), + name=f"time_{i}_{j}" + ) + # NOTE: Constraint (4) with x_{ij}=0 reduces to t_j >= t_i - (b_i - a_j), + # which is always satisfied by variable bounds (t_i <= b_i, t_j >= a_j). + + # ------------------------------------------------------------------------- + # Constraint (5): Load linking constraints + # y[j] >= y[i] + q_j - Q_j * (1 - x[i][j]) + # where Q_j = Q - q_j + # For i, j in I (customers only) + # ------------------------------------------------------------------------- + for i in I: + for j in I: + if i != j: + Q_j = Q - demand[j] + if (i, j) in x: + model.addConstr( + y[j] >= y[i] + demand[j] - Q_j * (1 - x[i, j]), + name=f"load_{i}_{j}" + ) + else: + # Arc excluded (x_{ij}=0): constraint becomes y_j >= y_i + q_j - Q_j + model.addConstr( + y[j] >= y[i] + demand[j] - Q_j, + name=f"load_{i}_{j}" + ) + + # ------------------------------------------------------------------------- + # Constraints (6) and (7) are handled by variable bounds: + # q_i <= y_i <= Q (set as lb/ub on y[i]) + # a_i <= t_i <= b_i (set as lb/ub on t[i]) + # ------------------------------------------------------------------------- + + # ------------------------------------------------------------------------- + # Solve + # ------------------------------------------------------------------------- + model.optimize() + + # ------------------------------------------------------------------------- + # Extract solution + # ------------------------------------------------------------------------- + result = {} + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + result["status"] = model.Status + result["status_description"] = { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + }.get(model.Status, f"STATUS_{model.Status}") + + # Extract routes + routes = [] + # Find all arcs leaving the depot + depot_successors = [] + for j in I: + if (0, j) in x and x[0, j].X > 0.5: + depot_successors.append(j) + + for start in depot_successors: + route = [0, start] + current = start + while current != 0: + next_node = None + for j in I0: + if (current, j) in x and x[current, j].X > 0.5: + next_node = j + break + if next_node is None or next_node == 0: + route.append(0) + break + route.append(next_node) + current = next_node + routes.append(route) + + result["num_vehicles"] = len(routes) + result["routes"] = routes + + # Compute total distance + total_dist = 0.0 + for i_node in I0: + for j_node in I0: + if (i_node, j_node) in x and x[i_node, j_node].X > 0.5: + total_dist += raw_dist[i_node][j_node] + result["total_distance"] = round(total_dist, 1) + + # Extract departure times and loads + departure_times = {} + loads = {} + for i in I: + departure_times[str(i)] = round(t[i].X, 2) + loads[str(i)] = round(y[i].X, 2) + result["departure_times"] = departure_times + result["loads"] = loads + + else: + result["objective_value"] = None + result["status"] = model.Status + result["status_description"] = "NO_SOLUTION_FOUND" + result["num_vehicles"] = None + result["routes"] = [] + + # Add solver info + result["solver"] = "Gurobi" + result["time_limit"] = time_limit + if hasattr(model, "Runtime"): + result["runtime_seconds"] = round(model.Runtime, 2) + if hasattr(model, "MIPGap") and model.SolCount > 0: + result["mip_gap"] = round(model.MIPGap, 6) + + # Write solution + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {solution_path}") + print(f"Objective value: {result['objective_value']}") + if result.get("num_vehicles") is not None: + print(f"Number of vehicles: {result['num_vehicles']}") + print(f"Total distance: {result.get('total_distance')}") + return result + + +def main(): + parser = argparse.ArgumentParser( + description="VRPTW Gurobi solver (Bard et al. 2002 formulation)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + build_and_solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/bard2002/gurobi_feasi_result/large_feasi_result_1.json b/tasks/bard2002/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bard2002/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/bard2002/gurobi_feasi_result/large_feasi_result_2.json b/tasks/bard2002/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bard2002/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/bard2002/gurobi_feasi_result/large_feasi_result_3.json b/tasks/bard2002/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bard2002/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/bard2002/gurobi_feasi_result/large_feasi_result_4.json b/tasks/bard2002/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bard2002/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/bard2002/gurobi_feasi_result/large_feasi_result_5.json b/tasks/bard2002/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bard2002/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/bard2002/gurobi_feasi_result/tiny_feasi_result.json b/tasks/bard2002/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bard2002/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/bard2002/gurobi_solution/large_solution_1.json b/tasks/bard2002/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..fd22b7cbf488ad4a50e167cb16e643ebb841ff95 --- /dev/null +++ b/tasks/bard2002/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8ee7cfdf31245bbba7077c799951054c4c4533267f08192f9371f7e8c81b404 +size 5193 diff --git a/tasks/bard2002/gurobi_solution/large_solution_2.json b/tasks/bard2002/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..2a0b03ba24986ab084c28555f244aa7b11cf17f4 --- /dev/null +++ b/tasks/bard2002/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:909b544c10e661b7a12acba8526587c69112114ab2f91eb8d1b75d21ef22a6e6 +size 5238 diff --git a/tasks/bard2002/gurobi_solution/large_solution_3.json b/tasks/bard2002/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6c2f72355756b37154934745bd991bd39259defe --- /dev/null +++ b/tasks/bard2002/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51a7f35e0e8c27a51b16f23382e715364a2c5e0b63a53cd5030d3f9d3976e46e +size 7405 diff --git a/tasks/bard2002/gurobi_solution/large_solution_4.json b/tasks/bard2002/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..117f8c28291c527e95934ef66cdf8ef6d13693e9 --- /dev/null +++ b/tasks/bard2002/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:351ed74e1b9386b83e823f1bcb6f5e803bf8b176453b45e413dd6a06b85fa650 +size 4888 diff --git a/tasks/bard2002/gurobi_solution/large_solution_5.json b/tasks/bard2002/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d8c1fb4847ab401321999d04b5dbd16c035ccfe8 --- /dev/null +++ b/tasks/bard2002/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ea8cf57aa0b6e0e99d0262cfa3ec3b44ac6c147ebf1928277780c1c52ea3d2a +size 4878 diff --git a/tasks/bard2002/gurobi_solution/tiny_solution.json b/tasks/bard2002/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..12800fb3d1048818302759fb3d6d47a8ea73b57f --- /dev/null +++ b/tasks/bard2002/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af5b10caae72680a452dc27aafb25a9e227f6dfc02af824b2b56188c54c99e79 +size 997 diff --git a/tasks/bard2002/gurobi_solution_log/large_log_1.jsonl b/tasks/bard2002/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cf07da496301b7986b39bea01481de57e5064125 --- /dev/null +++ b/tasks/bard2002/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:671f7a0f2d0bfaccfddc33ea6c0df2815db69e0998c78fa69d1e09401b423bfb +size 325 diff --git a/tasks/bard2002/gurobi_solution_log/large_log_2.jsonl b/tasks/bard2002/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..48217a0713429b6ed40fdea6e801ca87cb7c519c --- /dev/null +++ b/tasks/bard2002/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8bd8317326e20c07151ef21dcd8fea82acf0a3654704c6899f39452618ecf48 +size 333 diff --git a/tasks/bard2002/gurobi_solution_log/large_log_3.jsonl b/tasks/bard2002/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4db2d83e0bba8496b22d1ec5733042062b500164 --- /dev/null +++ b/tasks/bard2002/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77a5f4a3ca1d4d6751a67982dc285528cb08d84470062d8a0ef7615b62116cc9 +size 458 diff --git a/tasks/bard2002/gurobi_solution_log/large_log_4.jsonl b/tasks/bard2002/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..55b6203eed7f37d5313f8f79cdbb94bc3d695f25 --- /dev/null +++ b/tasks/bard2002/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35002aa9fef11eff9ba162f67d7a488354b555a91b813b7bb7e98530f7c36535 +size 449 diff --git a/tasks/bard2002/gurobi_solution_log/large_log_5.jsonl b/tasks/bard2002/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7e39397d7bae878c08719e9edc4d0d116503f4ab --- /dev/null +++ b/tasks/bard2002/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e28400bda1cbcc1ae4661b6d9c9f30e5bb1934f4dc9deaf89bf138386f098d06 +size 452 diff --git a/tasks/bard2002/gurobi_solution_log/tiny_log.jsonl b/tasks/bard2002/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..909faa1988fad48b30205032688e580af7c586ce --- /dev/null +++ b/tasks/bard2002/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e8b6940cfbda80cf95154542e831b28e27912f203367db89d1e87d2e98c2721 +size 41 diff --git a/tasks/bard2002/instance/large_instance_1.json b/tasks/bard2002/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c9e61054c5f24c28190b1478f9d3c85216b06406 --- /dev/null +++ b/tasks/bard2002/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be7064b9b4a5b5e28fc218766f1c24445d12cff997546c455fb72b4de2f56195 +size 150544 diff --git a/tasks/bard2002/instance/large_instance_2.json b/tasks/bard2002/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ab1a6213bc76c4a77bb1527505d8543a619097dc --- /dev/null +++ b/tasks/bard2002/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:072502888bee5c1695a772e816115f2c47f90955aed1d5b9ed48bc473cf9a296 +size 139636 diff --git a/tasks/bard2002/instance/large_instance_3.json b/tasks/bard2002/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..da3372f8a7ee0ff21cbdd83e6c40fa97f73e2abd --- /dev/null +++ b/tasks/bard2002/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:375b677d111c76069d96ddcdb6f51c5419726ca82f10f866e4497f0c00af2efb +size 138638 diff --git a/tasks/bard2002/instance/large_instance_4.json b/tasks/bard2002/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c8ba36831532fd4ca2560f0e860dd2f320fcab35 --- /dev/null +++ b/tasks/bard2002/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02f7d674224baed36314a2a00f11c8bce8c90da944419336a771e66924798611 +size 139630 diff --git a/tasks/bard2002/instance/large_instance_5.json b/tasks/bard2002/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..119ebb8d95e53201d89810ec8f9a11e01311ce77 --- /dev/null +++ b/tasks/bard2002/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7506c751f41af308d8420a0004ee8d694c85c2ae7f3df4167d3238b4d3ff7709 +size 139309 diff --git a/tasks/bard2002/instance/tiny_instance.json b/tasks/bard2002/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..7d64044e480d3f6efcd7d90a7cc4674e6e7ca577 --- /dev/null +++ b/tasks/bard2002/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4a86684bd05b2fc101bdbdacb10cea632480fb47752538f2c52e94c041d203f +size 6563 diff --git a/tasks/bard2002/instance_schema.json b/tasks/bard2002/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..81b11b3335b947a1f9711c9fa0c8841919e555de --- /dev/null +++ b/tasks/bard2002/instance_schema.json @@ -0,0 +1,29 @@ +{ + "num_customers": " Number of customers to be visited.", + "vehicle_capacity": " Maximum total demand that a single vehicle can carry on one route.", + "depot": { + "id": " Identifier for the depot node.", + "x": " Horizontal coordinate of the depot on the Euclidean grid.", + "y": " Vertical coordinate of the depot on the Euclidean grid.", + "demand": " Goods to be collected at the depot (always zero).", + "ready_time": " Earliest time a vehicle may depart from the depot.", + "due_date": " Latest time by which all vehicles must return to the depot.", + "service_time": " Time spent servicing at the depot (always zero)." + }, + "customers": [ + { + "id": " Unique identifier for the customer, numbered 1 through num_customers.", + "x": " Horizontal coordinate of the customer on the Euclidean grid.", + "y": " Vertical coordinate of the customer on the Euclidean grid.", + "demand": " Quantity of goods to be collected from this customer.", + "ready_time": " Earliest time at which a vehicle may depart from this customer.", + "due_date": " Latest time by which a vehicle must depart from this customer.", + "service_time": " Time a vehicle spends serving this customer before it can depart." + } + ], + "distance_matrix": " Euclidean distance between each pair of locations, where row/column 0 is the depot and rows/columns 1 through num_customers correspond to customers.", + "scheduling_horizon": " End of the planning period within which all routes must be completed.", + "travel_time_includes_service_time": " Whether the distance matrix already incorporates each customer's service time into outbound travel times.", + "primary_objective": " The first-priority goal for the optimization.", + "secondary_objective": " The second-priority goal for the optimization, applied as a tiebreaker." +} \ No newline at end of file diff --git a/tasks/bard2002/mathematical_formulation.md b/tasks/bard2002/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..9292c4e56161fa9044cfba70a48a0f385a2350d9 --- /dev/null +++ b/tasks/bard2002/mathematical_formulation.md @@ -0,0 +1,41 @@ +# Original Formulation: Vehicle Routing Problem with Time Windows (VRPTW) + +*Source: “A Branch-and-Cut Procedure for the Vehicle Routing Problem with Time Windows,” Bard, Kontoravdis, and Yu, Transportation Science 36(2):250–269, 2002.* + +## Sets and Parameters + +- $I = \{1,\ldots,n\}$: set of customers; $I_0 = I \cup \{0\}$ includes the depot $0$. + +- $G_0 = (V, E)$: connected graph with $V = I_0$. + +- $q_i > 0$, $\sigma_i \ge 0$, $[a_i, b_i]$: demand, service time, and time window for customer $i \in I$. + +- $Q$: vehicle capacity; $\tau_{ij}$: travel time between nodes $i,j \in I_0$ (service time $\sigma_i$ folded in; if $a_j - b_i > \tau_{ij}$, replace $\tau_{ij}$ by $a_j - b_i$). + +- Derived: $T_{ij} = b_i - a_j$; $Q_j = Q - q_j$. + +## Decision Variables + +- $x_{ij} \in \{0,1\}$ for $i,j \in I_0$: $1$ if a vehicle traverses arc $(i,j)$. + +- $t_i \in \mathbb{R}$ for $i \in I$: departure time from customer $i$. + +- $y_i \in \mathbb{R}$ for $i \in I$: accumulated vehicle load at departure from customer $i$. + +## Objective + +$$\begin{equation} +(\text{VRPTW}) \quad \min \sum_{i=1}^{n} x_{0i} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{j \in I_0} x_{ij} &= 1, & i \in I \tag{2} \\ +\sum_{j \in I_0} x_{ij} - \sum_{j \in I_0} x_{ji} &= 0, & i \in I_0 \tag{3} \\ +t_j &\ge t_i + \tau_{ij} x_{ij} - T_{ij}(1 - x_{ij}), & i,j \in I \tag{4} \\ +y_j &\ge y_i + q_j - Q_j(1 - x_{ij}), & i,j \in I \tag{5} \\ +q_i \le y_i &\le Q, & i \in I \tag{6} \\ +a_i \le t_i &\le b_i, & i \in I \tag{7} \\ +x_{ij} &\in \{0,1\}, & i,j \in I_0 \tag{8} +\end{align}$$ diff --git a/tasks/bard2002/problem_description.txt b/tasks/bard2002/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5afc37421cd99ccdeae6049010b3b29a7dea8aa --- /dev/null +++ b/tasks/bard2002/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A fleet of identical vehicles, all based at a single depot, must pick up goods from a set of customers. Each customer has a known positive demand, a known service time, and a time window defined by an earliest ready time and a latest due date. The depot has coordinates, a scheduling horizon, and zero demand and service time. Every pair of locations (including the depot) has a known travel time, which equals the Euclidean distance between them truncated to one decimal digit; vehicle speed is one, so travel time and distance are interchangeable. Service time at each customer is folded into the outbound travel times from that customer: the effective travel time from any customer to any other location equals the base travel time plus the service time at the origin customer. Furthermore, if the difference between the destination's ready time and the origin customer's due date exceeds this adjusted travel time, the effective travel time is replaced by that difference. The resulting travel times satisfy the triangle inequality. + +The goal is to determine a set of routes, each starting and ending at the depot, that collectively visit every customer exactly once, while using the fewest vehicles possible. Each route is a sequence of customers served by a single vehicle. The accumulated load picked up along any route must never exceed the vehicle capacity. A vehicle departing from a customer must do so no earlier than that customer's ready time and no later than that customer's due date. When a vehicle travels directly from one customer to another, its departure time at the second customer must be at least as large as its departure time at the first customer plus the effective travel time between them. The accumulated load aboard a vehicle when it departs a customer must be at least as large as that customer's demand and must also be at least as large as the accumulated load at the preceding customer on the route plus the current customer's demand. Arcs between pairs of customers that are infeasible due to time window or capacity incompatibility are excluded in advance. + +The primary quantity to be minimized is the number of vehicles dispatched from the depot, which equals the number of routes used. diff --git a/tasks/bard2002/solution_logger.py b/tasks/bard2002/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/bard2002/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/bard2002/solution_schema.json b/tasks/bard2002/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e50bc083cbf3e7b6bb6847c7be857113b517501f --- /dev/null +++ b/tasks/bard2002/solution_schema.json @@ -0,0 +1,8 @@ +{ + "objective_value": " Number of vehicles used, which is the primary quantity being minimized.", + "num_vehicles": " Number of vehicle routes dispatched from the depot.", + "routes": " Ordered sequence of node identifiers visited on each route, starting and ending at the depot (node 0).", + "total_distance": " Sum of Euclidean distances traveled across all routes.", + "departure_times": " Time at which the vehicle departs from each customer.", + "loads": " Cumulative demand aboard the vehicle when it departs from each customer." +} \ No newline at end of file diff --git a/tasks/barnhart2000/feasibility_check.py b/tasks/barnhart2000/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..300d9deb4d0b23f0c80e8a9aa6e8e124cdf6c990 --- /dev/null +++ b/tasks/barnhart2000/feasibility_check.py @@ -0,0 +1,567 @@ +""" +Feasibility Checker for the Origin-Destination Integer Multicommodity Flow (ODIMCF) Problem. + +Checks candidate solutions against the mathematical formulation from: +Barnhart, Hane, and Vance (2000), Operations Research 48(2), 318-326. + +Hard constraints checked (Formulation 1 — Node-Arc): + Constraint (2): Capacity constraints on arcs + Constraint (3): Flow conservation at each node for each commodity + Constraint (4): Binary (integrality) domain for arc-flow variables + Constraint (5): Objective consistency — reported objective_value must equal the + value recomputed from the routing decisions present in the + solution: sum over commodities of either (artificial_arc_cost * + demand) when rejected, else sum_{ij in path_arcs}(cost[ij] * demand). +""" + +import argparse +import json +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('commodities', '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_data, solution_data): + """ + Check all hard constraints of the ODIMCF formulation. + + Returns a dict with feasibility results. + """ + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_constraints_set = set() + + # ---- Parse instance ---- + nodes = instance_data["network"]["nodes"] + num_nodes = instance_data["network"]["num_nodes"] + arcs = instance_data["network"]["arcs"] + num_arcs = instance_data["network"]["num_arcs"] + commodities = instance_data["commodities"]["commodity_list"] + num_commodities = instance_data["commodities"]["num_commodities"] + + # Build arc lookup: arc_id -> arc info + arc_by_id = {} + for arc in arcs: + arc_by_id[arc["arc_id"]] = arc + + # Build adjacency info for arc validation + arc_set = set() + for arc in arcs: + arc_set.add((arc["from_node"], arc["to_node"], arc["arc_id"])) + + # ---- Parse solution ---- + sol_commodities = solution_data.get("commodities", []) + + # Handle infeasible/empty solutions + if not sol_commodities: + # No commodities in solution — check if this is a "no solution" marker + status = solution_data.get("status", "") + if status == "no_feasible_solution": + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Solution status is 'no_feasible_solution': no candidate to check."], + "violation_magnitudes": [] + } + # Empty commodities but not explicitly marked — treat as missing all assignments + # This violates constraint (3) for every commodity + for comm in commodities: + k = comm["commodity_id"] + origin = comm["origin"] + violated_constraints_set.add(3) + violations.append( + f"Commodity {k}: no assignment found in solution (flow conservation violated at origin {origin})" + ) + rhs_val = 1.0 + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": 0.0, + "rhs": rhs_val, + "raw_excess": abs(rhs_val), + "normalizer": normalizer, + "ratio": abs(rhs_val) / normalizer + }) + return { + "feasible": False, + "violated_constraints": sorted(violated_constraints_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + # Build commodity lookup from solution + sol_comm_by_id = {} + for sc in sol_commodities: + sol_comm_by_id[sc["commodity_id"]] = sc + + # ---- Reconstruct arc-flow variables x^k_{ij} ---- + # x^k_{ij} = 1 if commodity k uses arc ij (not rejected), 0 otherwise + # For the path-based solution, commodity k uses the arcs in its path_arcs list + x = defaultdict(lambda: defaultdict(float)) # x[k][arc_id] = 0 or 1 + + for comm in commodities: + k = comm["commodity_id"] + sc = sol_comm_by_id.get(k) + if sc is None: + continue + if sc.get("rejected", False): + # Commodity rejected (uses artificial arc) — no real arcs used + continue + for arc_entry in sc.get("path_arcs", []): + aid = arc_entry["arc_id"] + x[k][aid] = 1.0 + + # ==================================================================== + # Constraint (4): Binary variable domain + # x^k_{ij} in {0, 1} for all ij in A, for all k in K + # + # In the path-based solution encoding, each commodity is either rejected + # or assigned exactly one path with binary arc usage. We check: + # (a) Each x^k_{ij} value is 0 or 1 + # (b) Each commodity has exactly one assignment (one path or rejected) + # (c) Arc IDs referenced in the solution are valid arcs in the instance + # ==================================================================== + for comm in commodities: + k = comm["commodity_id"] + sc = sol_comm_by_id.get(k) + if sc is None: + # Commodity missing from solution entirely — this is an assignment issue + # Treated under constraint (3) flow conservation + continue + + rejected = sc.get("rejected", False) + path_arcs = sc.get("path_arcs", []) + + # Check: commodity must be either rejected or have a non-empty path + if not rejected and len(path_arcs) == 0: + violated_constraints_set.add(4) + violations.append( + f"Commodity {k}: neither rejected nor assigned a path " + f"(binary/assignment constraint violated)" + ) + # violation_amount: should be 1 path assigned, have 0 + rhs_val = 1.0 + violation_magnitudes.append({ + "constraint": 4, + "lhs": 0.0, + "rhs": rhs_val, + "raw_excess": 1.0, + "normalizer": max(abs(rhs_val), eps), + "ratio": 1.0 / max(abs(rhs_val), eps) + }) + + # Check arc validity: every arc referenced must exist in the instance + for arc_entry in path_arcs: + aid = arc_entry["arc_id"] + if aid not in arc_by_id: + violated_constraints_set.add(4) + violations.append( + f"Commodity {k}: references non-existent arc_id {aid}" + ) + rhs_val = 1.0 + violation_magnitudes.append({ + "constraint": 4, + "lhs": 0.0, + "rhs": rhs_val, + "raw_excess": 1.0, + "normalizer": max(abs(rhs_val), eps), + "ratio": 1.0 / max(abs(rhs_val), eps) + }) + + # ==================================================================== + # Constraint (2): Capacity constraints + # sum_{k in K} q^k * x^k_{ij} <= d_{ij}, for all ij in A + # ==================================================================== + for arc in arcs: + aid = arc["arc_id"] + capacity = arc["capacity"] + from_node = arc["from_node"] + to_node = arc["to_node"] + + # Compute LHS: sum of demands of commodities using this arc + lhs = 0.0 + for comm in commodities: + k = comm["commodity_id"] + demand = comm["demand"] + lhs += demand * x[k][aid] + + rhs_val = float(capacity) + violation_amount = lhs - rhs_val # For <= constraint + + if violation_amount > tol: + violated_constraints_set.add(2) + violations.append( + f"Arc {aid} ({from_node}->{to_node}): capacity exceeded, " + f"flow={lhs:.4f} > capacity={rhs_val:.4f}" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # ==================================================================== + # Constraint (3): Flow conservation + # sum_{ij in A} x^k_{ij} - sum_{ji in A} x^k_{ji} = b^k_i, + # for all i in N, for all k in K + # where b^k_i = 1 if i is origin of k, -1 if destination, 0 otherwise + # + # For rejected commodities (using the artificial arc from origin to + # destination), the flow on real arcs is 0. The artificial arc provides + # the unit flow, so net flow at origin = 1 (via artificial), at + # destination = -1. Since artificial arcs are not in the network arc set, + # for rejected commodities: all b^k_i checks with real arcs yield + # net flow = 0 at every node. This is consistent because the artificial + # arc is outside the real network — the model accounts for it separately. + # + # We check flow conservation on real arcs only for non-rejected + # commodities. For rejected commodities, real-arc flow must be 0 at all + # nodes (which is trivially satisfied since they have no path_arcs). + # ==================================================================== + # Build outgoing and incoming arc lookups + outgoing_arcs = defaultdict(list) # node -> [arc_id, ...] + incoming_arcs = defaultdict(list) # node -> [arc_id, ...] + for arc in arcs: + outgoing_arcs[arc["from_node"]].append(arc["arc_id"]) + incoming_arcs[arc["to_node"]].append(arc["arc_id"]) + + for comm in commodities: + k = comm["commodity_id"] + origin = comm["origin"] + destination = comm["destination"] + + sc = sol_comm_by_id.get(k) + if sc is None: + # Commodity missing — violated at origin node + violated_constraints_set.add(3) + violations.append( + f"Commodity {k}: missing from solution " + f"(flow conservation violated)" + ) + rhs_val = 1.0 + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": 0.0, + "rhs": rhs_val, + "raw_excess": 1.0, + "normalizer": normalizer, + "ratio": 1.0 / normalizer + }) + continue + + rejected = sc.get("rejected", False) + + if rejected: + # For rejected commodity, all real arc flows should be 0. + # This is trivially satisfied if path_arcs is empty. + # But check anyway in case solution has path_arcs AND rejected=true + if sc.get("path_arcs", []): + violated_constraints_set.add(3) + violations.append( + f"Commodity {k}: marked as rejected but has path_arcs " + f"(flow conservation inconsistency)" + ) + rhs_val = 0.0 + flow_sum = float(len(sc["path_arcs"])) + violation_amount = abs(flow_sum) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": flow_sum, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + continue + + # Non-rejected commodity: check flow conservation at every node + for node in nodes: + # b^k_i + if node == origin: + b_ki = 1.0 + elif node == destination: + b_ki = -1.0 + else: + b_ki = 0.0 + + # sum of x^k_{ij} for arcs leaving node i + out_flow = 0.0 + for aid in outgoing_arcs[node]: + out_flow += x[k][aid] + + # sum of x^k_{ji} for arcs entering node i + in_flow = 0.0 + for aid in incoming_arcs[node]: + in_flow += x[k][aid] + + lhs = out_flow - in_flow + rhs_val = b_ki + violation_amount = abs(lhs - rhs_val) + + if violation_amount > tol: + violated_constraints_set.add(3) + violations.append( + f"Commodity {k} at node {node}: flow conservation violated, " + f"net_flow={lhs:.4f}, expected={rhs_val:.4f}" + ) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # ==================================================================== + # Constraint (5): Objective consistency (Tier C defense vs score-gaming) + # reported objective_value must equal the value recomputed directly + # from the routing variables in the solution: + # true_obj = sum_{rejected k} (artificial_arc_cost[k] * demand[k]) + # + sum_{non-rejected k} sum_{ij in path_arcs[k]} (cost[ij] * demand[k]) + # All obj-determining variables (rejected flag + path_arcs) are in the + # solution, so a full recompute is exact. + # ==================================================================== + reported_obj_raw = solution_data.get("objective_value") + if reported_obj_raw is not None: + try: + reported = float(reported_obj_raw) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + comm_by_id = {c["commodity_id"]: c for c in commodities} + for comm in commodities: + k = comm["commodity_id"] + demand = comm["demand"] + sc = sol_comm_by_id.get(k) + if sc is None: + continue + if sc.get("rejected", False): + true_obj += float(comm["artificial_arc_cost"]) * float(demand) + else: + for arc_entry in sc.get("path_arcs", []): + aid = arc_entry["arc_id"] + arc = arc_by_id.get(aid) + if arc is None: + # already flagged under constraint (4); skip + continue + true_obj += float(arc["cost"]) * float(demand) + + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints_set.add(5) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed total cost=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 5, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer + }) + + # ---- Assemble result ---- + feasible = len(violated_constraints_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for ODIMCF (Barnhart et al. 2000)" + ) + 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_data = json.load(f) + + with open(args.solution_path, "r") as f: + solution_data = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution_data) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance_data, solution_data) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"FEASIBLE: No constraint violations found.") + else: + print(f"INFEASIBLE: {len(result['violated_constraints'])} constraint(s) violated.") + 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/barnhart2000/gurobi_code.py b/tasks/barnhart2000/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..65a76f547c52d639f2ab69e2b6dc0c3e072ab95c --- /dev/null +++ b/tasks/barnhart2000/gurobi_code.py @@ -0,0 +1,213 @@ +""" +Gurobi implementation of the Origin-Destination Integer Multicommodity Flow (ODIMCF) problem. + +Based on: Barnhart, Hane, and Vance (2000), "Using Branch-and-Price-and-Cut to Solve +Origin-Destination Integer Multicommodity Flow Problems", Operations Research 48(2), 318-326. + +This implements the Node-Arc (Formulation 1) from the paper: + min sum_{k in K} sum_{ij in A} c^k_{ij} * q^k * x^k_{ij} + s.t. sum_{k in K} q^k * x^k_{ij} <= d_{ij}, for all ij in A (capacity) + sum_{ij} x^k_{ij} - sum_{ji} x^k_{ji} = b^k_i, for all i, k (flow conservation) + x^k_{ij} in {0,1} (binary) + +Each commodity has an artificial arc from origin to destination with cost = revenue, +representing rejection. Original arcs have cost 0. +""" + +import argparse +import json +import os +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load the problem instance from a JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(data, time_limit): + """Build and solve the ODIMCF model using Gurobi.""" + + nodes = data["network"]["nodes"] + arcs = data["network"]["arcs"] + commodities = data["commodities"]["commodity_list"] + + num_nodes = data["network"]["num_nodes"] + num_arcs = data["network"]["num_arcs"] + num_commodities = data["commodities"]["num_commodities"] + + # Build adjacency: arc index -> (from, to, capacity, cost) + arc_list = [] + for arc in arcs: + arc_list.append((arc["from_node"], arc["to_node"], arc["capacity"], arc["cost"])) + + model = gp.Model("ODIMCF") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # --- Decision Variables --- + # x[k][a] = 1 if commodity k uses arc a (original arcs) + x = {} + for k_idx, comm in enumerate(commodities): + for a_idx, (i, j, cap, cost) in enumerate(arc_list): + x[k_idx, a_idx] = model.addVar( + vtype=GRB.BINARY, + name=f"x_{k_idx}_{a_idx}", + obj=cost * comm["demand"] # c^k_{ij} * q^k + ) + + # x_art[k] = 1 if commodity k is rejected (uses artificial arc) + x_art = {} + for k_idx, comm in enumerate(commodities): + x_art[k_idx] = model.addVar( + vtype=GRB.BINARY, + name=f"x_art_{k_idx}", + obj=comm["artificial_arc_cost"] * comm["demand"] # revenue * q^k + ) + + model.update() + + # --- Capacity Constraints --- + # sum_{k in K} q^k * x^k_{ij} <= d_{ij}, for all ij in A + for a_idx, (i, j, cap, cost) in enumerate(arc_list): + model.addConstr( + gp.quicksum( + commodities[k_idx]["demand"] * x[k_idx, a_idx] + for k_idx in range(num_commodities) + ) <= cap, + name=f"cap_{a_idx}" + ) + + # --- Flow Conservation Constraints --- + # For each commodity k, for each node i: + # sum_{ij in A} x^k_{ij} - sum_{ji in A} x^k_{ji} = b^k_i + # The artificial arc goes from origin to destination directly. + for k_idx, comm in enumerate(commodities): + origin = comm["origin"] + destination = comm["destination"] + for node in nodes: + # Compute b^k_i + if node == origin: + b_ki = 1 + elif node == destination: + b_ki = -1 + else: + b_ki = 0 + + # Outflow: arcs leaving node (including artificial if node == origin) + outflow = gp.quicksum( + x[k_idx, a_idx] + for a_idx, (i, j, cap, cost) in enumerate(arc_list) + if i == node + ) + if node == origin: + outflow += x_art[k_idx] + + # Inflow: arcs entering node (including artificial if node == destination) + inflow = gp.quicksum( + x[k_idx, a_idx] + for a_idx, (i, j, cap, cost) in enumerate(arc_list) + if j == node + ) + if node == destination: + inflow += x_art[k_idx] + + model.addConstr( + outflow - inflow == b_ki, + name=f"flow_{k_idx}_{node}" + ) + + # --- Optimize --- + model.optimize() + + # --- Extract Solution --- + solution = { + "objective_value": None, + "status": None, + "commodities": [] + } + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + for k_idx, comm in enumerate(commodities): + comm_sol = { + "commodity_id": comm["commodity_id"], + "origin": comm["origin"], + "destination": comm["destination"], + "demand": comm["demand"], + "rejected": False, + "path_arcs": [] + } + + if x_art[k_idx].X > 0.5: + comm_sol["rejected"] = True + else: + for a_idx, (i, j, cap, cost) in enumerate(arc_list): + if x[k_idx, a_idx].X > 0.5: + comm_sol["path_arcs"].append({"from": i, "to": j, "arc_id": a_idx}) + + solution["commodities"].append(comm_sol) + + # Compute gap + if model.Status == GRB.OPTIMAL: + solution["gap"] = 0.0 + else: + solution["gap"] = model.MIPGap + else: + solution["objective_value"] = None + solution["status"] = "infeasible_or_no_solution" + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Solve ODIMCF using Gurobi (Node-Arc formulation)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, 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) + + data = load_instance(args.instance_path) + solution = build_and_solve(data, 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) + + print(f"Solution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']}") + print(f"Status: {solution['status']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/barnhart2000/gurobi_feasi_result/large_feasi_result_1.json b/tasks/barnhart2000/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/barnhart2000/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/barnhart2000/gurobi_feasi_result/large_feasi_result_2.json b/tasks/barnhart2000/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/barnhart2000/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/barnhart2000/gurobi_feasi_result/large_feasi_result_3.json b/tasks/barnhart2000/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/barnhart2000/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/barnhart2000/gurobi_feasi_result/large_feasi_result_4.json b/tasks/barnhart2000/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/barnhart2000/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/barnhart2000/gurobi_feasi_result/large_feasi_result_5.json b/tasks/barnhart2000/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/barnhart2000/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/barnhart2000/gurobi_feasi_result/tiny_feasi_result.json b/tasks/barnhart2000/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/barnhart2000/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/barnhart2000/gurobi_solution/large_solution_1.json b/tasks/barnhart2000/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c10292c855f1f79e0201a856345d41af7829d922 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d50f0e85899371e46e7b524f4d84ef57820418347b78740368155bf76b9c3e2 +size 117723 diff --git a/tasks/barnhart2000/gurobi_solution/large_solution_2.json b/tasks/barnhart2000/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c1209670ef09aec4e93dc6ab648e12e4ce4e5f46 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d669fd6b5335d39091240f7920845fb639dceda19db5b56aa9324d1908422ff +size 115186 diff --git a/tasks/barnhart2000/gurobi_solution/large_solution_3.json b/tasks/barnhart2000/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..bb92891abdc6975ac585c92ed72718401ba94893 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71668234d89d5726c746395cbb04f30d857769f68f43372066ecc9b529b6903b +size 115096 diff --git a/tasks/barnhart2000/gurobi_solution/large_solution_4.json b/tasks/barnhart2000/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..eb6569ac69eac46ea078bb0223b69ba0bd8a185a --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f73140f3edbf7b4cc04e1168431a87185e4c86a8f827e1a4b18135302c93afaa +size 110202 diff --git a/tasks/barnhart2000/gurobi_solution/large_solution_5.json b/tasks/barnhart2000/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..6484c114f415420ea25ab7cf7c15f0b5443d9703 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98832262522a0ffdac34fb5968555e0eef3676d0890c73968ce1d9876dfc11d8 +size 115944 diff --git a/tasks/barnhart2000/gurobi_solution/tiny_solution.json b/tasks/barnhart2000/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..5232349040b59437aa3b2818a29da17a453de768 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4415adba2ae629167e33b8e52d69f6beef30a1eda061a96a58136278043d15a3 +size 5820 diff --git a/tasks/barnhart2000/gurobi_solution_log/large_log_1.jsonl b/tasks/barnhart2000/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c3cbc3fadfda6beb8083871880d99b905526eae3 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed30bce318f958c6590b637807fb2ef9f7514b262cb9928115468024ca8025ba +size 1015 diff --git a/tasks/barnhart2000/gurobi_solution_log/large_log_2.jsonl b/tasks/barnhart2000/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..827888b0d2fbae87f3c87e8625898e540fbab2e9 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ff43b123261ae12a043ad090309085ed5b3ab1cb2a240b5fd7030e8f7d712de +size 518 diff --git a/tasks/barnhart2000/gurobi_solution_log/large_log_3.jsonl b/tasks/barnhart2000/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45cc30ef77a8c070b39c2ac191c15253e4f30772 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a147f94f8857b8f4a6f1eb61f44875fd6ed5e5f01f7ebf36e5f9452ff759f20 +size 881 diff --git a/tasks/barnhart2000/gurobi_solution_log/large_log_4.jsonl b/tasks/barnhart2000/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4fccbc272254bb0424e3d4d46bd8dda8437adc95 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82a26d1bbf7ec77269efee87985852cc75beab596805873d0dcce04719156754 +size 302 diff --git a/tasks/barnhart2000/gurobi_solution_log/large_log_5.jsonl b/tasks/barnhart2000/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..99159a9c32d929707a2359f679d7ef45b3537e54 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b03599801dd917d7d5c1da12682d9b12a74844c689f78d7b4a1b9acd619bf61 +size 653 diff --git a/tasks/barnhart2000/gurobi_solution_log/tiny_log.jsonl b/tasks/barnhart2000/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6c8a8d894e423d3a719f63829a1e82765952d196 --- /dev/null +++ b/tasks/barnhart2000/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7171c41efc524370db430e26eb6425b2999fea6d4ec53dd29160737db5218048 +size 41 diff --git a/tasks/barnhart2000/instance/large_instance_1.json b/tasks/barnhart2000/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..bed3e8a89d70a0e822328077c89b537c997d65a1 --- /dev/null +++ b/tasks/barnhart2000/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8956f449a47a159bed55b94635f62c734b9c2be0496d7455a68a23e68fc1c52 +size 117848 diff --git a/tasks/barnhart2000/instance/large_instance_2.json b/tasks/barnhart2000/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..0558b68a453bb7414f1e6341957e6f96d1b34b91 --- /dev/null +++ b/tasks/barnhart2000/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f82d1f2fec0b72b980d1499dfa5bea04efd81833831be4d07ebc443d0b3ef98d +size 117871 diff --git a/tasks/barnhart2000/instance/large_instance_3.json b/tasks/barnhart2000/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9bc196629a51ed6cc2fe73fb3ebed8be631b0519 --- /dev/null +++ b/tasks/barnhart2000/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:809b0f291161f27cf36da2f37ec275487ebf3761bd5cc978a8732858d80d5d96 +size 117789 diff --git a/tasks/barnhart2000/instance/large_instance_4.json b/tasks/barnhart2000/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..61e07b8d198589538482434eb17a466935fc1352 --- /dev/null +++ b/tasks/barnhart2000/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:192cabc44d8af2c14f37f65fc3db8e1d178efdd6ce31b02b4d7398371cccd6ef +size 117833 diff --git a/tasks/barnhart2000/instance/large_instance_5.json b/tasks/barnhart2000/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..b55f2f6929994c082a8fb7d00388bcbc7a408d63 --- /dev/null +++ b/tasks/barnhart2000/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8edd9796644c92ff067fe439db6d9a0aa59ab5a59e3acb0869fc9e0343713414 +size 117828 diff --git a/tasks/barnhart2000/instance/tiny_instance.json b/tasks/barnhart2000/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b3c0f7ad589d285881b96232b2954e2279b7863d --- /dev/null +++ b/tasks/barnhart2000/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:483f7ac69127be4feb8faad5ffa5f63d3687d3480c392a33f36b6f11e0600835 +size 6957 diff --git a/tasks/barnhart2000/instance_schema.json b/tasks/barnhart2000/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b5d574e8542645870e4f880fd5eaab7bc19b96c4 --- /dev/null +++ b/tasks/barnhart2000/instance_schema.json @@ -0,0 +1,30 @@ +{ + "network": { + "num_nodes": " Total number of nodes in the directed network.", + "num_arcs": " Total number of directed physical arcs in the network.", + "nodes": " Identifiers for all nodes in the network.", + "arcs": [ + { + "arc_id": " Unique identifier for this arc.", + "from_node": " Node where this directed arc originates.", + "to_node": " Node where this directed arc terminates.", + "capacity": " Maximum total bandwidth that can flow through this arc across all commodities.", + "cost": " Per-unit routing cost for any commodity using this arc." + } + ] + }, + "commodities": { + "num_commodities": " Total number of commodities (call groups) to be routed or rejected.", + "commodity_list": [ + { + "commodity_id": " Unique identifier for this commodity.", + "origin": " Node where this commodity originates.", + "destination": " Node where this commodity must be delivered.", + "demand": " Bandwidth required by this commodity.", + "revenue": " Revenue earned if this commodity is successfully routed through the physical network.", + "artificial_arc_cost": " Cost incurred if this commodity is rejected instead of being routed." + } + ] + }, + "objective": " Direction of optimization for the total routing and rejection cost." +} diff --git a/tasks/barnhart2000/mathematical_formulation.md b/tasks/barnhart2000/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f4f6db157ed208f846333fc76c916e413baf7198 --- /dev/null +++ b/tasks/barnhart2000/mathematical_formulation.md @@ -0,0 +1,35 @@ +# Original Formulation: Origin-Destination Integer Multicommodity Flow (ODIMCF) + +*Source: “Using Branch-and-Price-and-Cut to Solve Origin-Destination Integer Multicommodity Flow Problems,” Barnhart, Hane, and Vance, Operations Research 48(2):318–326, 2000.* + +## Sets and Parameters + +- $G = (N, A)$: directed network with node set $N$ and arc set $A$. + +- $K$: set of commodities; each commodity $k \in K$ is defined by an origin–destination pair. + +- $q^k$: quantity (demand) of commodity $k$. + +- $c^k_{ij}$: unit flow cost for commodity $k$ on arc $ij$. + +- $d_{ij}$: capacity of arc $ij$, for $ij \in A$. + +- $b^k_i = 1$ if $i$ is the origin of $k$, $-1$ if destination of $k$, $0$ otherwise. + +## Decision Variables + +- $x^k_{ij} \in \{0,1\}$: $1$ if the entire quantity $q^k$ of commodity $k$ is assigned to arc $ij$, $0$ otherwise. + +## Objective + +$$\begin{equation} +\min \sum_{k \in K} \sum_{ij \in A} c^k_{ij}\, q^k\, x^k_{ij} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{k \in K} q^k\, x^k_{ij} &\le d_{ij}, & \forall\, ij \in A \tag{2} \\ +\sum_{ij \in A} x^k_{ij} - \sum_{ji \in A} x^k_{ji} &= b^k_i, & \forall\, i \in N,\; \forall\, k \in K \tag{3} \\ +x^k_{ij} &\in \{0,1\}, & \forall\, ij \in A,\; \forall\, k \in K \tag{4} +\end{align}$$ diff --git a/tasks/barnhart2000/problem_description.txt b/tasks/barnhart2000/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..99b608797901e97af8437688da5e960809b2553b --- /dev/null +++ b/tasks/barnhart2000/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A telecommunications network operator manages a directed network consisting of a set of nodes and a set of directed arcs connecting pairs of nodes. Each arc has a known capacity, expressed in units of bandwidth. The operator must handle a set of commodities, where each commodity represents a group of calls or messages sharing a common origin node and a common destination node. Each commodity has a known demand quantity representing the bandwidth it requires. + +Every commodity must be routed as a single, unsplittable unit along exactly one directed path from its origin node to its destination node, or it may be rejected entirely. To allow rejection, the network includes, for each commodity, an artificial direct arc from the commodity's origin to its destination. The artificial arc has no capacity limit and carries a cost equal to the revenue that would have been earned by successfully routing that commodity. All physical arcs in the network have zero routing cost for every commodity. + +The operator must choose, for each commodity, exactly one origin-to-destination path (which may be the artificial rejection arc or any path through the physical network). The total demand flowing through any physical arc, summed across all commodities whose chosen paths include that arc, must not exceed the arc's capacity. Flow must be conserved at every node for every commodity: at the origin node of a commodity, exactly one unit of that commodity's flow is produced; at the destination node, exactly one unit is absorbed; and at every intermediate node, the total flow of that commodity entering the node equals the total flow leaving it. + +The goal is to minimize the total cost. For each combination of commodity and arc, the cost contribution equals the commodity's demand multiplied by the per-unit cost for that commodity on that arc, counted only when that arc lies on the commodity's chosen path. The total cost is the sum of these contributions across all commodities and all arcs. Because physical arcs have zero cost, the total cost reduces to the sum of artificial-arc costs for rejected commodities, which equals the total lost revenue from commodities not routed through the physical network. Equivalently, minimizing total cost maximizes the total revenue earned from commodities successfully carried on the physical network. diff --git a/tasks/barnhart2000/solution_logger.py b/tasks/barnhart2000/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/barnhart2000/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/barnhart2000/solution_schema.json b/tasks/barnhart2000/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a5790908ce73a94190b4c1ad57b11b353124e0c1 --- /dev/null +++ b/tasks/barnhart2000/solution_schema.json @@ -0,0 +1,16 @@ +{ + "objective_value": " Total cost of rejected commodities across the entire routing plan.", + "commodities": [ + { + "commodity_id": " Identifier of the commodity whose routing outcome is described in this entry.", + "rejected": " Whether this commodity is rejected and sent on its artificial arc instead of being routed through the network.", + "path_arcs": [ + { + "from": " Origin node of an arc used on this commodity's routing path.", + "to": " Destination node of an arc used on this commodity's routing path.", + "arc_id": " Identifier of an arc used on this commodity's routing path." + } + ] + } + ] +} diff --git a/tasks/bayani2024/feasibility_check.py b/tasks/bayani2024/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..92dfe3ae6a986262b0933e8cd07c01b4eedb10cb --- /dev/null +++ b/tasks/bayani2024/feasibility_check.py @@ -0,0 +1,375 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for QSAP/AQSAP (Quadratic Semi-Assignment Problem). +Paper: Bayani, Rostami, Adulyasak, Rousseau (2021) +"A dual bounding framework for binary quadratic combinatorial optimization" + +Checks the compact formulation (Equations 12-14): + Constraint 1 (Eq 13): Each client assigned to exactly one server + Constraint 2 (Eq 14): Assignment variables are binary (0 or 1) + Constraint 3: Server indices are valid (0 <= j < h) + Constraint 4: All clients are assigned + Constraint 5: Objective value matches the computed cost +""" + +import json +import argparse + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('assignment',) +_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 main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for QSAP/AQSAP (Bayani et al. 2021)" + ) + 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() + + tol = 1e-4 + + # ---- Load instance ---- + with open(args.instance_path, "r") as f: + data = json.load(f) + + # ---- Load solution ---- + with open(args.solution_path, "r") as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + n = data["n_clients"] + h = data["n_servers"] + linear_costs = data["linear_costs"] + quadratic_costs = data["quadratic_costs"] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # Check if solution has a valid objective value + obj_val = sol.get("objective_value") + assignment = sol.get("assignment", {}) + + if obj_val is None or not assignment: + result = { + "feasible": None, + "violated_constraints": [], + "violations": ["No feasible solution found (objective_value is null or assignment is empty)"], + "violation_magnitudes": [] + } + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + print("Feasibility check: No solution to check (null objective or empty assignment)") + return + + # Convert assignment keys to int + assign = {} + for k, v in assignment.items(): + assign[int(k)] = int(v) + + # ================================================================ + # Constraint 1 (Eq 13): Each client assigned to exactly one server + # sum_{e in delta(i)} x_e = 1 for all i in N + # ================================================================ + for i in range(n): + if i not in assign: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (Assignment): Client {i} is not assigned to any server" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": 0, + "rhs": 1, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0 + }) + + # Check no client is assigned multiple times (shouldn't happen with dict) + # but verify all clients are covered + assigned_clients = set(assign.keys()) + expected_clients = set(range(n)) + missing = expected_clients - assigned_clients + if missing: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (Assignment): Missing clients: {sorted(missing)}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": len(assigned_clients), + "rhs": n, + "raw_excess": float(len(missing)), + "normalizer": float(n), + "ratio": float(len(missing)) / n + }) + + # ================================================================ + # Constraint 2 (Eq 14): Valid server indices + # x_e in {0,1}, server j in {0,...,h-1} + # ================================================================ + for i, j in assign.items(): + if j < 0 or j >= h: + violated_constraints.add(2) + violations.append( + f"Constraint 2 (Server range): Client {i} assigned to server {j}, " + f"but valid range is [0, {h-1}]" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": j, + "rhs": h - 1, + "raw_excess": float(max(j - (h-1), -j)), + "normalizer": float(h), + "ratio": float(max(j - (h-1), -j)) / h + }) + + # ================================================================ + # Constraint 3: Objective value check + # obj = sum_{e} c_e x_e + sum_{(e,f)} q_{ef} x_e x_f + # ================================================================ + if not violated_constraints: + # Compute linear cost + computed_linear = 0.0 + for i in range(n): + j = assign[i] + computed_linear += linear_costs[i][j] + + # Build quadratic cost lookup + quad_dict = {} + for entry in quadratic_costs: + i1, j1, i2, j2 = int(entry[0]), int(entry[1]), int(entry[2]), int(entry[3]) + q_val = entry[4] + e = (i1, j1) + f = (i2, j2) + if (e, f) not in quad_dict and (f, e) not in quad_dict: + quad_dict[(e, f)] = q_val + + # Compute quadratic cost + computed_quad = 0.0 + for (e, f), q_val in quad_dict.items(): + i1, j1 = e + i2, j2 = f + # x_e = 1 iff client i1 assigned to server j1 + # x_f = 1 iff client i2 assigned to server j2 + if assign.get(i1) == j1 and assign.get(i2) == j2: + computed_quad += q_val + + computed_obj = computed_linear + computed_quad + + obj_diff = abs(computed_obj - obj_val) + normalizer = max(abs(obj_val), abs(computed_obj), 1e-5) + relative_diff = obj_diff / normalizer + + if relative_diff > tol: + violated_constraints.add(3) + violations.append( + f"Constraint 3 (Objective): Reported objective = {obj_val:.6f}, " + f"computed objective = {computed_obj:.6f}, " + f"relative diff = {relative_diff:.6e}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": round(obj_val, 10), + "rhs": round(computed_obj, 10), + "raw_excess": round(obj_diff, 10), + "normalizer": round(normalizer, 10), + "ratio": round(relative_diff, 10) + }) + + # ---- Build result ---- + _domain_check_vars_binary = [] # assignment is facility index, not binary + _domain_check_vars_integer = [] + + # ===================================================================== + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # ===================================================================== + # Constraint 4: 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(4) + violations.append( + f"Constraint 4 (binary domain): {var_name}[{key}] = {v} not in {0, 1}") + violation_magnitudes.append({ + "constraint": 4, + "lhs": v, + "rhs": 1.0, + "raw_excess": float(viol), + "normalizer": 1.0, + "ratio": float(viol), + }) + + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes if not feasible else [] + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility check complete. Result: {'FEASIBLE' if feasible else 'INFEASIBLE'}") + if not feasible: + print(f"Violated constraints: {sorted(violated_constraints)}") + print(f"Number of violations: {len(violations)}") + + +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/bayani2024/gurobi_code.py b/tasks/bayani2024/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..7405f0fa6222791459f1490c7e5bfc2205d004e9 --- /dev/null +++ b/tasks/bayani2024/gurobi_code.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the QSAP/AQSAP compact BQP formulation. + +Paper: "A dual bounding framework for binary quadratic combinatorial optimization" +Authors: M. Bayani, B. Rostami, Y. Adulyasak, L.-M. Rousseau (2021) + +This implements the compact QSAP formulation (Equations 12-14) with +Standard Linearization Technique (SLT, Appendix A, Equations A.1-A.4) +to linearize quadratic terms, solved directly by Gurobi (GUROBI+SLT method). + +For AQSAP instances (out_of_star_density == 0), quadratic costs only exist +between adjacent edges (edges sharing a server endpoint), and q_{ef} = c_e + c_f. +For general QSAP instances, out-of-star quadratic interactions also exist. +""" + +import argparse +import json +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(instance_path): + """Load a QSAP/AQSAP instance from JSON.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def build_and_solve(data, time_limit): + """ + Build the linearized QSAP model (GUROBI+SLT) and solve it. + + The compact formulation is: + min sum_{e in A} c_e x_e + sum_{(e,f) in E} q_{ef} x_e x_f + s.t. sum_{e in delta(i)} x_e = 1 for all i in N (Eq. 13) + x_e in {0,1} for all e in A (Eq. 14) + + We linearize the quadratic terms using SLT: + y_{ef} >= x_e + x_f - 1 (A.1) + y_{ef} <= x_e (A.2) + y_{ef} <= x_f (A.3) + y_{ef} >= 0 (A.4) + + So the linearized model becomes: + min sum_{e in A} c_e x_e + sum_{(e,f)} q_{ef} y_{ef} + s.t. assignment constraints (13) + SLT constraints (A.1)-(A.4) + x_e in {0,1}, y_{ef} >= 0 + """ + n = data["n_clients"] + h = data["n_servers"] + linear_costs = data["linear_costs"] # n x h matrix + quadratic_costs = data["quadratic_costs"] # list of [i, j, k, l, q_val] + + model = gp.Model("QSAP_SLT") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x[i][j] = 1 if client i assigned to server j + x = {} + for i in range(n): + for j in range(h): + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}", + obj=linear_costs[i][j]) + + # Parse quadratic costs into a dictionary keyed by a canonical unordered pair. + # Per Eq. (12) the objective sums q_{ef} x_e x_f over ordered pairs in + # E = E x E, so every listed entry must contribute its q_val; we accumulate + # on the canonical key so any redundant (e,f)/(f,e) listings are summed + # rather than silently dropped. + quad_dict = {} + for entry in quadratic_costs: + i, j, k, l = int(entry[0]), int(entry[1]), int(entry[2]), int(entry[3]) + q_val = entry[4] + e = (i, j) + f = (k, l) + key = (e, f) if e <= f else (f, e) + quad_dict[key] = quad_dict.get(key, 0.0) + q_val + + # Linearization variables y_{ef} for each quadratic pair + y = {} + for (e, f), q_val in quad_dict.items(): + y[(e, f)] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, + name=f"y_{e[0]}{e[1]}_{f[0]}{f[1]}", + obj=q_val) + + model.update() + + # Constraint (13): each client assigned to exactly one server + for i in range(n): + model.addConstr( + gp.quicksum(x[i, j] for j in range(h)) == 1, + name=f"assign_{i}" + ) + + # SLT constraints for each quadratic pair + for (e, f), q_val in quad_dict.items(): + xe = x[e[0], e[1]] + xf = x[f[0], f[1]] + yef = y[(e, f)] + + # (A.1) y_{ef} >= x_e + x_f - 1 + model.addConstr(yef >= xe + xf - 1, + name=f"slt_a1_{e}_{f}") + # (A.2) y_{ef} <= x_e + model.addConstr(yef <= xe, + name=f"slt_a2_{e}_{f}") + # (A.3) y_{ef} <= x_f + model.addConstr(yef <= xf, + name=f"slt_a3_{e}_{f}") + # (A.4) y_{ef} >= 0 (already enforced by lb=0.0) + + # Optimize + model.optimize() + + # Extract solution + objective_value = None + assignment = {} + + if model.SolCount > 0: + objective_value = model.ObjVal + for i in range(n): + for j in range(h): + if x[i, j].X > 0.5: + assignment[i] = j + break + else: + # No feasible solution found + objective_value = None + + return objective_value, assignment, model + + +def main(): + parser = argparse.ArgumentParser( + description="Solve QSAP/AQSAP using Gurobi with SLT linearization" + ) + 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) + + # Solve + objective_value, assignment, model = build_and_solve(data, args.time_limit) + + # Build solution output + solution = { + "objective_value": objective_value, + "assignment": {str(k): v for k, v in assignment.items()}, + "solver_status": model.Status, + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + "solve_time": model.Runtime, + } + + # 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"Solution written to {args.solution_path}") + if objective_value is not None: + print(f"Objective value: {objective_value}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/bayani2024/gurobi_feasi_result/large_feasi_result_1.json b/tasks/bayani2024/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bayani2024/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/bayani2024/gurobi_feasi_result/large_feasi_result_2.json b/tasks/bayani2024/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bayani2024/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/bayani2024/gurobi_feasi_result/large_feasi_result_3.json b/tasks/bayani2024/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bayani2024/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/bayani2024/gurobi_feasi_result/large_feasi_result_4.json b/tasks/bayani2024/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bayani2024/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/bayani2024/gurobi_feasi_result/large_feasi_result_5.json b/tasks/bayani2024/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bayani2024/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/bayani2024/gurobi_feasi_result/tiny_feasi_result.json b/tasks/bayani2024/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bayani2024/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/bayani2024/gurobi_solution/large_solution_1.json b/tasks/bayani2024/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ce71fe53a749957d7550e23d9d74544bc36a63fb --- /dev/null +++ b/tasks/bayani2024/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bd9bf9302105e424ded8bc751ef5f258022f0ec2a927499a5d183d774ba8c3e +size 857 diff --git a/tasks/bayani2024/gurobi_solution/large_solution_2.json b/tasks/bayani2024/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..3f64e16f262a242467a237623a103aa4e226f013 --- /dev/null +++ b/tasks/bayani2024/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c868b8682c5fdcbbdf6a9d1eb8734d395577b184ccb17d7506eb991936a081c +size 828 diff --git a/tasks/bayani2024/gurobi_solution/large_solution_3.json b/tasks/bayani2024/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8d285a345350fb75674a376d2ab3a854f99a1fc5 --- /dev/null +++ b/tasks/bayani2024/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9237a2142e7904df3354205790829aa820ecfdf08c784f16f24c0135c981d9d3 +size 826 diff --git a/tasks/bayani2024/gurobi_solution/large_solution_4.json b/tasks/bayani2024/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f270c2c95b24f91f211fd68df45cbc7e73a007d5 --- /dev/null +++ b/tasks/bayani2024/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13998c4dd2e9c92e0cef88c73a8eeea8d23ea9308193ff43af82b51f52a87c3c +size 832 diff --git a/tasks/bayani2024/gurobi_solution/large_solution_5.json b/tasks/bayani2024/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..cc86dd74c978bfc920f5bc389fd2afb0d971bbed --- /dev/null +++ b/tasks/bayani2024/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf7a517e6091b643d2d2f0da3bfa472237c25ce1aef1dfc92da87b15a3dc1c4b +size 821 diff --git a/tasks/bayani2024/gurobi_solution/tiny_solution.json b/tasks/bayani2024/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..a658c512202378b06ce669fd9198d0d2e2d3967c --- /dev/null +++ b/tasks/bayani2024/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59ea885c678e3d4f752212b14e97cd85d4eb24f516487fd8d80ae7e6d2cb4e1b +size 273 diff --git a/tasks/bayani2024/gurobi_solution_log/tiny_log.jsonl b/tasks/bayani2024/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..878638ba6e0fa8d88f051ee45e1cd8fd07b20900 --- /dev/null +++ b/tasks/bayani2024/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6fd2ac1b16570f0827f7b89d2aee1265903cd6a55a61d5364dcf2ebcb465564a +size 163 diff --git a/tasks/bayani2024/instance/large_instance_1.json b/tasks/bayani2024/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..cea37266dd145cbfc00282bf145609dade6dbe62 --- /dev/null +++ b/tasks/bayani2024/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c8da1232a528067fa2735f93bd4543f2e37377370391ed8e8c4d3eba14b2c43 +size 2370478 diff --git a/tasks/bayani2024/instance/large_instance_2.json b/tasks/bayani2024/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ce791e93161bf37c38a5c8e58ddc47f6232c0910 --- /dev/null +++ b/tasks/bayani2024/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db6eefd7f83d7e7fb1a1e15b707bfb5eb8e5a70c2e4900c86cb7cdfa12e140f1 +size 560045 diff --git a/tasks/bayani2024/instance/large_instance_3.json b/tasks/bayani2024/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..90a165279885bff51b29433f4f473a766b174ba1 --- /dev/null +++ b/tasks/bayani2024/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dea9d03591659c8dab44e7099c905267f69507565bde957098c8bd4a8fab28cf +size 1281449 diff --git a/tasks/bayani2024/instance/large_instance_4.json b/tasks/bayani2024/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8ff4681256d7d0b6de87d488e3cfcedac53acfeb --- /dev/null +++ b/tasks/bayani2024/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:514f6020abbaa077a9d5f1aacaa000f3da6ba3ab1a9a3745617566cfa6d5d297 +size 1647815 diff --git a/tasks/bayani2024/instance/large_instance_5.json b/tasks/bayani2024/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..82322bb7d1310e4d537a45ffaa52f3f7f548e16e --- /dev/null +++ b/tasks/bayani2024/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a07873903fafc30b47fb9cfd039d6d851adc05549f1491ecee8e1656b68466e5 +size 2001704 diff --git a/tasks/bayani2024/instance/tiny_instance.json b/tasks/bayani2024/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b368238bb216c78d75366f8b1452e443f93bd24c --- /dev/null +++ b/tasks/bayani2024/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fad46746fed2c0d202f319bde49cf92deb7fe1044ec26c92a7003a440f44860d +size 4807 diff --git a/tasks/bayani2024/instance_schema.json b/tasks/bayani2024/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9a1e4162b8b9b5bdb5f589096745c302d1d57e99 --- /dev/null +++ b/tasks/bayani2024/instance_schema.json @@ -0,0 +1,9 @@ +{ + "n_clients": " Number of clients that must each be assigned to a server.", + "n_servers": " Number of servers available to process client demands.", + "out_of_star_density": " Fraction of cross-server assignment pairs that carry a nonzero pairwise interaction cost.", + "demands": " Processing demand of each client.", + "processing_rates": " Processing rate of each server.", + "linear_costs": " Cost of assigning each client to each server, equal to the product of the client's demand and the server's processing rate.", + "quadratic_costs": " Pairwise interaction costs, where each entry is [client_1, server_1, client_2, server_2, cost] representing the joint cost incurred when client_1 is assigned to server_1 and client_2 is assigned to server_2 simultaneously." +} diff --git a/tasks/bayani2024/mathematical_formulation.md b/tasks/bayani2024/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..9cfa4718abf2e8227e02adb6c3f9f11bfc20dfdb --- /dev/null +++ b/tasks/bayani2024/mathematical_formulation.md @@ -0,0 +1,38 @@ +# Original Formulation: Quadratic Semi-Assignment Problem (QSAP) + +*Source: A dual bounding framework for binary quadratic combinatorial optimization, M. Bayani, B. Rostami, Y. Adulyasak, L.-M. Rousseau, 2021 (Les Cahiers du GERAD, G–2021–43).* + +## Sets and Indices + +- $N = \{1, \dots, n\}$: set of clients. + +- $H = \{1, \dots, h\}$: set of servers. + +- $A$: set of edges (client–server assignment pairs). An edge $e = (i,j)$, $i \in N$, $j \in H$, represents assigning client $i$ to server $j$. ($A$ is the set of edges with one endpoint in $H$; here, with $N$ the clients and $H$ the servers, $A = E$.) + +- $\delta(i) \subseteq A$: set of edges incident to client $i \in N$ (i.e. all assignments of client $i$). + +- $\mathcal{E} = E \times E$: set of all (ordered) pairs of edges. + +## Parameters + +- $c_e = c_{ij} \in \mathbb{R}$: linear cost of assigning client $i$ to server $j$ (edge $e = (i,j)$). + +- $q_{ef} = q_{ijkl} \in \mathbb{R}$: quadratic cost incurred when client $i$ is assigned to server $j$ *and* client $k$ is assigned to server $l$ simultaneously, for the pair of edges $e = (i,j)$, $f = (k,l)$. + +## Decision Variables + +- $x_e \in \{0,1\}$: equals $1$ if the assignment corresponding to edge $e = (i,j)$ is selected (client $i$ assigned to server $j$), $0$ otherwise. + +## Objective + +$$\begin{align} +\min \quad & \sum_{e \in A} c_e x_e + \sum_{(e,f) \in \mathcal{E}} q_{ef}\, x_e x_f \tag{12} +\end{align}$$ + +## Constraints + +$$\begin{align} +& \sum_{e \in \delta(i)} x_e = 1 && \forall i \in N \tag{13} \\ +& x_e \in \{0,1\} && \forall e \in A \tag{14} +\end{align}$$ diff --git a/tasks/bayani2024/problem_description.txt b/tasks/bayani2024/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..939457cd147034f4f6de5c30c0056555e630783c --- /dev/null +++ b/tasks/bayani2024/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A distributed processing system consists of a set of clients and a set of servers. Each client has a known demand value drawn from a continuous range, and each server has a known processing rate. The linear processing cost of assigning a particular client to a particular server equals the product of that client's demand and that server's processing rate. In addition to these linear costs, there are pairwise quadratic interaction costs that arise whenever two client-server assignments are both active simultaneously. A quadratic cost is specified for each pair of client-server assignments and represents the joint cost incurred when both assignments are in effect at the same time. Two types of quadratic interactions exist: adjacent interactions, which occur between two assignments that share the same server, and out-of-star interactions, which occur between two assignments directed at different servers. For adjacent interactions where two clients share the same server, the quadratic cost equals the sum of the two individual linear processing costs of those assignments. Out-of-star interaction costs, when present, are specified independently for a subset of cross-server assignment pairs at a given density level. + +Each client must be assigned to exactly one server, but a server may serve any number of clients. The total cost of an assignment consists of two additive components: the sum of linear processing costs over all active client-server assignments, and the sum of quadratic interaction costs over all pairs of assignments that are both active. Specifically, for every pair of active assignments that has a specified quadratic cost, that cost coefficient is added to the total. The goal is to find an assignment of every client to exactly one server that minimizes this total cost. + +The input data provides the number of clients, the number of servers, a demand value for each client, a processing rate for each server, a matrix of linear costs for each client-server pair, and a list of quadratic cost entries each specified as a tuple of two client-server pairs together with the associated pairwise cost value. A density parameter indicates what fraction of non-adjacent assignment pairs carry a nonzero quadratic cost; when this density is zero, only adjacent (same-server) quadratic interactions exist. diff --git a/tasks/bayani2024/solution_logger.py b/tasks/bayani2024/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/bayani2024/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/bayani2024/solution_schema.json b/tasks/bayani2024/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..146d51d313ba830aa039b4f5513d6be5d71a3b2b --- /dev/null +++ b/tasks/bayani2024/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total cost of the assignment, combining linear processing costs and all active quadratic interaction costs.", + "assignment": " Index of the server that each client is assigned to." +} diff --git a/tasks/belhoul2014/feasibility_check.py b/tasks/belhoul2014/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..afe7870a6e908ddaf3c4c3bf3bca4d55d2f46aac --- /dev/null +++ b/tasks/belhoul2014/feasibility_check.py @@ -0,0 +1,483 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Multi-Objective Assignment Problem (MOAP) / +Linearized Compromise Assignment Problem (LCAP) from Zheng et al. (2014). + +Checks all hard constraints listed in math_model.txt, numbered strictly +from top to bottom: + + Constraint 1 (MOAP-1): sum_j x_ij = 1, i=1,...,n + Constraint 2 (MOAP-2): sum_i x_ij = 1, j=1,...,n + Constraint 3 (MOAP-3): x_ij in {0,1} + Constraint 4 (CAP-1): sum_j x_ij = 1, i=1,...,n + Constraint 5 (CAP-2): sum_i x_ij = 1, j=1,...,n + Constraint 6 (CAP-3): x_ij in {0,1} + Constraint 7 (LCAP-1): mu >= lambda_k * (sum_ij c^k_ij x_ij - z_bar_k), k=1,...,p + Constraint 8 (LCAP-2): sum_j x_ij = 1, i=1,...,n + Constraint 9 (LCAP-3): sum_i x_ij = 1, j=1,...,n + Constraint 10 (LCAP-4): x_ij in {0,1} + Constraint 11 (LCAP-5): mu unrestricted + Constraint 12 (RLCAP-1): sum_j x_ij = 1, i=1,...,n + Constraint 13 (RLCAP-2): sum_i x_ij = 1, j=1,...,n + Constraint 14 (RLCAP-3): mu >= lambda_k * (sum_ij c^k_ij x_ij - z_bar_k), k=1,...,p + Constraint 15 (RLCAP-4): x_ij >= 0 + Constraint 16 (RLCAP-5): mu unrestricted + Constraint 17 (2a): u_i + v_j <= sum_k lambda_k c^k_ij omega_k (dual; skipped) + Constraint 18 (2b): sum_k omega_k = 1 (dual; skipped) + Constraint 19 (2c): omega_k > 0 (dual; skipped) + Constraint 20 (obj): objective_value == max_k lambda_k * (z_k - z_bar_k) + (Tier C: catches reported-objective fabrication; the + LCAP-1 inequality alone only rules out under-reporting, + so a candidate that inflates mu to sys.float_info.max + would otherwise slip through.) +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'assignment_matrix', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def build_assignment_matrix(assignment, n): + """Build n x n binary matrix from assignment list.""" + x = [[0] * n for _ in range(n)] + for i, j in enumerate(assignment): + x[i][j] = 1 + return x + + +def compute_objective_per_criterion(assignment, cost_matrices, n, p): + """z_k(x) = sum_i sum_j c^k_ij * x_ij for each k.""" + z = [0.0] * p + for k in range(p): + for i in range(n): + j = assignment[i] + z[k] += cost_matrices[k][i][j] + return z + + +def add_violation(violations_list, magnitudes_list, constraint_idx, msg, lhs, rhs): + """Record a constraint violation with normalized magnitude.""" + raw_excess = abs(lhs - rhs) + # For = constraints, raw_excess is |LHS - RHS| + # For >= constraints (mu >= rhs_val), raw_excess is max(0, rhs - lhs) + # Caller computes the appropriate raw_excess and passes lhs, rhs accordingly. + normalizer = max(abs(rhs), EPS) + ratio = raw_excess / normalizer + violations_list.append(msg) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + }) + + +def check_row_assignment(x_mat, n, constraint_idx, label): + """Check sum_j x_ij = 1 for all i (= constraint).""" + violated_msgs = [] + violated_mags = [] + for i in range(n): + row_sum = sum(x_mat[i][j] for j in range(n)) + diff = abs(row_sum - 1.0) + if diff > TOL: + add_violation( + violated_msgs, violated_mags, constraint_idx, + f"{label}: Row {i} sum = {row_sum}, expected 1", + row_sum, 1.0, + ) + return violated_msgs, violated_mags + + +def check_col_assignment(x_mat, n, constraint_idx, label): + """Check sum_i x_ij = 1 for all j (= constraint).""" + violated_msgs = [] + violated_mags = [] + for j in range(n): + col_sum = sum(x_mat[i][j] for i in range(n)) + diff = abs(col_sum - 1.0) + if diff > TOL: + add_violation( + violated_msgs, violated_mags, constraint_idx, + f"{label}: Column {j} sum = {col_sum}, expected 1", + col_sum, 1.0, + ) + return violated_msgs, violated_mags + + +def check_binary(x_mat, n, constraint_idx, label): + """Check x_ij in {0, 1} for all i, j.""" + violated_msgs = [] + violated_mags = [] + for i in range(n): + for j in range(n): + val = x_mat[i][j] + dist_to_nearest = min(abs(val - 0.0), abs(val - 1.0)) + if dist_to_nearest > TOL: + # LHS = distance from binary, RHS = 0 (should be zero distance) + add_violation( + violated_msgs, violated_mags, constraint_idx, + f"{label}: x[{i}][{j}] = {val}, not binary", + dist_to_nearest, 0.0, + ) + return violated_msgs, violated_mags + + +def check_lcap_linearization(mu, z_vals, lam, z_bar, p, constraint_idx, label): + """Check mu >= lambda_k * (z_k - z_bar_k) for all k (>= constraint).""" + violated_msgs = [] + violated_mags = [] + for k in range(p): + rhs_val = lam[k] * (z_vals[k] - z_bar[k]) + violation_amount = rhs_val - mu # positive if mu < rhs_val + if violation_amount > TOL: + add_violation( + violated_msgs, violated_mags, constraint_idx, + f"{label}: mu ({mu:.6f}) < lambda_{k}*(z_{k} - z_bar_{k}) = {rhs_val:.6f}", + mu, rhs_val, + ) + return violated_msgs, violated_mags + + +def check_nonnegativity(x_mat, n, constraint_idx, label): + """Check x_ij >= 0 for all i, j (>= constraint).""" + violated_msgs = [] + violated_mags = [] + for i in range(n): + for j in range(n): + val = x_mat[i][j] + if val < -TOL: + violation_amount = -val + add_violation( + violated_msgs, violated_mags, constraint_idx, + f"{label}: x[{i}][{j}] = {val} < 0", + val, 0.0, + ) + return violated_msgs, violated_mags + + +def run_feasibility_check(instance, solution): + n = instance["n"] + p = instance["p"] + cost_matrices = instance["cost_matrices"] + z_bar = instance["reference_point"] + lam = instance["search_direction_lambda"] + + assignment = solution["assignment"] + + # Build assignment matrix + x_mat = build_assignment_matrix(assignment, n) + + # Use assignment_matrix from solution if available (for consistency check) + if "assignment_matrix" in solution: + x_mat_sol = solution["assignment_matrix"] + # Check consistency between assignment list and matrix + for i in range(n): + for j in range(n): + if x_mat[i][j] != x_mat_sol[i][j]: + # Use the assignment list as ground truth + pass + + # Compute objective values per criterion from the assignment + z_vals = compute_objective_per_criterion(assignment, cost_matrices, n, p) + + # Determine mu (objective_value) + mu = solution.get("objective_value") + if mu is None: + # Compute from the achievement function + mu = max(lam[k] * (z_vals[k] - z_bar[k]) for k in range(p)) + + violated_constraints = set() + all_msgs = [] + all_mags = [] + + # Helper to accumulate results + def accumulate(constraint_idx, msgs, mags): + if msgs: + violated_constraints.add(constraint_idx) + all_msgs.extend(msgs) + all_mags.extend(mags) + + # --- Constraint 1 (MOAP-1): sum_j x_ij = 1 for all i --- + msgs, mags = check_row_assignment(x_mat, n, 1, "MOAP-1") + accumulate(1, msgs, mags) + + # --- Constraint 2 (MOAP-2): sum_i x_ij = 1 for all j --- + msgs, mags = check_col_assignment(x_mat, n, 2, "MOAP-2") + accumulate(2, msgs, mags) + + # --- Constraint 3 (MOAP-3): x_ij in {0,1} --- + msgs, mags = check_binary(x_mat, n, 3, "MOAP-3") + accumulate(3, msgs, mags) + + # --- Constraint 4 (CAP-1): sum_j x_ij = 1 for all i --- + msgs, mags = check_row_assignment(x_mat, n, 4, "CAP-1") + accumulate(4, msgs, mags) + + # --- Constraint 5 (CAP-2): sum_i x_ij = 1 for all j --- + msgs, mags = check_col_assignment(x_mat, n, 5, "CAP-2") + accumulate(5, msgs, mags) + + # --- Constraint 6 (CAP-3): x_ij in {0,1} --- + msgs, mags = check_binary(x_mat, n, 6, "CAP-3") + accumulate(6, msgs, mags) + + # --- Constraint 7 (LCAP-1): mu >= lambda_k*(z_k - z_bar_k) for all k --- + msgs, mags = check_lcap_linearization(mu, z_vals, lam, z_bar, p, 7, "LCAP-1") + accumulate(7, msgs, mags) + + # --- Constraint 8 (LCAP-2): sum_j x_ij = 1 for all i --- + msgs, mags = check_row_assignment(x_mat, n, 8, "LCAP-2") + accumulate(8, msgs, mags) + + # --- Constraint 9 (LCAP-3): sum_i x_ij = 1 for all j --- + msgs, mags = check_col_assignment(x_mat, n, 9, "LCAP-3") + accumulate(9, msgs, mags) + + # --- Constraint 10 (LCAP-4): x_ij in {0,1} --- + msgs, mags = check_binary(x_mat, n, 10, "LCAP-4") + accumulate(10, msgs, mags) + + # --- Constraint 11 (LCAP-5): mu unrestricted --- + # Trivially satisfied for any real mu; no check needed. + + # --- Constraints 12-16 (RLCAP-1..RLCAP-5) SKIPPED --- + # These are the LP-relaxation (RLCAP) constraints. For any binary x + # that satisfies the LCAP constraints (assignment 6, 7; binary 10), + # the relaxation is automatically satisfied (row/col assignment is + # identical; x_ij >= 0 is weaker than x_ij in {0,1}). Checking them + # only duplicates the LCAP checks above. + # + # --- Constraints 17-19 (Dual: 2a, 2b, 2c) SKIPPED --- + # Dual variables (u, v, omega) are not part of the primal solution + # structure and not produced by a generated algorithm. + + # --- Constraint 20 (obj consistency): mu == max_k lambda_k*(z_k - z_bar_k) --- + # The LCAP linearization in constraint 7 only enforces mu >= achievement, + # so a candidate could pass by reporting an arbitrarily large mu. The + # actual achievement-function value at the chosen assignment is + # max_k lambda_k*(z_k - z_bar_k); the reported objective_value must + # equal it within tolerance. All variables that determine the achievement + # function (the assignment) are present in the solution, so we perform + # a full recompute rather than a lower-bound check. + 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 = max(lam[k] * (z_vals[k] - z_bar[k]) for k in range(p)) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + add_violation( + all_msgs, all_mags, 20, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed " + f"max_k lambda_k*(z_k - z_bar_k)={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={tol:.3g})", + reported, true_obj, + ) + violated_constraints.add(20) + + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": all_msgs, + "violation_magnitudes": all_mags, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MOAP/LCAP (Zheng et al. 2014)" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON instance file", + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON solution file", + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON feasibility result", + ) + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = run_feasibility_check(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE: All hard constraints satisfied.") + else: + print(f"INFEASIBLE: Violated constraints: {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/belhoul2014/gurobi_code.py b/tasks/belhoul2014/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..14e587659c092046e4196e2110813b8506013c1e --- /dev/null +++ b/tasks/belhoul2014/gurobi_code.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Linearized Compromise Assignment Problem (LCAP). + +Based on: Zheng et al. (2014), multi-objective assignment problem scalarized +using the weighted Tchebychev (achievement) function. + +The LCAP minimizes the maximum weighted deviation from a reference point: + + min mu + s.t. mu >= lambda_k * (sum_{i,j} c^k_{ij} * x_{ij} - z_bar_k) for k = 1,...,p + sum_j x_{ij} = 1 for i = 1,...,n + sum_i x_{ij} = 1 for j = 1,...,n + x_{ij} in {0,1} + mu unrestricted +""" + +import argparse +import json + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load an LCAP instance from JSON.""" + with open(path, "r") as f: + data = json.load(f) + return data + + +def solve_lcap(instance_path, solution_path, time_limit): + """Build and solve the LCAP model using Gurobi.""" + data = load_instance(instance_path) + + n = data["n"] + p = data["p"] + cost_matrices = data["cost_matrices"] # p matrices, each n x n + z_bar = data["reference_point"] # length p + lam = data["search_direction_lambda"] # length p + + print(f"LCAP Instance: n={n}, p={p}") + print(f"Reference point: {z_bar}") + print(f"Search direction (lambda): {lam}") + print(f"Time limit: {time_limit} seconds") + + # ---- Build model ---- + model = gp.Model("LCAP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i,j] binary assignment variables + x = {} + for i in range(n): + for j in range(n): + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + # mu: unrestricted continuous variable (the Tchebychev objective) + mu = model.addVar(lb=-GRB.INFINITY, vtype=GRB.CONTINUOUS, name="mu") + + model.update() + + # Objective: minimize mu + model.setObjective(mu, GRB.MINIMIZE) + + # Assignment constraints: each row assigned to exactly one column + for i in range(n): + model.addConstr( + gp.quicksum(x[i, j] for j in range(n)) == 1, + name=f"row_{i}" + ) + + # Assignment constraints: each column assigned to exactly one row + for j in range(n): + model.addConstr( + gp.quicksum(x[i, j] for i in range(n)) == 1, + name=f"col_{j}" + ) + + # Linearization constraints: + # mu >= lambda_k * (sum_{i,j} c^k_{ij} * x_{ij} - z_bar_k) for each k + for k in range(p): + c_k = cost_matrices[k] + model.addConstr( + mu >= lam[k] * ( + gp.quicksum(c_k[i][j] * x[i, j] for i in range(n) for j in range(n)) + - z_bar[k] + ), + name=f"tcheby_{k}" + ) + + model.update() + + # ---- Solve ---- + model.optimize() + + # ---- Extract solution ---- + result = { + "problem": "LCAP", + "instance": instance_path, + "instance_id": data.get("instance_id"), + } + + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + result["gap"] = model.MIPGap if hasattr(model, "MIPGap") else 0.0 + + # Extract the assignment matrix and permutation + assignment_matrix = [[0] * n for _ in range(n)] + assignment = [] # assignment[i] = j means row i assigned to column j + for i in range(n): + for j in range(n): + if x[i, j].X > 0.5: + assignment_matrix[i][j] = 1 + assignment.append(j) + + result["assignment"] = assignment + result["assignment_matrix"] = assignment_matrix + + # Compute objective value for each criterion + objective_values_per_criterion = [] + for k in range(p): + c_k = cost_matrices[k] + val = sum( + c_k[i][assignment[i]] for i in range(n) + ) + objective_values_per_criterion.append(val) + result["objective_values_per_criterion"] = objective_values_per_criterion + + # Compute weighted deviations for verification + weighted_deviations = [] + for k in range(p): + dev = lam[k] * (objective_values_per_criterion[k] - z_bar[k]) + weighted_deviations.append(dev) + result["weighted_deviations"] = weighted_deviations + else: + result["objective_value"] = None + result["status"] = "infeasible_or_no_solution" + + result["solve_time"] = model.Runtime + + # Write solution + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"\nSolution written to {solution_path}") + if model.SolCount > 0: + print(f"Objective value (mu): {result['objective_value']}") + print(f"Status: {result['status']}") + print(f"Assignment: {result['assignment']}") + print(f"Objective values per criterion: {result['objective_values_per_criterion']}") + print(f"Weighted deviations: {result['weighted_deviations']}") + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Solve the Linearized Compromise Assignment Problem (LCAP) using Gurobi" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON instance file" + ) + parser.add_argument( + "--solution_path", type=str, default="gurobi_solution_1.json", + help="Path for the output solution JSON file" + ) + parser.add_argument( + "--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds" + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_lcap(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/belhoul2014/gurobi_feasi_result/large_feasi_result_1.json b/tasks/belhoul2014/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belhoul2014/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/belhoul2014/gurobi_feasi_result/large_feasi_result_2.json b/tasks/belhoul2014/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belhoul2014/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/belhoul2014/gurobi_feasi_result/large_feasi_result_3.json b/tasks/belhoul2014/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belhoul2014/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/belhoul2014/gurobi_feasi_result/large_feasi_result_4.json b/tasks/belhoul2014/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belhoul2014/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/belhoul2014/gurobi_feasi_result/large_feasi_result_5.json b/tasks/belhoul2014/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belhoul2014/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/belhoul2014/gurobi_feasi_result/tiny_feasi_result.json b/tasks/belhoul2014/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belhoul2014/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/belhoul2014/gurobi_solution/large_solution_1.json b/tasks/belhoul2014/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a9c19d6f658516073871a6179d2b040a2a39b83b --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6d621820c097b317c69e7c4f17095a70214bb38027b86e1929ad23cf392e65c +size 11414776 diff --git a/tasks/belhoul2014/gurobi_solution/large_solution_2.json b/tasks/belhoul2014/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..95dd74597b73a539cf6914a7fe773ed3024818cc --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:567939cb78cb3b61a816b09d6a9d384b4b8286c4cfce20425cdf20dab64b7c90 +size 11414761 diff --git a/tasks/belhoul2014/gurobi_solution/large_solution_3.json b/tasks/belhoul2014/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ea9a0cf4fe0f002eaaf7d8eec6b005f7014804af --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b726860a2e90cb9d836d4b87aa96dd5f1f30ddd255fff526710fde30c4cad76b +size 11414784 diff --git a/tasks/belhoul2014/gurobi_solution/large_solution_4.json b/tasks/belhoul2014/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..18208f774ffc1a390e5e56893693fa8774ea1394 --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad466aa73b8376059040fce173de0aa836334cbeebdef03cb138065807a87ece +size 11414755 diff --git a/tasks/belhoul2014/gurobi_solution/large_solution_5.json b/tasks/belhoul2014/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..6d6f1e27c3c61c0b2a105fcb40090f247a99fa30 --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60b1e3f67711270bf364fbe53832effa4d1b4a98fe0396f70b2ae633d3a8cb2e +size 11414780 diff --git a/tasks/belhoul2014/gurobi_solution/tiny_solution.json b/tasks/belhoul2014/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..d1a3ee25720a88394f8dbc5e1efba597c565060c --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a13e5b6a79bc20e34e560e8f560410401169ce5ab6ba39da3179435ad4465fe5 +size 1575 diff --git a/tasks/belhoul2014/gurobi_solution_log/large_log_1.jsonl b/tasks/belhoul2014/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..74ec704e0b28445f532b52ebcb9ef5d72b29af49 --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0863b2e050e275b720242873ed80a0cc0ee8430586e6b450c821b33c7c96012 +size 113 diff --git a/tasks/belhoul2014/gurobi_solution_log/large_log_2.jsonl b/tasks/belhoul2014/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..508b4457cd872c372feb08fb0a53893cf59fed81 --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87bb95266e7102e6de59446acc768772ad6a768965c6c25b1917fc7d4eaafd9e +size 289 diff --git a/tasks/belhoul2014/gurobi_solution_log/large_log_3.jsonl b/tasks/belhoul2014/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cbcc781ad65a8ba2600c5ca2c1f6e04194f513af --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7225a05f8287a1d520e354aee64705f1f38eb650a5e93ec364927a8fc223e63a +size 460 diff --git a/tasks/belhoul2014/gurobi_solution_log/large_log_4.jsonl b/tasks/belhoul2014/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2136ac25bf7b0d3104e82f4e615aa4fb3a858dd7 --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7815366ce976d9af7e3a493a4b90cb4377d417d5a2930e1182b2416c18bcb8e +size 113 diff --git a/tasks/belhoul2014/gurobi_solution_log/large_log_5.jsonl b/tasks/belhoul2014/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f63e240fc7766a3e14d5e2e2f633e0abfd267073 --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1824200f5b55f26653fe674904b350d4e0f8d6fe08ad46b5acae2aab54f9180c +size 112 diff --git a/tasks/belhoul2014/gurobi_solution_log/tiny_log.jsonl b/tasks/belhoul2014/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..33c29ea2f49ec10aff101451a388a1d7fa6b49cd --- /dev/null +++ b/tasks/belhoul2014/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7681daa60b92f55edb3e052cfd2b1b05c737f23f97f15c36766b157ce2928354 +size 57 diff --git a/tasks/belhoul2014/instance/large_instance_1.json b/tasks/belhoul2014/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..369e3dfae5728fb994b6b5ddb72db6afab21f537 --- /dev/null +++ b/tasks/belhoul2014/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e23edb4e44fa69d4db8780c978f5fa8e755c9a029fca46b28ec1880396c7635 +size 30185812 diff --git a/tasks/belhoul2014/instance/large_instance_2.json b/tasks/belhoul2014/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..5d36d553db5bd055aeb7b225ab1af0116ab6a989 --- /dev/null +++ b/tasks/belhoul2014/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a07b45eee85da6abb9885f02782ec8b04d838fe37e06006f0e2733023dd1ee5f +size 30269681 diff --git a/tasks/belhoul2014/instance/large_instance_3.json b/tasks/belhoul2014/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..939fdeaead40c3df9c908c9e52af3dc7da807cce --- /dev/null +++ b/tasks/belhoul2014/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d4978c4538eb74c3c2a222fc38dd3b68ba7e64b7a28dbb2e09ae1f8dbffa030 +size 30375176 diff --git a/tasks/belhoul2014/instance/large_instance_4.json b/tasks/belhoul2014/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..66d67bf9795c242c3b5f087cb7be636831f7c054 --- /dev/null +++ b/tasks/belhoul2014/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1127186b3623349c5404297bf7933ac5940ae405cfcadbc99326322179b5b9d +size 30043725 diff --git a/tasks/belhoul2014/instance/large_instance_5.json b/tasks/belhoul2014/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9642c9a9f1885658795914bcc3c4987374bc5db3 --- /dev/null +++ b/tasks/belhoul2014/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c68e1d6ec3ec10879fa0e1a8f52822f66ceaa54ea9801616aa4db316915930e3 +size 30288196 diff --git a/tasks/belhoul2014/instance/tiny_instance.json b/tasks/belhoul2014/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..1da8ec89896a7cbd46fe714146c33a47b59dbeca --- /dev/null +++ b/tasks/belhoul2014/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8e8cafce722cd91bf6af7cb23aa7c1557a84cd2e871ebdeaa3f2a05808c9aec +size 3147 diff --git a/tasks/belhoul2014/instance_schema.json b/tasks/belhoul2014/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d896d23b04184dca70e1ec5607ab599768bac43f --- /dev/null +++ b/tasks/belhoul2014/instance_schema.json @@ -0,0 +1,9 @@ +{ + "n": " Number of tasks (and agents) to be matched one-to-one.", + "p": " Number of distinct performance criteria evaluated for each assignment.", + "cost_matrices": " Cost of assigning task i to agent j under criterion k.", + "ideal_point": " Best achievable total cost for each criterion when that criterion is optimized independently.", + "nadir_approximation": " Worst total cost observed for each criterion across the set of individually optimal solutions.", + "reference_point": " Target total cost for each criterion that the assignment should aim toward.", + "search_direction_lambda": " Weight controlling how deviations from the target are scaled for each criterion." +} diff --git a/tasks/belhoul2014/mathematical_formulation.md b/tasks/belhoul2014/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..e423eec8d799b1f4bbd0a9b8b8cc0703bb25a206 --- /dev/null +++ b/tasks/belhoul2014/mathematical_formulation.md @@ -0,0 +1,41 @@ +# Sets and Indices + +- $n$: number of tasks (equal to the number of agents); $i, j \in \{1,\ldots,n\}$. + +- $p$: number of objectives, indexed by $k = 1,\ldots,p$. + +# Parameters + +- $c^k_{ij} \in \mathbb{Z}_+$: cost of assigning task $i$ to agent $j$ with respect to objective $k$. + +- $\lambda = (\lambda_1,\ldots,\lambda_p) \in \mathbb{R}^p_{>0}$: strictly positive weighting vector representing the decision-maker’s search direction. + +- $\bar{z} = (\bar{z}_1,\ldots,\bar{z}_p) \in \mathbb{R}^p$: reference point (e.g. the ideal point $z^*$). + +# Decision Variables + +- $x_{ij} \in \{0,1\}$: equals $1$ if task $i$ is assigned to agent $j$, $0$ otherwise, for $i,j = 1,\ldots,n$. + +- $\mu$: unrestricted scalar variable (epigraph of the Tchebychev objective). + +# Compromise Assignment Problem (CAP) + +The Compromise Assignment Problem uses the weighted Tchebychev / achievement scalarizing function: $$\begin{align} + \min \quad & \max_{k=1,\ldots,p}\ \bigl\{\lambda_k\!\left(\sum_{i=1}^{n}\sum_{j=1}^{n} c^k_{ij}\, x_{ij} - \bar{z}_k\right)\bigr\} \tag{CAP} \\ + \text{s.t.}\quad + & \sum_{j=1}^{n} x_{ij} = 1, && i = 1,\ldots,n \notag \\ + & \sum_{i=1}^{n} x_{ij} = 1, && j = 1,\ldots,n \notag \\ + & x_{ij} \in \{0,1\}, && i,j = 1,\ldots,n \notag +\end{align}$$ + +# Linearized Compromise Assignment Problem (LCAP) + +The paper linearizes (CAP) by introducing a scalar variable $\mu$, yielding the mixed-integer linear program: $$\begin{align} + \min \quad & \mu \tag{LCAP-1} \\ + \text{s.t.}\quad + & \mu \;\ge\; \lambda_k\!\left(\sum_{i=1}^{n}\sum_{j=1}^{n} c^k_{ij}\, x_{ij} - \bar{z}_k\right), && k = 1,\ldots,p \tag{LCAP-2} \\ + & \sum_{j=1}^{n} x_{ij} = 1, && i = 1,\ldots,n \tag{LCAP-3} \\ + & \sum_{i=1}^{n} x_{ij} = 1, && j = 1,\ldots,n \tag{LCAP-4} \\ + & x_{ij} \in \{0,1\}, && i, j = 1,\ldots,n \notag \\ + & \mu \text{ unrestricted}. \notag +\end{align}$$ diff --git a/tasks/belhoul2014/problem_description.txt b/tasks/belhoul2014/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..6e43b00d87b1625a5096f995dc3f8d0d594e48f9 --- /dev/null +++ b/tasks/belhoul2014/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A company must assign n tasks to n agents on a one-to-one basis, so that every task is performed by exactly one agent and every agent performs exactly one task. There are p distinct performance criteria, and for each criterion the cost of assigning any particular task to any particular agent is a given non-negative integer. The input therefore specifies the number of tasks and agents (n), the number of criteria (p), one n-by-n cost matrix per criterion, a reference point consisting of one real-valued target per criterion, and a search direction consisting of one strictly positive weight per criterion. + +For a given assignment, the total cost under each criterion is the sum of the individual assignment costs for that criterion across all task-agent pairs that are selected. The goal is to find the assignment that best compromises among the p criteria, where the quality of a compromise is measured as follows: for each criterion, compute the product of its search-direction weight and the difference between the assignment's total cost on that criterion and the corresponding reference-point value, then take the maximum of these p products. The assignment to be found is the one that minimizes this worst-case weighted deviation. + +To express this as a single problem, an auxiliary value representing the worst-case weighted deviation is introduced. This value is unrestricted in sign and must be at least as large as, for every criterion, the product of that criterion's search-direction weight and the difference between the assignment's total cost on that criterion and the reference-point value for that criterion. Each task must be assigned to exactly one agent, and each agent must be assigned exactly one task. The goal is to minimize the worst-case weighted deviation value. diff --git a/tasks/belhoul2014/solution_logger.py b/tasks/belhoul2014/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/belhoul2014/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/belhoul2014/solution_schema.json b/tasks/belhoul2014/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9ff8c8b63231395109ce4ab2ef0b41fb54ac070b --- /dev/null +++ b/tasks/belhoul2014/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Worst-case weighted deviation of the chosen assignment's total costs from the reference point across all criteria.", + "assignment": " Agent assigned to each task, where entry i gives the agent performing task i.", + "assignment_matrix": " One-to-one pairing between tasks and agents (1 if task i is assigned to agent j, 0 otherwise)." +} diff --git a/tasks/belvaux2000/feasibility_check.py b/tasks/belvaux2000/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..766db3d2a6098255f16ce640913ab025c31c497d --- /dev/null +++ b/tasks/belvaux2000/feasibility_check.py @@ -0,0 +1,533 @@ +""" +Feasibility checker for the Con-NT Small Bucket Lot-Sizing Model. + +From: Belvaux & Wolsey (2000), "bc-prod: A Specialized Branch-and-Cut System +for Lot-Sizing Problems", Management Science 46(5):724-738. + +Checks all hard constraints from the mathematical formulation (math_model.txt), +numbered strictly top-to-bottom in the formulation section. + +Constraints in the formulation section (top to bottom): + Constraint 1: Flow balance for intermediate products (multilevel only) + Constraint 2: Flow conservation for final products (generic) + Constraint 3: Capacity / variable upper bound (generic) + Constraint 4: Minimum production (generic, only if L^{ik} > 0) + Constraint 5: Start-up / switch-off linking (generic) + Constraint 6: Variable domains (generic): x, s, r >= 0; y, z, w in {0,1} + Constraint 7: Single set-up per machine per period (additional linking) + Constraint 8: Machine capacity constraint (additional linking) + -- Example 1 (set1ch) constraints -- + Constraint 9: Flow balance for set1ch (eq 6) + Constraint 10: Capacity for set1ch (eq 7) + Constraint 11: Machine capacity for set1ch (eq 8) + Constraint 12: Variable domains for set1ch + -- Example 2 (Con-NT) constraints -- + Constraint 13: Flow balance (eq 9) + Constraint 14: Capacity with startup (eq 10) + Constraint 15: Startup definition (eq 11) + Constraint 16: One item per machine per period (eq 12) + Constraint 17: Startup bound z <= y (eq 13) + Constraint 18: Linking constraint (eq 14) + Constraint 19: Variable domains for Con-NT: s, r, x >= 0; y, z in {0,1}; s0=r0=0 + Constraint 20: Objective consistency (Tier C anti-exploit check) -- + reported objective_value must equal recomputed + sum_{i,k,t}(f*y + g*z) + sum_{i,t}(h_i*s + e_i*r). + +The instances are Con-NT (Example 2), so constraints 13-19 are the active ones. +Constraints 1-5 are generic templates; constraints 13-18 are the Con-NT specializations. +Constraint 6 variable domains are also checked via Constraint 19's specialization. +""" + +import json +import argparse +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('backlog', 'objective_value', 'production', 'setup', 'startup', 'stock') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def get_val(dct, key, default=0.0): + """Get a value from a sparse dict (solution), defaulting to 0.""" + return dct.get(key, default) + + +def record_violation(violations_list, magnitudes_list, constraint_idx, lhs, rhs, message): + """Record a constraint violation with normalized magnitude.""" + raw_excess = abs(lhs - rhs) + normalizer = max(abs(rhs), EPS) + ratio = raw_excess / normalizer + violations_list.append(message) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(raw_excess), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +def check_feasibility(instance, solution): + NI = instance["parameters"]["NI"] + NK = instance["parameters"]["NK"] + NT = instance["parameters"]["NT"] + + C = instance["machine_data"]["capacity_C"] + sigma = instance["machine_data"]["startup_time_sigma"] + demand = instance["demand"] + s0 = instance["initial_conditions"]["initial_stock_s0"] + r0 = instance["initial_conditions"]["initial_backlog_r0"] + + f_setup = instance["costs"]["setup_cost_f"] + g_startup = instance["costs"]["startup_cost_g"] + h_hold = instance["costs"]["holding_cost_h"] + e_back = instance["costs"]["backlogging_cost_e"] + + prod = solution.get("production", {}) + stock = solution.get("stock", {}) + backlog = solution.get("backlog", {}) + setup = solution.get("setup", {}) + startup = solution.get("startup", {}) + + # Helper to extract variable values from sparse solution dicts + def x(i, k, t): + return get_val(prod, f"x_{i}_{k}_{t}") + + def s(i, t): + return get_val(stock, f"s_{i}_{t}") + + def r(i, t): + return get_val(backlog, f"r_{i}_{t}") + + def y(i, k, t): + return get_val(setup, f"y_{i}_{k}_{t}") + + def z(i, k, t): + return get_val(startup, f"z_{i}_{k}_{t}") + + violations = [] + magnitudes = [] + violated_constraints = set() + + # ========================================================================= + # Constraint 13 (paper eq 9): Flow balance for final products (Con-NT) + # s_{i,t-1} - r_{i,t-1} + sum_k x_{ikt} = d_{it} + s_{it} - r_{it} + # for all i, t + # This is an equality constraint. + # ========================================================================= + for i in range(NI): + for t in range(NT): + s_prev = s0[i] if t == 0 else s(i, t - 1) + r_prev = r0[i] if t == 0 else r(i, t - 1) + + lhs = s_prev - r_prev + sum(x(i, k, t) for k in range(NK)) + rhs = demand[i][t] + s(i, t) - r(i, t) + + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(13) + record_violation( + violations, magnitudes, 13, lhs, rhs, + f"Constraint 13 (flow balance eq 9) violated for item {i}, period {t}: " + f"LHS={lhs:.6f}, RHS={rhs:.6f}, diff={violation_amount:.6f}" + ) + + # ========================================================================= + # Constraint 14 (paper eq 10): Capacity with startup + # x_{ikt} + sigma_k * z_{ikt} <= C_k * y_{ikt} + # for all i, k, t + # This is a <= constraint. + # ========================================================================= + for i in range(NI): + for k in range(NK): + for t in range(NT): + lhs = x(i, k, t) + sigma[k] * z(i, k, t) + rhs = C[k] * y(i, k, t) + + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(14) + record_violation( + violations, magnitudes, 14, lhs, rhs, + f"Constraint 14 (capacity eq 10) violated for item {i}, machine {k}, period {t}: " + f"x={x(i,k,t):.4f} + sigma*z={sigma[k]*z(i,k,t):.4f} = {lhs:.4f} > " + f"C*y={rhs:.4f}" + ) + + # ========================================================================= + # Constraint 15 (paper eq 11): Startup definition + # z_{ikt} >= y_{ikt} - y_{ik,t-1} + # for all i, k, t + # This is a >= constraint: z >= y_curr - y_prev + # Equivalently: violation if y_curr - y_prev - z > 0 + # ========================================================================= + for i in range(NI): + for k in range(NK): + for t in range(NT): + y_prev = 0 if t == 0 else y(i, k, t - 1) + lhs = z(i, k, t) + rhs = y(i, k, t) - y_prev + + violation_amount = rhs - lhs # >= constraint: RHS exceeds LHS + if violation_amount > TOL: + violated_constraints.add(15) + record_violation( + violations, magnitudes, 15, lhs, rhs, + f"Constraint 15 (startup def eq 11) violated for item {i}, machine {k}, period {t}: " + f"z={z(i,k,t):.4f} < y_curr - y_prev = {y(i,k,t):.4f} - {y_prev:.4f} = {rhs:.4f}" + ) + + # ========================================================================= + # Constraint 16 (paper eq 12): One item per machine per period + # sum_i y_{ikt} <= 1 for all k, t + # This is a <= constraint. + # ========================================================================= + for k in range(NK): + for t in range(NT): + lhs = sum(y(i, k, t) for i in range(NI)) + rhs = 1.0 + + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(16) + record_violation( + violations, magnitudes, 16, lhs, rhs, + f"Constraint 16 (one setup eq 12) violated for machine {k}, period {t}: " + f"sum_i y_ikt = {lhs:.4f} > 1" + ) + + # ========================================================================= + # Constraint 17 (paper eq 13): Startup bound + # z_{ikt} <= y_{ikt} for all i, k, t + # This is a <= constraint. + # ========================================================================= + for i in range(NI): + for k in range(NK): + for t in range(NT): + lhs = z(i, k, t) + rhs = y(i, k, t) + + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(17) + record_violation( + violations, magnitudes, 17, lhs, rhs, + f"Constraint 17 (z<=y eq 13) violated for item {i}, machine {k}, period {t}: " + f"z={z(i,k,t):.4f} > y={y(i,k,t):.4f}" + ) + + # ========================================================================= + # Constraint 18 (paper eq 14): Linking constraint + # y_{ik,t-1} + z_{ikt} + sum_{j!=i} (y_{jkt} - z_{jkt}) <= 1 + # for all i, k, t + # This is a <= constraint. + # ========================================================================= + for i in range(NI): + for k in range(NK): + for t in range(NT): + y_prev_i = 0 if t == 0 else y(i, k, t - 1) + lhs = y_prev_i + z(i, k, t) + for j in range(NI): + if j != i: + lhs += y(j, k, t) - z(j, k, t) + rhs = 1.0 + + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(18) + record_violation( + violations, magnitudes, 18, lhs, rhs, + f"Constraint 18 (linking eq 14) violated for item {i}, machine {k}, period {t}: " + f"LHS={lhs:.4f} > 1" + ) + + # ========================================================================= + # Constraint 19: Variable domains for Con-NT + # s, r, x >= 0; y, z in {0, 1}; s^i_0 = r^i_0 = 0 + # ========================================================================= + + # Check non-negativity of continuous variables (x, s, r >= 0) + for i in range(NI): + for k in range(NK): + for t in range(NT): + val = x(i, k, t) + if val < -TOL: + violated_constraints.add(19) + record_violation( + violations, magnitudes, 19, val, 0.0, + f"Constraint 19 (domain) violated: x_{i}_{k}_{t} = {val:.6f} < 0" + ) + + for i in range(NI): + for t in range(NT): + val_s = s(i, t) + if val_s < -TOL: + violated_constraints.add(19) + record_violation( + violations, magnitudes, 19, val_s, 0.0, + f"Constraint 19 (domain) violated: s_{i}_{t} = {val_s:.6f} < 0" + ) + val_r = r(i, t) + if val_r < -TOL: + violated_constraints.add(19) + record_violation( + violations, magnitudes, 19, val_r, 0.0, + f"Constraint 19 (domain) violated: r_{i}_{t} = {val_r:.6f} < 0" + ) + + # Check binary variables y, z in {0, 1} + for i in range(NI): + for k in range(NK): + for t in range(NT): + val_y = y(i, k, t) + if abs(val_y - round(val_y)) > TOL or round(val_y) not in (0, 1): + violated_constraints.add(19) + record_violation( + violations, magnitudes, 19, val_y, + round(val_y) if round(val_y) in (0, 1) else 0.0, + f"Constraint 19 (domain) violated: y_{i}_{k}_{t} = {val_y:.6f} is not binary" + ) + val_z = z(i, k, t) + if abs(val_z - round(val_z)) > TOL or round(val_z) not in (0, 1): + violated_constraints.add(19) + record_violation( + violations, magnitudes, 19, val_z, + round(val_z) if round(val_z) in (0, 1) else 0.0, + f"Constraint 19 (domain) violated: z_{i}_{k}_{t} = {val_z:.6f} is not binary" + ) + + # ========================================================================= + # Constraint 20: Objective consistency (Tier C anti-exploit check) + # reported objective_value must equal recomputed + # sum_{i,k,t} (f * y_{ikt} + g * z_{ikt}) + # + sum_{i,t} (h_i * s_{it} + e_i * r_{it}) + # All variables (y, z, s, r) appearing in the obj formula are present in + # the solution, so a full recompute is exact (modulo float rounding from + # solution serialization). Tolerance: 0.1% relative with 1e-3 absolute + # floor, matching the recipe in docs/data_review_fix/checker_add_obj_recompute.md. + # ========================================================================= + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None and math.isfinite(reported): + true_obj = 0.0 + for i in range(NI): + for k in range(NK): + for t in range(NT): + true_obj += f_setup * y(i, k, t) + g_startup * z(i, k, t) + for t in range(NT): + true_obj += h_hold[i] * s(i, t) + e_back[i] * r(i, t) + abs_diff = abs(reported - true_obj) + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(20) + record_violation( + violations, magnitudes, 20, reported, true_obj, + f"Constraint 20 (objective consistency) violated: " + f"reported objective_value={reported} differs from recomputed " + f"sum_(i,k,t)(f*y+g*z) + sum_(i,t)(h_i*s+e_i*r)={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={tol:.3g})" + ) + elif reported is not None: + # Non-finite reported value (e.g. inf, nan) -- always inconsistent. + violated_constraints.add(20) + record_violation( + violations, magnitudes, 20, reported, 0.0, + f"Constraint 20 (objective consistency) violated: " + f"reported objective_value={reported} is not a finite number" + ) + + feasible = len(violated_constraints) == 0 + + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the Con-NT lot-sizing model (Belvaux & Wolsey 2000)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON candidate solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + n_violations = len(result["violated_constraints"]) + print(f"{status} ({n_violations} violated constraint(s))") + 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/belvaux2000/gurobi_code.py b/tasks/belvaux2000/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8a5ef77ecbe3ab730482725d8ea2b87f251f82 --- /dev/null +++ b/tasks/belvaux2000/gurobi_code.py @@ -0,0 +1,289 @@ +""" +Gurobi implementation of the Con-NT Small Bucket Lot-Sizing Model (SB-1). + +From: Belvaux & Wolsey (2000), "bc-prod: A Specialized Branch-and-Cut System +for Lot-Sizing Problems", Management Science 46(5):724-738. + +This implements the Con-NT model (Example 2 in the paper, Equations 9-14): + min sum_{i,k,t} (f * y_{ikt} + g * z_{ikt}) + + sum_{i,t} (h_i * s_{it} + e_i * r_{it}) + s.t. + (9) s_{i,t-1} - r_{i,t-1} + sum_k x_{ikt} = d_{it} + s_{it} - r_{it} for all i, t + (10) x_{ikt} + sigma_k * z_{ikt} <= C_k * y_{ikt} for all i, k, t + (11) z_{ikt} >= y_{ikt} - y_{ik,t-1} for all i, k, t + (12) sum_i y_{ikt} <= 1 for all k, t + (13) z_{ikt} <= y_{ikt} for all i, k, t + (14) y_{ik,t-1} + z_{ikt} + sum_{j!=i} (y_{jkt} - z_{jkt}) <= 1 for all i, k, t + s, r, x >= 0; y, z in {0, 1} + s_0 = r_0 = 0 +""" + +import json +import argparse +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, 'r') as f: + return json.load(f) + + +def solve(instance_path, solution_path, time_limit): + data = load_instance(instance_path) + + NI = data["parameters"]["NI"] + NK = data["parameters"]["NK"] + NT = data["parameters"]["NT"] + + f = data["costs"]["setup_cost_f"] # scalar setup cost + g = data["costs"]["startup_cost_g"] # scalar startup cost + h = data["costs"]["holding_cost_h"] # list length NI + e = data["costs"]["backlogging_cost_e"] # list length NI + + C = data["machine_data"]["capacity_C"] # list length NK + sigma = data["machine_data"]["startup_time_sigma"] # list length NK + + # demand[i][t] -- NI x NT + demand = data["demand"] + + s0 = data["initial_conditions"]["initial_stock_s0"] # list length NI + r0 = data["initial_conditions"]["initial_backlog_r0"] # list length NI + + # Index ranges (0-based internally) + items = range(NI) + machines = range(NK) + periods = range(NT) # 0..NT-1 represents periods 1..NT + + # Create model + model = gp.Model("ConNT_LotSizing") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i,k,t]: production of item i on machine k in period t + x = {} + for i in items: + for k in machines: + for t in periods: + x[i, k, t] = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, + name=f"x_{i}_{k}_{t}") + + # s[i,t]: stock of item i at end of period t + s = {} + for i in items: + for t in periods: + s[i, t] = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, + name=f"s_{i}_{t}") + + # r[i,t]: backlog of item i at end of period t + r = {} + for i in items: + for t in periods: + r[i, t] = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, + name=f"r_{i}_{t}") + + # y[i,k,t]: setup variable (binary) + y = {} + for i in items: + for k in machines: + for t in periods: + y[i, k, t] = model.addVar(vtype=GRB.BINARY, + name=f"y_{i}_{k}_{t}") + + # z[i,k,t]: startup variable (binary) + z = {} + for i in items: + for k in machines: + for t in periods: + z[i, k, t] = model.addVar(vtype=GRB.BINARY, + name=f"z_{i}_{k}_{t}") + + model.update() + + # Objective: min sum_{i,k,t} (f * y + g * z) + sum_{i,t} (h_i * s + e_i * r) + obj = gp.LinExpr() + for i in items: + for k in machines: + for t in periods: + obj += f * y[i, k, t] + g * z[i, k, t] + for t in periods: + obj += h[i] * s[i, t] + e[i] * r[i, t] + model.setObjective(obj, GRB.MINIMIZE) + + # Constraint (9): Flow balance + # s_{i,t-1} - r_{i,t-1} + sum_k x_{ikt} = d_{it} + s_{it} - r_{it} + for i in items: + for t in periods: + lhs = gp.LinExpr() + # s_{i,t-1}: if t=0, use s0[i] + if t == 0: + lhs += s0[i] + else: + lhs += s[i, t - 1] + # -r_{i,t-1}: if t=0, use r0[i] + if t == 0: + lhs += -r0[i] + else: + lhs += -r[i, t - 1] + # + sum_k x_{ikt} + for k in machines: + lhs += x[i, k, t] + + rhs = demand[i][t] + s[i, t] - r[i, t] + model.addConstr(lhs == rhs, name=f"flow_{i}_{t}") + + # Constraint (10): Capacity with startup time + # x_{ikt} + sigma_k * z_{ikt} <= C_k * y_{ikt} + for i in items: + for k in machines: + for t in periods: + model.addConstr( + x[i, k, t] + sigma[k] * z[i, k, t] <= C[k] * y[i, k, t], + name=f"cap_{i}_{k}_{t}" + ) + + # Constraint (11): Startup definition + # z_{ikt} >= y_{ikt} - y_{ik,t-1} + # For t=0: y_{ik,-1} is not defined. + # ASSUMPTION (inferred): y_{ik,0} (period before the horizon) = 0, + # meaning no machine is set up before the planning horizon starts. + # This is consistent with the initial conditions s_0 = r_0 = 0. + for i in items: + for k in machines: + for t in periods: + if t == 0: + y_prev = 0 + else: + y_prev = y[i, k, t - 1] + model.addConstr( + z[i, k, t] >= y[i, k, t] - y_prev, + name=f"startup_{i}_{k}_{t}" + ) + + # Constraint (12): At most one item per machine per period + # sum_i y_{ikt} <= 1 + for k in machines: + for t in periods: + model.addConstr( + gp.quicksum(y[i, k, t] for i in items) <= 1, + name=f"onesetup_{k}_{t}" + ) + + # Constraint (13): z_{ikt} <= y_{ikt} + for i in items: + for k in machines: + for t in periods: + model.addConstr( + z[i, k, t] <= y[i, k, t], + name=f"zbound_{i}_{k}_{t}" + ) + + # Constraint (14): Linking constraint + # y_{ik,t-1} + z_{ikt} + sum_{j!=i} (y_{jkt} - z_{jkt}) <= 1 + # For t=0: y_{ik,-1} = 0 (same assumption as constraint 11) + for i in items: + for k in machines: + for t in periods: + if t == 0: + y_prev_i = 0 + else: + y_prev_i = y[i, k, t - 1] + lhs = y_prev_i + z[i, k, t] + for j in items: + if j != i: + lhs += y[j, k, t] - z[j, k, t] + model.addConstr(lhs <= 1, name=f"link_{i}_{k}_{t}") + + # Solve + model.optimize() + + # Extract solution + result = { + "instance_id": data.get("instance_id", 1), + "solver": "gurobi", + "status": model.Status, + "objective_value": None, + "production": {}, + "stock": {}, + "backlog": {}, + "setup": {}, + "startup": {} + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + + for i in items: + for k in machines: + for t in periods: + val = x[i, k, t].X + if val > 1e-6: + result["production"][f"x_{i}_{k}_{t}"] = round(val, 4) + for t in periods: + s_val = s[i, t].X + r_val = r[i, t].X + if s_val > 1e-6: + result["stock"][f"s_{i}_{t}"] = round(s_val, 4) + if r_val > 1e-6: + result["backlog"][f"r_{i}_{t}"] = round(r_val, 4) + for k in machines: + for t in periods: + if y[i, k, t].X > 0.5: + result["setup"][f"y_{i}_{k}_{t}"] = 1 + if z[i, k, t].X > 0.5: + result["startup"][f"z_{i}_{k}_{t}"] = 1 + + if model.Status == GRB.OPTIMAL: + result["status_text"] = "OPTIMAL" + elif model.Status == GRB.TIME_LIMIT: + result["status_text"] = "TIME_LIMIT" + result["best_bound"] = model.ObjBound + result["gap"] = model.MIPGap + else: + result["status_text"] = f"STATUS_{model.Status}" + else: + result["status_text"] = "NO_SOLUTION_FOUND" + result["objective_value"] = None + + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status_text']}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Gurobi solver for the Con-NT Small Bucket Lot-Sizing Problem" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, + default="gurobi_solution_1.json", + help="Path to write the solution JSON file") + parser.add_argument("--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/belvaux2000/gurobi_feasi_result/large_feasi_result_1.json b/tasks/belvaux2000/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belvaux2000/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/belvaux2000/gurobi_feasi_result/large_feasi_result_2.json b/tasks/belvaux2000/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belvaux2000/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/belvaux2000/gurobi_feasi_result/large_feasi_result_3.json b/tasks/belvaux2000/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belvaux2000/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/belvaux2000/gurobi_feasi_result/large_feasi_result_4.json b/tasks/belvaux2000/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belvaux2000/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/belvaux2000/gurobi_feasi_result/large_feasi_result_5.json b/tasks/belvaux2000/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belvaux2000/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/belvaux2000/gurobi_feasi_result/tiny_feasi_result.json b/tasks/belvaux2000/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/belvaux2000/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/belvaux2000/gurobi_solution/large_solution_1.json b/tasks/belvaux2000/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c1eac9fc957c2a15e3e949b989c931f6f0b8e70e --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4cf3ab2c0d1e67d1eaddf67f662d75b5310d05b655458ce6239549ebe47e8a11 +size 10332 diff --git a/tasks/belvaux2000/gurobi_solution/large_solution_2.json b/tasks/belvaux2000/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b9f178c4547a0980b12e164484c21418754a35b5 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:243824132eaf029e1276fbd7bbc179ee5308de0c1c8eead105883da9c8dcdfe4 +size 9932 diff --git a/tasks/belvaux2000/gurobi_solution/large_solution_3.json b/tasks/belvaux2000/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..85219ffcd90652394fcb5422cbd705264f88a5bf --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f16c9a444c6d784dfde18cf572a115527753d065242e0d1385fbfd81d78de50a +size 9819 diff --git a/tasks/belvaux2000/gurobi_solution/large_solution_4.json b/tasks/belvaux2000/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..6ab58727a93c5ca7a2949f9ea6c19ca18ab12b01 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b748a9274f1617b386c29a491261eeb0064c97132c956d01e1189bbe09c99fa +size 9524 diff --git a/tasks/belvaux2000/gurobi_solution/large_solution_5.json b/tasks/belvaux2000/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a238ee0a707c38befa96a07deed915165261750c --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7caf69b8260f920b85da7227b0455df2b29e8a718806c904fad29ac8b3d1f809 +size 10230 diff --git a/tasks/belvaux2000/gurobi_solution/tiny_solution.json b/tasks/belvaux2000/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb740779b5c263174eff476275cc904c7a95918 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7eff771b68db6c1644f3cfca8d9e015cef7da5193f383ad9c1208678f2631ba0 +size 1048 diff --git a/tasks/belvaux2000/gurobi_solution_log/large_log_1.jsonl b/tasks/belvaux2000/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..62460576b6c56993bd21f0c01505c2380d6cf5a9 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:589cef55da11474b52627e47e7678f6d0af42f9b5aaae040769547eec2b52885 +size 4772 diff --git a/tasks/belvaux2000/gurobi_solution_log/large_log_2.jsonl b/tasks/belvaux2000/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92a278f7f2bc6c244b03740dad5b2fc0ad7c9f10 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a9e4077dbe3024e743cf7a5b8fbb33b958ef41257d3351b065863c074e7c201 +size 4382 diff --git a/tasks/belvaux2000/gurobi_solution_log/large_log_3.jsonl b/tasks/belvaux2000/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac288c74d6d9121198fbbb4a3850442b79b617a9 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b308b230be1050a091e89df15808451480ecdc1ccbc0853a846e174f72d56ca +size 2698 diff --git a/tasks/belvaux2000/gurobi_solution_log/large_log_4.jsonl b/tasks/belvaux2000/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f33f56716e129b90ccd4e7236b44bec81429e8d5 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c01bdf55e1c80138c155ed928bcdd79b592a180f5448024ecbbb907a6b55f5e1 +size 2109 diff --git a/tasks/belvaux2000/gurobi_solution_log/large_log_5.jsonl b/tasks/belvaux2000/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e0d913952f4c9186205b0f42e5d57ea33f58b953 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e216da24315c8ec873979a6e297735214e2ab480bcda1d8cb7b3435eb225cdb +size 3145 diff --git a/tasks/belvaux2000/gurobi_solution_log/tiny_log.jsonl b/tasks/belvaux2000/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..51dd7ab20d5a5602c7ea22c7460f86920a1a93e1 --- /dev/null +++ b/tasks/belvaux2000/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2de60ba78d3b5317342cd284b238c47edac24f0547c4a168b69eae29286c995 +size 44 diff --git a/tasks/belvaux2000/instance/large_instance_1.json b/tasks/belvaux2000/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4582ab1132d1e5c45a0f55d2e0f75e6263754482 --- /dev/null +++ b/tasks/belvaux2000/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fef8685ad40ac5d66cf65e8aaa2f58700f24b5927f61b474d614b8742ce61c81 +size 5694 diff --git a/tasks/belvaux2000/instance/large_instance_2.json b/tasks/belvaux2000/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..462fb3693ca5595559c4aecd6b61535736f84ad3 --- /dev/null +++ b/tasks/belvaux2000/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31b15f886190175963f63c2a9aec3b76ada664a8954383276bbaa2e8cfc1227d +size 5451 diff --git a/tasks/belvaux2000/instance/large_instance_3.json b/tasks/belvaux2000/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e67c32e502fff6b1d66d693f073ac6fd4488de37 --- /dev/null +++ b/tasks/belvaux2000/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2cccd1beb01746162ff46facb13060db1768784a6e1b9fac64d6b5cda2790fe +size 5442 diff --git a/tasks/belvaux2000/instance/large_instance_4.json b/tasks/belvaux2000/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..be863100e2f765eee86141562b19c58cdf93e4f4 --- /dev/null +++ b/tasks/belvaux2000/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e188b7e56da488bf9ac6b1f378a0454998f55fdb11861d54c7064a35a667dc3 +size 5354 diff --git a/tasks/belvaux2000/instance/large_instance_5.json b/tasks/belvaux2000/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a066e6d608beb46232810794c797e74d438e6b8d --- /dev/null +++ b/tasks/belvaux2000/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74a5c28143287acc831ed91e313364d9b76b09c95a3bb6f3621789e652f1560d +size 5386 diff --git a/tasks/belvaux2000/instance/tiny_instance.json b/tasks/belvaux2000/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..289566da9ef94a86bac56263782c45081a08bd26 --- /dev/null +++ b/tasks/belvaux2000/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:520d862ba7f2334db869cca15742f86de5be9d0b736f636e6295c66df9c99ec8 +size 2251 diff --git a/tasks/belvaux2000/instance_schema.json b/tasks/belvaux2000/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..99b2f2388127594df1fd4073d047bd9b4e463294 --- /dev/null +++ b/tasks/belvaux2000/instance_schema.json @@ -0,0 +1,22 @@ +{ + "parameters": { + "NI": " Number of distinct items to be produced.", + "NK": " Number of machines available for production.", + "NT": " Number of discrete time periods in the planning horizon." + }, + "costs": { + "setup_cost_f": " Fixed cost incurred each period a machine is set up for any item, uniform across all items and machines.", + "startup_cost_g": " Fixed cost incurred each time a machine starts up for an item it was not set up for in the previous period, uniform across all items and machines.", + "holding_cost_h": " Per-unit cost of holding one unit of each item in inventory at the end of a period.", + "backlogging_cost_e": " Per-unit penalty cost for each unit of unmet demand (backlog) for each item at the end of a period." + }, + "machine_data": { + "capacity_C": " Maximum production quantity each machine can produce in any single period.", + "startup_time_sigma": " Amount of production capacity consumed on each machine when a startup occurs in a period." + }, + "demand": " Quantity of each item required by customers in each period.", + "initial_conditions": { + "initial_stock_s0": " Inventory on hand for each item at the start of the planning horizon.", + "initial_backlog_r0": " Unfulfilled demand for each item carried into the start of the planning horizon." + } +} diff --git a/tasks/belvaux2000/mathematical_formulation.md b/tasks/belvaux2000/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..b6e9f760fbd23c7bef4a200d78df8335a9f511fe --- /dev/null +++ b/tasks/belvaux2000/mathematical_formulation.md @@ -0,0 +1,65 @@ +# Original Formulation: Two-Machine Small-Bucket Lot-Sizing with Backlogging and Start-Ups (Con-NT) + +*Source: bc–prod: A Specialized Branch-and-Cut System for Lot-Sizing Problems, Gaetan Belvaux and Laurence A. Wolsey, 2000 (Management Science 46(5):724–738).* + +The paper describes the prototype system *bc–prod* via a generic lot-sizing template (Constraints (1)–(5)) and two concrete problem instances. The instance studied here is **Example 2 (Con-NT)**, the two-machine small-bucket model with backlogging and start-up costs/times stated in Eqs. (9)–(14); its variable symbols and reported objective are the ones carried into the computational experiments. The generic template and the big-bucket instance (set1ch) are recorded under **Variants**. + +## Sets and Indices + +- $i = 1, \dots, NI$ : items (products). + +- $k = 1, \dots, NK$ : machines (Con-NT uses two machines). + +- $t = 1, \dots, NT$ : time periods ($NT = 12/24$ in the instance). + +## Parameters + +- $f$ : set-up cost (uniform over all items and machines). + +- $g$ : start-up cost (uniform over all items and machines). + +- $h^i$ : per-unit inventory holding cost for item $i$. + +- $e^i$ : per-unit backlogging penalty cost for item $i$. + +- $d^i_t$ : prespecified demand for item $i$ in period $t$. + +- $C^k$ : production capacity of machine $k$ (constant over $t$). + +- $\sigma^k$ : start-up time – loss of production capacity on machine $k$ when a start-up occurs. + +## Decision Variables + +- $x^{ik}_t \geq 0$ : production of item $i$ on machine $k$ in period $t$ (continuous). + +- $s^i_t \geq 0$ : stock of item $i$ at the end of period $t$ (continuous). + +- $r^i_t \geq 0$ : backlog of item $i$ at the end of period $t$ (continuous). + +- $y^{ik}_t \in \{0,1\}$ : set-up variable; $1$ if machine $k$ is set up to produce item $i$ in period $t$. + +- $z^{ik}_t \in \{0,1\}$ : start-up variable; $1$ if machine $k$ starts a sequence of set-ups of item $i$ in period $t$. + +## Objective + +$$\begin{align} +\min \quad \sum_{i,k,t} \bigl( f\,y^{ik}_t + g\,z^{ik}_t \bigr) + + \sum_{i,t} \bigl( h^i\,s^i_t + e^i\,r^i_t \bigr) \notag +\end{align}$$ + +## Constraints + +$$\begin{align} +s^i_{t-1} - r^i_{t-1} + \sum_{k} x^{ik}_t + &= d^i_t + s^i_t - r^i_t && \forall\, i,\,t \tag{9}\\[2pt] +x^{ik}_t + \sigma^k z^{ik}_t + &\leq C^k y^{ik}_t && \forall\, i,\,k,\,t \tag{10}\\[2pt] +z^{ik}_t &\geq y^{ik}_t - y^{ik}_{t-1} && \forall\, i,\,k,\,t \tag{11}\\[2pt] +\sum_{i} y^{ik}_t &\leq 1 && \forall\, k,\,t \tag{12}\\[2pt] +z^{ik}_t &\leq y^{ik}_t && \forall\, i,\,k,\,t \tag{13}\\[2pt] +y^{ik}_{t-1} + z^{ik}_t + \sum_{j:\, j \neq i} \bigl( y^{jk}_t - z^{jk}_t \bigr) + &\leq 1 && \forall\, i,\,k,\,t \tag{14} +\end{align}$$ with domains and initial conditions $$\begin{align} +s,\, r,\, x &\geq 0, \qquad y,\, z \in \{0,1\}, \notag\\ +s^i_0 &= r^i_0 = 0. \notag +\end{align}$$ diff --git a/tasks/belvaux2000/problem_description.txt b/tasks/belvaux2000/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..ccd70b56101bfc3d297a4a8fe365af5a5c46063b --- /dev/null +++ b/tasks/belvaux2000/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A manufacturing facility produces NI distinct items using NK machines over a planning horizon of NT discrete periods. The instance data specifies the demand for each item in each period (demand, indexed by item and period), each machine's per-period production capacity (capacity_C, indexed by machine) and startup capacity loss (startup_time_sigma, indexed by machine), a uniform setup cost (setup_cost_f) and a uniform startup cost (startup_cost_g) applying to all items and machines, item-specific per-unit inventory holding costs (holding_cost_h, indexed by item) and backlogging penalty costs (backlogging_cost_e, indexed by item), and initial inventory (initial_stock_s0) and backlog levels (initial_backlog_r0) for each item. + +In each period, for each item, the prior period's closing inventory plus total production of that item across all machines minus the prior period's closing backlog must equal the current demand plus this period's closing inventory minus this period's closing backlog. Each machine may produce at most one item per period and can only produce an item it is set up for. Each machine has a fixed per-period production capacity that does not vary over time. A startup is incurred on a machine precisely when it becomes set up for an item it was not set up for in the immediately preceding period; no machine is considered set up for any item before the first period. Each startup consumes a machine-specific amount of that period's production capacity, so the quantity produced on a machine plus any startup capacity loss cannot exceed the machine's capacity. Furthermore, if a machine was set up for a certain item in the previous period, that same item cannot incur a startup on that machine in the current period, and every different item assigned to that machine in the current period must incur a startup. + +The facility pays the setup cost each period a machine is set up for any item, the startup cost for each startup event, the item-specific holding cost for each unit of inventory at each period's end, and the item-specific backlogging penalty for each unit of backlog at each period's end. The goal is to choose production quantities, inventory and backlog levels, and setup and startup schedules for every item, machine, and period so as to minimize the total of all setup, startup, holding, and backlogging costs over the entire horizon. diff --git a/tasks/belvaux2000/solution_logger.py b/tasks/belvaux2000/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/belvaux2000/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/belvaux2000/solution_schema.json b/tasks/belvaux2000/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5f87c325315651eb570c0e7f71478b44d3a4d67d --- /dev/null +++ b/tasks/belvaux2000/solution_schema.json @@ -0,0 +1,8 @@ +{ + "objective_value": " Total cost of the production plan, combining setup, startup, inventory holding, and backlogging costs over the planning horizon.", + "production": " Quantity of an item produced on a specific machine in a specific period.", + "stock": " Inventory of an item held on hand at the end of a specific period.", + "backlog": " Unfulfilled demand for an item carried as backlog at the end of a specific period.", + "setup": " Whether a machine is set up to produce a given item in a given period (1 = set up).", + "startup": " Whether a machine begins a new setup for a given item in a given period, having not been set up for that item in the previous period (1 = startup occurs)." +} diff --git a/tasks/bentert2022/feasibility_check.py b/tasks/bentert2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..30242c2b684b9a1b6c0300148759eb61f3eeaa69 --- /dev/null +++ b/tasks/bentert2022/feasibility_check.py @@ -0,0 +1,425 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Min-Power Symmetric Connectivity (MinPSC). + +Checks candidate solutions against the hard constraints from the mathematical +formulation in Bentert et al. (2020): + + Constraint 1 (C1): Spanning subgraph — F ⊆ E, and all edges in F must use + valid vertices from V. + Constraint 2 (C2): Connectivity — T = (V, F) must be a connected subgraph. + Constraint 3 (C3): Cost definition — For each v ∈ V, + p_v = max_{{u,v} ∈ F} w({u,v}). +""" + +import argparse +import json +from collections import defaultdict, deque + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'selected_edges', 'vertex_costs') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_instance(instance_path): + with open(instance_path, 'r') as f: + data = json.load(f) + + vertices = data["vertices"] + V = [] + coords = {} + for v_info in vertices: + vid = v_info["id"] + V.append(vid) + coords[vid] = (v_info["x"], v_info["y"]) + + # Build edge weight lookup (squared Euclidean distance, complete graph) + edge_weights = {} + for i in range(len(V)): + for j in range(i + 1, len(V)): + u, v = V[i], V[j] + dx = coords[u][0] - coords[v][0] + dy = coords[u][1] - coords[v][1] + w = dx * dx + dy * dy + edge_weights[(u, v)] = w + edge_weights[(v, u)] = w + + return V, coords, edge_weights + + +def check_connectivity(V, selected_edges): + """Check if (V, selected_edges) is connected. Returns number of components.""" + adj = defaultdict(set) + for u, v in selected_edges: + adj[u].add(v) + adj[v].add(u) + + if not V: + return 0 + + visited = set() + queue = deque([V[0]]) + visited.add(V[0]) + while queue: + node = queue.popleft() + for nb in adj[node]: + if nb not in visited: + visited.add(nb) + queue.append(nb) + + V_set = set(V) + num_visited = len(visited & V_set) + if num_visited == len(V_set): + return 1 + + # Count actual components + components = 0 + visited = set() + for start in V: + if start in visited: + continue + components += 1 + queue = deque([start]) + visited.add(start) + while queue: + node = queue.popleft() + for nb in adj[node]: + if nb in V_set and nb not in visited: + visited.add(nb) + queue.append(nb) + return components + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MinPSC solutions" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + tol = 1e-5 + eps = 1e-5 + + V, coords, edge_weights = load_instance(args.instance_path) + V_set = set(V) + + 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 + + selected_edges = [tuple(e) for e in solution.get("selected_edges", [])] + objective_value = solution.get("objective_value", None) + vertex_costs = solution.get("vertex_costs", {}) + # Keys in vertex_costs may be strings + vertex_costs = {int(k): float(v) for k, v in vertex_costs.items()} + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint 1 (C1): Spanning subgraph — F ⊆ E + # All edges in F must connect valid vertices from V, and each edge must + # exist in E (the complete graph over V, so just check vertex validity). + # ========================================================================= + invalid_edges = [] + for u, v in selected_edges: + if u not in V_set or v not in V_set: + invalid_edges.append((u, v)) + elif u == v: + invalid_edges.append((u, v)) + + if invalid_edges: + violated_constraints.add(1) + violations.append( + f"C1: {len(invalid_edges)} edge(s) in F use invalid or duplicate " + f"vertex IDs not in V: {invalid_edges[:5]}" + ) + # LHS = number of invalid edges, RHS = 0 (equality: should be 0) + lhs = float(len(invalid_edges)) + rhs = 0.0 + violation_amount = abs(lhs - rhs) + 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 (C2): Connectivity — T = (V, F) must be connected + # ========================================================================= + num_components = check_connectivity(V, selected_edges) + if num_components != 1: + violated_constraints.add(2) + violations.append( + f"C2: Subgraph (V, F) has {num_components} connected components " + f"(must be 1)" + ) + # LHS = num_components, RHS = 1 (equality: should be exactly 1) + lhs = float(num_components) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 3 (C3): Cost definition — p_v = max_{{u,v} ∈ F} w({u,v}) + # For each vertex v, the reported cost must equal the maximum weight of + # any selected edge incident to v. Vertices with no incident selected + # edges have an implied cost of 0. + # ========================================================================= + # Compute actual max incident edge weight for each vertex + actual_costs = {v: 0.0 for v in V} + for u, v in selected_edges: + if u in V_set and v in V_set and u != v: + w = edge_weights[(u, v)] + if w > actual_costs[u]: + actual_costs[u] = w + if w > actual_costs[v]: + actual_costs[v] = w + + c3_violations = [] + for v in V: + reported = vertex_costs.get(v, 0.0) + actual = actual_costs[v] + diff = abs(reported - actual) + if diff > tol: + c3_violations.append((v, reported, actual, diff)) + + if c3_violations: + violated_constraints.add(3) + # Summarize + example_strs = [] + for v, reported, actual, diff in c3_violations[:5]: + example_strs.append( + f"v={v}: reported={reported:.6f}, actual={actual:.6f}, " + f"diff={diff:.6f}" + ) + violations.append( + f"C3: {len(c3_violations)} vertex cost(s) do not match " + f"max incident edge weight. Examples: {'; '.join(example_strs)}" + ) + # Record one violation magnitude entry per violated vertex + for v, reported, actual, diff in c3_violations: + lhs = reported + rhs = actual + violation_amount = diff + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 4 (C4): Objective value — objective_value == sum of p_v + # The reported objective_value must equal the sum of all vertex costs. + # From math_model: min sum_{v in V} p_v + # ========================================================================= + if objective_value is not None: + computed_obj = sum(vertex_costs.get(v, 0.0) for v in V) + obj_diff = abs(objective_value - computed_obj) + if obj_diff > tol: + violated_constraints.add(4) + violations.append( + f"C4: Reported objective_value={objective_value:.6f} does not " + f"match sum of vertex_costs={computed_obj:.6f}, " + f"diff={obj_diff:.6f}" + ) + lhs = float(objective_value) + rhs = computed_obj + violation_amount = obj_diff + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Build output + # ========================================================================= + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if feasible: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: " + f"{sorted(violated_constraints)}") + for msg in 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/bentert2022/gurobi_code.py b/tasks/bentert2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..8bbf2e3a5cefecb41c5a224ddea896600eae5f53 --- /dev/null +++ b/tasks/bentert2022/gurobi_code.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +""" +Gurobi ILP implementation of Min-Power Symmetric Connectivity (MinPSC). + +Paper: Bentert et al., "Parameterized Algorithms for Power-Efficiently + Connecting Wireless Sensor Networks: Theory and Experiments" (2020) + +Problem 1.1 (MinPSC): + Given a connected undirected graph G=(V,E) with edge weights w: E -> N, + find a connected spanning subgraph T=(V,F), F subset of E, that minimizes + sum_{v in V} max_{{u,v} in F} w({u,v}) + +The paper does NOT provide its own ILP formulation. It references ILP models +EX1 and EX2 from Montemanni and Gambardella (2005), which are +**NOT EXPLICITLY SPECIFIED IN THIS PAPER**. + +INFERRED ASSUMPTION: We implement a standard ILP for MinPSC using: + - Binary edge selection variables x_e + - Continuous variables p_v for vertex power cost + - Linearization of max via p_v >= w(e) * x_e + - Single-commodity flow for connectivity enforcement + (pick an arbitrary root, send n-1 units of flow, each vertex absorbs 1) +""" + +import argparse +import json +import math +import sys +from itertools import combinations + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(instance_path): + """Load a MinPSC instance from JSON.""" + with open(instance_path, 'r') as f: + data = json.load(f) + + vertices = data["vertices"] + n = data["n"] + m = data["m"] + + # Build vertex list + V = [] + coords = {} + lower_bounds = {} + for v_info in vertices: + vid = v_info["id"] + V.append(vid) + coords[vid] = (v_info["x"], v_info["y"]) + lower_bounds[vid] = v_info["lower_bound"] + + # Build complete graph edges with squared Euclidean distance weights + # The instance specifies "complete" graph with "squared_euclidean_distance" + edges = [] + edge_weights = {} + for i in range(len(V)): + for j in range(i + 1, len(V)): + u, v = V[i], V[j] + dx = coords[u][0] - coords[v][0] + dy = coords[u][1] - coords[v][1] + w = dx * dx + dy * dy + edges.append((u, v)) + edge_weights[(u, v)] = w + edge_weights[(v, u)] = w + + return V, edges, edge_weights, coords, lower_bounds, data + + +def solve_minpsc_gurobi(V, edges, edge_weights, time_limit): + """ + Solve MinPSC using Gurobi ILP. + + Formulation: + min sum_{v in V} p_v + s.t. + p_v >= w({u,v}) * x_{u,v} for all edges {u,v} and both endpoints + T = (V, F) is connected (enforced via single-commodity flow) + x_e in {0,1}, p_v >= 0 + + Connectivity via single-commodity flow: + - Pick root r (vertex 0). Root sends n-1 units of flow. + - Each non-root vertex absorbs exactly 1 unit. + - Flow on directed arc (u,v) is bounded by (n-1)*x_{u,v}. + + **NOT EXPLICITLY SPECIFIED IN PAPER**: The exact connectivity formulation. + INFERRED ASSUMPTION: We use single-commodity flow which is a standard + approach for enforcing connectivity in ILP formulations. + """ + n = len(V) + if n == 0: + return 0.0, [] + if n == 1: + return 0.0, [] + + model = gp.Model("MinPSC") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Binary edge selection variables + x = {} + for (u, v) in edges: + x[(u, v)] = model.addVar(vtype=GRB.BINARY, name=f"x_{u}_{v}") + + # Vertex power cost variables + p = {} + for v in V: + p[v] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"p_{v}") + + # Flow variables: directed arcs for each undirected edge + # Pick root as V[0] + root = V[0] + f_var = {} + for (u, v) in edges: + f_var[(u, v)] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, + ub=n - 1, name=f"f_{u}_{v}") + f_var[(v, u)] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, + ub=n - 1, name=f"f_{v}_{u}") + + model.update() + + # Objective: minimize sum of vertex power costs + model.setObjective(gp.quicksum(p[v] for v in V), GRB.MINIMIZE) + + # Constraint: p_v >= w(e) * x_e for each edge e incident to v + for (u, v) in edges: + w = edge_weights[(u, v)] + model.addConstr(p[u] >= w * x[(u, v)], name=f"pwr_{u}_{u}_{v}") + model.addConstr(p[v] >= w * x[(u, v)], name=f"pwr_{v}_{u}_{v}") + + # Flow conservation: each non-root absorbs 1 unit + # Build adjacency for flow + # For root: outflow - inflow = n - 1 + # For others: outflow - inflow = -1 + for v in V: + outflow = gp.LinExpr() + inflow = gp.LinExpr() + for (u, w_v) in edges: + if u == v: + outflow.add(f_var[(u, w_v)]) + inflow.add(f_var[(w_v, u)]) + elif w_v == v: + outflow.add(f_var[(w_v, u)]) + inflow.add(f_var[(u, w_v)]) + + if v == root: + model.addConstr(outflow - inflow == n - 1, + name=f"flow_root_{v}") + else: + model.addConstr(outflow - inflow == -1, + name=f"flow_{v}") + + # Flow capacity: flow on arc (u,v) <= (n-1) * x_{u,v} + for (u, v) in edges: + model.addConstr(f_var[(u, v)] <= (n - 1) * x[(u, v)], + name=f"cap_{u}_{v}") + model.addConstr(f_var[(v, u)] <= (n - 1) * x[(u, v)], + name=f"cap_{v}_{u}") + + # Solve + model.optimize() + + # Extract solution + obj_val = None + selected_edges = [] + + if model.SolCount > 0: + obj_val = model.ObjVal + for (u, v) in edges: + if x[(u, v)].X > 0.5: + selected_edges.append((u, v)) + else: + obj_val = None + + return obj_val, selected_edges + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi ILP solver for MinPSC (Min-Power Symmetric Connectivity)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # Load instance + V, edges, edge_weights, coords, lower_bounds, instance_data = \ + load_instance(args.instance_path) + + # Solve + obj_val, selected_edges = solve_minpsc_gurobi( + V, edges, edge_weights, args.time_limit + ) + + # Build solution output + solution = { + "problem": "MinPSC", + "instance_path": args.instance_path, + "solver": "Gurobi", + "objective_value": obj_val if obj_val is not None else None, + "selected_edges": [list(e) for e in selected_edges], + "num_selected_edges": len(selected_edges), + } + + # Compute per-vertex costs if solution found + if obj_val is not None: + vertex_costs = {v: 0.0 for v in V} + for (u, v) in selected_edges: + w = edge_weights[(u, v)] + if w > vertex_costs[u]: + vertex_costs[u] = w + if w > vertex_costs[v]: + vertex_costs[v] = w + solution["vertex_costs"] = {str(v): c for v, c in vertex_costs.items()} + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + if obj_val is not None: + print(f"Optimal objective value: {obj_val}") + else: + print("No feasible solution found within time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/bentert2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/bentert2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bentert2022/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/bentert2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/bentert2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bentert2022/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/bentert2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/bentert2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bentert2022/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/bentert2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/bentert2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bentert2022/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/bentert2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/bentert2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bentert2022/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/bentert2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/bentert2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bentert2022/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/bentert2022/gurobi_solution/large_solution_1.json b/tasks/bentert2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3b2f7b50d88732bfa0ccd95a06391b2194757c43 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6b43ad4ec163c7faf55d06da7441c6f7a23ea8c6281a099e3dd9f6ab1268a33 +size 5808 diff --git a/tasks/bentert2022/gurobi_solution/large_solution_2.json b/tasks/bentert2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..2778c98404a86383a8c56458bb4997ffa1f6ebe5 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec6f3dbd6728bdc9ed9d29baff5addd8b1decaa28868cceb9924bbe86d8add6a +size 6038 diff --git a/tasks/bentert2022/gurobi_solution/large_solution_3.json b/tasks/bentert2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3f29a8e39656a31be973304d18916f6b34312904 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6be2d93e5cde584c6e4ea2fdbebf28c209bf12e922a40ab5604b60411f36c4b3 +size 4838 diff --git a/tasks/bentert2022/gurobi_solution/large_solution_4.json b/tasks/bentert2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f3d72540f5e95ad223c6064e8bf2fe0efbeaf934 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97d545e738570e1b001f9ae32b49268d4165d201e4ecb9c26b62124f629e384e +size 4892 diff --git a/tasks/bentert2022/gurobi_solution/large_solution_5.json b/tasks/bentert2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f9e1611c28f2258257e5641fcdf8f403bb9187be --- /dev/null +++ b/tasks/bentert2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6d0dbe50ba99770a780b16956d2fca673a3736993f9cc955f78fd07d3b01093 +size 4838 diff --git a/tasks/bentert2022/gurobi_solution/tiny_solution.json b/tasks/bentert2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..131da47686d3b722d13a277f9fa10c47d421f999 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1abe851cb5fb49afc8ce2c6521ac8e702c441ee1c0e1a500973133377a576509 +size 5812 diff --git a/tasks/bentert2022/gurobi_solution_log/large_log_1.jsonl b/tasks/bentert2022/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..58a0b673bbc4cf14d8055edd8df2154c8b16c354 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba4984d34aa751ca35c8ab948c0fccfcae0f884008349c230ff42d2606a909de +size 1086 diff --git a/tasks/bentert2022/gurobi_solution_log/large_log_2.jsonl b/tasks/bentert2022/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c10900cb6f5bcff15f3e7a59549f88d33270574 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:337e9994c84e06ce396e15a6736e5ac8143a1b56d2098d5df9c9ccaa84685ff9 +size 1191 diff --git a/tasks/bentert2022/gurobi_solution_log/large_log_3.jsonl b/tasks/bentert2022/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f16e9fec0e12349c73f7975d49707f6374db9442 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9118a8543d293426a9d4c1b3db6bf21c6d52472ab8c6dc4269f2e48f7e16cdd +size 2872 diff --git a/tasks/bentert2022/gurobi_solution_log/large_log_4.jsonl b/tasks/bentert2022/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f7c63dd37106b5266c4bef00b3d3b1e4ae26d1f6 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b0a396648861e6fcd96fec6b91f8a95015ff441920d7c185ea4ce70239edc10 +size 2871 diff --git a/tasks/bentert2022/gurobi_solution_log/large_log_5.jsonl b/tasks/bentert2022/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..256d824c5c8162d6b08f712d4409084995f0a89e --- /dev/null +++ b/tasks/bentert2022/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e99b376b9db77e8e6676730036469884157c9b5a6d267ba0f32dc17eb4983788 +size 2034 diff --git a/tasks/bentert2022/gurobi_solution_log/tiny_log.jsonl b/tasks/bentert2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..155d35f0fc6b99f1ae9aa7877fa60570685972b4 --- /dev/null +++ b/tasks/bentert2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d686a2043f6a0b9408547ec436b69a91d9dcf5087b4b52a95d996d8fb7284f21 +size 1480 diff --git a/tasks/bentert2022/instance/large_instance_1.json b/tasks/bentert2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..66d8b3fec4f481103d690be3e2e9a2e73f5c5289 --- /dev/null +++ b/tasks/bentert2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:174adc65a519b725b9088cd060d841d80abc634b669d68d3ce5feaad207c17de +size 7623 diff --git a/tasks/bentert2022/instance/large_instance_2.json b/tasks/bentert2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1e5fb58436ccf5e2f1ff66d9e5f6f80b477dd5ef --- /dev/null +++ b/tasks/bentert2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd713d77cb05c5650e0badc949a298883b83b71d8ce6721f2dc3b7e58b013f28 +size 7752 diff --git a/tasks/bentert2022/instance/large_instance_3.json b/tasks/bentert2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7c87cdba9908f87411b303bdd008be460a7b688c --- /dev/null +++ b/tasks/bentert2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18500c3b32a532572988d668ce865406831551d469be515c53bbdc3ef2262a0b +size 8940 diff --git a/tasks/bentert2022/instance/large_instance_4.json b/tasks/bentert2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..21ad260856b160243e6e8c04362f4d6847fb08c9 --- /dev/null +++ b/tasks/bentert2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b64e275b0d09ce30ab9e0d42dea1e9f0b75e4017a9362c8718d90f17d0553600 +size 9099 diff --git a/tasks/bentert2022/instance/large_instance_5.json b/tasks/bentert2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..53ac27bbecf644db97fb45de5a119bda716e8a3d --- /dev/null +++ b/tasks/bentert2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c848d908b2ab8d4b187b28d929a1e630692b601aff404ce5a8485eebab177f3 +size 8979 diff --git a/tasks/bentert2022/instance/tiny_instance.json b/tasks/bentert2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..ccc8415b99e2bb9cf156c9ff42d5c65c2f7533b1 --- /dev/null +++ b/tasks/bentert2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e2a38a8af25933b2569391fd89eecbf7c6a3f0473bb45e1c8efab2ddd337f0c +size 7558 diff --git a/tasks/bentert2022/instance_schema.json b/tasks/bentert2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..4d019b772a8e45e06f51b5f7094fd6b76017c540 --- /dev/null +++ b/tasks/bentert2022/instance_schema.json @@ -0,0 +1,15 @@ +{ + "n": " Number of sensors in the network.", + "m": " Number of communication links between sensors.", + "graph_type": " Structure of the graph connecting sensors.", + "edge_weight_rule": " Rule used to compute the power cost of each communication link from sensor positions.", + "vertices": [ + { + "id": " Unique identifier of the sensor.", + "x": " Horizontal coordinate of the sensor.", + "y": " Vertical coordinate of the sensor.", + "lower_bound": " Minimum link weight among all links incident to this sensor." + } + ], + "c_obligatory_components": " Number of connected components in the obligatory subgraph formed by mutually nearest-neighbor sensor pairs." +} diff --git a/tasks/bentert2022/mathematical_formulation.md b/tasks/bentert2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..58ef59ae572125dd327b8b48db1da0a62b732aa2 --- /dev/null +++ b/tasks/bentert2022/mathematical_formulation.md @@ -0,0 +1,35 @@ +# Original Formulation: Min-Power Symmetric Connectivity (MinPSC) + +*Source: Parameterized Algorithms for Power-Efficiently Connecting Wireless Sensor Networks: Theory and Experiments, Matthias Bentert, René van Bevern, André Nichterlein, Rolf Niedermeier, Pavel V. Smirnov, 2020 (arXiv:1706.03177v3).* + +## Sets and Parameters + +- $G = (V, E)$: a connected, undirected, finite, simple graph. + +- $V$: set of vertices (wireless sensors), $|V| = n$. + +- $E \subseteq \big\{\,\{v, w\} \mid v \neq w \text{ and } v, w \in V\,\big\}$: set of undirected edges, $|E| = m$. + +- $w : E \to \mathbb{N}$: edge-weight function; weights are natural numbers (the paper takes $\mathbb{N}$ to include $0$). + +- Convention (Section 2.1): $\max \emptyset = -\infty$ and $\min \emptyset = \infty$. + +## Decision Variables + +- $F \subseteq E$: the set of edges selected for the spanning subgraph $T = (V, F)$. (The vertex set of $T$ is fixed to $V$; $T$ *spans* $G$.) + +## Objective + +Find a connected spanning subgraph $T = (V, F)$, $F \subseteq E$, of $G$ that minimizes $$\begin{equation*} + \sum_{v \in V} \ \max_{\{u, v\} \in F} w(\{u, v\}). + \tag{Problem 1.1} +\end{equation*}$$ That is, each vertex $v$ pays the most expensive edge incident to it in the solution, and the cost of $T$ is the sum of these payments. The minimum cost of a solution to an instance $I = (G, w)$ is denoted $\mathrm{Opt}(I)$. + +## Constraints + +$$\begin{align*} + & T = (V, F), \quad F \subseteq E + && \text{(spanning subgraph: vertex set is all of $V$)} \tag{C1} \\ + & T = (V, F) \text{ is connected} + && \text{(every pair of vertices joined by a path in $F$)} \tag{C2} +\end{align*}$$ diff --git a/tasks/bentert2022/problem_description.txt b/tasks/bentert2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d49fdd11d87a42a4a712d96992b15741f2a96ad --- /dev/null +++ b/tasks/bentert2022/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A wireless sensor network consists of a set of sensors (nodes) and a set of possible communication links (edges) between pairs of distinct sensors, forming a connected undirected simple graph. Each link has a non-negative integer weight representing the power cost required to maintain that link, where in typical instances weights equal the squared Euclidean distance between the two sensors' positions. + +The network operator must select a subset of communication links such that the resulting subgraph spans all sensors (every sensor is included) and is connected (every sensor can reach every other sensor through the chosen links). The power cost paid by each sensor equals the maximum weight among all chosen links incident to that sensor. The goal is to minimize the total power cost across all sensors, defined as the sum over all sensors of the maximum-weight chosen link incident to each sensor. + +The input specifies the number of sensors, the number of links, the two-dimensional coordinates of each sensor, and the weight of each link. The graph over which the optimization takes place is complete, meaning every pair of sensors is connected by a link whose weight is the squared Euclidean distance between them. diff --git a/tasks/bentert2022/solution_logger.py b/tasks/bentert2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/bentert2022/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/bentert2022/solution_schema.json b/tasks/bentert2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e8f817bf4bc42c647504b9b5ca3aff77f54619c6 --- /dev/null +++ b/tasks/bentert2022/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total power cost across all sensors, where each sensor's cost is the maximum weight among its chosen links.", + "selected_edges": " Pairs of sensor identifiers for each communication link chosen in the spanning subgraph.", + "vertex_costs": " Power cost paid by each sensor, equal to the maximum weight among chosen links incident to that sensor." +} diff --git a/tasks/bergman2019/feasibility_check.py b/tasks/bergman2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a954ca03e85630d27056a19621aa2365efed2a96 --- /dev/null +++ b/tasks/bergman2019/feasibility_check.py @@ -0,0 +1,438 @@ +""" +Feasibility checker for the Quadratic Multiknapsack Problem (QMKP-QP). +Source: Bergman (2019), INFORMS Journal on Computing. + +Constraints (numbered top-to-bottom from the QMKP-QP formulation): + 1. Capacity: sum_i w_i * x_{i,k} <= C_k, for all k in [m] + 2. Assignment: sum_k x_{i,k} <= 1, for all i in [n] + 3. Binary: x_{i,k} in {0,1}, for all i in [n], k in [m] + 6. Objective consistency: reported objective_value must equal the + recomputed QMKP-QP objective + sum_{i,k} p_i * x_{i,k} + + sum_{i 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["n"] + m = instance["m"] + weights = instance["weights"] + capacities = instance["capacities"] + + assignment = solution.get("assignment", []) + + violations = [] + violation_magnitudes = [] + violated_set = set() + + # ── Constraint 3 (index validity): validate BEFORE downstream lookups. + # Fix_7 reviewer item 2: weights[i] was indexed before the bounds + # check ran, so i >= n would raise IndexError and i < 0 would silently + # wrap via Python's negative indexing. + # Fix_7 reviewer item 1: assignment is now a list of [item, knapsack] + # pairs (schema reshape) so multi-assignment is expressible and + # constraint 2 below is no longer a tautology. + valid_pairs = [] + for entry in assignment: + item = int(entry[0]) + kk = int(entry[1]) + item_ok = 0 <= item < n + k_ok = 0 <= kk < m + if not item_ok: + violated_set.add(3) + violations.append( + f"Item index {item} out of range [0, {n-1}]" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(item), + "rhs": float(n - 1), + "raw_excess": float(abs(item - (n - 1)) if item >= n else abs(item)), + "normalizer": max(float(n - 1), eps), + "ratio": float(abs(item - (n - 1)) if item >= n else abs(item)) + / max(float(n - 1), eps), + }) + if not k_ok: + violated_set.add(3) + violations.append( + f"Knapsack index {kk} for item {item} out of range [0, {m-1}]" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(kk), + "rhs": float(m - 1), + "raw_excess": float(abs(kk - (m - 1)) if kk >= m else abs(kk)), + "normalizer": max(float(m - 1), eps), + "ratio": float(abs(kk - (m - 1)) if kk >= m else abs(kk)) + / max(float(m - 1), eps), + }) + if item_ok and k_ok: + valid_pairs.append((item, kk)) + + # ── Constraint 1: Capacity ── + # sum_i w_i * x_{i,k} <= C_k, for each k in [m] + for k in range(m): + lhs = sum(weights[i] for i, kk in valid_pairs if kk == k) + rhs = capacities[k] + violation_amount = lhs - rhs # for <= constraint + if violation_amount > tol: + violated_set.add(1) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Capacity exceeded on knapsack {k}: " + f"total weight {lhs} > capacity {rhs}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ── Constraint 2: Assignment ── + # sum_k x_{i,k} <= 1, for each i in [n]. + # The list-of-pairs schema lets the same item index appear more than + # once; the prior dict-keyed schema structurally collapsed duplicates, + # making this branch unreachable. + counts = {} + for i, kk in valid_pairs: + counts[i] = counts.get(i, 0) + 1 + for i, count in counts.items(): + violation_amount = count - 1 + if violation_amount > tol: + violated_set.add(2) + normalizer = max(abs(1), eps) + ratio = violation_amount / normalizer + violations.append( + f"Item {i} assigned to {count} knapsacks (max 1 allowed)" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(count), + "rhs": float(1), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + _domain_check_vars_binary = [] + _domain_check_vars_integer = [("assignment", assignment)] + + # ===================================================================== + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # ===================================================================== + # Constraint 4: 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(4) + violations.append( + f"Constraint 4 (binary domain): {var_name}[{key}] = {v} not in {0, 1}") + violation_magnitudes.append({ + "constraint": 4, + "lhs": v, + "rhs": 1.0, + "raw_excess": float(viol), + "normalizer": 1.0, + "ratio": float(viol), + }) + + # Constraint 5: 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(5) + violations.append( + f"Constraint 5 (integer domain): {var_name}[{key}] = {v} is not integer") + violation_magnitudes.append({ + "constraint": 5, + "lhs": v, + "rhs": round(v), + "raw_excess": float(frac), + "normalizer": max(abs(round(v)), eps), + "ratio": float(frac / max(abs(round(v)), eps)), + }) + + # ── Constraint 6: Objective consistency (Tier C) ── + # Recompute the QMKP-QP objective from the solution's assignment and + # compare against the reported objective_value. The solution contains + # every variable the objective depends on (x_{i,k}), so a full + # recompute applies. Profits and pairwise_profits are integers per + # math_model.txt, so the true objective is integral; a tolerance of + # max(0.5, 1e-6 * |true_obj|) flags any integer-level mismatch while + # absorbing float-formatting noise (e.g. trailing ".0" round-trips). + profits = instance.get("profits") + pairwise_profits = instance.get("pairwise_profits") + reported_obj = solution.get("objective_value") + if profits is not None and pairwise_profits is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + # Dedup per knapsack: x_{i,k} is binary, so an item appearing + # twice in the same knapsack contributes only once to the obj + # (the duplicate is already flagged separately by constraint 2). + items_per_knap = {} + for i, kk in valid_pairs: + items_per_knap.setdefault(kk, set()).add(i) + linear_part = 0.0 + for kk, items in items_per_knap.items(): + for i in items: + linear_part += float(profits[i]) + quad_part = 0.0 + for kk, items in items_per_knap.items(): + items_sorted = sorted(items) + for a in range(len(items_sorted)): + i = items_sorted[a] + row_i = pairwise_profits[i] + for b in range(a + 1, len(items_sorted)): + j = items_sorted[b] + quad_part += float(row_i[j]) + true_obj = linear_part + quad_part + abs_diff = abs(reported - true_obj) + tol_obj = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > tol_obj: + violated_set.add(6) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed QMKP-QP objective=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol_obj:.6g})" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + feasible = len(violated_set) == 0 + violated_constraints = sorted(violated_set) + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for QMKP-QP (Bergman 2019)" + ) + 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"Feasible: {result['feasible']}") + 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/bergman2019/gurobi_code.py b/tasks/bergman2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..b6fe22305dcc94a49f2983ab3321d6227a4a1802 --- /dev/null +++ b/tasks/bergman2019/gurobi_code.py @@ -0,0 +1,161 @@ +""" +Gurobi implementation of the Quadratic Multiknapsack Problem (QMKP-QP). +Source: Bergman (2019), "An Exact Algorithm for the Quadratic Multiknapsack Problem + with an Application to Event Seating", INFORMS Journal on Computing. + +Model: QMKP-QP (Section 3.1) + maximize sum_{i,k} p_i * x_{i,k} + + sum_{i 0): + obj_val = model.ObjVal + # Fix_7: emit list-of-pairs so the feasibility checker can detect + # multi-assignment violations; the prior dict keying collapsed + # duplicate item keys, making constraint 2 unreachable. + assignment = [] + for i in range(n): + for k in range(m): + if x[i, k].X > 0.5: + assignment.append([i, k]) + + result["objective_value"] = obj_val + result["assignment"] = assignment + result["status"] = "optimal" if status == GRB.OPTIMAL else "time_limit_feasible" + result["gap"] = model.MIPGap if model.SolCount > 0 else None + elif status == GRB.INFEASIBLE: + result["objective_value"] = None + result["status"] = "infeasible" + else: + result["objective_value"] = None + result["status"] = "no_solution_found" + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for the Quadratic Multiknapsack Problem (QMKP-QP)" + ) + 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 must be written.") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + result = solve_qmkp(instance, args.time_limit) + + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status']}") + print(f"Solution written to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/bergman2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/bergman2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bergman2019/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/bergman2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/bergman2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bergman2019/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/bergman2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/bergman2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bergman2019/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/bergman2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/bergman2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bergman2019/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/bergman2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/bergman2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bergman2019/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/bergman2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/bergman2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/bergman2019/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/bergman2019/gurobi_solution/large_solution_1.json b/tasks/bergman2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f3e51c48ff8a8e3a666b1645e113a07b0a9f3acb --- /dev/null +++ b/tasks/bergman2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea0cfecf04808850b970383c9a729c9c42b656119f5ebc4ad46236ab3f7f3ca6 +size 1028 diff --git a/tasks/bergman2019/gurobi_solution/large_solution_2.json b/tasks/bergman2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ba35db49b06a4390be3b241e252b589df0b4c695 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3838283e68b7fc6f57a144b95f57385cfbd8b0e14b8e6be55ae39410f5fdeb3 +size 1063 diff --git a/tasks/bergman2019/gurobi_solution/large_solution_3.json b/tasks/bergman2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..85910f259805d5b03faa6e558749657f658b4743 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68397f7cb52412556699cb181617eefa4929cf2f5b4f6145549738258743171c +size 1063 diff --git a/tasks/bergman2019/gurobi_solution/large_solution_4.json b/tasks/bergman2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a8ef337f41c08b95b4ea60c7fbbc7c079f264a32 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:650a9ca0f0e4d34df386cd3d21ad02fdd1e6bee8430c8ce4fdf8534623205c01 +size 1063 diff --git a/tasks/bergman2019/gurobi_solution/large_solution_5.json b/tasks/bergman2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..57457acf39ea63dfb0a88f46046bbb47961ec0da --- /dev/null +++ b/tasks/bergman2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:043a52aa8cbb9bde21327b96002a61b39a6d9395c6bd0643e404146dff41b407 +size 1063 diff --git a/tasks/bergman2019/gurobi_solution/tiny_solution.json b/tasks/bergman2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..409add77a9246d90b082ca153a4c6329173ee95d --- /dev/null +++ b/tasks/bergman2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e450ab513dc1393cc87f65a1481f34af5e292fa735d1522f3c276345832d2ab5 +size 629 diff --git a/tasks/bergman2019/gurobi_solution_log/large_log_1.jsonl b/tasks/bergman2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b8557d96de69130d3b428271cbc35c13ac477bdd --- /dev/null +++ b/tasks/bergman2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bdb1b1cf137a2f25f10d4b8a0df327028e9163cb7c35ea19ce4d551d8eceb6a +size 41 diff --git a/tasks/bergman2019/gurobi_solution_log/large_log_2.jsonl b/tasks/bergman2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..890ca6e282f6c7e4f3ad01af7c113eb985ba6470 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ad8834a23e95fe351e5fd167c41942c59de2a9d771aa497818033fd77d45fb9 +size 40 diff --git a/tasks/bergman2019/gurobi_solution_log/large_log_3.jsonl b/tasks/bergman2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d9d4822a9beefed3224103037b7ffcd45d3ca1d3 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:522a462cc2d7490a699445c7b13f6d21de92e3dda29619230b0fb1c8b6f8908b +size 40 diff --git a/tasks/bergman2019/gurobi_solution_log/large_log_4.jsonl b/tasks/bergman2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..85e592ce2ae48f50feec5a72bbb504f07ce12024 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02cb5369e4d4ef7aef212aa3cf7c74c935470bf307e3c56ce299cc71db7636db +size 41 diff --git a/tasks/bergman2019/gurobi_solution_log/large_log_5.jsonl b/tasks/bergman2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..493abdeed0de8047e69dc4a80dfb6eaacda80398 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87f2c326deb7523804cc22551f74fce7b418a149a3d8038ce2b4be99516d5331 +size 41 diff --git a/tasks/bergman2019/gurobi_solution_log/tiny_log.jsonl b/tasks/bergman2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..abc28a285f226fbfb124b665cdb94d5a467c4bc6 --- /dev/null +++ b/tasks/bergman2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e5236e77035974fc76a3f639960443ed0af70abceafaf71bb2ea1789230bb2a +size 41 diff --git a/tasks/bergman2019/instance/large_instance_1.json b/tasks/bergman2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4e2a73567096cfbae030ba868fbf5df8e164270e --- /dev/null +++ b/tasks/bergman2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d49cb231948545a0f69503161f867aec8bfab28f3ea4f8cadff1f4cce374e0b5 +size 13100 diff --git a/tasks/bergman2019/instance/large_instance_2.json b/tasks/bergman2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..758c34e7872a4659e0e2456347f03d04f72c7ce4 --- /dev/null +++ b/tasks/bergman2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bba08094f7a9f4455d4d72d4be1267f591c5931c96f36c191d7820d933c879b +size 12884 diff --git a/tasks/bergman2019/instance/large_instance_3.json b/tasks/bergman2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..806a654eb3e5d79f8fb7f8963ff62a109a3a8d42 --- /dev/null +++ b/tasks/bergman2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b9d3a166057e064c04a3a075516a3756b10ca6b5a014326ebc89447e98f3a18 +size 13278 diff --git a/tasks/bergman2019/instance/large_instance_4.json b/tasks/bergman2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..922dcfb4a12150563bc0b623bb6065daf8721e63 --- /dev/null +++ b/tasks/bergman2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62ac96fd9a60c85ba8c2a7db05631b1e70bfc245aa4c8efee39229a7104a6b15 +size 12885 diff --git a/tasks/bergman2019/instance/large_instance_5.json b/tasks/bergman2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..af7ac15ee1ae9195dac13bec0f7e27e7c8694d77 --- /dev/null +++ b/tasks/bergman2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:559645e5285313ae6091e6f537f6fe3d477940fe773128278a7baa952a650800 +size 13234 diff --git a/tasks/bergman2019/instance/tiny_instance.json b/tasks/bergman2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c1aa81c5259e4047c97945a7b4a3b9bc8e6db6de --- /dev/null +++ b/tasks/bergman2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36afa4535b8ea21fae17a1b514023a8d437364b02da0e08ae4dd97a320a9eac3 +size 4459 diff --git a/tasks/bergman2019/instance_schema.json b/tasks/bergman2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fe8fc39e3334de7826469c52dbab0b0b5ab56fd2 --- /dev/null +++ b/tasks/bergman2019/instance_schema.json @@ -0,0 +1,8 @@ +{ + "n": " Number of items available for assignment to knapsacks.", + "m": " Number of knapsacks available to hold items.", + "profits": " Individual profit earned when each item is placed in any knapsack.", + "pairwise_profits": " Symmetric matrix of bonus profit earned when two items are placed together in the same knapsack, with zero diagonal.", + "weights": " Weight consumed by each item when placed in a knapsack.", + "capacities": " Maximum total weight each knapsack can hold." +} diff --git a/tasks/bergman2019/mathematical_formulation.md b/tasks/bergman2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..65f0b88bb8a07cbba01710bbd5d07bf6792d6ad0 --- /dev/null +++ b/tasks/bergman2019/mathematical_formulation.md @@ -0,0 +1,49 @@ +# Original Formulation: Quadratic Multiknapsack Problem (QMKP) + +*Source: An Exact Algorithm for the Quadratic Multiknapsack Problem with an Application to Event Seating, David Bergman, 2019 (INFORMS Journal on Computing).* + +## Sets and Indices + +- $n \in \mathbb{Z}^+$: number of items; $[n] := \{1,\dots,n\}$. + +- $m \in \mathbb{Z}^+$: number of knapsacks; $[m] := \{1,\dots,m\}$. + +- $i,j \in [n]$: item indices. + +- $k \in [m]$: knapsack index. + +## Parameters + +- $p_i \in \mathbb{Z}$: individual profit of item $i \in [n]$ (not required to be nonnegative). + +- $p_{i,j} \in \mathbb{Z}$: pairwise profit of distinct items $i,j \in [n]$, with $p_{i,j} = p_{j,i}$ (not required to be nonnegative). + +- $w_i \geq 0$: weight of item $i \in [n]$. + +- $C_k \in \mathbb{Z}^+$: capacity of knapsack $k \in [m]$. + +## Decision Variables + +- $x_{i,k} \in \{0,1\}$ for $i \in [n],\, k \in [m]$: equals $1$ iff item $i$ is placed in knapsack $k$. + +## Objective + +$$\begin{align} +\text{maximize} \quad + & \sum_{i=1}^{n}\sum_{k=1}^{m} p_i\, x_{i,k} + + \sum_{i=1}^{n-1}\sum_{j=i+1}^{n}\sum_{k=1}^{m} x_{i,k}\, x_{j,k}\, p_{i,j} + \notag +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{subject to} \quad + & \sum_{i=1}^{n} w_i\, x_{i,k} \leq C_k, + && k \in [m], \\ + & \sum_{k=1}^{m} x_{i,k} \leq 1, + && i \in [n], \\ + & x_{i,k} \in \{0,1\}, + && i \in [n],\; k \in [m]. + \tag{QMKP-QP} +\end{align}$$ diff --git a/tasks/bergman2019/problem_description.txt b/tasks/bergman2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0cde24b9afd971332ff8281ea036d9bff66995a --- /dev/null +++ b/tasks/bergman2019/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +A collection of items must be allocated among a set of knapsacks so as to maximize total profit. Each item has an individual profit (which may be negative) and a weight (which may be zero). Each distinct pair of items has a pairwise profit (which may also be negative), and the pairwise profit matrix is symmetric. Each knapsack has a positive integer capacity. The planner must decide, for each item, whether to place it in one of the knapsacks or to leave it unassigned. Each item may be placed in at most one knapsack. The total weight of items assigned to any single knapsack must not exceed that knapsack's capacity. The total profit to be maximized is the sum of two components: first, the individual profits of all items that are placed in some knapsack, and second, for every pair of distinct items that are placed together in the same knapsack, the pairwise profit associated with that pair. + +The input data specifies the number of items, the number of knapsacks, a vector of individual profits (one integer per item, not necessarily nonnegative), a symmetric matrix of pairwise profits (one integer per unordered pair of distinct items, not necessarily nonnegative), a vector of item weights (one nonnegative value per item), and a vector of knapsack capacities (one positive integer per knapsack). The goal is to determine an assignment of items to knapsacks that maximizes the sum of the individual profits of all assigned items plus the sum of the pairwise profits of every co-assigned pair, while respecting the capacity of every knapsack and placing each item in at most one knapsack. diff --git a/tasks/bergman2019/solution_logger.py b/tasks/bergman2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/bergman2019/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/bergman2019/solution_schema.json b/tasks/bergman2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..552389cafe7b51e4722bfa851329ef53b73f9633 --- /dev/null +++ b/tasks/bergman2019/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total profit from individual item profits plus pairwise profits of items sharing a knapsack.", + "assignment": " List of [item_index, knapsack_index] pairs; item indices 0-indexed in [0, n-1] and knapsack indices 0-indexed in [0, m-1]. Unassigned items are omitted. An item index appearing more than once indicates a multi-assignment infeasibility (math_model label {assign})." +} diff --git a/tasks/bertsimas2022/feasibility_check.py b/tasks/bertsimas2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b7654733c868180f644295d77406e2512df4578f --- /dev/null +++ b/tasks/bertsimas2022/feasibility_check.py @@ -0,0 +1,403 @@ +""" +Feasibility checker for sparse portfolio selection solutions. + +Checks candidate solutions against the hard constraints from: + Bertsimas and Cory-Wright (2022), + "A Scalable Algorithm for Sparse Portfolio Selection" + +Constraint numbering (first unique appearance, top to bottom in formulation section): + C1: e^T x = 1 (budget constraint, Problem 1) + C2: l <= A x <= u (linear constraints, Problem 2) + - C2: mu^T x >= r_bar (min return, when applicable) + - C2: x_i >= l_i * z_i (min investment, when applicable) + - C2: x_i <= u_i * z_i (max investment, when applicable) + C3: ||x||_0 <= k (cardinality on x, Problem 2) + C4: x_i = 0 if z_i = 0 forall i (linking, Problem 3) + C5: x_i^2 <= z_i * theta_i forall i (perspective, Problem 5; gurobi only) + C6: x_i >= 0 forall i (non-negativity of x, domain) + C7: z_i in {0,1} forall i (binary z, domain) + C8: e^T z <= k (cardinality on z, domain) + C9: theta_i >= 0 forall i (non-negativity of theta, domain; gurobi only) + C10: objective_value matches the recomputed objective (Tier C obj-recompute) +""" + +import argparse +import json +import numpy as np + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'x') +_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"] + k = instance["k"] + mu = np.array(instance["mu"], dtype=float) + + x = np.array(solution["x"], dtype=float) + # z and theta are reformulation auxiliaries (perspective MISOCO); the + # original Problem (4) only has x. We tolerate their absence. + z = (np.array(solution["z"], dtype=float) + if "z" in solution and solution["z"] is not None else None) + has_theta = "theta" in solution and solution["theta"] is not None + theta = np.array(solution["theta"], dtype=float) if has_theta else None + + constr = instance.get("constraints", {}) + has_min_return = constr.get("has_min_return_constraint", False) + r_bar = constr.get("r_bar", None) + has_min_inv = constr.get("has_min_investment_constraint", False) + l_min = constr.get("l_min_investment", None) + u_max = constr.get("u_max_investment", None) + + violations = [] + violation_magnitudes = [] + violated_set = set() + + def record(constraint_idx, msg, lhs, rhs, raw_excess): + violated_set.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + ratio = raw_excess / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(raw_excess), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ------------------------------------------------------------------ + # Constraint 1: e^T x = 1 (budget) + # ------------------------------------------------------------------ + lhs_c1 = float(np.sum(x)) + rhs_c1 = 1.0 + viol_c1 = abs(lhs_c1 - rhs_c1) + if viol_c1 > tol: + record(1, f"Budget constraint violated: sum(x)={lhs_c1:.8f}, expected 1.0", + lhs_c1, rhs_c1, viol_c1) + + # ------------------------------------------------------------------ + # Constraint 2: l <= Ax <= u (linear constraints, when applicable) + # ------------------------------------------------------------------ + # 2a: min return constraint: mu^T x >= r_bar + if has_min_return and r_bar is not None: + lhs_ret = float(mu @ x) + rhs_ret = float(r_bar) + viol_ret = rhs_ret - lhs_ret # >= constraint: violation if RHS > LHS + if viol_ret > tol: + record(2, f"Min return violated: mu^T x={lhs_ret:.8f} < r_bar={rhs_ret:.8f}", + lhs_ret, rhs_ret, viol_ret) + + # 2b: min investment threshold (semi-continuous on x): if x_i > 0 then x_i >= l_i. + if has_min_inv and l_min is not None: + l_arr = np.array(l_min, dtype=float) + for i in range(n): + if x[i] > tol: + lhs_mi = float(x[i]) + rhs_mi = float(l_arr[i]) + viol_mi = rhs_mi - lhs_mi # >= constraint + if viol_mi > tol: + record(2, f"Min investment violated for asset {i}: x[{i}]={lhs_mi:.8f} < l_min={rhs_mi:.8f}", + lhs_mi, rhs_mi, viol_mi) + + # 2c: max investment cap on x: x_i <= u_i. + if u_max is not None: + u_arr = np.array(u_max, dtype=float) + for i in range(n): + if x[i] > tol: + lhs_ui = float(x[i]) + rhs_ui = float(u_arr[i]) + viol_ui = lhs_ui - rhs_ui # <= constraint + if viol_ui > tol: + record(2, f"Max investment violated for asset {i}: x[{i}]={lhs_ui:.8f} > u_max={rhs_ui:.8f}", + lhs_ui, rhs_ui, viol_ui) + + # 2d: general linear constraints: l_lin <= A x <= u_lin + A_lin = constr.get("A_lin", None) + l_lin = constr.get("l_lin", None) + u_lin = constr.get("u_lin", None) + if A_lin is not None: + A_mat = np.array(A_lin, dtype=float) + Ax = A_mat @ x + m_lin = Ax.shape[0] + if l_lin is not None: + l_arr_lin = np.array(l_lin, dtype=float) + for j in range(m_lin): + viol_lj = float(l_arr_lin[j] - Ax[j]) + if viol_lj > tol: + record(2, f"General linear lower bound violated at row {j}: (Ax)[{j}]={float(Ax[j]):.8f} < l[{j}]={float(l_arr_lin[j]):.8f}", + float(Ax[j]), float(l_arr_lin[j]), viol_lj) + if u_lin is not None: + u_arr_lin = np.array(u_lin, dtype=float) + for j in range(m_lin): + viol_uj = float(Ax[j] - u_arr_lin[j]) + if viol_uj > tol: + record(2, f"General linear upper bound violated at row {j}: (Ax)[{j}]={float(Ax[j]):.8f} > u[{j}]={float(u_arr_lin[j]):.8f}", + float(Ax[j]), float(u_arr_lin[j]), viol_uj) + + # ------------------------------------------------------------------ + # Constraint 3: ||x||_0 <= k (cardinality) + # ------------------------------------------------------------------ + nnz_x = int(np.sum(np.abs(x) > tol)) + lhs_c3 = float(nnz_x) + rhs_c3 = float(k) + viol_c3 = lhs_c3 - rhs_c3 # <= constraint + if viol_c3 > tol: + record(3, f"Cardinality violated: ||x||_0={nnz_x} > k={k}", + lhs_c3, rhs_c3, viol_c3) + + # ------------------------------------------------------------------ + # NOTE: Constraints 4 (x_i=0 if z_i=0), 5 (perspective x_i^2 <= z_i*theta_i), + # 7 (z binary), 8 (e^T z <= k via z), and 9 (theta >= 0) all enforce the + # auxiliary variables z and theta of the perspective MISOCO + # reformulation (Problem 35). They are NOT constraints of the original + # Problem (4), whose only decision variable is x. Per project rule + # they are intentionally NOT enforced so that any solver that does + # not introduce z / theta is not falsely flagged as infeasible. + # Cardinality is verified above (C3) directly from x. + # ------------------------------------------------------------------ + + # ------------------------------------------------------------------ + # Constraint 6: x_i >= 0 (non-negativity) + # ------------------------------------------------------------------ + for i in range(n): + if x[i] < -tol: + lhs_c6 = float(x[i]) + rhs_c6 = 0.0 + viol_c6 = -x[i] # >= constraint: violation = RHS - LHS = -x[i] + record(6, f"Non-negativity violated: x[{i}]={x[i]:.8f} < 0", + lhs_c6, rhs_c6, viol_c6) + + # ------------------------------------------------------------------ + # Constraint 10: objective consistency (Tier C obj-recompute) + # The objective (Problem 34 / 4 equivalent) is fully determined by x: + # obj = (1/2) x^T Sigma x + (1/(2*gamma)) ||x||_2^2 - kappa * mu^T x + # where Sigma = F F^T + diag(idiosyncratic_variance). + # ------------------------------------------------------------------ + 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: + try: + F = np.array(instance["factor_loadings"], dtype=float) + idio = np.array(instance["idiosyncratic_variance"], dtype=float) + gamma = float(instance["gamma"]) + kappa = float(instance["kappa"]) + except (KeyError, TypeError, ValueError): + F = idio = None + gamma = kappa = None + if F is not None and idio is not None and gamma is not None and gamma > 0: + Fx = F.T @ x + xSx = float(Fx @ Fx + np.sum(idio * x * x)) + ridge = float(x @ x) / (2.0 * gamma) + ret = float(mu @ x) + true_obj = 0.5 * xSx + ridge - kappa * ret + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-6 absolute floor + obj_tol = max(1e-6, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + record( + 10, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed " + f"(1/2)*x^T Sigma x + (1/(2*gamma))*||x||^2 - kappa*mu^T x=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})", + reported, true_obj, abs_diff, + ) + + # ------------------------------------------------------------------ + # Build result + # ------------------------------------------------------------------ + feasible = len(violated_set) == 0 + violated_constraints = sorted(violated_set) + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for sparse portfolio selection (Bertsimas 2022)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + 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) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Result: {status}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + print(f"Written to {args.result_path}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/bertsimas2022/gurobi_code.py b/tasks/bertsimas2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a9fd15c357b425fe15df321b6fa7d45fd103d1fa --- /dev/null +++ b/tasks/bertsimas2022/gurobi_code.py @@ -0,0 +1,271 @@ +""" +Gurobi implementation of the MISOCO formulation (Problem 35) from: + Bertsimas and Cory-Wright (2022), + "A Scalable Algorithm for Sparse Portfolio Selection" + +Problem (35): + min_{z in Z_k^n, x in R^n_+, theta in R^n_+} + (1/2) x^T Sigma x + (1/(2*gamma)) * e^T theta - kappa * mu^T x + s.t. + e^T z <= k, + e^T x = 1, + l <= A x <= u (if any linear constraints), + x_i^2 <= z_i * theta_i for all i in [n] (perspective constraints) + +The covariance matrix is reconstructed from the factor model: + Sigma = F @ F^T + diag(idiosyncratic_variance) +where F = factor_loadings (n x r). + +Usage: + python gurobi_code.py --instance_path instance_1.json \ + --solution_path gurobi_solution_1.json \ + --time_limit 300 +""" + +import argparse +import json +import numpy as np +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 project_x_to_support(x_raw, z_raw, k, n): + """Hard-project x onto the cardinality-feasible set with budget sum=1. + + The big-M perspective formulation can leak small nonzero x_i (~1e-4) at + time-out when the binary z_i has not been fully driven to 0. The original + Problem (4) requires ||x||_0 <= k, which the leaked x violates. We project + by: + 1. Pick the support: indices with z_i >= 0.5 (or top-k by |x_i| if z is + degenerate or violates the cardinality budget itself). + 2. Zero x outside the support; clamp to non-negativity. + 3. Renormalize so sum(x) = 1. + Returns (x_proj, sorted_support_indices). + """ + if z_raw is not None: + support = sorted(int(i) for i in np.where(z_raw >= 0.5)[0]) + else: + support = [] + if len(support) == 0 or len(support) > k: + # Fall back to magnitude-based top-k + order = np.argsort(-np.abs(x_raw)) + support = sorted(int(i) for i in order[:k]) + + x_proj = np.zeros(n, dtype=float) + for i in support: + x_proj[i] = max(float(x_raw[i]), 0.0) + s = x_proj.sum() + if s > 0: + x_proj /= s + return x_proj, support + + +def evaluate_objective(x, Sigma, gamma, kappa, mu): + """Objective with theta_i = x_i^2 (optimal given z_i=1 in the support).""" + quad = 0.5 * float(x @ Sigma @ x) + persp = (1.0 / (2.0 * gamma)) * float((x ** 2).sum()) + ret = kappa * float(mu @ x) + return quad + persp - ret + + +def main(): + parser = argparse.ArgumentParser( + description="Solve sparse portfolio selection via MISOCO (Gurobi)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the JSON solution 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 + # ------------------------------------------------------------------ # + with open(args.instance_path, "r") as fh: + inst = json.load(fh) + + n = inst["n"] # number of assets + k = inst["k"] # cardinality budget + gamma = inst["gamma"] # ridge regularizer + kappa = inst["kappa"] # return weight (0 or 1) + mu = np.array(inst["mu"], dtype=float) # expected returns (n,) + F = np.array(inst["factor_loadings"], dtype=float) # factor loadings (n, r) + eps_var = np.array(inst["idiosyncratic_variance"], dtype=float) # (n,) + + # ------------------------------------------------------------------ # + # Build covariance matrix: Sigma = F @ F^T + diag(eps_var) + # ------------------------------------------------------------------ # + Sigma = F @ F.T + np.diag(eps_var) # (n, n) positive definite + + # ------------------------------------------------------------------ # + # Read optional constraints + # ------------------------------------------------------------------ # + constr = inst.get("constraints", {}) + has_min_return = constr.get("has_min_return_constraint", False) + r_bar = constr.get("r_bar", None) + has_min_inv = constr.get("has_min_investment_constraint", False) + l_min = constr.get("l_min_investment", None) # per-asset lower bounds + u_max = constr.get("u_max_investment", None) # per-asset upper bounds + A_lin = inst.get("A", None) # (m, n) linear constraint matrix + l_lin = inst.get("l", None) # (m,) linear lower bounds + u_lin = inst.get("u", None) # (m,) linear upper bounds + + # ------------------------------------------------------------------ # + # Build Gurobi model + # ------------------------------------------------------------------ # + model = gp.Model("SparsePortfolio_MISOCO") + model.setParam("TimeLimit", args.time_limit) + model.setParam("Threads", 1) + model.setParam("OutputFlag", 1) + + # Decision variables + x = model.addVars(n, lb=0.0, name="x") # portfolio weights + z = model.addVars(n, vtype=GRB.BINARY, name="z") # support indicators + theta = model.addVars(n, lb=0.0, name="theta") # auxiliary perspective vars + + # ------------------------------------------------------------------ # + # Objective: (1/2) x^T Sigma x + (1/(2*gamma)) sum(theta) - kappa * mu^T x + # ------------------------------------------------------------------ # + # Build quadratic objective using the factor structure for efficiency: + # x^T Sigma x = x^T (F F^T + diag(eps)) x + # = ||F^T x||_2^2 + eps^T (x o x) + # We use auxiliary variables v = F^T x (r-dimensional) to keep the + # objective quadratic rather than constructing the dense n x n Sigma. + # For correctness on any instance size we use the dense Sigma here. + obj = gp.QuadExpr() + # Quadratic term: (1/2) x^T Sigma x + for i in range(n): + for j in range(n): + coeff = Sigma[i, j] + if abs(coeff) > 1e-16: + obj += 0.5 * coeff * x[i] * x[j] + # Regularization / perspective term: (1/(2*gamma)) sum theta_i + obj += (1.0 / (2.0 * gamma)) * gp.quicksum(theta[i] for i in range(n)) + # Return term: -kappa * mu^T x + obj -= kappa * gp.quicksum(mu[i] * x[i] for i in range(n)) + model.setObjective(obj, GRB.MINIMIZE) + + # ------------------------------------------------------------------ # + # Constraints + # ------------------------------------------------------------------ # + # Cardinality: sum(z) <= k + model.addConstr( + gp.quicksum(z[i] for i in range(n)) <= k, + name="cardinality" + ) + # Budget: sum(x) = 1 + model.addConstr( + gp.quicksum(x[i] for i in range(n)) == 1.0, + name="budget" + ) + # Perspective constraints: x_i^2 <= z_i * theta_i (rotated SOC) + for i in range(n): + model.addQConstr( + x[i] * x[i] <= z[i] * theta[i], + name=f"persp_{i}" + ) + + # Optional: minimum return constraint mu^T x >= r_bar + if has_min_return and r_bar is not None: + model.addConstr( + gp.quicksum(mu[i] * x[i] for i in range(n)) >= r_bar, + name="min_return" + ) + + # Optional: minimum investment x_i >= l_i * z_i (semi-continuous) + if has_min_inv and l_min is not None: + l_arr = np.array(l_min, dtype=float) + for i in range(n): + model.addConstr(x[i] >= l_arr[i] * z[i], name=f"min_inv_{i}") + + # Optional: maximum investment x_i <= u_i * z_i + if u_max is not None: + u_arr = np.array(u_max, dtype=float) + for i in range(n): + model.addConstr(x[i] <= u_arr[i] * z[i], name=f"max_inv_{i}") + + # General linear constraints: l <= A x <= u (math_model.txt eq (35)) + if A_lin is not None: + A_arr = np.array(A_lin, dtype=float) + l_arr_lin = np.array(l_lin, dtype=float) if l_lin is not None else None + u_arr_lin = np.array(u_lin, dtype=float) if u_lin is not None else None + for j in range(A_arr.shape[0]): + lhs = gp.quicksum(A_arr[j, i] * x[i] for i in range(n)) + if l_arr_lin is not None: + model.addConstr(lhs >= l_arr_lin[j], name=f"lin_lb_{j}") + if u_arr_lin is not None: + model.addConstr(lhs <= u_arr_lin[j], name=f"lin_ub_{j}") + + # ------------------------------------------------------------------ # + # Solve + # ------------------------------------------------------------------ # + model.optimize() + + # ------------------------------------------------------------------ # + # Extract and save solution + # ------------------------------------------------------------------ # + if model.SolCount > 0: + x_raw = np.array([x[i].X for i in range(n)]) + z_raw = np.array([z[i].X for i in range(n)]) + solver_obj_val = float(model.ObjVal) + + # Hard projection onto cardinality-feasible set: needed because at + # time-out the big-M perspective lets x_i leak ~1e-4 even when z_i is + # supposed to be 0, which would violate ||x||_0 <= k in the original + # problem. The projected x exactly satisfies cardinality and budget. + x_sol, support = project_x_to_support(x_raw, z_raw, k, n) + obj_val = evaluate_objective(x_sol, Sigma, gamma, kappa, mu) + else: + x_sol = None + support = None + solver_obj_val = None + obj_val = None + + solution = { + "instance_id": inst.get("instance_id", ""), + "objective_value": obj_val, # objective evaluated on projected x + # The original Problem (4) decision variable is x. z and theta are + # auxiliary variables of the perspective MISOCO reformulation + # (Problem 35) and are NOT emitted — feasibility_check verifies only + # the original problem against x. + "x": x_sol.tolist() if x_sol is not None else None, + "support": support, # indices with x_i > 0, len <= k + "solver_obj_val": solver_obj_val, # Gurobi's ObjVal on the un-projected x + "solver_status": model.Status, + "solver_status_str": { + 1: "LOADED", 2: "OPTIMAL", 3: "INFEASIBLE", + 4: "INF_OR_UNBD", 5: "UNBOUNDED", 9: "TIME_LIMIT", + }.get(model.Status, f"STATUS_{model.Status}"), + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + "runtime_s": model.Runtime, + } + + with open(args.solution_path, "w") as fh: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, fh, indent=2) + + print(f"Status : {solution['solver_status_str']}") + print(f"Obj val : {obj_val}") + print(f"Runtime : {model.Runtime:.2f}s") + + +if __name__ == "__main__": + main()