diff --git a/tasks/carosi2019/solution_schema.json b/tasks/carosi2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..67ed16f94d1ff014fa5cd98cc4a11aff6a954e44 --- /dev/null +++ b/tasks/carosi2019/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total weighted cost combining vehicle-scheduling cost (fleet size, terminal waiting, pull-in/pull-out) and the sum of squared headway-deviation penalties across all selected trips.", + "selected_trips": " IDs of the potential trips that are chosen to operate in the final timetable.", + "num_vehicles": " Number of vehicles required to cover all selected trips.", + "tt_arcs_used": { + "{pattern_id}": " Ordered list of arcs forming the timetable chain for this direction/pattern, where each arc is a pair [from_node, to_node] consisting of either a trip ID or a source/sink marker." + }, + "vs_flows": "{to_node}'> Flow value on each used arc of the vehicle-scheduling network, including per-trip operation arcs, in-line and deadhead connection arcs between consecutive trips, pull-out/pull-in arcs to and from the depot, and the depot circulation arc whose value equals the fleet size." +} diff --git a/tasks/carvalho1999/feasibility_check.py b/tasks/carvalho1999/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b2efd559b3fe826c2e6e9ccfef3ab1b6493d75 --- /dev/null +++ b/tasks/carvalho1999/feasibility_check.py @@ -0,0 +1,463 @@ +""" +Feasibility checker for the Arc Flow Model for 1D Bin Packing. +Based on: Carvalho (1999), Annals of Operations Research 86, 629-659. + +Checks constraints: + (1) Flow conservation (Eq 8) + (2) Demand satisfaction (Eq 9) + (3) Non-negativity (Eq 10) + (4) Integrality (Eq 11) + (5) Integer-domain auto-check on arc_flows / z + (6) Non-negativity auto-check on arc_flows / z + (7) Objective consistency: reported objective_value must equal the true + number of bins used, i.e. len(bin_assignments). Defends against + score-gaming solutions that pass constraints (1)-(6) but lie about + the cost. +""" + +import argparse +import json +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('bin_assignments', 'num_bins', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Arc Flow Bin Packing (Carvalho 1999)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility result written to {args.result_path}") + print(f"Feasible: {result['feasible']}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +def check_feasibility(instance, solution): + W = instance["bin_capacity"] + items = instance["items"] + + # Group items by size to get demands (sorted decreasing) + size_counts = defaultdict(int) + for s in items: + size_counts[s] += 1 + sizes = sorted(size_counts.keys(), reverse=True) + demands = [size_counts[s] for s in sizes] + m = len(sizes) + + tol = 1e-5 + eps = 1e-5 + + violations = [] + violated_constraints = set() + violation_magnitudes = [] + + # ---- Parse solution: original structure is bin_assignments (list of + # dicts with 'items'); legacy 'bins' is also accepted. We reconstruct + # arc flows internally for arc-flow conservation checks. ---- + bins_input = None + if "bin_assignments" in solution: + bins_input = solution["bin_assignments"] + elif "bins" in solution: + bins_input = solution["bins"] + if bins_input is None: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Unknown solution format: 'bin_assignments' (or legacy 'bins') not found"], + "violation_magnitudes": [] + } + + arc_flows = defaultdict(int) + for bin_data in bins_input: + bin_items = bin_data["items"] + sorted_items = sorted(bin_items, reverse=True) + pos = 0 + for item in sorted_items: + arc_flows[(pos, pos + item)] += 1 + pos += item + while pos < W: + arc_flows[(pos, pos + 1)] += 1 + pos += 1 + arc_flows = dict(arc_flows) + z = solution.get("num_bins", len(bins_input)) + + # ---- Domain check on num_bins (z): integer >= 0 (paper Eq 11) ---- + violations_z = [] + if not isinstance(z, (int, float)): + violations_z.append( + f"Constraint 5 (integer domain): num_bins z={z!r} is not numeric") + else: + if z < -1e-9: + violations_z.append( + f"Constraint 6 (non-negativity): num_bins z = {z} < 0") + if abs(z - round(z)) > 1e-6: + violations_z.append( + f"Constraint 5 (integer domain): num_bins z = {z} is not integer") + violations.extend(violations_z) + if violations_z: + for msg in violations_z: + cidx = 5 if "integer" in msg else 6 + violation_magnitudes.append({ + "constraint": cidx, "lhs": float(z), "rhs": 0.0 if cidx == 6 else round(z), + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + + # ---- Precompute inflow and outflow at each node ---- + inflow_at = defaultdict(float) + outflow_at = defaultdict(float) + for (i, j), v in arc_flows.items(): + outflow_at[i] += v + inflow_at[j] += v + + # ================================================================ + # Constraint (1): Flow conservation (Eq 8) + # ================================================================ + for node in range(W + 1): + lhs_val = inflow_at[node] - outflow_at[node] + if node == 0: + rhs_val = float(-z) + elif node == W: + rhs_val = float(z) + else: + rhs_val = 0.0 + + violation_amount = abs(lhs_val - rhs_val) + if violation_amount > tol: + violated_constraints.add(1) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Flow conservation violated at node {node}: " + f"net flow = {lhs_val}, expected {rhs_val}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs_val), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ================================================================ + # Constraint (2): Demand constraints (Eq 9) + # ================================================================ + for d_idx in range(m): + w_d = sizes[d_idx] + b_d = demands[d_idx] + total_packed = sum(v for (i, j), v in arc_flows.items() if j - i == w_d) + lhs_val = float(total_packed) + rhs_val = float(b_d) + violation_amount = max(rhs_val - lhs_val, 0.0) + if violation_amount > tol: + violated_constraints.add(2) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Demand not met for item size {w_d}: " + f"packed {int(lhs_val)}, required {b_d}" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ================================================================ + # Constraint (3): Non-negativity (Eq 10) + # ================================================================ + for (i, j), v in arc_flows.items(): + violation_amount = max(-v, 0.0) + if violation_amount > tol: + violated_constraints.add(3) + normalizer = eps + violations.append( + f"Negative flow on arc ({i},{j}): x = {v}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(v), + "rhs": 0.0, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ================================================================ + # Constraint (4): Integrality (Eq 11) + # ================================================================ + for (i, j), v in arc_flows.items(): + nearest_int = round(v) + violation_amount = abs(v - nearest_int) + if violation_amount > tol: + violated_constraints.add(4) + normalizer = max(abs(nearest_int), eps) + violations.append( + f"Non-integer flow on arc ({i},{j}): x = {v}" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(v), + "rhs": float(nearest_int), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ---- Build output ---- + _domain_check_vars_binary = [] + _domain_check_vars_integer = [("arc_flows", arc_flows)] + + # ===================================================================== + # Non-negativity check for carvalho1999 + arc_flows_dict = solution.get("arc_flows", {}) + if isinstance(arc_flows_dict, dict): + for arc, val in arc_flows_dict.items(): + try: + v = float(val) + except (TypeError, ValueError): + continue + if v < -tol: + violated_constraints.add(6) + violations.append( + f"Constraint 6 (non-negativity): arc_flows[{arc}] = {v} < 0" + ) + violation_magnitudes.append({ + "constraint": 6, "lhs": v, "rhs": 0.0, + "raw_excess": -v, "normalizer": max(abs(v), eps), + "ratio": -v / max(abs(v), eps), + }) + + # ===================================================================== + # Constraint 5: Integer domain + 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 (7): Objective consistency. + # The objective z is exactly the number of bins used. Recompute it + # from len(bin_assignments) and reject if reported objective_value + # disagrees by 0.5 or more (objective is integer-valued). + # ================================================================ + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(len(bins_input)) + abs_diff = abs(reported - true_obj) + obj_tol = 0.5 # integer-valued objective + if abs_diff > obj_tol: + violated_constraints.add(7) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Constraint 7 (objective consistency): reported " + f"objective_value={reported} differs from recomputed " + f"num_bins=len(bin_assignments)={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol})" + ) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + feasible = len(violated_constraints) == 0 + + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + +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/carvalho1999/gurobi_code.py b/tasks/carvalho1999/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..b9fb213c0a302b8e25af07b0752b38643cbd0ad5 --- /dev/null +++ b/tasks/carvalho1999/gurobi_code.py @@ -0,0 +1,314 @@ +""" +Arc Flow Model for the One-Dimensional Bin-Packing Problem. +Based on: Carvalho (1999), "Exact solution of bin-packing problems using +column generation and branch-and-bound", Annals of Operations Research 86, 629-659. + +Implements the full arc flow IP formulation (Equations 7-11) with arc reduction +criteria 1-3 and valid inequalities (Propositions 2.2, 2.3). +""" + +import argparse +import json +import math +from collections import defaultdict +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path) as f: + data = json.load(f) + W = data["bin_capacity"] + items = data["items"] + # Group items by size, compute demands + size_counts = defaultdict(int) + for s in items: + size_counts[s] += 1 + # Sort in decreasing order of width + sizes = sorted(size_counts.keys(), reverse=True) + demands = [size_counts[s] for s in sizes] + return W, sizes, demands, data + + +def build_reduced_arc_set(W, sizes, demands): + """ + Build the reduced arc set A_LP using Criteria 1-3. + + Criterion 1: An arc of size w_e from node k is valid only if k=0 or + k is the head of an arc of size w_d >= w_e. + Criterion 2: Loss arcs x_{k,k+1} are removed for k < w_m (smallest item size). + Criterion 3: From a valid starting node k for size w_e, only arcs at + k + s*w_e for s=0,...,b_e-1 are valid (if they fit). + """ + m = len(sizes) + w_m = sizes[-1] # smallest item size + + # We'll compute valid nodes for each item size using a BFS/forward pass. + # A node is a "valid head" for items of size >= w_e if it's 0 or reachable + # by an arc of size >= w_e. + + # For each item size index e, collect the set of valid starting nodes. + # We process sizes from largest to smallest. + # valid_heads[e] = set of nodes where an arc of size w_e can start + + # First, compute which nodes are heads of arcs of each size. + # A node k is a valid starting point for w_e if: + # k = 0, OR there exists d with w_d >= w_e and an arc (k - w_d, k) is valid. + + # We'll build this iteratively. + # "anchor nodes" for size w_e: nodes that are either 0 or heads of arcs of + # strictly larger size. From each anchor, we can place up to b_e consecutive + # arcs of size w_e (Criterion 3). + + item_arcs = set() # set of (i, j, size_index) + + # Track which nodes are reachable as heads of valid arcs + # reachable_by_size[e] = set of nodes that are heads of arcs of size w_e + # We need "anchor" nodes: nodes reachable by arcs of strictly larger sizes (or node 0) + + # Process sizes from largest to smallest + # For the largest size, anchors are just {0} + # For each subsequent size, anchors include all heads from larger sizes + + all_heads = set([0]) # nodes that are heads of some arc of any size processed so far + + for e in range(m): + w_e = sizes[e] + b_e = demands[e] + # Anchor nodes for this size: all_heads (includes 0 and heads of larger arcs) + anchors = sorted(all_heads) + + new_heads = set() + for anchor in anchors: + # From this anchor, place up to b_e consecutive arcs of size w_e + for s in range(b_e): + start = anchor + s * w_e + end = start + w_e + if end > W: + break + item_arcs.add((start, end, e)) + new_heads.add(end) + + all_heads = all_heads | new_heads + + # Loss arcs: (k, k+1) for k >= w_m (Criterion 2) + loss_arcs = set() + for k in range(w_m, W): + loss_arcs.add((k, k + 1)) + + return item_arcs, loss_arcs + + +def solve(instance_path, solution_path, time_limit): + W, sizes, demands, data = load_instance(instance_path) + m = len(sizes) + w_m = sizes[-1] # smallest item size + + # Build reduced arc set + item_arcs, loss_arcs = build_reduced_arc_set(W, sizes, demands) + + # Build Gurobi model + model = gp.Model("ArcFlowBinPacking") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i,j] for item arcs + x = {} + for (i, j, e) in item_arcs: + key = (i, j) + if key not in x: + x[key] = model.addVar(vtype=GRB.INTEGER, lb=0, name=f"x_{i}_{j}") + + # x[k,k+1] for loss arcs + for (k, k1) in loss_arcs: + key = (k, k1) + if key not in x: + x[key] = model.addVar(vtype=GRB.INTEGER, lb=0, name=f"x_{k}_{k1}") + + # z = number of bins (feedback arc from W to 0) + z = model.addVar(vtype=GRB.INTEGER, lb=0, name="z") + + model.update() + + # Objective: minimize z + model.setObjective(z, GRB.MINIMIZE) + + # Collect all arcs by their endpoints for flow conservation + # Build adjacency: arcs_into[j] and arcs_outof[j] + arcs_into = defaultdict(list) + arcs_outof = defaultdict(list) + for key in x: + i, j = key + arcs_into[j].append(key) + arcs_outof[i].append(key) + + # Flow conservation constraints (Equation 8) + # For j=0: sum of arcs into 0 - sum of arcs out of 0 = -z + # But arcs into 0: only the feedback arc (W,0) which is z + # So: z - sum_outof_0 = -z => sum_outof_0 = 2z ... + # Actually, the feedback arc z = x_{W,0} is separate. + # Flow conservation at node j: + # (inflow) - (outflow) = { -z if j=0, 0 if 1<=j<=W-1, z if j=W } + # Inflow to j from forward arcs: sum_{(i,j) in A} x_{ij} + # Plus feedback: if j=0, inflow includes z (from W->0) + # Outflow from j via forward arcs: sum_{(j,k) in A} x_{jk} + # Plus feedback: if j=W, outflow includes z (to 0) + + for j in range(W + 1): + inflow = gp.LinExpr() + outflow = gp.LinExpr() + + for key in arcs_into.get(j, []): + inflow += x[key] + for key in arcs_outof.get(j, []): + outflow += x[key] + + if j == 0: + # inflow (from feedback) + forward_inflow - outflow = -z + # z + forward_inflow - outflow = -z (feedback arc z goes into node 0) + # forward_inflow - outflow = -2z ... that's not right. + # + # Actually: the flow conservation says: + # For the feedback arc (W, 0) with flow z: + # At node 0: inflow = z (from feedback), outflow = sum of forward arcs out of 0 + # Net: z - outflow = -z => not standard. + # + # The paper formulation (Eq 8): + # sum_{(i,j) in A} x_{ij} - sum_{(j,k) in A} x_{jk} = -z if j=0 + # Here A does NOT include the feedback arc. The feedback arc is implicit via z. + # So at j=0: forward_inflow - forward_outflow = -z + model.addConstr(inflow - outflow == -z, name=f"flow_{j}") + elif j == W: + model.addConstr(inflow - outflow == z, name=f"flow_{j}") + else: + model.addConstr(inflow - outflow == 0, name=f"flow_{j}") + + # Demand constraints (Equation 9) + for e in range(m): + w_e = sizes[e] + b_e = demands[e] + expr = gp.LinExpr() + for (i, j, d) in item_arcs: + if d == e: + key = (i, j) + expr += x[key] + model.addConstr(expr >= b_e, name=f"demand_{e}") + + # --- Valid inequality: minimum loss (Proposition 2.2) --- + # We add this after the model is set up. We first solve the LP relaxation + # to get z_LP, then add the cut. For simplicity in the Gurobi formulation, + # we add a callback or solve LP first. + # + # **INFERRED ASSUMPTION**: For the direct Gurobi solve, we compute a simple + # lower bound for z_LP as ceil(sum(w_d * b_d) / W) and use that for L_min. + # Gurobi's own presolve and cutting planes will handle tightening. + total_item_area = sum(sizes[e] * demands[e] for e in range(m)) + z_lb = math.ceil(total_item_area / W) + L_min = z_lb * W - total_item_area + + if L_min > 0: + loss_expr = gp.LinExpr() + for (k, k1) in loss_arcs: + loss_expr += x[(k, k1)] + model.addConstr(loss_expr >= L_min, name="min_loss") + + # Optimize + model.optimize() + + # Extract solution + result = {"instance": data.get("instance_id", 1)} + + if model.SolCount > 0: + result["objective_value"] = round(model.ObjVal) + + # Decode arc flows into bin assignments. Each unit of flow on an + # item arc (i, i+w_e) represents placing one item of size w_e + # starting at position i in some bin. Trace flow units along + # complete 0->W paths to recover the items each bin contains. + item_size_by_arc = {(i, j): sizes[e] for (i, j, e) in item_arcs} + loss_arc_set = set(loss_arcs) + flow_left = {} + for key, var in x.items(): + val = int(round(var.X)) + if val > 0: + flow_left[key] = val + out_arcs = defaultdict(list) + for (i, j) in flow_left: + out_arcs[i].append((i, j)) + + bin_assignments = [] + n_bins = int(round(z.X)) + for _ in range(n_bins): + pos = 0 + items_in_bin = [] + while pos < W: + chosen = None + for arc in out_arcs.get(pos, []): + if flow_left.get(arc, 0) > 0: + chosen = arc + break + if chosen is None: + break + flow_left[chosen] -= 1 + if chosen not in loss_arc_set: + items_in_bin.append(item_size_by_arc[chosen]) + pos = chosen[1] + bin_assignments.append({ + "items": items_in_bin, + "total_size": sum(items_in_bin), + }) + + result["bin_assignments"] = bin_assignments + result["num_bins"] = n_bins + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + else: + result["objective_value"] = None + result["status"] = "infeasible_or_no_solution" + + result["solver_status"] = model.Status + result["mip_gap"] = model.MIPGap if model.SolCount > 0 else 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 model.SolCount > 0: + print(f"Objective value (bins used): {result['objective_value']}") + + +def main(): + parser = argparse.ArgumentParser( + description="Arc Flow Model for 1D Bin Packing (Carvalho 1999) - 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 for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/carvalho1999/gurobi_feasi_result/large_feasi_result_1.json b/tasks/carvalho1999/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho1999/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/carvalho1999/gurobi_feasi_result/large_feasi_result_2.json b/tasks/carvalho1999/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho1999/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/carvalho1999/gurobi_feasi_result/large_feasi_result_3.json b/tasks/carvalho1999/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho1999/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/carvalho1999/gurobi_feasi_result/large_feasi_result_4.json b/tasks/carvalho1999/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho1999/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/carvalho1999/gurobi_feasi_result/large_feasi_result_5.json b/tasks/carvalho1999/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho1999/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/carvalho1999/gurobi_feasi_result/tiny_feasi_result.json b/tasks/carvalho1999/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho1999/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/carvalho1999/gurobi_solution/large_solution_1.json b/tasks/carvalho1999/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9ba36193872cd69200aecefd2cdad101d5fe0a48 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a08a58813c06fb372b8be5750c15dd17311c3aa864d25e80850e1e124287976 +size 850246 diff --git a/tasks/carvalho1999/gurobi_solution/large_solution_2.json b/tasks/carvalho1999/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c34abd50a0d5c3ead4fe3b8fae2c9fcb32338423 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77ca508621d843a60cdbf1d5285588ad9a8b7f89bf32e5069d5907418749909a +size 955831 diff --git a/tasks/carvalho1999/gurobi_solution/large_solution_3.json b/tasks/carvalho1999/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..bd0acd64f7e8931b933f3caedd52e34cd26ba865 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e097b8e1521535f35b2f33755d8629f4a9b7c56ec180b227eca2cd1aa4f0742 +size 1100267 diff --git a/tasks/carvalho1999/gurobi_solution/large_solution_4.json b/tasks/carvalho1999/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..256986a76cf6f0e8ece184b7cacbdcb8d30da071 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38f9413fda65ec29f5165adefa512c91938076eb720a4e166a3b1e380a6a0e7a +size 1164512 diff --git a/tasks/carvalho1999/gurobi_solution/large_solution_5.json b/tasks/carvalho1999/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..30ee0e5255f2616baf478340c4993c95eae66c5f --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a784a00ddaf512bee7ffa81bb887e3da72ceb80a083b12fd23f8ddb4ee5bdb9b +size 487903 diff --git a/tasks/carvalho1999/gurobi_solution/tiny_solution.json b/tasks/carvalho1999/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..25bd49003b5f4753e88c9ff4ab45e9cd9c604a73 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fad431899852310d98f849b61d6c55e41f6cc98037242245b06fc9e4ed681b9e +size 2212 diff --git a/tasks/carvalho1999/gurobi_solution_log/large_log_1.jsonl b/tasks/carvalho1999/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ca41bd25bc43d1938cdb167647d2edabb386f8c --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:321e2972b03af2e03d336f20d7a31a8b3d92cebd00b6c3cfc62651f579e9ae99 +size 176 diff --git a/tasks/carvalho1999/gurobi_solution_log/large_log_2.jsonl b/tasks/carvalho1999/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..871fa6e78e4149b1237450de2341a2e7e45aa274 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:faf06e6249d242a9b81dc8a87dd22ec62c379ab09154e47860663a614452230a +size 272 diff --git a/tasks/carvalho1999/gurobi_solution_log/large_log_3.jsonl b/tasks/carvalho1999/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3c3b1d02e31f0fda2394ce68456044210759da54 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f96829328e56463ef04d6155b1accfe57ac70655594acb65044d6131276a7607 +size 44 diff --git a/tasks/carvalho1999/gurobi_solution_log/large_log_4.jsonl b/tasks/carvalho1999/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2e94c76d064b8df577ca340d81d0890e1c2cb381 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8e49985e6e15ad2435f0783bf0a4410a8ed94ba57c756ad9de1d54c5ca0f1e3 +size 43 diff --git a/tasks/carvalho1999/gurobi_solution_log/large_log_5.jsonl b/tasks/carvalho1999/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..335c51b27364f9f33c48616d7c37c3bfaff43af7 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:705cbd3d766777d1dd9ca5f6f9b30c9e37e29e21bcc58092e632229b3aab86be +size 265 diff --git a/tasks/carvalho1999/gurobi_solution_log/tiny_log.jsonl b/tasks/carvalho1999/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a364d5735027bc4e53fd5e2c1b960a100896c576 --- /dev/null +++ b/tasks/carvalho1999/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f02718aa610775e78ae9d0c014a0f11bbfb59e057e626b920e75e9f1e0ff5b6 +size 41 diff --git a/tasks/carvalho1999/instance/large_instance_1.json b/tasks/carvalho1999/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..1126cf15c5d565bfd79510f136b7731e31444907 --- /dev/null +++ b/tasks/carvalho1999/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2bf11fbcc0efc25a742a59db6e33f7404d4ec396d56810e1236be0af51a89cc +size 225485 diff --git a/tasks/carvalho1999/instance/large_instance_2.json b/tasks/carvalho1999/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4979d3dbd588e06dc529b5ed6fe9e3291fa89ae6 --- /dev/null +++ b/tasks/carvalho1999/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30faf9361dded876b5be829de97d45c262e80449a40eadd4e055dc381bf81776 +size 225364 diff --git a/tasks/carvalho1999/instance/large_instance_3.json b/tasks/carvalho1999/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..eb82ef2190456cdcb61bbaf65e3c48733ac4cc3c --- /dev/null +++ b/tasks/carvalho1999/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03737737d19e0762d577dad127540a3d2edefb814b04288ebd641328f6aa0310 +size 225356 diff --git a/tasks/carvalho1999/instance/large_instance_4.json b/tasks/carvalho1999/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9c9cdb1b216a36c7303fd270a7ac40b5d9b2696d --- /dev/null +++ b/tasks/carvalho1999/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7e7453cf1514381cc781c47d8263e92f4897ff8f0369e39668535b178c60617 +size 219034 diff --git a/tasks/carvalho1999/instance/large_instance_5.json b/tasks/carvalho1999/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f5ab0346833903dbc1e625a34bb9559cd8f65b75 --- /dev/null +++ b/tasks/carvalho1999/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:557c26e1030d7d6aebffd39a16fa0fb1cd0b918d4c0609fc8e59431dc3063506 +size 208928 diff --git a/tasks/carvalho1999/instance/tiny_instance.json b/tasks/carvalho1999/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..aae8ffd49b88da6582c06cf1def8d9f3a40b4ae1 --- /dev/null +++ b/tasks/carvalho1999/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b5391ccae4346c430203c32db7ec1472e6fdc0fb2c8f45250ccc24e68dd94f3 +size 815 diff --git a/tasks/carvalho1999/instance_schema.json b/tasks/carvalho1999/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..6d6798db42beeff8ce73627b7dd7225241a2e33f --- /dev/null +++ b/tasks/carvalho1999/instance_schema.json @@ -0,0 +1,5 @@ +{ + "bin_capacity": " Maximum total size that each bin can hold.", + "num_items": " Total number of items to be packed into bins.", + "items": " Size of each item to be packed." +} \ No newline at end of file diff --git a/tasks/carvalho1999/mathematical_formulation.md b/tasks/carvalho1999/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..9f9a81d256eceb0eb492ac456c39225fd62f8586 --- /dev/null +++ b/tasks/carvalho1999/mathematical_formulation.md @@ -0,0 +1,50 @@ +# Original Formulation: One-Dimensional Bin-Packing – Arc Flow Model (Arc Flow) + +*Source: Exact solution of bin-packing problems using column generation and branch-and-bound, J.M. Valério de Carvalho, Annals of Operations Research 86 (1999) 629–659.* + +## Sets and Indices + +$$\begin{align*} +V &= \{0, 1, 2, \ldots, W\} && \text{set of vertices of the graph } G=(V,A) \\ +A &= \{(i,j) : 0 \le i < j \le W,\ j - i = w_d \text{ for some } d \le m\} && \text{item arcs} \\ + &\quad \cup\ \{(k, k+1) : k = 0, 1, \ldots, W-1\} && \text{loss arcs} \\ +d &= 1, 2, \ldots, m && \text{index over the different item sizes} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +W &\quad \text{bin capacity (positive integer)} \\ +m &\quad \text{number of different item sizes} \\ +w_d &\quad \text{size of item type } d,\ d = 1,\ldots,m,\ \ 0 \le w_d \le W \\ +b_d &\quad \text{demand (number of items required) of type } d,\ d = 1,\ldots,m +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x_{ij} &\quad \text{flow on arc } (i,j) \in A:\ \text{number of items of size } j-i \\ + &\quad \text{placed in any bin at a distance } i \text{ from the beginning of the bin} \\ +z &\quad \text{feedback arc flow from vertex } W \text{ to vertex } 0\ (z = x_{W0});\ \text{number of bins used} +\end{align*}$$ + +## Objective + +$$\begin{align} +\text{minimize} \quad z \tag{7} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{(i,j) \in A} x_{ij} \;-\; \sum_{(j,k) \in A} x_{jk} &= +\begin{cases} +-z, & \text{if } j = 0, \\ +\phantom{-}0, & \text{if } j = 1, 2, \ldots, W-1, \\ +\phantom{-}z, & \text{if } j = W; +\end{cases} +\tag{8} \\[1ex] +\sum_{(k,\, k+w_d) \in A} x_{k,\, k+w_d} &\ge b_d, \quad d = 1, 2, \ldots, m, \tag{9} \\[1ex] +x_{ij} &\ge 0, \quad \forall (i,j) \in A, \tag{10} \\[1ex] +x_{ij} &\ \text{integer}, \quad \forall (i,j) \in A. \tag{11} +\end{align}$$ diff --git a/tasks/carvalho1999/problem_description.txt b/tasks/carvalho1999/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..795a4417e7026f550c9b3a11727b8fec010f06f4 --- /dev/null +++ b/tasks/carvalho1999/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A packing facility has an unlimited supply of identical bins, each with a fixed integer capacity W (equivalently, identical stock rolls of width W in a one-dimensional cutting-stock setting). The facility receives a list of items to be packed, where every item has a known positive integer size that does not exceed the bin capacity. Items of the same size may appear multiple times, and the input data specifies the bin capacity, the number of distinct item sizes, the size of each item type, and the number of copies (the demand) required for each item type. + +Each item must be assigned to exactly one bin, and within any single bin the total size of the items packed into it cannot exceed the bin capacity W. Every demanded item must be packed (the full demand for each size must be satisfied). The number of bins available is effectively unlimited, but each bin that contains at least one item counts as "used". + +The goal is to assign all the demanded items to bins so that the total number of bins used is as small as possible. diff --git a/tasks/carvalho1999/solution_logger.py b/tasks/carvalho1999/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/carvalho1999/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/carvalho1999/solution_schema.json b/tasks/carvalho1999/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9c9ca126aa5ce1e515075ff09fbf5aef7f03fba8 --- /dev/null +++ b/tasks/carvalho1999/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total number of bins used to pack all demanded items.", + "bin_assignments": " One entry per bin used. Each entry has 'items' (a list of item sizes packed into the bin, summing to at most W) and 'total_size' (the sum of those item sizes).", + "num_bins": " Total number of bins used to pack all demanded items." +} diff --git a/tasks/carvalho2022/feasibility_check.py b/tasks/carvalho2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..696aea41d4eddc7aef4f7fd788b77c63965584b8 --- /dev/null +++ b/tasks/carvalho2022/feasibility_check.py @@ -0,0 +1,672 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the ILSSP-NT (Integrated Lot Sizing and Scheduling Problem +with Non-Triangular setup) on parallel machines. + +Based on: Carvalho & Nascimento (2022) +Checks constraints (2)-(20) from the mathematical formulation, plus +constraint (1) — objective-value consistency: the reported objective_value +must match the recomputed sum of inventory and setup costs derived from the +solution's x and y variables. +""" + +import argparse +import json +import math +from collections import deque + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('carryover', 'objective_value', 'production', 'setups') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def parse_solution(sol, n, m, p): + """Parse solution JSON into structured variable dictionaries.""" + # Parse x[i,k,t,u] + x = {} + for key, val in sol.get("production", {}).items(): + parts = key.split("_") # x_i_k_t_u + i, k, t, u = int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4]) + x[i, k, t, u] = float(val) + + # Parse y[i,j,k,t] + y = {} + for key, val in sol.get("setups", {}).items(): + parts = key.split("_") # y_i_j_k_t + i, j, k, t = int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4]) + y[i, j, k, t] = int(round(float(val))) + + # Parse z[i,k,t] + z = {} + for key, val in sol.get("carryover", {}).items(): + parts = key.split("_") # z_i_k_t + i, k, t = int(parts[1]), int(parts[2]), int(parts[3]) + z[i, k, t] = int(round(float(val))) + + return x, y, z + + +def get_x(x, i, k, t, u): + return x.get((i, k, t, u), 0.0) + + +def get_y(y, i, j, k, t): + return y.get((i, j, k, t), 0) + + +def get_z(z, i, k, t): + return z.get((i, k, t), 0) + + +def derive_G(z, y, n, m, p): + """Derive G[i,k,t] = 1 if machine k is ready to produce item i in period t.""" + G = {} + for i in range(n): + for k in range(m): + for t in range(p): + val = get_z(z, i, k, t) + sum(get_y(y, j, i, k, t) for j in range(n)) + G[i, k, t] = 1 if val > 0.5 else 0 + return G + + +def derive_R(y, n, m, p): + """Derive R[k,t] = 1 if at least one setup is performed at machine k in period t.""" + R = {} + for k in range(m): + for t in range(p): + total = sum(get_y(y, i, j, k, t) for i in range(n) for j in range(n)) + R[k, t] = 1 if total > 0.5 else 0 + return R + + +def compute_production_split(x, z, M, n, m, p): + """Compute x_a and x_b by maximizing x_b (production before first setup).""" + total_prod = {} + x_b = {} + x_a = {} + for i in range(n): + for k in range(m): + for t in range(p): + tot = sum(get_x(x, i, k, t, u) for u in range(t, p)) + total_prod[i, k, t] = tot + max_xb = M[i][t] * get_z(z, i, k, t) + xb = min(tot, max_xb) + x_b[i, k, t] = xb + x_a[i, k, t] = tot - xb + return total_prod, x_a, x_b + + +def check_subtour_reachability(z, y, G, n, m, p): + """ + Check sub-tour elimination: for each (k,t), all active items (G[i,k,t]=1) + must be reachable from the initial state item (z[i,k,t]=1) via y-edges. + Returns list of (k, t, unreachable_items) for violations. + """ + violations = [] + for k in range(m): + for t in range(p): + active = {i for i in range(n) if G.get((i, k, t), 0) == 1} + if not active: + continue + + # Find the initial state item + start_items = {i for i in range(n) if get_z(z, i, k, t) == 1} + + # BFS from start items through y-edges + visited = set() + queue = deque(start_items) + visited.update(start_items) + while queue: + node = queue.popleft() + for j in range(n): + if j not in visited and get_y(y, node, j, k, t) > 0: + visited.add(j) + queue.append(j) + # Also check incoming edges that create reachability + # (y[j,node,k,t] > 0 means node is reachable from j) + # Need to also check reverse: items reachable TO via incoming y + # Actually, the flow goes from initial state forward through transitions. + # y[i,j,k,t] means transition from i to j, so j is reachable from i. + + unreachable = active - visited + if unreachable: + violations.append((k, t, unreachable)) + return violations + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["dimensions"]["n"] + m = instance["dimensions"]["m"] + p = instance["dimensions"]["p"] + + d = instance["demands"] + h = instance["inventory_costs"] + proc_time_val = instance["processing_time"] + b_raw = instance["setup_times"] + c_raw = instance["setup_costs"] + T_cap = instance["machine_capacities"] + M = instance["max_production"] + q_raw = instance["max_setups_per_item"] + min_lot = instance["minimum_lot_sizes"] + + x, y, z = parse_solution(solution, n, m, p) + G = derive_G(z, y, n, m, p) + R = derive_R(y, n, m, p) + total_prod, x_a, x_b = compute_production_split(x, z, M, n, m, p) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs, rhs, op): + """Record a constraint violation with normalized magnitude.""" + if op == "eq": + violation_amount = abs(lhs - rhs) + elif op == "leq": + violation_amount = max(0, lhs - rhs) + elif op == "geq": + violation_amount = max(0, rhs - lhs) + else: + violation_amount = 0.0 + + if violation_amount > tol: + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(violation_amount, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + # ========================================================================= + # Constraint (2): Demand satisfaction (equality) + # sum_k sum_{t=1}^{u} x_{iktu} = d_{iu} forall (i, u) + # ========================================================================= + for i in range(n): + for u in range(p): + lhs = sum(get_x(x, i, k, t, u) for k in range(m) for t in range(u + 1)) + rhs = d[i][u] + record_violation(2, + f"Demand violation: item {i}, period {u}: produced={lhs:.4f}, demand={rhs}", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint (3): Capacity (<=) + # sum_i (sum_{u>=t} f*x_{iktu} + sum_j b_{jik}*y_{jikt}) <= T_{kt} + # ========================================================================= + for k in range(m): + for t in range(p): + prod_time = sum( + proc_time_val * get_x(x, i, k, t, u) + for i in range(n) for u in range(t, p)) + setup_time = sum( + b_raw[j][i][k] * get_y(y, j, i, k, t) + for i in range(n) for j in range(n)) + lhs = prod_time + setup_time + rhs = T_cap[k][t] + record_violation(3, + f"Capacity exceeded: machine {k}, period {t}: used={lhs:.4f}, capacity={rhs}", + lhs, rhs, "leq") + + # ========================================================================= + # Constraint (4): Production-setup link (<=) + # x_{iktu} <= M_{it} * G_{ikt} forall (i, k, t, u) + # ========================================================================= + for i in range(n): + for k in range(m): + for t in range(p): + g_val = G.get((i, k, t), 0) + for u in range(t, p): + lhs = get_x(x, i, k, t, u) + rhs = M[i][t] * g_val + record_violation(4, + f"Production without setup: item {i}, machine {k}, period {t}, " + f"demand period {u}: x={lhs:.4f}, bound={rhs}", + lhs, rhs, "leq") + + # ========================================================================= + # Constraint (5): One setup state per machine per period (equality) + # sum_i z_{ikt} = 1 forall (k, t) + # ========================================================================= + for k in range(m): + for t in range(p + 1): + lhs = sum(get_z(z, i, k, t) for i in range(n)) + rhs = 1 + record_violation(5, + f"Setup state count: machine {k}, period {t}: sum_z={lhs}, expected=1", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint (6): Flow conservation (equality) + # z_{ikt} + sum_j y_{jikt} = sum_j y_{ijkt} + z_{ik,t+1} forall (i, k, t) + # ========================================================================= + for i in range(n): + for k in range(m): + for t in range(p): + lhs = get_z(z, i, k, t) + sum(get_y(y, j, i, k, t) for j in range(n)) + rhs = sum(get_y(y, i, j, k, t) for j in range(n)) + get_z(z, i, k, t + 1) + record_violation(6, + f"Flow conservation: item {i}, machine {k}, period {t}: " + f"in={lhs}, out={rhs}", + lhs, rhs, "eq") + + # ========================================================================= + # Constraint (7): G link (>=) + # z_{ikt} + sum_j y_{jikt} >= G_{ikt} forall (i, k, t) + # ========================================================================= + for i in range(n): + for k in range(m): + for t in range(p): + lhs = get_z(z, i, k, t) + sum(get_y(y, j, i, k, t) for j in range(n)) + rhs = G.get((i, k, t), 0) + record_violation(7, + f"G link: item {i}, machine {k}, period {t}: " + f"z+sum_y={lhs}, G={rhs}", + lhs, rhs, "geq") + + # ========================================================================= + # Constraint (8): Max setups (<=) + # z_{ikt} + sum_j y_{jikt} <= q_{ikt} * G_{ikt} forall (i, k, t) + # ========================================================================= + for i in range(n): + for k in range(m): + for t in range(p): + lhs = get_z(z, i, k, t) + sum(get_y(y, j, i, k, t) for j in range(n)) + rhs = q_raw[i][k][t] * G.get((i, k, t), 0) + record_violation(8, + f"Max setups exceeded: item {i}, machine {k}, period {t}: " + f"count={lhs}, limit={rhs}", + lhs, rhs, "leq") + + # ========================================================================= + # Constraints (9) and (10) SKIPPED: definitional identities for the + # reformulation variables x_a, x_b (split of production into before-/ + # after-first-changeover portions). They are construction-satisfied and + # thus purely redundant under the Rule 4 relaxation. + # ========================================================================= + + # ========================================================================= + # Constraint (11)+(12) simplified as the original BUSINESS rule: + # Non-triangular setups require a minimum-lot rule — when a setup occurs + # for item i on machine k in period t (sum_j y_{jikt} >= 1) without + # carry-over into the next period (z_{ik,t+1} = 0), the total production + # of item i on machine k across periods t..p-1 (before being changed out) + # must be at least m_i. This replaces the x_a/x_b reformulation with a + # direct business check on the primary x, y, z variables. + # ========================================================================= + for i in range(n): + if min_lot[i] == 0: + continue # trivially satisfied + for k in range(m): + for t in range(p): + sum_y_in = sum(get_y(y, j, i, k, t) for j in range(n)) + if sum_y_in == 0: + continue # no setup in this period, no min-lot requirement + # Setup occurs here; check total production of item i on + # machine k from period t onward at least once exceeds m_i. + # Use the largest possible production window (whichever first + # "runs out" by being changed out via setup to another item). + total_production_ahead = total_prod[i, k, t] + # Also accumulate production in later periods while item i + # remains carried over (z = 1 across intermediate periods). + for lam in range(t + 1, p): + if get_z(z, i, k, lam) < 0.5: + break + total_production_ahead += total_prod.get((i, k, lam), 0) + required = min_lot[i] * sum_y_in + if required - total_production_ahead > tol: + record_violation(11, + f"Min lot violated: item {i}, machine {k}, period {t}: " + f"total production = {total_production_ahead:.4f} < " + f"required {required:.4f} (min_lot={min_lot[i]} x " + f"num_setups={sum_y_in})", + total_production_ahead, required, "geq") + + # ========================================================================= + # Constraint (13): Sub-tour flow origin (equality) + # sum_j F_{0jkt} = sum_i G_{ikt} forall (k, t) + # Constraint (14): Sub-tour flow balance (equality) + # F_{0ikt} + sum_j F_{jikt} = G_{ikt} + sum_j F_{ijkt} forall (i, k, t) + # Constraint (15): Flow capacity from origin (<=) + # F_{0ikt} <= n * z_{ikt} forall (i, k, t) + # Constraint (16): Flow capacity on arcs (<=) + # F_{ijkt} <= n * y_{ijkt} forall (i, j, k, t) + # + # These constraints ensure sub-tour elimination. We check by verifying + # all active items are reachable from the initial state via y-transitions. + # If reachable, valid F, F0 exist satisfying (13)-(16). + # ========================================================================= + subtour_violations = check_subtour_reachability(z, y, G, n, m, p) + for k_v, t_v, unreachable in subtour_violations: + for constraint_idx in [13, 14, 15, 16]: + # Report against all sub-tour constraints since the flow is infeasible + pass + # Report as constraint 13 (the primary sub-tour constraint) + num_active = sum(1 for i in range(n) if G.get((i, k_v, t_v), 0) == 1) + num_reachable = num_active - len(unreachable) + record_violation(13, + f"Sub-tour elimination: machine {k_v}, period {t_v}: " + f"unreachable items {unreachable} from initial state " + f"(reachable={num_reachable}, active={num_active})", + num_reachable, num_active, "eq") + + # Also check constraint (15): flow from origin only to initial state item + # If z[i,k,t]=0 for some active item that has no y-path from z-item, it's caught above. + # Additionally check: if there is no initial state (sum z = 0) but active items exist + for k in range(m): + for t in range(p): + num_active = sum(1 for i in range(n) if G.get((i, k, t), 0) == 1) + has_initial = sum(get_z(z, i, k, t) for i in range(n)) + if num_active > 0 and has_initial == 0: + record_violation(15, + f"No initial state for flow: machine {k}, period {t}: " + f"active items={num_active} but no z[i,k,t]=1", + 0, num_active, "geq") + + # Check constraint (16): F_{ijkt} <= n * y_{ijkt} + # If y[i,j,k,t] = 0 but transition is needed for reachability, caught by (13) check. + # No additional check needed beyond reachability. + + # ========================================================================= + # Constraint (17): F_{ijkt} >= 0 + # Satisfied by construction (F is derived as non-negative flow). + # No check needed. + # ========================================================================= + + # ========================================================================= + # Constraint (18): G_{ikt}, R_{kt} in {0, 1} + # Satisfied by construction (derived as binary). + # No check needed. + # ========================================================================= + + # ========================================================================= + # Constraint (19): z_{ikt} in {0, 1}, x_{iktu} >= 0 + # ========================================================================= + for key, val in z.items(): + if val not in (0, 1): + i, k, t = key + record_violation(19, + f"z not binary: z[{i},{k},{t}]={val}", + val, round(val), "eq") + + for key, val in x.items(): + if val < -tol: + i, k, t, u = key + record_violation(19, + f"Negative production: x[{i},{k},{t},{u}]={val:.6f}", + val, 0.0, "geq") + + # ========================================================================= + # Constraint (20): y_{ijkt} in {0, ..., q_{jkt}} + # ========================================================================= + for key, val in y.items(): + i, j, k, t = key + if val < 0 or val != int(val): + record_violation(20, + f"y not non-negative integer: y[{i},{j},{k},{t}]={val}", + val, 0, "geq") + elif val > q_raw[j][k][t]: + record_violation(20, + f"y exceeds max setups: y[{i},{j},{k},{t}]={val}, " + f"max q[{j},{k},{t}]={q_raw[j][k][t]}", + val, q_raw[j][k][t], "leq") + + # ========================================================================= + # Constraint (1): Objective-value consistency (full recompute). + # The reported objective_value must equal the recomputed sum of inventory + # holding costs and setup changeover costs: + # obj = Σ (u-t) * h_i * x_{iktu} + Σ c_{ijk} * y_{ijkt} + # Every variable that determines the objective (x and y) is present in + # the solution, so a full recompute is exact (no lower-bound looseness). + # Tolerance: max(1e-3, 1e-3 * |true|) — 0.1% relative with 1e-3 floor. + # ========================================================================= + reported_raw = solution.get("objective_value") + try: + reported = float(reported_raw) if reported_raw is not None else None + except (TypeError, ValueError): + reported = None + if reported is not None and (math.isnan(reported) or math.isinf(reported)): + # NaN / inf is itself a lie; treat as unbounded deviation. + reported_finite = False + else: + reported_finite = reported is not None + if reported is not None: + inv_cost = 0.0 + for (i, k, t, u), xv in x.items(): + if u >= t: + inv_cost += (u - t) * h[i] * float(xv) + setup_cost = 0.0 + for (i, j, k, t), yv in y.items(): + setup_cost += c_raw[i][j][k] * int(yv) + true_obj = float(inv_cost + setup_cost) + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if not reported_finite: + abs_diff = float("inf") + else: + abs_diff = abs(reported - true_obj) + if abs_diff > obj_tol: + violated_constraints.add(1) + msg = ( + f"Objective consistency violated: reported objective_value=" + f"{reported_raw} differs from recomputed inventory+setup cost=" + f"{true_obj:.6f} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g}); " + f"inv_cost={inv_cost:.6f}, setup_cost={setup_cost:.6f}" + ) + violations.append(msg) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": round(reported, 10) if reported_finite else reported_raw, + "rhs": round(true_obj, 10), + "raw_excess": round(abs_diff, 10) if reported_finite else abs_diff, + "normalizer": round(normalizer, 10), + "ratio": round(abs_diff / normalizer, 10) if reported_finite else abs_diff, + }) + + # Build result + sorted_violated = sorted(violated_constraints) + feasible = len(sorted_violated) == 0 + + # Deduplicate violation messages per constraint + seen_constraints_msgs = {} + deduped_violations = [] + for msg in violations: + if msg not in seen_constraints_msgs: + seen_constraints_msgs[msg] = True + deduped_violations.append(msg) + + result = { + "feasible": feasible, + "violated_constraints": sorted_violated, + "violations": deduped_violations, + "violation_magnitudes": violation_magnitudes if not feasible else [] + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for ILSSP-NT 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 feasibility result JSON") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {result['violated_constraints']}") + for v in result["violations"][:10]: + print(f" - {v}") + if len(result["violations"]) > 10: + print(f" ... and {len(result['violations']) - 10} more 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/carvalho2022/gurobi_code.py b/tasks/carvalho2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..9be520661020dd4f7e88d1f78de20222998256e7 --- /dev/null +++ b/tasks/carvalho2022/gurobi_code.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the ILSSP-NT (Integrated Lot Sizing and Scheduling Problem +with Non-Triangular setup) on parallel machines. + +Based on: Carvalho & Nascimento (2022) - "Hybrid matheuristics to solve the integrated +lot sizing and scheduling problem on parallel machines with sequence-dependent and +non-triangular setup" + +The MIP formulation (1)-(20) uses a facility location problem reformulation with +network flow for feasible setup sequences. +""" + +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(instance_path): + """Load instance data from JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def build_and_solve(data, time_limit): + """Build and solve the ILSSP-NT MIP model using Gurobi.""" + + # ========================================================================= + # EXTRACT DATA + # ========================================================================= + n = data["dimensions"]["n"] # number of items + m = data["dimensions"]["m"] # number of machines + p = data["dimensions"]["p"] # number of periods + + # d[i][t]: demand of item i in period t (0-indexed) + d = data["demands"] # n x p + + # h[i]: unitary inventory cost of item i + h = data["inventory_costs"] # length n + + # processing_time: f_{ikt} = processing time of item i on machine k in period t + # In the instance this is a scalar (=1 for all i,k,t) + proc_time_val = data["processing_time"] + + # setup_times[i][j][k]: setup time to change machine k from item i to item j + b_raw = data["setup_times"] # n x n x m + + # setup_costs[i][j][k]: setup cost to change machine k from item i to item j + c_raw = data["setup_costs"] # n x n x m + + # machine_capacities[k][t]: production capacity of machine k in period t + T_cap = data["machine_capacities"] # m x p + + # max_production[i][t]: M_{it} maximum production of item i in period t + # **NOT SPECIFIED IN PAPER**: Exact formula not given; typically M_{it} = sum_{u=t}^{p} d_{iu}. + # The instance provides this directly. + M = data["max_production"] # n x p + + # max_setups_per_item[i][k][t]: q_{ikt} + # **NOT SPECIFIED IN PAPER**: Exact computation not given. + # The instance provides this directly. + q_raw = data["max_setups_per_item"] # n x m x p + + # minimum_lot_sizes[i]: m_i + min_lot = data["minimum_lot_sizes"] # length n + + # shortcut_items: list of shortcut item indices (0-indexed) + shortcut_items = data.get("shortcut_items", []) + + # machine_eligibility[i][k]: 1 if item i can be produced on machine k + eligibility = data.get("machine_eligibility", [[1] * m for _ in range(n)]) + + # ========================================================================= + # CREATE MODEL + # ========================================================================= + model = gp.Model("ILSSP_NT") + model.setParam("TimeLimit", time_limit) + model.setParam("Threads", 1) # Paper uses 1 thread + + # ========================================================================= + # DECISION VARIABLES + # ========================================================================= + + # x[i,k,t,u]: amount of item i produced at machine k in period t for demand of period u + # continuous >= 0, only defined for u >= t + x = {} + for i in range(n): + for k in range(m): + for t in range(p): + for u in range(t, p): + x[i, k, t, u] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"x_{i}_{k}_{t}_{u}") + + # x_b[i,k,t]: production before the first setup in period t + x_b = {} + for i in range(n): + for k in range(m): + for t in range(p): + x_b[i, k, t] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"xb_{i}_{k}_{t}") + + # x_a[i,k,t]: production after the first setup in period t + x_a = {} + for i in range(n): + for k in range(m): + for t in range(p): + x_a[i, k, t] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"xa_{i}_{k}_{t}") + + # z[i,k,t]: binary, 1 if machine k is ready to produce item i at beginning of period t + # We define t = 0..p (extra period p for boundary condition in constraint 6) + # **NOT SPECIFIED IN PAPER**: Boundary for z_{ik,p+1}. We add z for t=p as a free + # binary variable constrained by sum_i z_{ikt}=1 and flow conservation. + z = {} + for i in range(n): + for k in range(m): + for t in range(p + 1): + z[i, k, t] = model.addVar( + vtype=GRB.BINARY, name=f"z_{i}_{k}_{t}") + + # y[i,j,k,t]: number of times production changes from item i to item j + # on machine k in period t. Integer in {0, ..., q_{jkt}} + y = {} + for i in range(n): + for j in range(n): + for k in range(m): + for t in range(p): + ub_val = q_raw[j][k][t] + y[i, j, k, t] = model.addVar( + lb=0, ub=ub_val, vtype=GRB.INTEGER, + name=f"y_{i}_{j}_{k}_{t}") + + # R[k,t]: binary, 1 if at least one setup is performed at machine k in period t + R = {} + for k in range(m): + for t in range(p): + R[k, t] = model.addVar(vtype=GRB.BINARY, name=f"R_{k}_{t}") + + # G[i,k,t]: binary, 1 if machine k is ready at least once to produce item i in period t + G = {} + for i in range(n): + for k in range(m): + for t in range(p): + G[i, k, t] = model.addVar(vtype=GRB.BINARY, name=f"G_{i}_{k}_{t}") + + # F0[j,k,t]: commodity flow from dummy origin (node 0) to item j + F0 = {} + for j in range(n): + for k in range(m): + for t in range(p): + F0[j, k, t] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"F0_{j}_{k}_{t}") + + # F[i,j,k,t]: commodity flow from item i to item j + F = {} + for i in range(n): + for j in range(n): + for k in range(m): + for t in range(p): + F[i, j, k, t] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"F_{i}_{j}_{k}_{t}") + + model.update() + + # ========================================================================= + # OBJECTIVE FUNCTION (1) + # min sum_{i,k,t,u>=t} (u-t)*h_i*x_{iktu} + sum_{i,j,k,t} c_{ijk}*y_{ijkt} + # ========================================================================= + obj = gp.LinExpr() + for i in range(n): + for k in range(m): + for t in range(p): + for u in range(t, p): + obj += (u - t) * h[i] * x[i, k, t, u] + + for i in range(n): + for j in range(n): + for k in range(m): + for t in range(p): + obj += c_raw[i][j][k] * y[i, j, k, t] + + model.setObjective(obj, GRB.MINIMIZE) + + # ========================================================================= + # CONSTRAINTS + # ========================================================================= + + # --- Constraint (2): Demand satisfaction --- + # sum_k sum_{t=1}^{u} x_{iktu} = d_{iu} forall (i, u) + for i in range(n): + for u in range(p): + model.addConstr( + gp.quicksum(x[i, k, t, u] for k in range(m) for t in range(u + 1)) + == d[i][u], + name=f"demand_{i}_{u}") + + # --- Constraint (3): Capacity --- + # sum_i (sum_{u>=t} f_{ikt}*x_{iktu} + sum_j b_{jik}*y_{jikt}) <= T_{kt} + for k in range(m): + for t in range(p): + model.addConstr( + gp.quicksum( + proc_time_val * x[i, k, t, u] + for i in range(n) for u in range(t, p) + ) + gp.quicksum( + b_raw[j][i][k] * y[j, i, k, t] + for i in range(n) for j in range(n) + ) <= T_cap[k][t], + name=f"capacity_{k}_{t}") + + # --- Constraint (4): Production only if setup ready --- + # x_{iktu} <= M_{it} * G_{ikt} forall (i, k, t, u) + for i in range(n): + for k in range(m): + for t in range(p): + for u in range(t, p): + model.addConstr( + x[i, k, t, u] <= M[i][t] * G[i, k, t], + name=f"prod_setup_{i}_{k}_{t}_{u}") + + # --- Constraint (5): One setup state per machine per period --- + # sum_i z_{ikt} = 1 forall (k, t) + for k in range(m): + for t in range(p + 1): # includes boundary period p + model.addConstr( + gp.quicksum(z[i, k, t] for i in range(n)) == 1, + name=f"one_state_{k}_{t}") + + # --- Constraint (6): Flow conservation of setup states --- + # z_{ikt} + sum_j y_{jikt} = sum_j y_{ijkt} + z_{ik,t+1} forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + z[i, k, t] + gp.quicksum(y[j, i, k, t] for j in range(n)) + == gp.quicksum(y[i, j, k, t] for j in range(n)) + z[i, k, t + 1], + name=f"flow_cons_{i}_{k}_{t}") + + # --- Constraint (7): G link --- + # z_{ikt} + sum_j y_{jikt} >= G_{ikt} forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + z[i, k, t] + gp.quicksum(y[j, i, k, t] for j in range(n)) + >= G[i, k, t], + name=f"G_link_{i}_{k}_{t}") + + # --- Constraint (8): Max setups limit --- + # z_{ikt} + sum_j y_{jikt} <= q_{ikt} * G_{ikt} forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + z[i, k, t] + gp.quicksum(y[j, i, k, t] for j in range(n)) + <= q_raw[i][k][t] * G[i, k, t], + name=f"max_setup_{i}_{k}_{t}") + + # --- Constraint (9): Split production --- + # sum_{u>=t} x_{iktu} = x^a_{ikt} + x^b_{ikt} forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + gp.quicksum(x[i, k, t, u] for u in range(t, p)) + == x_a[i, k, t] + x_b[i, k, t], + name=f"split_{i}_{k}_{t}") + + # --- Constraint (10): Before-setup production requires carry-over --- + # x^b_{ikt} <= M_{it} * z_{ikt} forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + x_b[i, k, t] <= M[i][t] * z[i, k, t], + name=f"before_setup_{i}_{k}_{t}") + + # --- Constraint (11): Minimum lot size (not carried over) --- + # x^a_{ikt} >= m_i * (sum_j y_{jikt} - z_{ik,t+1}) forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + x_a[i, k, t] >= min_lot[i] * ( + gp.quicksum(y[j, i, k, t] for j in range(n)) + - z[i, k, t + 1]), + name=f"min_lot_{i}_{k}_{t}") + + # --- Constraint (12): Minimum lot size with carry-over --- + # x^a_{ikt} + sum_{lambda=t+1}^{u} x^b_{ik,lambda} + # >= m_i * sum_j y_{jikt} - M_{it} * (sum_{lambda=t+1}^{u-1} R_{k,lambda} + 1 - R_{ku}) + # forall (i, k, t, u), u != t + for i in range(n): + for k in range(m): + for t in range(p): + for u in range(t + 1, p): + lhs = x_a[i, k, t] + gp.quicksum( + x_b[i, k, lam] for lam in range(t + 1, u + 1)) + rhs_setup = gp.quicksum(y[j, i, k, t] for j in range(n)) + rhs_big_m = ( + gp.quicksum(R[k, lam] for lam in range(t + 1, u)) + + 1 - R[k, u]) + model.addConstr( + lhs >= min_lot[i] * rhs_setup - M[i][t] * rhs_big_m, + name=f"min_lot_co_{i}_{k}_{t}_{u}") + + # --- R linking constraints --- + # R_{kt} is 1 iff at least one setup is performed at machine k in period t + # We link R to y variables: + # sum_{i,j} y_{ijkt} >= R_{kt} (if any setup, R=1) + # sum_{i,j} y_{ijkt} <= BigM * R_{kt} (if no setup, R=0) + for k in range(m): + for t in range(p): + total_y = gp.quicksum( + y[i, j, k, t] for i in range(n) for j in range(n)) + model.addConstr(total_y >= R[k, t], name=f"R_lb_{k}_{t}") + big_M_val = sum(q_raw[j][k][t] for j in range(n)) * n + if big_M_val > 0: + model.addConstr( + total_y <= big_M_val * R[k, t], name=f"R_ub_{k}_{t}") + + # --- Constraint (13): Sub-tour flow origin --- + # sum_j F_{0jkt} = sum_i G_{ikt} forall (k, t) + for k in range(m): + for t in range(p): + model.addConstr( + gp.quicksum(F0[j, k, t] for j in range(n)) + == gp.quicksum(G[i, k, t] for i in range(n)), + name=f"flow_origin_{k}_{t}") + + # --- Constraint (14): Sub-tour flow balance --- + # F_{0ikt} + sum_j F_{jikt} = G_{ikt} + sum_j F_{ijkt} forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + F0[i, k, t] + gp.quicksum(F[j, i, k, t] for j in range(n)) + == G[i, k, t] + gp.quicksum(F[i, j, k, t] for j in range(n)), + name=f"flow_bal_{i}_{k}_{t}") + + # --- Constraint (15): Flow capacity from origin --- + # F_{0ikt} <= n * z_{ikt} forall (i, k, t) + for i in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + F0[i, k, t] <= n * z[i, k, t], + name=f"flow_cap_origin_{i}_{k}_{t}") + + # --- Constraint (16): Flow capacity on arcs --- + # F_{ijkt} <= n * y_{ijkt} forall (i, j, k, t) + for i in range(n): + for j in range(n): + for k in range(m): + for t in range(p): + model.addConstr( + F[i, j, k, t] <= n * y[i, j, k, t], + name=f"flow_cap_{i}_{j}_{k}_{t}") + + # --- Machine eligibility constraints --- + # **INFERRED ASSUMPTION**: If machine_eligibility[i][k] == 0, item i cannot be + # produced on machine k. We enforce G[i,k,t]=0 for ineligible pairs. + # The q_{ikt}=0 in data already partially handles this, but we add explicit constraints. + for i in range(n): + for k in range(m): + if eligibility[i][k] == 0: + for t in range(p): + model.addConstr(G[i, k, t] == 0, name=f"elig_{i}_{k}_{t}") + + # ========================================================================= + # OPTIMIZE + # ========================================================================= + model.optimize() + + # ========================================================================= + # EXTRACT SOLUTION + # ========================================================================= + result = {} + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + result["mip_gap"] = model.MIPGap + + # Extract production quantities + production = {} + for key, var in x.items(): + val = var.X + if val > 1e-6: + i, k, t, u = key + production[f"x_{i}_{k}_{t}_{u}"] = round(val, 4) + result["production"] = production + + # Extract setup decisions + setups = {} + for key, var in y.items(): + val = var.X + if val > 0.5: + i, j, k, t = key + setups[f"y_{i}_{j}_{k}_{t}"] = round(val) + result["setups"] = setups + + # Extract setup carry-over + carryover = {} + for key, var in z.items(): + val = var.X + if val > 0.5: + i, k, t = key + carryover[f"z_{i}_{k}_{t}"] = 1 + result["carryover"] = carryover + + else: + result["objective_value"] = None + result["status"] = ( + "infeasible" if model.Status == GRB.INFEASIBLE else "no_solution") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the ILSSP-NT using Gurobi (MIP formulation)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + result = build_and_solve(data, args.time_limit) + + with open(args.solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/carvalho2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/carvalho2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho2022/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/carvalho2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/carvalho2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho2022/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/carvalho2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/carvalho2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho2022/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/carvalho2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/carvalho2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho2022/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/carvalho2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/carvalho2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho2022/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/carvalho2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/carvalho2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/carvalho2022/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/carvalho2022/gurobi_solution/large_solution_1.json b/tasks/carvalho2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0b888fac213e9348b8c9d959d9336ab17342e2c4 --- /dev/null +++ b/tasks/carvalho2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08415d59c1832fb99adb8e290f810f59205e86a76f310c524da9f2631165345e +size 8462 diff --git a/tasks/carvalho2022/gurobi_solution/large_solution_2.json b/tasks/carvalho2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b45224f4bed63195033caeb4c24e4419184556d1 --- /dev/null +++ b/tasks/carvalho2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ec0e37f0351682a3c6859d47657d4a36a5dd5dc5b6dd906bbb547fbda051089 +size 10169 diff --git a/tasks/carvalho2022/gurobi_solution/large_solution_3.json b/tasks/carvalho2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..10da27207802a6780af5c41851b1bc252ce3809e --- /dev/null +++ b/tasks/carvalho2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2cc8508b7e3c2406f64c775ae5bab6766e0b1a6e5fd11f5d05be8d02d7dc4d8 +size 8677 diff --git a/tasks/carvalho2022/gurobi_solution/large_solution_4.json b/tasks/carvalho2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e227aac071139426b840118e2ecb61fcce84c879 --- /dev/null +++ b/tasks/carvalho2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49d8243e7e690a18972ba3ff6b233aa13fed8afa460275fd1b5bad0104e47cf8 +size 9150 diff --git a/tasks/carvalho2022/gurobi_solution/large_solution_5.json b/tasks/carvalho2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fca6c2746e7104b3e8db8b5c24fbf90b41417c3f --- /dev/null +++ b/tasks/carvalho2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3f17494402431707996b927a93b543621e97740c2a8ed720b0d59e084639d2d +size 8658 diff --git a/tasks/carvalho2022/gurobi_solution/tiny_solution.json b/tasks/carvalho2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..19e98189fa985a78cb6b9f9922989d1e6c334ce4 --- /dev/null +++ b/tasks/carvalho2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cdf6d76f638238a4177ee3f0960695fb6acc0e53df4c56757876e8a09ba1dc57 +size 2493 diff --git a/tasks/carvalho2022/gurobi_solution_log/tiny_log.jsonl b/tasks/carvalho2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bdbcf56bd2c87c7372946f042e44f92283f9536f --- /dev/null +++ b/tasks/carvalho2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec892d97f29366210afa964fa5bc40d340292a2ced4262916379f70360ac291d +size 1301 diff --git a/tasks/carvalho2022/instance/large_instance_1.json b/tasks/carvalho2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ee6992c77884ce15e21f58d68022d1e2545e9d62 --- /dev/null +++ b/tasks/carvalho2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ad91149afbd22161d8da3cf5f02c5e3ba5623d4d402224b877629e7482aa8b0 +size 57238 diff --git a/tasks/carvalho2022/instance/large_instance_2.json b/tasks/carvalho2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..82a3b10c694bb2e752e6ac8992399a002d8377f5 --- /dev/null +++ b/tasks/carvalho2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:648fa21be7bb7939d6f1890df4e0c40ea271cd2205a62adce5754f8e4a0fbce1 +size 57374 diff --git a/tasks/carvalho2022/instance/large_instance_3.json b/tasks/carvalho2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..a3ba40844878f620235944c47590e7fd92b79310 --- /dev/null +++ b/tasks/carvalho2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4e095d0a825fa9c33f12a356ce3ca0e65f1b9c1f580121aac500ce2b7cba0ee +size 57487 diff --git a/tasks/carvalho2022/instance/large_instance_4.json b/tasks/carvalho2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4673bdac1e48e197669eb90620948ec2391ad28d --- /dev/null +++ b/tasks/carvalho2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31a7eb15dce1a5eaf16255417ac7efc84d3770f6649a3db7a48e592c52647b61 +size 57492 diff --git a/tasks/carvalho2022/instance/large_instance_5.json b/tasks/carvalho2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..99c539866d14d8cccdc889bbf54b66a60bbae0ae --- /dev/null +++ b/tasks/carvalho2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72693f3490d57ba85063aa19271bf4ffc5808dfa38a077be1d0807bef07a01a9 +size 57371 diff --git a/tasks/carvalho2022/instance/tiny_instance.json b/tasks/carvalho2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..5a851d154297b6c24bd34333da12e378a006e3c3 --- /dev/null +++ b/tasks/carvalho2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a203685f4ba58635fa7bb95b3c96864619d46a11b91a5e16244225fbe9f14fc4 +size 12366 diff --git a/tasks/carvalho2022/instance_schema.json b/tasks/carvalho2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c8c9812a2ac5e9874f2c7e9e87882ee5736ee0d4 --- /dev/null +++ b/tasks/carvalho2022/instance_schema.json @@ -0,0 +1,25 @@ +{ + "dimensions": { + "n": " Number of item types to be produced.", + "m": " Number of parallel machines available for production.", + "p": " Number of planning periods in the horizon." + }, + "parameters": { + "Cut": " Capacity utilization factor scaling total demand to determine base machine capacity.", + "CutVar": " Capacity variation factor controlling the spread of capacity across machines.", + "Theta": " Multiplier applied to setup times to compute the corresponding setup costs.", + "MProb": " Probability that each additional machine is eligible to produce a given item.", + "MBal": " Maximum allowed imbalance in the number of items assignable to any two machines, as a fraction of n." + }, + "demands": " Quantity of each item that must be delivered in each period.", + "inventory_costs": " Per-unit cost of holding one unit of each item in inventory for one period.", + "processing_time": " Time required to produce one unit of any item on any machine.", + "setup_times": " Time needed to change each machine from producing one item to another.", + "setup_costs": " Cost incurred when changing each machine from producing one item to another.", + "machine_capacities": " Available production time on each machine in each period.", + "max_production": " Maximum quantity of each item that can be produced from each period onward.", + "max_setups_per_item": " Maximum number of times each machine can be set up to produce a given item in a given period.", + "minimum_lot_sizes": " Minimum production batch size required for each item when its setup is not carried over.", + "shortcut_items": " Indices of items with cleansing properties that reduce transition costs and times when used as intermediaries.", + "machine_eligibility": " Whether each machine is allowed to produce each item (1 = eligible, 0 = not eligible)." +} diff --git a/tasks/carvalho2022/mathematical_formulation.md b/tasks/carvalho2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..e3e6711d81a372acf3f6ed8a299f6fef37d75445 --- /dev/null +++ b/tasks/carvalho2022/mathematical_formulation.md @@ -0,0 +1,95 @@ +# Original Formulation: Integrated Lot Sizing and Scheduling Problem with Non-Triangular Setup on Parallel Machines (ILSSP-NT) + +*Source: Hybrid matheuristics to solve the integrated lot sizing and scheduling problem on parallel machines with sequence-dependent and non-triangular setup, Desiree M. Carvalho, Mariá C. V. Nascimento, 2022.* + +## Sets and Indices + +$$\begin{align*} +&n && \text{number of items} \\ +&m && \text{number of machines} \\ +&p && \text{number of periods (macro-periods)} \\ +&i, j \in \{1,\ldots,n\} && \text{indexes representing items} \\ +&k \in \{1,\ldots,m\} && \text{index representing the machines} \\ +&t, u \in \{1,\ldots,p\} && \text{indexes representing the macro-periods} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +&c_{ijk} && \text{setup cost to change the state of machine } k \text{ from item } i \text{ to item } j \\ +&h_i && \text{unitary inventory cost of item } i \\ +&d_{it} && \text{demand of item } i \text{ in period } t \\ +&b_{ijk} && \text{setup time to change the state of machine } k \text{ from item } i \text{ to item } j \\ +&M_{it} && \text{maximum amount of item } i \text{ that can be produced in period } t \\ +&f_{ikt} && \text{processing time of item } i \text{ at machine } k \text{ in period } t \\ +&m_i && \text{minimum production lot size of item } i \\ +&T_{kt} && \text{production capacity of machine } k \text{ in period } t \\ +&q_{ikt} && \text{maximum number of times machine } k \text{ can be set up to produce item } i \text{ in period } t +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +&x_{iktu} && \text{amount of item } i \text{ produced at machine } k \text{ in period } t \text{ to meet the demand of period } u \;(\geq 0) \\ +&x^b_{ikt} && \text{amount of item } i \text{ produced at machine } k \text{ in the beginning of period } t, \\ +& && \text{before the first machine setup is performed in period } t \;(\geq 0) \\ +&x^a_{ikt} && \text{amount of item } i \text{ produced at machine } k \text{ during period } t, \\ +& && \text{after the first machine setup is performed} \;(\geq 0) \\ +&z_{ikt} && \text{binary; } 1 \text{ if machine } k \text{ is ready to produce item } i \text{ at the beginning of period } t \text{ (setup carry-over)} \\ +&y_{ijkt} && \text{number of times a production process changes from item } i \text{ to item } j \text{ at machine } k \text{ in period } t \\ +&R_{kt} && \text{binary; } 1 \text{ if at least one setup is performed at machine } k \text{ in period } t \;(\textstyle\sum_{i=1}^{n}\sum_{j=1}^{n} y_{ijkt}\geq 1) \\ +&G_{ikt} && \text{binary; } 1 \text{ if machine } k \text{ is ready at least once to produce item } i \text{ during period } t \\ +&F_{ijkt} && \text{commodity flow from node (item) } i \text{ to node (item) } j \text{ at machine } k \text{ in period } t \;(\geq 0) +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad \sum_{i=1}^{n}\sum_{k=1}^{m}\sum_{t=1}^{p}\sum_{u=t}^{p}(u-t)\,h_i\,x_{iktu} + \;+\; \sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{k=1}^{m}\sum_{t=1}^{p} c_{ijk}\,y_{ijkt} + \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +& \sum_{k}\sum_{t=1}^{u} x_{iktu} = d_{iu} + && \forall (i,u) \tag{2} \\[2pt] +& \sum_{i}\left( \sum_{u=t}^{p} f_{ikt}\,x_{iktu} + \sum_{j} b_{jik}\,y_{jikt} \right) \leq T_{kt} + && \forall (k,t) \tag{3} \\[2pt] +& x_{iktu} \leq M_{it}\,G_{ikt} + && \forall (i,k,t,u) \tag{4} \\[2pt] +& \sum_{i} z_{ikt} = 1 + && \forall (k,t) \tag{5} \\[2pt] +& z_{ikt} + \sum_{j} y_{jikt} = \sum_{j} y_{ijkt} + z_{ik,t+1} + && \forall (i,k,t) \tag{6} \\[2pt] +& z_{ikt} + \sum_{j} y_{jikt} \geq G_{ikt} + && \forall (i,k,t) \tag{7} \\[2pt] +& z_{ikt} + \sum_{j} y_{jikt} \leq q_{ikt}\,G_{ikt} + && \forall (i,k,t) \tag{8} \\[2pt] +& \sum_{u=t}^{p} x_{iktu} = x^a_{ikt} + x^b_{ikt} + && \forall (i,k,t) \tag{9} \\[2pt] +& x^b_{ikt} \leq M_{it}\,z_{ikt} + && \forall (i,k,t) \tag{10} \\[2pt] +& x^a_{ikt} \geq m_i\left( \sum_{j} y_{jikt} - z_{ik,t+1} \right) + && \forall (i,j,k,t) \tag{11} \\[2pt] +& x^a_{ikt} + \sum_{\lambda=t+1}^{u} x^b_{ik\lambda} \geq m_i \sum_{j} y_{jikt} + - M_{it}\left( \sum_{\lambda=t+1}^{u-1} R_{k\lambda} + 1 - R_{ku} \right) + && \forall (i,k,t,u),\, u \neq t \tag{12} \\[2pt] +& \sum_{j} F_{0jkt} = \sum_{i} G_{ikt} + && \forall (k,t) \tag{13} \\[2pt] +& F_{0ikt} + \sum_{j} F_{jikt} = G_{ikt} + \sum_{j} F_{ijkt} + && \forall (i,k,t) \tag{14} \\[2pt] +& F_{0ikt} \leq n\,z_{ikt} + && \forall (i,k,t) \tag{15} \\[2pt] +& F_{ijkt} \leq n\,y_{ijkt} + && \forall (i,j,k,t) \tag{16} \\[2pt] +& F_{ijkt} \geq 0 + && \forall (i,j,k,t) \tag{17} \\[2pt] +& G_{ikt},\, R_{kt} \in \{0,1\} + && \forall (i,k,t) \tag{18} \\[2pt] +& z_{ikt} \in \{0,1\},\; x_{iktu} \geq 0 + && \forall (i,k,t,u) \tag{19} \\[2pt] +& y_{ijkt} \in \{0,\ldots,q_{jkt}\} + && \forall (i,j,k,t) \tag{20} +\end{align}$$ diff --git a/tasks/carvalho2022/problem_description.txt b/tasks/carvalho2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c30429ef090f695f03010df05746ada1afeb1338 --- /dev/null +++ b/tasks/carvalho2022/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A manufacturing facility produces multiple items on a set of non-identical parallel machines over a finite planning horizon divided into periods. The input data specifies the number of items, machines, and periods; a demand for each item in each period; a per-unit inventory holding cost for each item; a processing time for each item on each machine in each period; a production capacity (in time units) for each machine in each period; a maximum producible amount for each item in each period; a minimum production lot size for each item; a sequence-dependent setup cost and a sequence-dependent setup time for switching each machine from any item to any other item (these costs and times may differ across machines); and a maximum number of times each machine can be set up to produce a given item in a given period, where a value of zero means the item cannot be produced on that machine in that period. Some items have cleansing properties that reduce the cost and time of transitioning between certain other items when used as intermediaries, so the triangular inequality on setup costs and times does not necessarily hold. + +The planner must decide, for each machine and each period, how much of each item to produce, the sequence in which items are produced (which determines the setup changeovers performed during the period), and which item the machine is configured for at the start of the period (i.e., whether the setup state is carried over from the previous period). The planner must also decide how the production of each item in each period is allocated to satisfy current demand or to be held in inventory for later periods. + +Demand for every item in every period must be met in full, either from production in that period or from inventory built up in earlier periods. On each machine in each period, the total time spent producing items plus the time spent on setup changeovers cannot exceed the machine's available capacity. A machine can only produce an item in a period if it is actually set up for that item (either through carry-over from the previous period or through a changeover into that item during the period). Each machine is configured for exactly one item at the start of each period. The number of times a given item can be set up on a given machine in a given period is limited by the specified maximum; an item that cannot be produced on a given machine in a given period simply has this maximum equal to zero. Because setup times and costs do not obey the triangular inequality, whenever an item is produced on a machine in a period as the result of a setup changeover (rather than as a continuation of the carried-over setup), the amount produced of that item must be at least the specified minimum lot size; this prevents fictitious zero-quantity setups used only as cost-reducing intermediaries. + +The objective is to minimize total cost, which is the sum of inventory holding costs (the per-unit holding cost of each item multiplied by the number of periods units remain in inventory before serving demand, summed over all items) and setup costs (the cost of each changeover multiplied by the number of times it occurs, summed over all item pairs, machines, and periods). diff --git a/tasks/carvalho2022/solution_logger.py b/tasks/carvalho2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/carvalho2022/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/carvalho2022/solution_schema.json b/tasks/carvalho2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..94e8713edbf353cdab43c79e0072a278f10d81b2 --- /dev/null +++ b/tasks/carvalho2022/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Total cost comprising inventory holding costs and setup changeover costs.", + "production": " Quantity of each item produced on each machine in each production period to satisfy each demand period.", + "setups": " Number of times production changes from one item to another on each machine in each period.", + "carryover": " Whether each machine is configured to produce a given item at the beginning of each period (1 = yes)." +} diff --git a/tasks/castro2021/feasibility_check.py b/tasks/castro2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5e590118bb2c71625faaeab708ab0628beb616ac --- /dev/null +++ b/tasks/castro2021/feasibility_check.py @@ -0,0 +1,429 @@ +""" +Feasibility checker for the Minimum Convex Cost Flow in Bipartite Networks (MCCFBN) +problem from Castro & Nasini (2021). + +Hard constraints from the mathematical formulation (Eqs 2-4, counted as Constraints 1-3): + + Constraint 1 (Eq 2): sum_{i in I} x_{ij} = d_j, for all j in J (demand satisfaction) + Constraint 2 (Eq 3): sum_{j in J} x_{ij} <= s_i, for all i in I (supply capacity) + Constraint 3 (Eq 4): 0 <= x_{ij} <= u_{ij}, for all i in I, j in J (arc bounds) + +Objective-consistency check (Eq 1, counted as Constraint 4): + + Constraint 4 (Eq 1): reported objective_value must equal the objective + recomputed from the flow variables, + f(x) = sum_{i,j} ( c_{ij}*x_{ij} + q_{ij}*x_{ij}^2 ). + This is a Tier C defense against candidates that + return a fabricated objective_value while the flows + themselves satisfy Constraints 1-3. + +NOTE: this file is the obj-recompute variant of `feasibility_check.py`. +Constraints 1-3 are byte-for-byte identical to the original; the only +addition is Constraint 4. The original file is kept untouched. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('flows', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["n"] + m = instance["m"] + supplies = instance["supplies"] + demands = instance["demands"] + arc_capacity = instance["arc_capacity"] + # Objective coefficients (Eq 1). gurobi_code.py builds the objective as + # sum_{i,j} ( linear_costs[i][j]*x_ij + quadratic_costs[i][j]*x_ij^2 ) + # for every cost_type; the quadratic term simply vanishes when q_ij == 0. + linear_costs = instance.get("linear_costs") + quadratic_costs = instance.get("quadratic_costs") + + # For summation constraints, accumulated floating-point error from a + # barrier (interior-point) solver grows with the number of terms. The + # Gurobi model for this paper uses BarConvTol=1e-4, Crossover=0, so + # per-variable imprecision is ~1e-4 (NOT 1e-6 as previously assumed — + # measured violations at l31 reached ratio 5.5e-3 / raw_excess 1.3e-2, + # well above the prior 1e-4 rel_tol). When summing k terms the worst- + # case accumulated error is O(k * 1e-4). We therefore scale the absolute + # tolerance by the number of summands. A violation is only reported when + # it also exceeds a relative threshold (ratio > 1e-2) to avoid flagging + # solutions that are essentially feasible. — 2026-05-19 retuned: was + # rel_tol=1e-4 / per-var=1e-6, both too tight for BarConvTol=1e-4. + tol_demand = max(tol, n * 1e-4) # Constraint 1 sums n terms + tol_supply = max(tol, m * 1e-4) # Constraint 2 sums m terms + rel_tol = 1e-2 # relative tolerance: violation / |rhs| must exceed this + + flows_dict = solution.get("flows", {}) + if flows_dict is None: + flows_dict = {} + + # Build full flow matrix x[i][j], default 0 + x = [[0.0] * m for _ in range(n)] + # Constraint 4 piggybacks on this parse pass: accumulate the true + # objective f(x) directly from the flow variables. Arcs absent from + # `flows` carry zero flow and contribute zero cost, so iterating the + # dict is exact. + obj_recomputable = linear_costs is not None + true_obj = 0.0 + for key, val in flows_dict.items(): + # keys are "x_i_j" + parts = key.split("_") + i = int(parts[1]) + j = int(parts[2]) + v = float(val) + x[i][j] = v + if obj_recomputable: + true_obj += float(linear_costs[i][j]) * v + if quadratic_costs is not None: + true_obj += float(quadratic_costs[i][j]) * v * v + + violations = [] + violation_magnitudes = [] + violated_set = set() + + # ------------------------------------------------------------------ + # Constraint 1 (Eq 2): sum_{i in I} x_{ij} = d_j, for all j in J + # Equality constraint: violation_amount = |LHS - RHS| + # ------------------------------------------------------------------ + for j in range(m): + lhs = sum(x[i][j] for i in range(n)) + rhs = float(demands[j]) + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + if violation_amount > tol_demand and ratio > rel_tol: + violated_set.add(1) + violations.append( + f"Constraint 1 (demand satisfaction): demand node j={j} has " + f"total inflow {lhs:.6f} but demand is {rhs:.6f} " + f"(difference {violation_amount:.6e})" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 2 (Eq 3): sum_{j in J} x_{ij} <= s_i, for all i in I + # <= constraint: violation_amount = max(LHS - RHS, 0) + # ------------------------------------------------------------------ + for i in range(n): + lhs = sum(x[i][j] for j in range(m)) + rhs = float(supplies[i]) + violation_amount = lhs - rhs + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + if violation_amount > tol_supply and ratio > rel_tol: + violated_set.add(2) + violations.append( + f"Constraint 2 (supply capacity): supply node i={i} has " + f"total outflow {lhs:.6f} but supply capacity is {rhs:.6f} " + f"(excess {violation_amount:.6e})" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 3 (Eq 4): 0 <= x_{ij} <= u_{ij}, for all i in I, j in J + # Two-sided bound constraint, checked as two separate inequalities: + # (a) x_{ij} >= 0 (>= constraint: violation = max(RHS - LHS, 0) = max(-x_{ij}, 0)) + # (b) x_{ij} <= u_{ij} (<= constraint: violation = max(LHS - RHS, 0) = max(x_{ij} - u_{ij}, 0)) + # ------------------------------------------------------------------ + # Arc capacity is per-arc u_{ij}: build n x m matrix (expand scalar if given). + if isinstance(arc_capacity, list): + u = [[float(arc_capacity[i][j]) for j in range(m)] for i in range(n)] + else: + u = [[float(arc_capacity) for _ in range(m)] for _ in range(n)] + for i in range(n): + for j in range(m): + val = x[i][j] + u_ij = u[i][j] + # Lower bound: x_{ij} >= 0 + if val < -tol: + violation_amount = -val # how much RHS(0) exceeds LHS(x_{ij}) + violated_set.add(3) + normalizer = eps # RHS is 0, so max(|0|, eps) = eps + ratio = violation_amount / normalizer + violations.append( + f"Constraint 3 (lower bound): x_{i}_{j} = {val:.6e} < 0 " + f"(violation {violation_amount:.6e})" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": val, + "rhs": 0.0, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # Upper bound: x_{ij} <= u_{ij} + violation_amount = val - u_ij + if violation_amount > tol: + violated_set.add(3) + normalizer = max(abs(u_ij), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 3 (upper bound): x_{i}_{j} = {val:.6e} > u_{i}{j} = {u_ij:.6f} " + f"(excess {violation_amount:.6e})" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": val, + "rhs": u_ij, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint 4 (Eq 1): objective consistency. + # The eval pipeline trusts the solver's self-reported objective_value. + # Recompute the true objective f(x) = sum_{i,j}( c_ij*x_ij + q_ij*x_ij^2 ) + # from the flow variables (accumulated above) and reject the solution + # when the reported value disagrees beyond tolerance. + # Equality check: violation_amount = |reported - recomputed|. + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value") + if obj_recomputable and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + violation_amount = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. The + # objective sums up to n*m terms produced by a barrier solver + # (BarConvTol=1e-4, Crossover=0); a relative band absorbs that + # accumulated imprecision plus the omission of near-zero flows + # (the solver writes only x_ij > 1e-8 into `flows`), while still + # catching fabricated objective values, which are off by 100%+. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + normalizer = max(abs(true_obj), eps) + ratio = violation_amount / normalizer + if violation_amount > obj_tol: + violated_set.add(4) + violations.append( + f"Constraint 4 (objective consistency): reported " + f"objective_value {reported:.6f} differs from objective " + f"recomputed from flows {true_obj:.6f} " + f"(difference {violation_amount:.6e})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": reported, + "rhs": true_obj, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + violated_constraints = sorted(violated_set) + feasible = len(violated_constraints) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MCCFBN (Castro & Nasini 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() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/castro2021/gurobi_code.py b/tasks/castro2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d48c5f55b44270c881d9725e1d41adc67825763c --- /dev/null +++ b/tasks/castro2021/gurobi_code.py @@ -0,0 +1,184 @@ +""" +Gurobi implementation of the Minimum Convex Cost Flow in Bipartite Networks (MCCFBN) +problem from Castro & Nasini (2021). + +Model (Equations 1-4 from the paper): + min sum_{i in I} sum_{j in J} f_{ij}(x_{ij}) + s.t. sum_{i in I} x_{ij} = d_j, for all j in J (demand satisfaction) + sum_{j in J} x_{ij} <= s_i, for all i in I (supply capacity) + 0 <= x_{ij} <= u_{ij}, for all i in I, j in J (arc bounds) + +Cost functions: + - Linear: f_{ij}(x) = c_{ij} * x + - Quadratic: f_{ij}(x) = c_{ij} * x + q_{ij} * x^2 +""" + +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): + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def build_and_solve(data, time_limit): + n = data["n"] # number of supply nodes + m = data["m"] # number of demand nodes + + supplies = data["supplies"] + demands = data["demands"] + linear_costs = data["linear_costs"] # n x m matrix + quadratic_costs = data["quadratic_costs"] # n x m matrix + arc_capacity = data["arc_capacity"] # scalar upper bound for all arcs + cost_type = data.get("cost_type", "linear_integer") + + # Determine if we have individual arc capacities or a single scalar. + # The instance provides a single "arc_capacity" value applied to all arcs. + # Paper Eq. (4): 0 <= x_{ij} <= u_{ij} + u = [[arc_capacity for _ in range(m)] for _ in range(n)] # n x m matrix per Eq. (4) + + model = gp.Model("MCCFBN") + model.setParam("TimeLimit", time_limit) + model.setParam("Threads", 1) # single thread as in paper + # Paper uses optimality tolerance of 1e-4 + model.setParam("OptimalityTol", 1e-4) + model.setParam("BarConvTol", 1e-4) + + # Decision variables: x[i][j] = flow from supply i to demand j + x = {} + for i in range(n): + for j in range(m): + x[i, j] = model.addVar( + lb=0.0, + ub=u[i][j], + name=f"x_{i}_{j}" + ) + + model.update() + + # Objective: min sum_{i,j} f_{ij}(x_{ij}) + obj = gp.QuadExpr() + has_quadratic = False + for i in range(n): + for j in range(m): + c_ij = linear_costs[i][j] + q_ij = quadratic_costs[i][j] + obj += c_ij * x[i, j] + if q_ij != 0: + obj += q_ij * x[i, j] * x[i, j] + has_quadratic = True + + model.setObjective(obj, GRB.MINIMIZE) + + # Constraint (2): sum_{i in I} x_{ij} = d_j, for all j in J + for j in range(m): + model.addConstr( + gp.quicksum(x[i, j] for i in range(n)) == demands[j], + name=f"demand_{j}" + ) + + # Constraint (3): sum_{j in J} x_{ij} <= s_i, for all i in I + for i in range(n): + model.addConstr( + gp.quicksum(x[i, j] for j in range(m)) <= supplies[i], + name=f"supply_{i}" + ) + + # Use barrier method (interior-point) to match the paper's approach + if has_quadratic: + model.setParam("Method", 2) # barrier + model.setParam("BarHomogeneous", 0) + else: + # For linear problems, let Gurobi choose, but prefer barrier + model.setParam("Method", 2) + + # Disable crossover to match paper setting (no crossover for BlockIP) + model.setParam("Crossover", 0) + + model.optimize() + + result = { + "objective_value": None, + "status": None, + "flows": None + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + # Barrier (interior-point) without crossover leaves ~all n*m variables + # with positive dust values just above the prior 1e-8 threshold; for + # n=200, m=500000 (l41) that's 100M+ dict entries → 10+GB RAM → OOM + # during solution extraction (gurobi already solved). Raise the + # threshold to 1e-3 — dust below this is below the BarConvTol that + # the checker also uses, so it carries no meaningful flow. + FLOW_THRESHOLD = 1e-3 + flows = {} + for i in range(n): + for j in range(m): + val = x[i, j].X + if val > FLOW_THRESHOLD: + flows[f"x_{i}_{j}"] = val + result["flows"] = flows + else: + result["status"] = "infeasible_or_no_solution" + result["objective_value"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for MCCFBN (Castro & Nasini 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 write the solution JSON file." + ) + parser.add_argument( + "--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds." + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + result = build_and_solve(data, args.time_limit) + + with open(args.solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/castro2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/castro2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/castro2021/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/castro2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/castro2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/castro2021/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/castro2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/castro2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/castro2021/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/castro2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/castro2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/castro2021/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/castro2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/castro2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/castro2021/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/castro2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/castro2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/castro2021/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/castro2021/gurobi_solution/large_solution_1.json b/tasks/castro2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..74f65de9a68f7607fee04c023793181bc52d757c --- /dev/null +++ b/tasks/castro2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64f237a4d87623d865d79758be89927fb765392b556eff75885fc3778c985500 +size 59256671 diff --git a/tasks/castro2021/gurobi_solution/large_solution_2.json b/tasks/castro2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c2ea7c778d50ba081314d2ffb8e3a6f3cb36fa40 --- /dev/null +++ b/tasks/castro2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25f06b536d62dde2c6b97037af3599a10ca1a8e350fbb6f6ef5be6052381e9e6 +size 21692543 diff --git a/tasks/castro2021/gurobi_solution/large_solution_3.json b/tasks/castro2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1058fa802c600bf52be945967a2e6139090f606b --- /dev/null +++ b/tasks/castro2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18f34d543ffad260fb0ebfecd983e1432eb71aeea9ebe5dbf3c81a12eb8f9840 +size 67702494 diff --git a/tasks/castro2021/gurobi_solution/large_solution_4.json b/tasks/castro2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..14a654c88243525940d538a9f55655536e6baac4 --- /dev/null +++ b/tasks/castro2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5308b5e62ffa87ea5c90980e19e50e4a19d316ea151e2c59a09c6b0729d9b55e +size 194964051 diff --git a/tasks/castro2021/gurobi_solution/large_solution_5.json b/tasks/castro2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3bbcc7391a4a3dbaaf45eb9d65c3030a7d20d435 --- /dev/null +++ b/tasks/castro2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:512faafcbf9bd44f7547efbfbc8ec6ce7f8c62139f984ea5b488003abfe689ee +size 784254921 diff --git a/tasks/castro2021/gurobi_solution/tiny_solution.json b/tasks/castro2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..31dfb8c8f03685ff57e988bc1579bc42935b127a --- /dev/null +++ b/tasks/castro2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dab67e72847a8fb88cb8a04340f6259b87c0e4ea9e6206354691563381e0cf2d +size 1886 diff --git a/tasks/castro2021/gurobi_solution_log/large_log_1.jsonl b/tasks/castro2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/castro2021/gurobi_solution_log/large_log_2.jsonl b/tasks/castro2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/castro2021/gurobi_solution_log/large_log_3.jsonl b/tasks/castro2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/castro2021/gurobi_solution_log/large_log_4.jsonl b/tasks/castro2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/castro2021/gurobi_solution_log/large_log_5.jsonl b/tasks/castro2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/castro2021/gurobi_solution_log/tiny_log.jsonl b/tasks/castro2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/castro2021/instance/large_instance_1.json b/tasks/castro2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5bdc86ecbc1418dfe5b9c8148bb8fa4a1f384acb --- /dev/null +++ b/tasks/castro2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16d78d2233cd828066e6d2e797d3ee1d15e499c48568341f567cae7a20881f28 +size 1799707176 diff --git a/tasks/castro2021/instance/large_instance_2.json b/tasks/castro2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..84c03ed435cfbebe607e539083c297e54f59367d --- /dev/null +++ b/tasks/castro2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63cdfa1e4c0578d25d5600e5e465e0e95b87c5fd01a5cfbd743e445beabee8ef +size 821805484 diff --git a/tasks/castro2021/instance/large_instance_3.json b/tasks/castro2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..0c45082c3d0fce7e12c95df3ecd547de158981e4 --- /dev/null +++ b/tasks/castro2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2170d3e8c21deca0dcc4d6fdb9e8a2a67d82f6210ba677ba18fc83c332a487c +size 1310970576 diff --git a/tasks/castro2021/instance/large_instance_4.json b/tasks/castro2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8caa0d86c8ea6df5f062eb6ee401c106ffa2d5dd --- /dev/null +++ b/tasks/castro2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34f1fd0e58c437aabfd5a7239bc346dfbfb43d64423f934882c0665a0a3d8f5b +size 1690849330 diff --git a/tasks/castro2021/instance/large_instance_5.json b/tasks/castro2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a3bb8a4ec285fd37346dc8d6e7accd9e16986df8 --- /dev/null +++ b/tasks/castro2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b33aa27f217e72a4ce2161d89f2bac81730844ad6038dfc5d468a19b14c3034e +size 1928578153 diff --git a/tasks/castro2021/instance/tiny_instance.json b/tasks/castro2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..558b61f1a644948e27b4b7d04a56fe8343edf428 --- /dev/null +++ b/tasks/castro2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de143fab4659b2d3f1bb2ebc9d66cffba13c0e553a1352cf121defc3eb69ec80 +size 4948 diff --git a/tasks/castro2021/instance_schema.json b/tasks/castro2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..cdcc5bcf0adcf8147d4affeb4d695cb7261bff15 --- /dev/null +++ b/tasks/castro2021/instance_schema.json @@ -0,0 +1,18 @@ +{ + "n": " Number of suppliers in the transportation network.", + "m": " Number of customers in the transportation network.", + "num_arcs": " Total number of shipping arcs in the bipartite network, equal to n times m.", + "num_variables": " Total number of flow variables in the model, equal to n times m plus n.", + "num_constraints": " Total number of constraints in the model, equal to m plus n.", + "cost_type": " Type of arc cost function used: 'linear_integer', 'linear_fractional', or 'quadratic'.", + "relative_demand_slack": " Ratio of excess total supply beyond total demand to total supply.", + "total_supply": " Sum of all supplier capacities.", + "total_demand": " Sum of all customer demands.", + "arc_capacity": " Upper bound on the flow that can be shipped on any single arc.", + "supplier_locations": " Two-dimensional spatial coordinates for each supplier.", + "customer_locations": " Two-dimensional spatial coordinates for each customer.", + "supplies": " Maximum total flow that each supplier can ship across all its outgoing arcs.", + "demands": " Quantity of flow that must arrive at each customer from all suppliers combined.", + "linear_costs": " Per-unit shipping cost on the arc from each supplier to each customer.", + "quadratic_costs": " Quadratic cost coefficient on the arc from each supplier to each customer, applied to the square of the flow." +} diff --git a/tasks/castro2021/mathematical_formulation.md b/tasks/castro2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..ecc38153f2a7ad93ecc31ec176e29c2b67e28f77 --- /dev/null +++ b/tasks/castro2021/mathematical_formulation.md @@ -0,0 +1,42 @@ +# Original Formulation: Minimum Convex Cost Flows in Bipartite Networks (MCCFBN) + +*Source: A specialized interior-point algorithm for huge minimum convex cost flows in bipartite networks, Jordi Castro and Stefano Nasini, 2018/2021.* + +## Sets and Indices + +- $I$ : set of supply nodes (operating suppliers or machines), with $n = |I|$. + +- $J$ : set of demand nodes (customers or tasks), with $m = |J|$. + +- $(i,j)$ : arc from $i \in I$ to $j \in J$ in the complete bipartite network $I \times J$. + +## Parameters + +- $f_{ij} : \mathbb{R} \to \mathbb{R}$, convex cost function of the flow from $i \in I$ to $j \in J$. + +- $d_j \in \mathbb{R}_+$, demand of node $j \in J$. + +- $s_i \in \mathbb{R}_+$, supply (or supply capacity) of node $i \in I$. + +- $u_{ij} \in \mathbb{R}_+$, capacity of the arc $(i,j) \in I \times J$. + +where $\mathbb{R}$ and $\mathbb{R}_+$ are the sets of real and nonnegative real numbers respectively. + +## Decision Variables + +- $x_{ij} \in \mathbb{R}$ : flow from node $i \in I$ to node $j \in J$. + +## Objective + +$$\begin{align} +\min \quad & \sum_{i \in I} \sum_{j \in J} f_{ij}(x_{ij}), \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{subject to} \quad +& \sum_{i \in I} x_{ij} = d_j, && j \in J, \tag{2} \\ +& \sum_{j \in J} x_{ij} \le s_i, && i \in I, \tag{3} \\ +& 0 \le x_{ij} \le u_{ij}, && i \in I,\ j \in J. \tag{4} +\end{align}$$ diff --git a/tasks/castro2021/problem_description.txt b/tasks/castro2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..7b0b223245c32c9f1ba627054e6806a318c729c0 --- /dev/null +++ b/tasks/castro2021/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A transportation network connects a set of suppliers to a set of customers. There are n suppliers and m customers, and every supplier is connected to every customer by a direct shipping arc, forming a complete bipartite network with n times m arcs. Each supplier has a known supply capacity specifying the maximum total flow it can send across all its outgoing arcs. Each customer has a known demand that must be met exactly: the total flow arriving at that customer from all suppliers must equal that customer's demand. Each arc from a supplier to a customer also has an individual capacity limiting the flow on that arc. The planner must determine the flow shipped on every arc from each supplier to each customer, where each arc's flow must be between zero and the arc's capacity. + +Shipping flow on an arc from a supplier to a customer incurs a cost given by a convex function of the flow on that arc. Two specific cost structures are considered. In the linear case, the cost on each arc equals a per-unit cost coefficient times the flow on that arc. In the quadratic case, the cost on each arc equals a linear cost coefficient times the flow plus a quadratic cost coefficient times the square of the flow. Each arc has its own linear and quadratic cost coefficients, which are provided as input data. In both cases the cost on one arc depends only on the flow on that arc and not on flows elsewhere. + +The input data for an instance specifies the number of suppliers n and the number of customers m, the supply capacity of each supplier, the demand of each customer, the capacity of each arc, and the cost coefficients for each arc. Suppliers and customers may also have two-dimensional spatial coordinates used to generate cost coefficients, though the optimization model itself operates on the cost coefficients directly. Total supply across all suppliers must be at least as large as total demand across all customers. A parameter called relative demand slack captures the ratio of excess total supply beyond total demand to total supply; when this value is zero, total supply equals total demand and every unit of supply must be used. + +The goal is to determine the flow on every arc so as to minimize the total shipping cost summed over all arcs, subject to three families of rules. First, each customer's demand must be satisfied exactly by the combined flows arriving from all suppliers. Second, the total flow leaving each supplier across all its arcs must not exceed that supplier's supply capacity. Third, the flow on each individual arc must be at least zero and must not exceed that arc's capacity. diff --git a/tasks/castro2021/solution_logger.py b/tasks/castro2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/castro2021/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/castro2021/solution_schema.json b/tasks/castro2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0308e27ed99e400c8c40a816b08b7f3e95e07e00 --- /dev/null +++ b/tasks/castro2021/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total shipping cost across all supplier-to-customer arcs in the bipartite network.", + "flows": " Quantity of flow shipped from each supplier to each customer." +} diff --git a/tasks/chebil2015/feasibility_check.py b/tasks/chebil2015/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..06aa94d293325956f37694639300e46d124a2d95 --- /dev/null +++ b/tasks/chebil2015/feasibility_check.py @@ -0,0 +1,356 @@ +""" +Feasibility checker for the Knapsack Problem with Setup (KPS). +Based on: Chebil & Khemakhem (2015), Computers & Operations Research. + +Constraints (numbered top-to-bottom from the formulation): + Constraint 1: sum_i sum_j a_{ij} x_{ij} + sum_i d_i y_i <= b (capacity) + Constraint 2: x_{ij} <= y_i for all i, j (linking) + Constraint 3: x_{ij}, y_i in {0, 1} (binary) + Constraint 4: reported objective_value must equal + sum_i sum_j c_{ij} x_{ij} + sum_i f_i y_i (obj consistency) +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('classes', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def check_feasibility(instance, solution): + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + b = instance["b"] + inst_classes = {cls["class_id"]: cls for cls in instance["classes"]} + sol_classes = {cls["class_id"]: cls for cls in solution["classes"]} + + # --- Constraint 3: Binary constraints on x_ij and y_i --- + for cid, sol_cls in sol_classes.items(): + y_i = sol_cls["y_i"] + if y_i not in (0, 1) and abs(y_i - round(y_i)) > TOL: + violated_constraints.add(3) + violation_amount = min(abs(y_i - 0), abs(y_i - 1)) + rhs = round(y_i) + normalizer = max(abs(rhs), EPS) + violations.append(f"y_{cid} = {y_i} is not binary") + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(y_i), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + for item_sol in sol_cls["items"]: + x_ij = item_sol["x_ij"] + jid = item_sol["item_id"] + if x_ij not in (0, 1) and abs(x_ij - round(x_ij)) > TOL: + violated_constraints.add(3) + violation_amount = min(abs(x_ij - 0), abs(x_ij - 1)) + rhs = round(x_ij) + normalizer = max(abs(rhs), EPS) + violations.append( + f"x_{cid}_{jid} = {x_ij} is not binary" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(x_ij), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # --- Constraint 1: Capacity constraint --- + # LHS = sum_i sum_j a_ij * x_ij + sum_i d_i * y_i + # RHS = b + # Constraint: LHS <= RHS + lhs_cap = 0.0 + for cid, sol_cls in sol_classes.items(): + inst_cls = inst_classes[cid] + y_i = sol_cls["y_i"] + d_i = inst_cls["d_i"] + lhs_cap += d_i * y_i + + inst_items = {it["item_id"]: it for it in inst_cls["items"]} + for item_sol in sol_cls["items"]: + jid = item_sol["item_id"] + x_ij = item_sol["x_ij"] + a_ij = inst_items[jid]["a_ij"] + lhs_cap += a_ij * x_ij + + violation_amount = max(lhs_cap - b, 0.0) + if violation_amount > TOL: + violated_constraints.add(1) + normalizer = max(abs(b), EPS) + violations.append( + f"Capacity exceeded: total weight {lhs_cap} > capacity {b}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs_cap), + "rhs": float(b), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # --- Constraint 2: Linking constraints x_ij <= y_i --- + for cid, sol_cls in sol_classes.items(): + y_i = sol_cls["y_i"] + for item_sol in sol_cls["items"]: + x_ij = item_sol["x_ij"] + jid = item_sol["item_id"] + # LHS = x_ij, RHS = y_i, constraint: LHS <= RHS + violation_amount = max(x_ij - y_i, 0.0) + if violation_amount > TOL: + violated_constraints.add(2) + normalizer = max(abs(y_i), EPS) + violations.append( + f"Linking violated: x_{cid}_{jid} = {x_ij} > y_{cid} = {y_i}" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(x_ij), + "rhs": float(y_i), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # --- Constraint 4: Objective consistency --- + # True obj = sum_i sum_j c_ij * x_ij + sum_i f_i * y_i + # Must equal reported objective_value within tolerance. + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + for cid, sol_cls in sol_classes.items(): + inst_cls = inst_classes[cid] + y_i = sol_cls["y_i"] + f_i = inst_cls["f_i"] + true_obj += f_i * y_i + + inst_items = {it["item_id"]: it for it in inst_cls["items"]} + for item_sol in sol_cls["items"]: + jid = item_sol["item_id"] + x_ij = item_sol["x_ij"] + c_ij = inst_items[jid]["c_ij"] + true_obj += c_ij * x_ij + true_obj = float(true_obj) + + abs_diff = abs(reported - true_obj) + # All coefficients (c_ij, f_i) are integers and variables are binary, + # so the true objective is an integer. A 0.5 absolute floor catches + # any integer mismatch >= 1, plus a 0.1% relative band for safety. + tol = max(0.5, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(4) + normalizer = max(abs(true_obj), EPS) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum_ij(c_ij*x_ij)+sum_i(f_i*y_i)=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + feasible = len(violated_constraints) == 0 + 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 KPS (Chebil & Khemakhem 2015)" + ) + 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) + + print(f"Feasible: {result['feasible']}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/chebil2015/gurobi_code.py b/tasks/chebil2015/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d9fae44551e2f8e2f407fb521b4113906c4af4c3 --- /dev/null +++ b/tasks/chebil2015/gurobi_code.py @@ -0,0 +1,133 @@ +""" +Gurobi implementation of the Knapsack Problem with Setup (KPS). +Based on: Chebil & Khemakhem (2015), Computers & Operations Research. + +Maximize z = sum_i sum_j c_{ij} x_{ij} + sum_i f_i y_i +subject to: + sum_i sum_j a_{ij} x_{ij} + sum_i d_i y_i <= b + x_{ij} <= y_i for all i, j + x_{ij}, y_i in {0, 1} +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def solve_kps(instance_path, solution_path, time_limit): + with open(instance_path, "r") as f: + data = json.load(f) + + N = data["N"] + b = data["b"] + classes = data["classes"] + + model = gp.Model("KPS") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + x = {} # x[i][j]: binary, select item j of class i + y = {} # y[i]: binary, setup class i + + for cls in classes: + i = cls["class_id"] + y[i] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}") + for item in cls["items"]: + j = item["item_id"] + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + model.update() + + # Objective: maximize total profit (f_i are negative, so +f_i*y_i subtracts setup cost) + obj = gp.LinExpr() + for cls in classes: + i = cls["class_id"] + obj += cls["f_i"] * y[i] + for item in cls["items"]: + j = item["item_id"] + obj += item["c_ij"] * x[i, j] + model.setObjective(obj, GRB.MAXIMIZE) + + # Capacity constraint + cap = gp.LinExpr() + for cls in classes: + i = cls["class_id"] + cap += cls["d_i"] * y[i] + for item in cls["items"]: + j = item["item_id"] + cap += item["a_ij"] * x[i, j] + model.addConstr(cap <= b, "capacity") + + # Linking constraints: x_{ij} <= y_i + for cls in classes: + i = cls["class_id"] + for item in cls["items"]: + j = item["item_id"] + model.addConstr(x[i, j] <= y[i], f"link_{i}_{j}") + + # Solve + model.optimize() + + # Extract solution + objective_value = None + solution = {"classes": []} + + if model.SolCount > 0: + objective_value = model.ObjVal + for cls in classes: + i = cls["class_id"] + cls_sol = { + "class_id": i, + "y_i": int(round(y[i].X)), + "items": [], + } + for item in cls["items"]: + j = item["item_id"] + cls_sol["items"].append( + {"item_id": j, "x_ij": int(round(x[i, j].X))} + ) + solution["classes"].append(cls_sol) + + solution["objective_value"] = objective_value + + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Objective value: {objective_value}") + print(f"Solution written to: {solution_path}") + + +def main(): + parser = argparse.ArgumentParser(description="Solve KPS 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, 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) + solve_kps(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/chebil2015/gurobi_feasi_result/large_feasi_result_1.json b/tasks/chebil2015/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2015/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/chebil2015/gurobi_feasi_result/large_feasi_result_2.json b/tasks/chebil2015/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2015/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/chebil2015/gurobi_feasi_result/large_feasi_result_3.json b/tasks/chebil2015/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2015/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/chebil2015/gurobi_feasi_result/large_feasi_result_4.json b/tasks/chebil2015/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2015/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/chebil2015/gurobi_feasi_result/large_feasi_result_5.json b/tasks/chebil2015/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2015/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/chebil2015/gurobi_feasi_result/tiny_feasi_result.json b/tasks/chebil2015/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2015/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/chebil2015/gurobi_solution/large_solution_1.json b/tasks/chebil2015/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..680d4516a426f76652700885ad83cae99932266f --- /dev/null +++ b/tasks/chebil2015/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ef0262b94e46074822244ffcd5cbfdc8946a77c9000f2ca0b3ac411fa48eec7 +size 669074 diff --git a/tasks/chebil2015/gurobi_solution/large_solution_2.json b/tasks/chebil2015/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..150398fd1ac0e0df9c610958f568e12c842f1e09 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:640b4129930a5b57a49e82ad081d7af40aff4bd671d6c1ae6ba575dbfb4ab95e +size 669073 diff --git a/tasks/chebil2015/gurobi_solution/large_solution_3.json b/tasks/chebil2015/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6c5a69e9e18cd13243c613988115e82ea99e183e --- /dev/null +++ b/tasks/chebil2015/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d968ff2fd01addf8f1335808379d048f2f1ec855a5296781377e8c8506612bf +size 669073 diff --git a/tasks/chebil2015/gurobi_solution/large_solution_4.json b/tasks/chebil2015/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2995ccc6a7df3a24b17ae23db198de9b6162d236 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f2fea460ec3d4bede715bc57d9ae8d0c94b8b89a23a5197972fe86101f756be +size 669073 diff --git a/tasks/chebil2015/gurobi_solution/large_solution_5.json b/tasks/chebil2015/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..26b1942e2a760b57716ab5ff6b96c21373ec8d96 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05d7aeab5f1ebd1820d7eb5e97e70a8d8dcd6a3eb0704ac1d5c3034a4f709b06 +size 669075 diff --git a/tasks/chebil2015/gurobi_solution/tiny_solution.json b/tasks/chebil2015/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..baec1b4b57d9cb735fe03124f2dd0ad09ac52668 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9286603165d8fffe5926a74601dc580aa43dbfb569d64c540fc2ee6d02e8a736 +size 33409 diff --git a/tasks/chebil2015/gurobi_solution_log/large_log_1.jsonl b/tasks/chebil2015/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac53a5b98c99774666af8600ea71803f5c61cc74 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9d3e4e1cd3c943a5d217de80d9bde50e94b340ca14be687b8052d8a063fd482 +size 40 diff --git a/tasks/chebil2015/gurobi_solution_log/large_log_2.jsonl b/tasks/chebil2015/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..deb36c8a2107e5b3833f4a00191c7516d8a4e764 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6155d899b7431612142f477fd13119209f6b1dd0c756d67c51d104bfa67a4e24 +size 41 diff --git a/tasks/chebil2015/gurobi_solution_log/large_log_3.jsonl b/tasks/chebil2015/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b2696eced59eacce5144508e3dd2c6f4efcdb00 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e53791cf45bfc9cbbe7165018ccc93c317fd7ac6dbc3e6c9d272215d0db87bec +size 41 diff --git a/tasks/chebil2015/gurobi_solution_log/large_log_4.jsonl b/tasks/chebil2015/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6df85aa5dd8863a12caa5fe51a603a6f9a105e67 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eaf964540d0be19ea1027533ce529e2a2185f4a80f7a9b48c0a56ec55370658 +size 41 diff --git a/tasks/chebil2015/gurobi_solution_log/large_log_5.jsonl b/tasks/chebil2015/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac53a5b98c99774666af8600ea71803f5c61cc74 --- /dev/null +++ b/tasks/chebil2015/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9d3e4e1cd3c943a5d217de80d9bde50e94b340ca14be687b8052d8a063fd482 +size 40 diff --git a/tasks/chebil2015/gurobi_solution_log/tiny_log.jsonl b/tasks/chebil2015/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8edcf239a5916cc2f1fdbb0826982f10ef44e61d --- /dev/null +++ b/tasks/chebil2015/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db0e0d098800bb2106598b422cea49a5e8e5c628da200a0fb687a87a5c80cecc +size 41 diff --git a/tasks/chebil2015/instance/large_instance_1.json b/tasks/chebil2015/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..93bce6f0ad05a51abf28d2546d2511d388430323 --- /dev/null +++ b/tasks/chebil2015/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25b79acff2bf14f11078baafe4523b7910199c9e6f542bf5467bed56ac2a8b01 +size 901743 diff --git a/tasks/chebil2015/instance/large_instance_2.json b/tasks/chebil2015/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ccd27d895a5d2f97717dd4ee3343d7cfb3a30132 --- /dev/null +++ b/tasks/chebil2015/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24d23f933b97f2156e898fb94eac4abc05c2740d6da62b6b961483f226a28470 +size 902620 diff --git a/tasks/chebil2015/instance/large_instance_3.json b/tasks/chebil2015/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..65cd7b91dc08686352b83f5d62bcfd31de9699dd --- /dev/null +++ b/tasks/chebil2015/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:910b1719e833357fe83dc8b7dfd202918ec33474a4ae88b2a42595623cc9e264 +size 900645 diff --git a/tasks/chebil2015/instance/large_instance_4.json b/tasks/chebil2015/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..80ad3778f0b4dc0e9be3bc293ea1a0b530fbb0d0 --- /dev/null +++ b/tasks/chebil2015/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a11bee4898bc266e20ca928112fb7fa511051c0bd46afc6c411cf11e2eaa735 +size 901726 diff --git a/tasks/chebil2015/instance/large_instance_5.json b/tasks/chebil2015/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..2a29025b46c6b00dda9729ce23b5bb639fb63a40 --- /dev/null +++ b/tasks/chebil2015/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ac816695ccc39894652ea333a843b13c68b1d17302baada75f8e2f322ebc205 +size 900669 diff --git a/tasks/chebil2015/instance/tiny_instance.json b/tasks/chebil2015/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..52b5c941d5bc387d8aec22209bcd96dffb2a15c5 --- /dev/null +++ b/tasks/chebil2015/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e4648b9f58fafa9d03488fac31150eafdc264564b728c568e72b301e78e69e5 +size 45309 diff --git a/tasks/chebil2015/instance_schema.json b/tasks/chebil2015/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b4f3af8e6dcc793e66a1c01b6b870fcdafe4ecaf --- /dev/null +++ b/tasks/chebil2015/instance_schema.json @@ -0,0 +1,21 @@ +{ + "problem": " Name of the optimization problem.", + "n_star": " Total number of items across all classes.", + "N": " Number of item classes (families).", + "b": " Capacity of the knapsack.", + "classes": [ + { + "class_id": " Identifier of this class, ranging from 1 to N.", + "n_i": " Number of items in this class.", + "f_i": " Fixed setup cost incurred when this class is activated (negative value representing a profit reduction).", + "d_i": " Knapsack capacity consumed when this class is activated.", + "items": [ + { + "item_id": " Identifier of this item within its class, ranging from 1 to n_i.", + "a_ij": " Weight of this item.", + "c_ij": " Profit earned by selecting this item." + } + ] + } + ] +} diff --git a/tasks/chebil2015/mathematical_formulation.md b/tasks/chebil2015/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..899a44676ea66cfd5b93a95bf0189c1aae3a0684 --- /dev/null +++ b/tasks/chebil2015/mathematical_formulation.md @@ -0,0 +1,40 @@ +# Original Formulation: Knapsack Problem with Setup (KPS) + +*Source: A dynamic programming algorithm for the Knapsack Problem with Setup, Khalil Chebil, Mahdi Khemakhem, Computers & Operations Research, 2015.* + +## Sets and Parameters + +- $N$ : number of classes (families) of items, indexed by $i \in \{1, \ldots, N\}$. + +- $n_i$ : number of items in class $i$, indexed by $j \in \{1, \ldots, n_i\}$. + +- $b \in \mathbb{N}$ : knapsack capacity (non-negative integer). + +- $f_i$ : setup cost of class $i$, a negative integer. + +- $d_i$ : setup capacity consumption of class $i$, a non-negative integer. + +- $c_{ij} \in \mathbb{N}^{N \times n_i}$ : profit of item $j$ of class $i$. + +- $a_{ij} \in \mathbb{N}^{N \times n_i}$ : capacity consumption (weight) of item $j$ of class $i$. + +## Decision Variables + +- $x_{ij} \in \{0,1\}$ : equals $1$ if item $j$ of class $i$ is placed in the knapsack, $0$ otherwise. + +- $y_i \in \{0,1\}$ : equals $1$ if the knapsack is set up to accept items belonging to class $i$, $0$ otherwise. + +## Objective + +$$\begin{align} +\text{Max } z &= \sum_{i=1}^{N} \sum_{j=1}^{n_i} c_{ij}\, x_{ij} + \sum_{i=1}^{N} f_i\, y_i \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.} \quad +& \sum_{i=1}^{N} \sum_{j=1}^{n_i} a_{ij}\, x_{ij} + \sum_{i=1}^{N} d_i\, y_i \leq b \tag{2} \\ +& x_{ij} \leq y_i && \forall i \in \{1, \ldots, N\},\ \forall j \in \{1, \ldots, n_i\} \tag{3} \\ +& x_{ij},\, y_i \in \{0,1\} && \forall i \in \{1, \ldots, N\},\ \forall j \in \{1, \ldots, n_i\} \tag{4} +\end{align}$$ diff --git a/tasks/chebil2015/problem_description.txt b/tasks/chebil2015/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..2535ce40f092bf52d060ecc2762ec82b03abcbd3 --- /dev/null +++ b/tasks/chebil2015/problem_description.txt @@ -0,0 +1,3 @@ +# Problem Description + +A company has a knapsack with a given non-negative integer capacity and a collection of items organized into classes (also called families). The number of classes is specified, and each class contains a specific number of items, with the total number of items across all classes being the sum of the per-class counts. Each item has a non-negative integer profit and a non-negative integer weight. Each class has a fixed setup cost, represented as a negative integer, and a setup capacity consumption, represented as a non-negative integer. The company must decide which items to place in the knapsack, but an item from a given class may only be selected if that class has been activated (set up). Activating a class incurs its fixed setup cost, which reduces overall profit, and also consumes a portion of the knapsack's capacity equal to that class's setup capacity consumption. The total weight of all selected items plus the total setup capacity consumption of all activated classes must not exceed the knapsack's capacity. Each item is either fully selected or not selected, and each class is either activated or not. The goal is to maximize the total profit, defined as the sum of the profits of all selected items plus the sum of the setup costs of all activated classes (since setup costs are negative, activating a class effectively reduces total profit by the magnitude of its setup cost). diff --git a/tasks/chebil2015/solution_logger.py b/tasks/chebil2015/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/chebil2015/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/chebil2015/solution_schema.json b/tasks/chebil2015/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f296c61e6f6755409cd9629cf93742c60ef5bf79 --- /dev/null +++ b/tasks/chebil2015/solution_schema.json @@ -0,0 +1,15 @@ +{ + "classes": [ + { + "class_id": " Identifier of this class, matching the corresponding class in the instance.", + "y_i": " Whether this class is activated (1 = activated, 0 = not activated).", + "items": [ + { + "item_id": " Identifier of this item within its class, matching the corresponding item in the instance.", + "x_ij": " Whether this item is selected for the knapsack (1 = selected, 0 = not selected)." + } + ] + } + ], + "objective_value": " Total profit from all selected items minus the setup costs of all activated classes." +} diff --git a/tasks/chebil2019/feasibility_check.py b/tasks/chebil2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..64079648ea27380ac666eef0e944eee658cf620d --- /dev/null +++ b/tasks/chebil2019/feasibility_check.py @@ -0,0 +1,420 @@ +""" +Feasibility checker for the 0-1 Knapsack Problem with Setups (KPS). + +Checks all hard constraints from the KPS_1 formulation: + Constraint 1 (capacity): sum w_{ij} x_{ij} + sum d_i y_i <= b + Constraint 2 (linking): x_{ij} <= y_i for all i, j + Constraint 3 (binary x): x_{ij} in {0, 1} + Constraint 4 (binary y): y_i in {0, 1} + Constraint 5 (objective): reported objective_value must equal + sum_{i,j} p_{ij} x_{ij} - sum_i f_i y_i +""" + +import json +import argparse + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('families_selected', 'items_selected', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_constraints_set = set() + + N = instance["N"] + b = instance["knapsack_capacity"] + families = instance["families"] + + # Build lookup: family_id -> family data + fam_lookup = {} + for fam in families: + fam_lookup[fam["family_id"]] = fam + # Build item lookup within family + item_lookup = {} + for item in fam["items"]: + item_lookup[item["item_id"]] = item + fam["_item_lookup"] = item_lookup + + families_selected = set(solution.get("families_selected", [])) + items_selected = solution.get("items_selected", []) + + # Build x values: (family_id, item_id) -> 1 + x_vals = {} + for entry in items_selected: + key = (entry["family"], entry["item"]) + x_vals[key] = 1 + + # Build y values + y_vals = {} + for fam in families: + fid = fam["family_id"] + y_vals[fid] = 1 if fid in families_selected else 0 + + # --- Constraint 4: y_i in {0, 1} --- + for fid in families_selected: + if fid not in fam_lookup: + violation_amount = 1.0 + rhs = 0.0 + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(4) + violations.append(f"Family {fid} in families_selected is not a valid family ID") + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(fid), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # --- Constraint 3: x_{ij} in {0, 1} --- + # Check that all selected items reference valid families and item IDs + for entry in items_selected: + fid = entry["family"] + iid = entry["item"] + if fid not in fam_lookup: + violation_amount = 1.0 + rhs = 0.0 + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(3) + violations.append(f"Item ({fid},{iid}) references invalid family {fid}") + violation_magnitudes.append({ + "constraint": 3, + "lhs": 1.0, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + elif iid not in fam_lookup[fid]["_item_lookup"]: + violation_amount = 1.0 + rhs = 0.0 + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(3) + violations.append(f"Item ({fid},{iid}) has invalid item_id {iid} in family {fid}") + violation_magnitudes.append({ + "constraint": 3, + "lhs": 1.0, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # Check for duplicate items (x_{ij} > 1 would violate binary domain) + from collections import Counter + item_counts = Counter((e["family"], e["item"]) for e in items_selected) + for (fid, iid), count in item_counts.items(): + if count > 1: + violation_amount = float(count - 1) + rhs = 1.0 + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(3) + violations.append(f"Item ({fid},{iid}) selected {count} times, violates binary domain") + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(count), + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # --- Constraint 2: x_{ij} <= y_i (linking) --- + for entry in items_selected: + fid = entry["family"] + iid = entry["item"] + x_val = 1.0 + y_val = float(y_vals.get(fid, 0)) + # x_{ij} <= y_i => violation if x_{ij} - y_i > tol + violation_amount = x_val - y_val + if violation_amount > tol: + rhs = y_val + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(2) + violations.append( + f"Item ({fid},{iid}) selected but family {fid} not activated (x=1, y=0)" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": x_val, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # --- Constraint 1: capacity --- + # LHS = sum w_{ij} x_{ij} + sum d_i y_i + total_weight = 0.0 + for entry in items_selected: + fid = entry["family"] + iid = entry["item"] + if fid in fam_lookup and iid in fam_lookup[fid]["_item_lookup"]: + total_weight += fam_lookup[fid]["_item_lookup"][iid]["weight"] + + total_setup_cap = 0.0 + for fid in families_selected: + if fid in fam_lookup: + total_setup_cap += fam_lookup[fid]["setup_capacity"] + + lhs_capacity = total_weight + total_setup_cap + rhs_capacity = float(b) + violation_amount = lhs_capacity - rhs_capacity + if violation_amount > tol: + normalizer = max(abs(rhs_capacity), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(1) + violations.append( + f"Capacity exceeded: total weight {total_weight} + setup capacity " + f"{total_setup_cap} = {lhs_capacity} > {rhs_capacity}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_capacity, + "rhs": rhs_capacity, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # --- Constraint 5: objective consistency (Tier C defense) --- + # Recompute obj = sum p_{ij} x_{ij} - sum f_i y_i from the solution + # variables and reject when the reported value disagrees. Only valid + # (family, item) entries contribute; invalid ones are already flagged + # by constraints 3/4 and their would-be contributions are undefined. + reported_obj_raw = solution.get("objective_value") + reported_obj = None + if reported_obj_raw is not None: + try: + reported_obj = float(reported_obj_raw) + except (TypeError, ValueError): + reported_obj = None + if reported_obj is not None: + true_obj = 0.0 + for (fid, iid) in x_vals: + if fid in fam_lookup and iid in fam_lookup[fid]["_item_lookup"]: + true_obj += float(fam_lookup[fid]["_item_lookup"][iid]["profit"]) + for fid in families_selected: + if fid in fam_lookup: + true_obj -= float(fam_lookup[fid]["setup_cost"]) + + abs_diff = abs(reported_obj - true_obj) + # KPS profits and setup costs are integers per the formulation, so + # the true objective is integer-valued. Use 0.5 absolute tolerance + # so any integer mismatch fires; keep a tiny relative floor for + # robustness on very large magnitudes (e.g. sys.float_info.max). + obj_tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > obj_tol: + normalizer = max(abs(true_obj), eps) + ratio = abs_diff / normalizer + violated_constraints_set.add(5) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} differs from recomputed " + f"sum p_{{ij}} x_{{ij}} - sum f_i y_i = {true_obj} " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(reported_obj), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": normalizer, + "ratio": ratio, + }) + + feasible = len(violated_constraints_set) == 0 + violated_constraints = sorted(violated_constraints_set) + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for KPS (0-1 Knapsack Problem with Setups)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result") + args = parser.parse_args() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility result written to {args.result_path}") + print(f"Feasible: {result['feasible']}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/chebil2019/gurobi_code.py b/tasks/chebil2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..92dab73c2d3252f8ff327620be9d6c767052da78 --- /dev/null +++ b/tasks/chebil2019/gurobi_code.py @@ -0,0 +1,149 @@ +""" +Gurobi implementation of KPS_1: 0-1 Knapsack Problem with Setups. + +Source: Della Croce, Salassa, Scatamacchia (2016) - "An exact approach for + the 0-1 Knapsack Problem with Setups" + +Formulation KPS_1 (Standard ILP): + maximize sum_i sum_j p_{ij} x_{ij} - sum_i f_i y_i + subject to sum_i sum_j w_{ij} x_{ij} + sum_i d_i y_i <= b + x_{ij} <= y_i for all i, j + x_{ij} in {0,1}, y_i in {0,1} +""" + +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_kps(instance, time_limit): + N = instance["N"] + b = instance["knapsack_capacity"] + families = instance["families"] + + model = gp.Model("KPS_1") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + x = {} # x[i][j]: 1 if item j of family i is selected + y = {} # y[i]: 1 if family i is activated + + for fam in families: + i = fam["family_id"] + y[i] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}") + for item in fam["items"]: + j = item["item_id"] + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + model.update() + + # Objective: maximize total profit minus setup costs + obj = gp.LinExpr() + for fam in families: + i = fam["family_id"] + f_i = fam["setup_cost"] + obj -= f_i * y[i] + for item in fam["items"]: + j = item["item_id"] + p_ij = item["profit"] + obj += p_ij * x[i, j] + model.setObjective(obj, GRB.MAXIMIZE) + + # Constraint (2): capacity + cap_expr = gp.LinExpr() + for fam in families: + i = fam["family_id"] + d_i = fam["setup_capacity"] + cap_expr += d_i * y[i] + for item in fam["items"]: + j = item["item_id"] + w_ij = item["weight"] + cap_expr += w_ij * x[i, j] + model.addConstr(cap_expr <= b, "capacity") + + # Constraint (3): linking constraints x_{ij} <= y_i + for fam in families: + i = fam["family_id"] + for item in fam["items"]: + j = item["item_id"] + model.addConstr(x[i, j] <= y[i], f"link_{i}_{j}") + + # Solve + model.optimize() + + # Extract solution + solution = { + "objective_value": None, + "status": None, + "families_selected": [], + "items_selected": [], + } + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + for fam in families: + i = fam["family_id"] + if y[i].X > 0.5: + solution["families_selected"].append(i) + for item in fam["items"]: + j = item["item_id"] + if x[i, j].X > 0.5: + solution["items_selected"].append({"family": i, "item": j}) + else: + solution["objective_value"] = 0 + solution["status"] = "no_solution_found" + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Solve KPS using Gurobi (KPS_1 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) + + instance = load_instance(args.instance_path) + solution = solve_kps(instance, args.time_limit) + + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {args.solution_path}") + print(f"Objective value: {solution['objective_value']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/chebil2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/chebil2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2019/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/chebil2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/chebil2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2019/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/chebil2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/chebil2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2019/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/chebil2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/chebil2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2019/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/chebil2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/chebil2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2019/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/chebil2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/chebil2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chebil2019/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/chebil2019/gurobi_solution/large_solution_1.json b/tasks/chebil2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..1d9ae80916499649b02f9b5d0183cdecdbdc27c6 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa64b8010318b2db80b183173b7d2dfe8274a895fbcd29397ed4d0a565cc96c1 +size 1040033 diff --git a/tasks/chebil2019/gurobi_solution/large_solution_2.json b/tasks/chebil2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..2dc947b9c189ae88edb7c2d659eccc32c2903c81 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0671bf0678a6de3c3ef8679ec5c6702832ab2965183f7c64dc114213012a8dc6 +size 1200571 diff --git a/tasks/chebil2019/gurobi_solution/large_solution_3.json b/tasks/chebil2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1d7421b720a707c92dd6488f96d8f7e343e45c0c --- /dev/null +++ b/tasks/chebil2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:177a561ad3e573dbfad236d3323a9cc74fea667060bfeb073f4b260aa9d94281 +size 1044014 diff --git a/tasks/chebil2019/gurobi_solution/large_solution_4.json b/tasks/chebil2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..bda6a4a334906b3b38646e7ac83906b5bf62e06b --- /dev/null +++ b/tasks/chebil2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38d5048b4bde529bc7856c96351dec77833ba1fe3c023bd8336394e236191609 +size 961421 diff --git a/tasks/chebil2019/gurobi_solution/large_solution_5.json b/tasks/chebil2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5893f10ea6c37e1ccb9aeef919c5d45ff35004d7 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:463d69a07b4ada4444e64040eb424772744b7d14f9d01dade3b6634b9ac58180 +size 1064725 diff --git a/tasks/chebil2019/gurobi_solution/tiny_solution.json b/tasks/chebil2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..37b4d4e058cb01e0a80266e665e871649d29e525 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cdc56228cc9343a405c133b0d8560c98df5b5d5024d6e1526e4127d8db4e34b +size 9928 diff --git a/tasks/chebil2019/gurobi_solution_log/large_log_1.jsonl b/tasks/chebil2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0d3193b79a56f85c740a425856dd3af5464f4b11 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07dc32bc3b9fd18ae134aa9807acbbe27ea19d4b446dfbc1821b387ef20d669e +size 41 diff --git a/tasks/chebil2019/gurobi_solution_log/large_log_2.jsonl b/tasks/chebil2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6077778e4213e825a4c2b6cf246021c11dce1160 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e43cd6737eabd354e94e5d20e99b8ed84bbd3704d7b00a4b4afe7a237a6bdd1c +size 41 diff --git a/tasks/chebil2019/gurobi_solution_log/large_log_3.jsonl b/tasks/chebil2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..859dea99b9b8fd5827d0131f25d8c723b908ea2f --- /dev/null +++ b/tasks/chebil2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce51e1b2f954ac605bdbe1cd5355acf909797558a666e8f12932b6e9f2a16fca +size 41 diff --git a/tasks/chebil2019/gurobi_solution_log/large_log_4.jsonl b/tasks/chebil2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0a6b2d3b2fc22a01086d7b5839023d6e2c18bcc7 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:544411f25f3525f022285a0ffa8efbc32a9fffd13a02d022bc87120745a7c1c6 +size 41 diff --git a/tasks/chebil2019/gurobi_solution_log/large_log_5.jsonl b/tasks/chebil2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fc675b6275f331a7b8f0d33f8a14bfc7c9e2dfb9 --- /dev/null +++ b/tasks/chebil2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d89b99c9998db2886928c72d50dc18818cd82835e6d128cfa581efa2de9c4988 +size 41 diff --git a/tasks/chebil2019/gurobi_solution_log/tiny_log.jsonl b/tasks/chebil2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0e2845f4e775bb12ae0bbb8959505c5ef0f3ab8b --- /dev/null +++ b/tasks/chebil2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14bc63a5b70ce461ce8de9db8d30d212869b8166bf2087ee9819c8dd994f50c8 +size 40 diff --git a/tasks/chebil2019/instance/large_instance_1.json b/tasks/chebil2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..53689bbfdccdf565454acc6481e949f571cc1fe1 --- /dev/null +++ b/tasks/chebil2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a04d0b58db2bd818ee55572c8b633baaa5d62367d9ddd5513e117207eacb1091 +size 4709520 diff --git a/tasks/chebil2019/instance/large_instance_2.json b/tasks/chebil2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..118a6be4c31ede600718ca60599cc609b7be5805 --- /dev/null +++ b/tasks/chebil2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5627cc620d886665f3b119c50c3dd27fb2cde597ae5c1141716551b8606d6b6 +size 4892480 diff --git a/tasks/chebil2019/instance/large_instance_3.json b/tasks/chebil2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..663dbb6078a004f79c50906d9e2db9e4df90336a --- /dev/null +++ b/tasks/chebil2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2175f6b357b9e6cdc00e6147a768ba832a1bb6c3412f5c423b432a63d2db705e +size 4893963 diff --git a/tasks/chebil2019/instance/large_instance_4.json b/tasks/chebil2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2e881c38198ecee474b0e717798d0d04e5f66f05 --- /dev/null +++ b/tasks/chebil2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4af1bd926495e9118caf62a0a7b73f7c458c26224140275f994358975f587fb +size 4703404 diff --git a/tasks/chebil2019/instance/large_instance_5.json b/tasks/chebil2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9c88f722c3b89738531936e05693097bcd3b9868 --- /dev/null +++ b/tasks/chebil2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5bdc631d020061c39e1e1c744c71c53123337085f2a83c4a04a845385eb2ccd +size 4703923 diff --git a/tasks/chebil2019/instance/tiny_instance.json b/tasks/chebil2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..cf64e578c9c43999a1637f943c864a54b64fb860 --- /dev/null +++ b/tasks/chebil2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8efaa0b85592b30e80318c664a81784eed9e620c4c9c809b52b23257b8509d23 +size 47415 diff --git a/tasks/chebil2019/instance_schema.json b/tasks/chebil2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b20453b8056e7f110c2f8499ec2392c0cbf0fd56 --- /dev/null +++ b/tasks/chebil2019/instance_schema.json @@ -0,0 +1,19 @@ +{ + "N": " Number of item families available for selection.", + "knapsack_capacity": " Maximum total weight the knapsack can hold, including both item weights and family setup capacity consumptions.", + "families": [ + { + "family_id": " Unique identifier for this family.", + "n_i": " Number of items belonging to this family.", + "setup_cost": " Fixed cost subtracted from profit when this family is activated.", + "setup_capacity": " Knapsack capacity consumed when this family is activated.", + "items": [ + { + "item_id": " Unique identifier for this item within its family.", + "weight": " Knapsack capacity consumed when this item is placed in the knapsack.", + "profit": " Profit earned when this item is placed in the knapsack." + } + ] + } + ] +} diff --git a/tasks/chebil2019/mathematical_formulation.md b/tasks/chebil2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..bbfea64beb59398973ecc118fff4e3e59130cf51 --- /dev/null +++ b/tasks/chebil2019/mathematical_formulation.md @@ -0,0 +1,40 @@ +# Original Formulation: 0–1 Knapsack Problem with Setups (KPS) + +*Source: An exact approach for the 0–1 Knapsack Problem with Setups, Federico Della Croce, Fabio Salassa, Rosario Scatamacchia, 2016 (Computers and Operations Research).* + +## Sets and Parameters + +- $N$: number of families of items; $i \in \{1, \ldots, N\}$. + +- $n_i$: number of items in family $i$; $j \in \{1, \ldots, n_i\}$. + +- $b$: knapsack capacity (non-negative integer). + +- $f_i$: setup cost of family $i$ (non-negative integer). + +- $d_i$: setup capacity consumption of family $i$ (non-negative integer). + +- $p_{ij}$: profit of item $j$ of family $i$ (non-negative integer). + +- $w_{ij}$: capacity consumption (weight) of item $j$ of family $i$ (non-negative integer). + +## Decision Variables + +- $x_{ij} \in \{0,1\}$: equals $1$ if item $j$ of family $i$ is placed in the knapsack, $0$ otherwise. + +- $y_i \in \{0,1\}$: equals $1$ if the knapsack is set up to accept items belonging to family $i$, $0$ otherwise. + +## Objective + +$$\begin{align} +\text{maximize} \quad & \sum_{i=1}^{N} \sum_{j=1}^{n_i} p_{ij}\, x_{ij} - \sum_{i=1}^{N} f_i\, y_i \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{subject to} \quad & \sum_{i=1}^{N} \sum_{j=1}^{n_i} w_{ij}\, x_{ij} + \sum_{i=1}^{N} d_i\, y_i \leq b \tag{2}\\ +& x_{ij} \leq y_i \quad && \forall\, j = 1, \ldots, n_i, \quad \forall\, i = 1, \ldots, N \tag{3}\\ +& x_{ij} \in \{0,1\} \quad && \forall\, j = 1, \ldots, n_i, \quad \forall\, i = 1, \ldots, N \tag{4}\\ +& y_i \in \{0,1\} \quad && \forall\, i = 1, \ldots, N \tag{5} +\end{align}$$ diff --git a/tasks/chebil2019/problem_description.txt b/tasks/chebil2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..dacf72119121be888feb3d855d418208a86529b5 --- /dev/null +++ b/tasks/chebil2019/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +A logistics operator must pack a single knapsack whose total weight capacity is a given non-negative integer value. The available items are organized into a known number of families, and each family contains a known number of items. Every item has a profit and a weight, both given as non-negative integers. Before any item from a particular family can be placed in the knapsack, that family must first be activated. Activating a family incurs two costs: a fixed setup cost, which is subtracted from the overall profit, and a setup capacity consumption, which uses up a portion of the knapsack's weight capacity just as an item's weight would. Each family's setup cost and setup capacity consumption are given as non-negative integers. + +The operator must decide which families to activate and which individual items to place in the knapsack. An item may only be placed in the knapsack if its family has been activated. The combined weight of all selected items plus the setup capacity consumptions of all activated families must not exceed the knapsack's total capacity. The goal is to maximize the net profit, defined as the sum of the profits of all selected items minus the sum of the setup costs of all activated families. diff --git a/tasks/chebil2019/solution_logger.py b/tasks/chebil2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/chebil2019/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/chebil2019/solution_schema.json b/tasks/chebil2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3c54ed49d2020f7c0e5e5298c68ae4928ed28c4f --- /dev/null +++ b/tasks/chebil2019/solution_schema.json @@ -0,0 +1,10 @@ +{ + "objective_value": " Net profit, equal to total profit of selected items minus total setup cost of activated families.", + "families_selected": " Identifiers of families that are activated so their items become eligible to enter the knapsack.", + "items_selected": [ + { + "family": " Family to which this selected item belongs.", + "item": " Identifier of the selected item within its family." + } + ] +} diff --git a/tasks/chen1999/feasibility_check.py b/tasks/chen1999/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..da502fc8005712b5436d500630d60197d3aca122 --- /dev/null +++ b/tasks/chen1999/feasibility_check.py @@ -0,0 +1,782 @@ +""" +Feasibility checker for parallel machine scheduling solutions from +Chen & Powell (1999) "Solving Parallel Machine Scheduling Problems by Column Generation". + +Checks constraints from the mathematical formulations in the paper: + +For Weighted Completion Time problems (IP1: Eqs 2-6; IP2: Eqs 8-12): + General (non-identical) IP1: + Constraint 1 (Eq 2): Each job assigned exactly once + Constraint 2 (Eq 3): At most one first job per machine + Constraint 3 (Eq 4): Flow conservation (each job has exactly one predecessor and one successor) + Constraint 4 (Eq 5): Completion time consistency + Constraint 5 (Eq 6): Binary/integrality of assignment variables + + Identical machines IP2: + Constraint 1 (Eq 8): Each job assigned exactly once + Constraint 2 (Eq 9): Number of machines used <= m + Constraint 3 (Eq 10): Flow conservation + Constraint 4 (Eq 11): Completion time consistency + Constraint 5 (Eq 12): Binary/integrality of assignment variables + +For Weighted Tardy Jobs problems (IP1': Eqs 33-39): + Constraint 1 (Eq 33): Each job is either on-time on some machine or tardy (z_j + sum x = 1) + Constraint 2 (Eq 34): At most one first job per machine + Constraint 3 (Eq 35): Flow conservation for on-time jobs + Constraint 4 (Eq 36): Completion time consistency for on-time jobs + Constraint 5 (Eq 37): On-time jobs finish by due date (0 <= C_j <= d_j) + Constraint 6 (Eq 38): Binary/integrality of x variables + Constraint 7 (Eq 39): Binary/integrality of z variables + Constraint 8 (Eq 32, obj consistency): reported objective_value must equal + sum_{j} w_j * z_j (full recompute from the solution's tardy set). + +Since the candidate solutions represent schedules (lists of job indices per machine), +we verify the constraints by reconstructing the implied assignment and computing +completion times from the schedule. +""" + +import argparse +import json +import sys + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value',) +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('completion_times',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = (('problem_type', 'weighted_completion_time', ('schedule', 'completion_times')), ('problem_type', 'weighted_tardy_jobs', ('tardy_jobs', 'on_time_jobs'))) + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def get_processing_time(instance, job, machine): + """Get processing time of job on machine.""" + pt_2d = instance["jobs"]["processing_times"] + return pt_2d[job][machine] + + +def check_weighted_completion_time(instance, solution): + """ + Check feasibility for the total weighted completion time problem. + + For identical machines, checks constraints from IP2 (Eqs 8-12): + Constraint 1 (Eq 8): Each job assigned exactly once + Constraint 2 (Eq 9): At most m machines used + Constraint 3 (Eq 10): Flow conservation + Constraint 4 (Eq 11): Completion time consistency + Constraint 5 (Eq 12): Binary/integrality + + For non-identical machines (uniform/unrelated), checks constraints from IP1 (Eqs 2-6): + Constraint 1 (Eq 2): Each job assigned exactly once + Constraint 2 (Eq 3): At most one first job per machine + Constraint 3 (Eq 4): Flow conservation + Constraint 4 (Eq 5): Completion time consistency + Constraint 5 (Eq 6): Binary/integrality + """ + tol = 1e-5 + eps = 1e-5 + + n = instance["num_jobs"] + m = instance["num_machines"] + machine_type = instance.get("machine_type", "identical") + weights = instance["jobs"]["weights"] + + schedule = solution.get("schedule", {}) + reported_obj = solution.get("objective_value") + + violations = [] + violation_magnitudes = [] + + # Reconstruct assignment from schedule + job_assignment = {} # job -> machine + job_count = {} # job -> count of appearances + for mk, job_list in schedule.items(): + k = int(mk) + for job in job_list: + job_count[job] = job_count.get(job, 0) + 1 + job_assignment[job] = k + + # --- Constraint 1: Each job assigned exactly once --- + # IP2 Eq(8): sum_{i in B_j union {0}} x_{ij} = 1, for all j + # IP1 Eq(2): sum_{k} sum_{i in B_j^k union {0}} x_{ij}^k = 1, for all j + # This means every job must appear exactly once in the schedule. + for j in range(n): + count = job_count.get(j, 0) + if count != 1: + rhs = 1.0 + lhs = float(count) + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + if count == 0: + violations.append(f"Job {j} is not assigned to any machine") + else: + violations.append(f"Job {j} is assigned {count} times (expected exactly 1)") + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 2: Machine capacity --- + # IP2 Eq(9): sum_j x_{0j} <= m (number of machines used <= m) + # IP1 Eq(3): sum_j x_{0j}^k <= 1 for all k (at most one first job per machine) + machines_used = len([k for k, jobs in schedule.items() if len(jobs) > 0]) + + if machine_type == "identical": + # Eq(9): number of machines used <= m + lhs = float(machines_used) + rhs = float(m) + violation_amount = max(0.0, lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + violations.append( + f"Number of machines used ({machines_used}) exceeds available machines ({m})") + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + else: + # Eq(3): For each machine k, at most 1 first job + # Since the schedule is given as a list per machine, each machine has at most + # one first job by construction. But we also need to check that machine indices + # are valid (0..m-1). + for mk in schedule.keys(): + k = int(mk) + if k < 0 or k >= m: + lhs = float(k) + rhs = float(m - 1) + violation_amount = max(0.0, lhs - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Machine index {k} is out of range [0, {m-1}]") + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + # Also check that number of machines used does not exceed m + if machines_used > m: + lhs = float(machines_used) + rhs = float(m) + violation_amount = lhs - rhs + normalizer = max(abs(rhs), eps) + violations.append( + f"Number of machines used ({machines_used}) exceeds available machines ({m})") + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 3: Flow conservation --- + # IP2 Eq(10): sum_{i in B_j union {0}} x_{ij} = sum_{i in A_j union {n+1}} x_{ji}, for all j + # IP1 Eq(4): same but per machine k + # In the schedule representation, each job on a machine has exactly one predecessor + # (the previous job or the start) and one successor (the next job or the end). + # This is satisfied by construction of the list representation. We verify that + # job indices are valid (in range [0, n-1]). + for mk, job_list in schedule.items(): + k = int(mk) + for idx, job in enumerate(job_list): + if job < 0 or job >= n: + violations.append( + f"Invalid job index {job} on machine {k} (must be in [0, {n-1}])") + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(job), + "rhs": float(n - 1), + "raw_excess": max(0.0, float(job) - float(n - 1)), + "normalizer": max(abs(float(n - 1)), eps), + "ratio": max(0.0, float(job) - float(n - 1)) / max(abs(float(n - 1)), eps) + }) + + # --- Constraint 4: Completion time consistency --- + # IP2 Eq(11): C_j = p_j * x_{0j} + sum_{i in B_j} (C_i + p_j) * x_{ij}, for all j + # IP1 Eq(5): C_j = sum_k (p_{jk} * x_{0j}^k + sum_{i in B_j^k} (C_i + p_{jk}) * x_{ij}^k) + # We compute completion times from the schedule and verify against reported values + # (if available). The completion times must be non-negative. + computed_completion_times = {} + computed_obj = 0.0 + + for mk, job_list in schedule.items(): + k = int(mk) + cumulative_time = 0.0 + for job in job_list: + p_jk = get_processing_time(instance, job, k) + cumulative_time += p_jk + computed_completion_times[job] = cumulative_time + computed_obj += weights[job] * cumulative_time + + # If the solution provides completion times, check consistency + reported_completion_times = solution.get("completion_times") + if reported_completion_times is not None: + for j_str, reported_cj in reported_completion_times.items(): + j = int(j_str) + if j in computed_completion_times: + computed_cj = computed_completion_times[j] + diff = abs(computed_cj - reported_cj) + rhs = reported_cj + if diff > tol: + normalizer = max(abs(rhs), eps) + violations.append( + f"Completion time mismatch for job {j}: " + f"computed={computed_cj:.4f}, reported={reported_cj:.4f}") + violation_magnitudes.append({ + "constraint": 4, + "lhs": computed_cj, + "rhs": rhs, + "raw_excess": diff, + "normalizer": normalizer, + "ratio": diff / normalizer + }) + + # Check that all completion times are non-negative + for job, cj in computed_completion_times.items(): + if cj < -tol: + rhs = 0.0 + violation_amount = abs(cj) + normalizer = max(abs(rhs), eps) + violations.append(f"Completion time of job {job} is negative: {cj:.4f}") + violation_magnitudes.append({ + "constraint": 4, + "lhs": cj, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # Check objective value consistency + # This is not a mathematical constraint from the formulation, but a + # consistency check. Use relative tolerance for large objective values + # to avoid false positives from solver floating-point rounding. + if reported_obj is not None: + obj_diff = abs(computed_obj - reported_obj) + normalizer = max(abs(reported_obj), eps) + relative_diff = obj_diff / normalizer + if obj_diff > tol and relative_diff > tol: + rhs = float(reported_obj) + violations.append( + f"Objective value mismatch: computed={computed_obj:.4f}, " + f"reported={reported_obj}") + violation_magnitudes.append({ + "constraint": 4, + "lhs": computed_obj, + "rhs": rhs, + "raw_excess": obj_diff, + "normalizer": normalizer, + "ratio": relative_diff + }) + + # --- Constraint 5: Binary/integrality --- + # IP2 Eq(12) / IP1 Eq(6): x_{ij} in {0,1} + # In the schedule representation, assignments are inherently binary (a job is either + # in a machine's list or not). We verify that all job indices are integers. + for mk, job_list in schedule.items(): + for job in job_list: + if not isinstance(job, int): + violations.append( + f"Job index {job} on machine {mk} is not an integer") + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(job), + "rhs": round(float(job)), + "raw_excess": abs(float(job) - round(float(job))), + "normalizer": max(abs(round(float(job))), eps), + "ratio": abs(float(job) - round(float(job))) / max(abs(round(float(job))), eps) + }) + + return violations, violation_magnitudes + + +def check_weighted_tardy_jobs(instance, solution): + """ + Check feasibility for the weighted number of tardy jobs problem. + + Checks constraints from IP1' (Eqs 33-39): + Constraint 1 (Eq 33): Each job is either on-time on some machine or tardy + Constraint 2 (Eq 34): At most one first job per machine + Constraint 3 (Eq 35): Flow conservation for on-time jobs + Constraint 4 (Eq 36): Completion time consistency for on-time jobs + Constraint 5 (Eq 37): On-time jobs finish by due date (0 <= C_j <= d_j) + Constraint 6 (Eq 38): Binary/integrality of x variables + Constraint 7 (Eq 39): Binary/integrality of z variables + Constraint 8 (Eq 32, obj consistency): reported objective_value must equal + sum_{j} w_j * z_j computed from the solution's tardy set. + """ + tol = 1e-5 + eps = 1e-5 + + n = instance["num_jobs"] + m = instance["num_machines"] + machine_type = instance.get("machine_type", "identical") + weights = instance["jobs"]["weights"] + due_dates = instance["jobs"]["due_dates"] + + schedule = solution.get("schedule", {}) + reported_obj = solution.get("objective_value") + reported_tardy = solution.get("tardy_jobs") + + violations = [] + violation_magnitudes = [] + + # Determine on-time and tardy jobs from the solution + on_time_jobs_in_schedule = set() + job_assignment = {} + job_count = {} + + for mk, job_list in schedule.items(): + k = int(mk) + for job in job_list: + on_time_jobs_in_schedule.add(job) + job_count[job] = job_count.get(job, 0) + 1 + job_assignment[job] = k + + # Tardy jobs: either explicitly listed or inferred as not in any schedule + if reported_tardy is not None: + tardy_jobs = set(reported_tardy) + else: + tardy_jobs = set(range(n)) - on_time_jobs_in_schedule + + # On-time jobs: from schedule or from explicit list + reported_on_time = solution.get("on_time_jobs") + if reported_on_time is not None: + on_time_jobs = set(reported_on_time) + else: + on_time_jobs = on_time_jobs_in_schedule + + # For solutions without schedules (e.g., gurobi tardy solutions that only + # report tardy_jobs/on_time_jobs), use the on_time/tardy lists for constraint 1 + # and update job_count accordingly. + has_schedule = len(schedule) > 0 + if not has_schedule: + for j in on_time_jobs: + job_count[j] = job_count.get(j, 0) + 1 + + # --- Constraint 1 (Eq 33): sum_k sum_i x_{ij}^k + z_j = 1, for all j --- + # Each job must be either on-time (in schedule) or tardy, but not both and not missing. + for j in range(n): + in_schedule = job_count.get(j, 0) + is_tardy = 1 if j in tardy_jobs else 0 + lhs = float(in_schedule + is_tardy) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + if in_schedule == 0 and is_tardy == 0: + violations.append( + f"Job {j} is neither on-time nor tardy") + elif in_schedule > 0 and is_tardy > 0: + violations.append( + f"Job {j} is both on-time (in schedule) and marked tardy") + elif in_schedule > 1: + violations.append( + f"Job {j} appears {in_schedule} times in schedule (expected at most 1)") + else: + violations.append( + f"Job {j}: on-time count ({in_schedule}) + tardy ({is_tardy}) != 1") + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 2 (Eq 34): sum_j x_{0j}^k <= 1, for all k --- + # At most one first job per machine (satisfied by list structure). + # Also check machine indices are valid and number of machines used <= m. + machines_used = len([k for k, jobs in schedule.items() if len(jobs) > 0]) + for mk in schedule.keys(): + k = int(mk) + if k < 0 or k >= m: + lhs = float(k) + rhs = float(m - 1) + violation_amount = max(0.0, lhs - rhs) + normalizer = max(abs(rhs), eps) + violations.append(f"Machine index {k} is out of range [0, {m-1}]") + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + if machines_used > m: + lhs = float(machines_used) + rhs = float(m) + violation_amount = lhs - rhs + normalizer = max(abs(rhs), eps) + violations.append( + f"Number of machines used ({machines_used}) exceeds available machines ({m})") + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 3 (Eq 35): Flow conservation --- + # Verified by list structure. Check valid job indices. + for mk, job_list in schedule.items(): + k = int(mk) + for job in job_list: + if job < 0 or job >= n: + violations.append( + f"Invalid job index {job} on machine {k} (must be in [0, {n-1}])") + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(job), + "rhs": float(n - 1), + "raw_excess": max(0.0, float(job) - float(n - 1)), + "normalizer": max(abs(float(n - 1)), eps), + "ratio": max(0.0, float(job) - float(n - 1)) / max(abs(float(n - 1)), eps) + }) + + # --- Constraint 4 (Eq 36): Completion time consistency --- + # C_j = sum_k (p_{jk} * x_{0j}^k + sum_{i in B_j} (C_i + p_{jk}) * x_{ij}^k) + # Compute completion times from the schedule for on-time jobs. + computed_completion_times = {} + for mk, job_list in schedule.items(): + k = int(mk) + cumulative_time = 0.0 + for job in job_list: + p_jk = get_processing_time(instance, job, k) + cumulative_time += p_jk + computed_completion_times[job] = cumulative_time + + # Check against reported completion times if available + reported_completion_times = solution.get("completion_times") + if reported_completion_times is not None: + for j_str, reported_cj in reported_completion_times.items(): + j = int(j_str) + if j in computed_completion_times: + computed_cj = computed_completion_times[j] + diff = abs(computed_cj - reported_cj) + if diff > tol: + rhs = reported_cj + normalizer = max(abs(rhs), eps) + violations.append( + f"Completion time mismatch for job {j}: " + f"computed={computed_cj:.4f}, reported={reported_cj:.4f}") + violation_magnitudes.append({ + "constraint": 4, + "lhs": computed_cj, + "rhs": rhs, + "raw_excess": diff, + "normalizer": normalizer, + "ratio": diff / normalizer + }) + + # --- Constraint 5 (Eq 37): 0 <= C_j <= d_j for on-time jobs --- + for job in on_time_jobs: + if job in computed_completion_times: + cj = computed_completion_times[job] + dj = due_dates[job] + + # Check C_j >= 0 + if cj < -tol: + rhs = 0.0 + violation_amount = abs(cj) + normalizer = max(abs(rhs), eps) + violations.append( + f"Completion time of on-time job {job} is negative: {cj:.4f}") + violation_magnitudes.append({ + "constraint": 5, + "lhs": cj, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # Check C_j <= d_j + violation_amount = max(0.0, cj - dj) + if violation_amount > tol: + rhs = float(dj) + normalizer = max(abs(rhs), eps) + violations.append( + f"On-time job {job} finishes at {cj:.4f} but due date is {dj} " + f"(exceeds by {violation_amount:.4f})") + violation_magnitudes.append({ + "constraint": 5, + "lhs": cj, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer + }) + + # --- Constraint 6 (Eq 38): Binary x variables --- + # Satisfied by construction of list-based schedule. + for mk, job_list in schedule.items(): + for job in job_list: + if not isinstance(job, int): + violations.append( + f"Job index {job} on machine {mk} is not an integer") + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(job), + "rhs": round(float(job)), + "raw_excess": abs(float(job) - round(float(job))), + "normalizer": max(abs(round(float(job))), eps), + "ratio": abs(float(job) - round(float(job))) / max(abs(round(float(job))), eps) + }) + + # --- Constraint 7 (Eq 39): Binary z variables --- + # z_j in {0,1}: each job is either tardy or not. Verified by checking + # no job is both on-time and tardy (already checked in constraint 1). + # Nothing additional to check here beyond constraint 1. + + # --- Constraint 8 (Eq 32, obj consistency): reported objective_value must + # equal sum_{j} w_j * z_j. The tardy set z is fully present in the solution + # (or unambiguously inferable from on_time_jobs / schedule), so this is a + # full recompute rather than a lower bound. Tier C defense against + # candidates that lie about objective_value (e.g. obj=0 or obj=MAX_FLOAT) + # while leaving the constraint-level structure feasible. + 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(weights[j] for j in tardy_jobs + if 0 <= j < n)) + obj_diff = abs(reported - true_obj) + # weights are integer and the objective is an integer sum; + # tighten to 0.5 so any integer-magnitude mismatch fires, with + # a relative floor for very large recomputed values. + obj_tol = max(0.5, 1e-6 * abs(true_obj)) + if obj_diff > obj_tol: + rhs = reported + normalizer = max(abs(rhs), eps) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum_j w_j*z_j=" + f"{true_obj} (|diff|={obj_diff:.4g}, tol={obj_tol:.4g})") + violation_magnitudes.append({ + "constraint": 8, + "lhs": true_obj, + "rhs": rhs, + "raw_excess": obj_diff, + "normalizer": normalizer, + "ratio": obj_diff / normalizer + }) + + return violations, violation_magnitudes + + +def check_feasibility(instance, solution): + """Dispatch on problem_type and return a result dict matching main()'s output.""" + problem_type = instance.get( + "problem_type", + solution.get("problem_type", "weighted_completion_time")) + + if problem_type == "weighted_completion_time": + violations, violation_magnitudes = check_weighted_completion_time(instance, solution) + elif problem_type in ("weighted_tardy_jobs", "weighted_number_of_tardy_jobs"): + violations, violation_magnitudes = check_weighted_tardy_jobs(instance, solution) + else: + violations = [f"Unknown problem type: {problem_type}"] + violation_magnitudes = [] + + violated_constraints = sorted(set( + vm["constraint"] for vm in violation_magnitudes + )) + feasible = len(violations) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for parallel machine scheduling solutions " + "(Chen & Powell 1999)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"{status}: {len(result['violations'])} violation(s) found") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/chen1999/gurobi_code.py b/tasks/chen1999/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c7d9bccb7bf08f4a25a504b16ba45dae9347074c --- /dev/null +++ b/tasks/chen1999/gurobi_code.py @@ -0,0 +1,633 @@ +""" +Gurobi MIP implementation for the Parallel Machine Scheduling Problem +from Chen & Powell (1999), "Solving Parallel Machine Scheduling Problems +_GUROBI_CODE_START_TIME = time.time() +by Column Generation", INFORMS Journal on Computing, 11(1):78-94. + +This implements the IP2 formulation (for identical machines P||sum w_j C_j) +with Big-M linearization for the bilinear completion time constraints. + +For non-identical machines (Q, R), it implements the IP1 formulation. + +The paper's formulation has bilinear terms C_i * x_{ij} in constraint (5)/(11). +We linearize these using McCormick envelopes with auxiliary variables L_{ij}. +""" + +import argparse +import json +import math +import sys +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load problem instance from JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def solve_weighted_completion_time(data, time_limit): + """ + Solve the total weighted completion time problem: P||sum w_j C_j, + Q||sum w_j C_j, or R||sum w_j C_j. + + Uses IP2 for identical machines, IP1 for non-identical machines. + """ + n = data["num_jobs"] + m = data["num_machines"] + machine_type = data.get("machine_type", "identical") + weights = data["jobs"]["weights"] + processing_times = data["jobs"]["processing_times"] # p[j][k] for job j, machine k + + # For identical machines, use base_processing_times + if machine_type == "identical": + base_p = data["jobs"]["base_processing_times"] + else: + base_p = None + + # Determine SWPT order for feasible predecessor sets + # SWPT: p_j/w_j non-decreasing. Ties broken by smaller index first. + jobs = list(range(n)) + + if machine_type == "identical": + # Single SWPT order for all machines + swpt_order = sorted(jobs, key=lambda j: (base_p[j] / weights[j], j)) + swpt_rank = [0] * n + for rank, j in enumerate(swpt_order): + swpt_rank[j] = rank + + # B_j = {i in N | i precedes j in SWPT order} + B = {} + for j in jobs: + B[j] = [i for i in jobs if swpt_rank[i] < swpt_rank[j]] + + # A_j = {i in N | i succeeds j in SWPT order} + A = {} + for j in jobs: + A[j] = [i for i in jobs if swpt_rank[i] > swpt_rank[j]] + else: + # For non-identical machines, SWPT order may differ per machine + # B_j^k and A_j^k defined per machine + B_k = {} + A_k = {} + for k in range(m): + swpt_order_k = sorted(jobs, key=lambda j: (processing_times[j][k] / weights[j], j)) + swpt_rank_k = [0] * n + for rank, j in enumerate(swpt_order_k): + swpt_rank_k[j] = rank + for j in jobs: + B_k[(j, k)] = [i for i in jobs if swpt_rank_k[i] < swpt_rank_k[j]] + A_k[(j, k)] = [i for i in jobs if swpt_rank_k[i] > swpt_rank_k[j]] + + # Total processing time (upper bound for completion times) + if machine_type == "identical": + P_total = sum(base_p) + else: + P_total = max(sum(processing_times[j][k] for j in jobs) for k in range(m)) + + # Big-M value for linearization + M_val = P_total + + # Create Gurobi model + model = gp.Model("PMAC_WCT") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + if machine_type == "identical": + # ============================================================ + # IP2 formulation (identical machines) + # ============================================================ + # Variables: x_{ij} for i in B_j union {0}, j in N + # x_{0j} = 1 if job j is first on some machine + # x_{ij} = 1 if job i immediately precedes job j + # Also x_{j,n+1} for flow conservation + + model.remove(model.getVars()) + model = gp.Model("PMAC_WCT") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # x[i][j]: i is the predecessor of j. i=-1 means j is first on a machine. + # j=-1 means j is last (dummy sink n+1) + x = {} + DUMMY_START = -1 + DUMMY_END = n + + # x_{0,j}: job j is first on some machine + for j in jobs: + x[(DUMMY_START, j)] = model.addVar(vtype=GRB.BINARY, name=f"x_start_{j}") + + # x_{i,j}: job i immediately before job j, for i in B_j + for j in jobs: + for i in B[j]: + x[(i, j)] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}") + + # x_{j, n+1}: job j is last on some machine + for j in jobs: + x[(j, DUMMY_END)] = model.addVar(vtype=GRB.BINARY, name=f"x_{j}_end") + + # Completion time variables + C = {} + for j in jobs: + C[j] = model.addVar(lb=0, ub=M_val, vtype=GRB.CONTINUOUS, name=f"C_{j}") + + # Linearization variables L_{ij} = C_i * x_{ij} + L = {} + for j in jobs: + for i in B[j]: + L[(i, j)] = model.addVar(lb=0, ub=M_val, vtype=GRB.CONTINUOUS, + name=f"L_{i}_{j}") + + model.update() + + # Objective: minimize sum w_j * C_j (Eq. 7) + model.setObjective( + gp.quicksum(weights[j] * C[j] for j in jobs), + GRB.MINIMIZE + ) + + # Constraint (8): each job has exactly one predecessor + # sum_{i in B_j union {0}} x_{ij} = 1, for all j in N + for j in jobs: + model.addConstr( + x[(DUMMY_START, j)] + gp.quicksum(x[(i, j)] for i in B[j]) == 1, + name=f"pred_{j}" + ) + + # Constraint (9): at most m machines start + # sum_j x_{0j} <= m + model.addConstr( + gp.quicksum(x[(DUMMY_START, j)] for j in jobs) <= m, + name="machine_limit" + ) + + # Constraint (10): flow conservation + # sum_{i in B_j union {0}} x_{ij} = sum_{i in A_j union {n+1}} x_{ji} + for j in jobs: + lhs = x[(DUMMY_START, j)] + gp.quicksum(x[(i, j)] for i in B[j]) + rhs = x[(j, DUMMY_END)] + gp.quicksum(x[(j, i)] for i in A[j]) + model.addConstr(lhs == rhs, name=f"flow_{j}") + + # Constraint (11) linearized: C_j = p_j * x_{0j} + sum_{i in B_j} (L_{ij} + p_j * x_{ij}) + # where L_{ij} = C_i * x_{ij} (linearized) + for j in jobs: + p_j = base_p[j] + model.addConstr( + C[j] == p_j * x[(DUMMY_START, j)] + + gp.quicksum(L[(i, j)] + p_j * x[(i, j)] for i in B[j]), + name=f"completion_{j}" + ) + + # McCormick linearization for L_{ij} = C_i * x_{ij}: + # L_{ij} <= C_i + # L_{ij} <= M * x_{ij} + # L_{ij} >= C_i - M * (1 - x_{ij}) + # L_{ij} >= 0 (already set as lb) + for j in jobs: + for i in B[j]: + model.addConstr(L[(i, j)] <= C[i], name=f"mc1_{i}_{j}") + model.addConstr(L[(i, j)] <= M_val * x[(i, j)], name=f"mc2_{i}_{j}") + model.addConstr(L[(i, j)] >= C[i] - M_val * (1 - x[(i, j)]), + name=f"mc3_{i}_{j}") + + else: + # ============================================================ + # IP1 formulation (non-identical machines: Q or R) + # ============================================================ + DUMMY_START = -1 + DUMMY_END = n + + x = {} + for k in range(m): + for j in jobs: + x[(DUMMY_START, j, k)] = model.addVar( + vtype=GRB.BINARY, name=f"x_start_{j}_{k}") + for j in jobs: + for i in B_k[(j, k)]: + x[(i, j, k)] = model.addVar( + vtype=GRB.BINARY, name=f"x_{i}_{j}_{k}") + for j in jobs: + x[(j, DUMMY_END, k)] = model.addVar( + vtype=GRB.BINARY, name=f"x_{j}_end_{k}") + + C = {} + for j in jobs: + C[j] = model.addVar(lb=0, ub=M_val, vtype=GRB.CONTINUOUS, name=f"C_{j}") + + L = {} + for k in range(m): + for j in jobs: + for i in B_k[(j, k)]: + L[(i, j, k)] = model.addVar( + lb=0, ub=M_val, vtype=GRB.CONTINUOUS, + name=f"L_{i}_{j}_{k}") + + model.update() + + # Objective: minimize sum w_j * C_j + model.setObjective( + gp.quicksum(weights[j] * C[j] for j in jobs), + GRB.MINIMIZE + ) + + # Constraint (2): each job assigned exactly once + for j in jobs: + model.addConstr( + gp.quicksum( + x[(DUMMY_START, j, k)] + + gp.quicksum(x[(i, j, k)] for i in B_k[(j, k)]) + for k in range(m) + ) == 1, + name=f"assign_{j}" + ) + + # Constraint (3): at most one job starts on each machine + for k in range(m): + model.addConstr( + gp.quicksum(x[(DUMMY_START, j, k)] for j in jobs) <= 1, + name=f"machine_start_{k}" + ) + + # Constraint (4): flow conservation per machine + for k in range(m): + for j in jobs: + lhs = x[(DUMMY_START, j, k)] + gp.quicksum( + x[(i, j, k)] for i in B_k[(j, k)]) + rhs = x[(j, DUMMY_END, k)] + gp.quicksum( + x[(j, i, k)] for i in A_k[(j, k)]) + model.addConstr(lhs == rhs, name=f"flow_{j}_{k}") + + # Constraint (5) linearized + for j in jobs: + model.addConstr( + C[j] == gp.quicksum( + processing_times[j][k] * x[(DUMMY_START, j, k)] + + gp.quicksum( + L[(i, j, k)] + processing_times[j][k] * x[(i, j, k)] + for i in B_k[(j, k)] + ) + for k in range(m) + ), + name=f"completion_{j}" + ) + + # McCormick linearization + for k in range(m): + for j in jobs: + for i in B_k[(j, k)]: + model.addConstr(L[(i, j, k)] <= C[i], + name=f"mc1_{i}_{j}_{k}") + model.addConstr(L[(i, j, k)] <= M_val * x[(i, j, k)], + name=f"mc2_{i}_{j}_{k}") + model.addConstr( + L[(i, j, k)] >= C[i] - M_val * (1 - x[(i, j, k)]), + name=f"mc3_{i}_{j}_{k}") + + # Optimize + model.optimize() + + # Extract solution + result = { + "problem_type": "weighted_completion_time", + "machine_type": machine_type, + "num_jobs": n, + "num_machines": m, + "status": model.Status, + "status_name": { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + }.get(model.Status, f"OTHER_{model.Status}"), + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["gap"] = model.MIPGap + + # Extract schedule + schedule = {k: [] for k in range(m)} + completion_times = {} + for j in jobs: + completion_times[j] = C[j].X + + if machine_type == "identical": + # Reconstruct schedule from x variables + # Find which jobs start on a machine + machine_assignments = _reconstruct_schedule_identical( + x, B, A, jobs, n, m, DUMMY_START, DUMMY_END) + result["schedule"] = machine_assignments + else: + machine_assignments = _reconstruct_schedule_nonidentical( + x, B_k, A_k, jobs, n, m, DUMMY_START, DUMMY_END) + result["schedule"] = machine_assignments + + result["completion_times"] = {str(j): completion_times[j] for j in jobs} + else: + result["objective_value"] = None + + return result + + +def _reconstruct_schedule_identical(x, B, A, jobs, n, m, DUMMY_START, DUMMY_END): + """Reconstruct the machine schedule from x-variable solution (identical machines).""" + schedules = [] + + # Find jobs that start a machine (x_{0,j} = 1) + start_jobs = [j for j in jobs if x[(DUMMY_START, j)].X > 0.5] + + for start_j in start_jobs: + machine_schedule = [start_j] + current = start_j + while True: + # Find successor + next_job = None + for succ in A[current]: + if (current, succ) in x and x[(current, succ)].X > 0.5: + next_job = succ + break + if next_job is None: + break + machine_schedule.append(next_job) + current = next_job + schedules.append(machine_schedule) + + return {str(i): sched for i, sched in enumerate(schedules)} + + +def _reconstruct_schedule_nonidentical(x, B_k, A_k, jobs, n, m, DUMMY_START, DUMMY_END): + """Reconstruct the machine schedule from x-variable solution (non-identical machines).""" + schedules = {} + for k in range(m): + # Find the starting job on machine k + start_job = None + for j in jobs: + if x[(DUMMY_START, j, k)].X > 0.5: + start_job = j + break + if start_job is None: + schedules[str(k)] = [] + continue + + machine_schedule = [start_job] + current = start_job + while True: + next_job = None + for succ in A_k[(current, k)]: + if (current, succ, k) in x and x[(current, succ, k)].X > 0.5: + next_job = succ + break + if next_job is None: + break + machine_schedule.append(next_job) + current = next_job + schedules[str(k)] = machine_schedule + + return schedules + + +def solve_weighted_tardy_jobs(data, time_limit): + """ + Solve the weighted number of tardy jobs problem: P||sum w_j U_j, + Q||sum w_j U_j, or R||sum w_j U_j. + + Uses the modified IP1' formulation from the paper (Section 3.1). + """ + n = data["num_jobs"] + m = data["num_machines"] + machine_type = data.get("machine_type", "identical") + weights = data["jobs"]["weights"] + processing_times = data["jobs"]["processing_times"] + due_dates = data["jobs"]["due_dates"] + + if machine_type == "identical": + base_p = data["jobs"]["base_processing_times"] + else: + base_p = None + + jobs = list(range(n)) + + # EDD order: sort by due date, ties broken by smaller index + edd_order = sorted(jobs, key=lambda j: (due_dates[j], j)) + edd_rank = [0] * n + for rank, j in enumerate(edd_order): + edd_rank[j] = rank + + # B_j = {i in N | i precedes j in EDD order} + B = {} + A = {} + for j in jobs: + B[j] = [i for i in jobs if edd_rank[i] < edd_rank[j]] + A[j] = [i for i in jobs if edd_rank[i] > edd_rank[j]] + + # Upper bound on time + if machine_type == "identical": + P_total = sum(base_p) + else: + P_total = max(sum(processing_times[j][k] for j in jobs) for k in range(m)) + + M_val = P_total + + model = gp.Model("PMAC_TARDY") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + DUMMY_START = -1 + DUMMY_END = n + + # z_j: 1 if job j is tardy + z = {} + for j in jobs: + z[j] = model.addVar(vtype=GRB.BINARY, name=f"z_{j}") + + # x_{ij}^k variables (on-time jobs only) + x = {} + for k in range(m): + for j in jobs: + x[(DUMMY_START, j, k)] = model.addVar( + vtype=GRB.BINARY, name=f"x_start_{j}_{k}") + for j in jobs: + for i in B[j]: + x[(i, j, k)] = model.addVar( + vtype=GRB.BINARY, name=f"x_{i}_{j}_{k}") + for j in jobs: + x[(j, DUMMY_END, k)] = model.addVar( + vtype=GRB.BINARY, name=f"x_{j}_end_{k}") + + # Completion time for on-time jobs + C = {} + for j in jobs: + C[j] = model.addVar(lb=0, ub=M_val, vtype=GRB.CONTINUOUS, name=f"C_{j}") + + # Linearization variables + L = {} + for k in range(m): + for j in jobs: + for i in B[j]: + L[(i, j, k)] = model.addVar( + lb=0, ub=M_val, vtype=GRB.CONTINUOUS, + name=f"L_{i}_{j}_{k}") + + model.update() + + # Objective (32): minimize sum w_j z_j + model.setObjective( + gp.quicksum(weights[j] * z[j] for j in jobs), + GRB.MINIMIZE + ) + + # Constraint (33): sum_k sum_{i in B_j union {0}} x_{ij}^k + z_j = 1 + for j in jobs: + model.addConstr( + gp.quicksum( + x[(DUMMY_START, j, k)] + + gp.quicksum(x[(i, j, k)] for i in B[j]) + for k in range(m) + ) + z[j] == 1, + name=f"cover_{j}" + ) + + # Constraint (34): sum_j x_{0j}^k <= 1 + for k in range(m): + model.addConstr( + gp.quicksum(x[(DUMMY_START, j, k)] for j in jobs) <= 1, + name=f"machine_start_{k}" + ) + + # Constraint (35): flow conservation + for k in range(m): + for j in jobs: + lhs = x[(DUMMY_START, j, k)] + gp.quicksum( + x[(i, j, k)] for i in B[j]) + rhs = x[(j, DUMMY_END, k)] + gp.quicksum( + x[(j, i, k)] for i in A[j]) + model.addConstr(lhs == rhs, name=f"flow_{j}_{k}") + + # Constraint (36) linearized: completion time + for j in jobs: + p_j_terms = [] + for k in range(m): + p_jk = processing_times[j][k] + p_j_terms.append( + p_jk * x[(DUMMY_START, j, k)] + + gp.quicksum( + L[(i, j, k)] + p_jk * x[(i, j, k)] + for i in B[j] + ) + ) + model.addConstr(C[j] == gp.quicksum(p_j_terms), name=f"completion_{j}") + + # Constraint (37): 0 <= C_j <= d_j (for on-time jobs) + # If z_j = 1 (tardy), C_j = 0 (all x's are 0) + # If z_j = 0 (on-time), C_j <= d_j + for j in jobs: + model.addConstr(C[j] <= due_dates[j] * (1 - z[j]), name=f"due_{j}") + + # McCormick linearization + for k in range(m): + for j in jobs: + for i in B[j]: + model.addConstr(L[(i, j, k)] <= C[i], + name=f"mc1_{i}_{j}_{k}") + model.addConstr(L[(i, j, k)] <= M_val * x[(i, j, k)], + name=f"mc2_{i}_{j}_{k}") + model.addConstr( + L[(i, j, k)] >= C[i] - M_val * (1 - x[(i, j, k)]), + name=f"mc3_{i}_{j}_{k}") + + model.optimize() + + result = { + "problem_type": "weighted_tardy_jobs", + "machine_type": machine_type, + "num_jobs": n, + "num_machines": m, + "status": model.Status, + "status_name": { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.INFEASIBLE: "INFEASIBLE", + }.get(model.Status, f"OTHER_{model.Status}"), + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["gap"] = model.MIPGap + + tardy = [j for j in jobs if z[j].X > 0.5] + on_time = [j for j in jobs if z[j].X < 0.5] + result["tardy_jobs"] = tardy + result["on_time_jobs"] = on_time + result["total_tardy_weight"] = sum(weights[j] for j in tardy) + else: + result["objective_value"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi MIP solver for Parallel Machine Scheduling (Chen & Powell 1999)") + 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) + + problem_type = data.get("problem_type", "weighted_completion_time") + + if problem_type == "weighted_completion_time": + result = solve_weighted_completion_time(data, args.time_limit) + elif problem_type == "weighted_tardy_jobs": + result = solve_weighted_tardy_jobs(data, args.time_limit) + else: + print(f"Error: Unknown problem type '{problem_type}'") + sys.exit(1) + + # Ensure objective_value is at the top level + if result.get("objective_value") is not None: + # Round to avoid floating point noise for integer-valued objectives + result["objective_value"] = round(result["objective_value"], 6) + + # Write solution + with open(args.solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"\nSolution written to: {args.solution_path}") + if result.get("objective_value") is not None: + print(f"Objective value: {result['objective_value']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/chen1999/gurobi_feasi_result/large_feasi_result_1.json b/tasks/chen1999/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chen1999/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/chen1999/gurobi_feasi_result/large_feasi_result_2.json b/tasks/chen1999/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chen1999/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/chen1999/gurobi_feasi_result/large_feasi_result_3.json b/tasks/chen1999/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chen1999/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/chen1999/gurobi_feasi_result/large_feasi_result_4.json b/tasks/chen1999/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chen1999/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/chen1999/gurobi_feasi_result/large_feasi_result_5.json b/tasks/chen1999/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chen1999/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/chen1999/gurobi_feasi_result/tiny_feasi_result.json b/tasks/chen1999/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/chen1999/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/chen1999/gurobi_solution/large_solution_1.json b/tasks/chen1999/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f2a14259ccf4994f5877314019cd77dc45107d7b --- /dev/null +++ b/tasks/chen1999/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:324f3363b39f53525e47fb0a5ee10b88b2eddf883218f9b67be0a27ed0eca24c +size 1127 diff --git a/tasks/chen1999/gurobi_solution/large_solution_2.json b/tasks/chen1999/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..bcc25866ab48c2e0eb80d9717a3f6c6ab7d790dc --- /dev/null +++ b/tasks/chen1999/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c12a1341de11a65ddb11feaabf72d3185997c011379ce9be224408687f49d0df +size 1129 diff --git a/tasks/chen1999/gurobi_solution/large_solution_3.json b/tasks/chen1999/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d68c297b2ea0b5e4c4639c6e9fd7bc47fffb6dc9 --- /dev/null +++ b/tasks/chen1999/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:835d0994a6ec28523b88a31b98498fd65e67df0c34e76401564bae17750cf379 +size 1128 diff --git a/tasks/chen1999/gurobi_solution/large_solution_4.json b/tasks/chen1999/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..500fb678f71178431ca64001b907d7e7e0d1267a --- /dev/null +++ b/tasks/chen1999/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:664dffea566491d6082c0f7a84a23be5df6ed0e581def22e1f4233cda4747057 +size 1099 diff --git a/tasks/chen1999/gurobi_solution/large_solution_5.json b/tasks/chen1999/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7407a9e833e23b866b53157191204418caa455f0 --- /dev/null +++ b/tasks/chen1999/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0425bad805ec866ee1f77296a6a493f336aa2f0c94f0145d0a9233ec575f585 +size 1100 diff --git a/tasks/chen1999/gurobi_solution/tiny_solution.json b/tasks/chen1999/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..c4054281427b71669aa74f8877798adfbb54412d --- /dev/null +++ b/tasks/chen1999/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b69adcc68d0c39c583efd421de09597b659278dc94cd6da8d164ecf73d1787e2 +size 958 diff --git a/tasks/chen1999/gurobi_solution_log/large_log_1.jsonl b/tasks/chen1999/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e8ff1f2464dc9f0ab1f9e12338922c1c7d1ad233 --- /dev/null +++ b/tasks/chen1999/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62e9e523b7a1d1f83733961256e87c6de00194d95021a8773eab3cca3a44c70f +size 1018 diff --git a/tasks/chen1999/gurobi_solution_log/large_log_2.jsonl b/tasks/chen1999/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5577b98b42cf037bd2b181daae1f17998b205f27 --- /dev/null +++ b/tasks/chen1999/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7397be3db720337cd44cbdbf7d3e3b9f78fd35abc50f897f8f4d06a8a9281b78 +size 1160 diff --git a/tasks/chen1999/gurobi_solution_log/large_log_3.jsonl b/tasks/chen1999/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4c9cc5f34a58b83e0cea7921bb19ea879c7d8bf7 --- /dev/null +++ b/tasks/chen1999/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ae615fbc74dfe75d7cce7fca55030d3233ce8b30dafc03deab8c4f5b32ae2ec +size 691 diff --git a/tasks/chen1999/gurobi_solution_log/large_log_4.jsonl b/tasks/chen1999/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5d19613acdd8ea3901c1cbe9697666b6f7e6bd4e --- /dev/null +++ b/tasks/chen1999/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bda2ab568e3cdabe5512fae43d73a30b1b9ca5392bf24c9d0602b9ec1235607 +size 342 diff --git a/tasks/chen1999/gurobi_solution_log/large_log_5.jsonl b/tasks/chen1999/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..38979e1c32b9338551a0c544a0fdbafd5839b7e6 --- /dev/null +++ b/tasks/chen1999/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0016fdc387a4c5a8e9e3ba09e0a5e3ce9540b453b0f905e9804ce1f75a4248df +size 310 diff --git a/tasks/chen1999/gurobi_solution_log/tiny_log.jsonl b/tasks/chen1999/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a28689f66f30487b6a5ba27fdc311c55b976e163 --- /dev/null +++ b/tasks/chen1999/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:314715265a3f325c276d7dee43fc5e1c14308a953f9c07b8f9cd1b8172041a2a +size 274 diff --git a/tasks/chen1999/instance/large_instance_1.json b/tasks/chen1999/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e20046c15fcabebfb96013b73edf27b667a9658e --- /dev/null +++ b/tasks/chen1999/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:475b322b72875665314519dbe82424323cba3f8b753e487d88fd97ada057c82b +size 18864 diff --git a/tasks/chen1999/instance/large_instance_2.json b/tasks/chen1999/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..696f81b7cef327aa37d6f56e902ba51f86fd6b01 --- /dev/null +++ b/tasks/chen1999/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b7e1c59cce67dab9525a4708e884dc8b5409af7aa5eca8a94f0e28f152ba47d +size 17282 diff --git a/tasks/chen1999/instance/large_instance_3.json b/tasks/chen1999/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..5adaf1c28eb65390bdad38515736834d5a6bf65a --- /dev/null +++ b/tasks/chen1999/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be2a7ae4cc7627c56db9b214cd32d57bd6f5673680b578c6a2114298ca9e95af +size 17111 diff --git a/tasks/chen1999/instance/large_instance_4.json b/tasks/chen1999/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ea4d0f1ae4a50e17568a10bbd306fb4acd994147 --- /dev/null +++ b/tasks/chen1999/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c1b6312e2b383870848c767a74ec8d8b1049745953f57d62aceb63816b94da8 +size 17345 diff --git a/tasks/chen1999/instance/large_instance_5.json b/tasks/chen1999/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..22b69d6b0f22a02bd4a4e132c31fbcc647bfc1f7 --- /dev/null +++ b/tasks/chen1999/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edffd5e1877f0e3e686fe839e9eb2d50f4980a0ab1936eda20d9e338b3110582 +size 17313 diff --git a/tasks/chen1999/instance/tiny_instance.json b/tasks/chen1999/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..6898a3608fdbdc5790d2d177e1c2dd8eb0f61fe1 --- /dev/null +++ b/tasks/chen1999/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99af1d2045630c9c6238c1261fb819064ad1c86b73a04cb469387cf2491c25c9 +size 1792 diff --git a/tasks/chen1999/instance_schema.json b/tasks/chen1999/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..ec66a8aa763795d0556afc9a46cf514ddc8eb28c --- /dev/null +++ b/tasks/chen1999/instance_schema.json @@ -0,0 +1,17 @@ +{ + "problem_type": " Scheduling variant, either 'weighted_completion_time' or 'weighted_tardy_jobs'.", + "machine_type": " Machine environment: 'identical' (same speed), 'uniform' (speed factors), or 'unrelated' (independent times).", + "objective": " Objective function: 'minimize_total_weighted_completion_time' or 'minimize_weighted_number_of_tardy_jobs'.", + "num_jobs": " Total number of jobs to be scheduled.", + "num_machines": " Total number of parallel machines available.", + "congestion_parameter_q": " Controls the tightness of due dates for the tardy-jobs variant; null for the completion-time variant.", + "machines": { + "speeds": " Speed factor of each machine for uniform machines; null for identical or unrelated machines." + }, + "jobs": { + "weights": " Priority weight of each job, used in the objective function.", + "processing_times": " Time required to process each job on each machine.", + "base_processing_times": " Inherent processing time of each job before applying machine speed factors; null for unrelated machines.", + "due_dates": " Deadline by which each job should be completed for the tardy-jobs variant; null for the completion-time variant." + } +} diff --git a/tasks/chen1999/mathematical_formulation.md b/tasks/chen1999/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..c3b1eb45017525d8f8567ab67d1ec72770ea03ad --- /dev/null +++ b/tasks/chen1999/mathematical_formulation.md @@ -0,0 +1,61 @@ +# Original Formulation: Parallel Machine Scheduling with an Additive Criterion (PMAC) + +*Source: Solving Parallel Machine Scheduling Problems by Column Generation, Zhi-Long Chen and Warren B. Powell, 1999 (INFORMS Journal on Computing 11(1):78–94).* + +The paper studies the general PMAC problem of scheduling $n$ jobs on $m$ parallel machines (identical $P$, uniform $Q$, or unrelated $R$) to minimize an additive criterion $\sum_{j\in N} f_j(C_j)$. The first and defining formulation, written in Section 1.1 (“Integer Programming Formulation”), is **IP1** (Eqs. (1)–(6)); its notation $x_{ij}^k$, $C_j$ is carried into every later section. The set-partitioning forms SP1/SP2 (Section 1.2) are a Dantzig–Wolfe decomposition used by the algorithm and are therefore not part of the original formulation. + +## Sets and Indices + +$$\begin{align*} +N &= \{1,2,\dots,n\} && \text{set of jobs};\quad i,j \in N \\ +M &= \{1,2,\dots,m\} && \text{set of machines};\quad k \in M \\ +0,\, n+1 && && \text{dummy ``start'' and ``end'' jobs on a machine} \\ +A_j^k &= \{i \in N \mid i \text{ can succeed } j \text{ in a feasible partial schedule on machine } k\} \\ +B_j^k &= \{i \in N \mid i \text{ can precede } j \text{ in a feasible partial schedule on machine } k\} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +p_{ij} &: \text{processing time of job } i \text{ on machine } j \quad + (p_{ij}=p_i \text{ for } P;\ p_{ij}=p_i/s_j \text{ for } Q;\ \text{arbitrary for } R) \\ +s_j &: \text{speed of machine } j \quad (\text{uniform machines}) \\ +w_i &: \text{weight of job } i \\ +d_i &: \text{due date of job } i \\ +f_j(\cdot) &: \text{real-valued additive cost function for job } j +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x_{ij}^k &\in \{0,1\}, \quad i,j\in N,\ k\in M: + && = 1 \text{ if job } j \text{ is processed immediately after job } i \text{ on machine } k \\ +x_{0j}^k &\in \{0,1\}, \quad j\in N,\ k\in M: + && = 1 \text{ if job } j \text{ is processed first on machine } k \\ +x_{j,n+1}^k &\in \{0,1\}, \quad j\in N,\ k\in M: + && = 1 \text{ if job } j \text{ is processed last on machine } k \\ +C_j &\ge 0, \quad j\in N: && \text{completion time of job } j +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad \sum_{j \in N} f_j(C_j) \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{k \in M} \sum_{i \in B_j^k \cup \{0\}} x_{ij}^k &= 1, + && \forall j \in N \tag{2}\\[2pt] +\sum_{j \in N} x_{0j}^k &\le 1, + && \forall k \in M \tag{3}\\[2pt] +\sum_{i \in B_j^k \cup \{0\}} x_{ij}^k &= + \sum_{i \in A_j^k \cup \{n+1\}} x_{ji}^k, + && \forall j \in N,\ k \in M \tag{4}\\[2pt] +C_j &= \sum_{k \in M}\!\left( p_{jk}\, x_{0j}^k + + \sum_{i \in B_j^k} (C_i + p_{jk})\, x_{ij}^k \right), + && \forall j \in N \tag{5}\\[2pt] +x_{ij}^k &\in \{0,1\}, + && \forall i,j \in N,\ k \in M \tag{6} +\end{align}$$ diff --git a/tasks/chen1999/problem_description.txt b/tasks/chen1999/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e74da30d8fbf59232ce103ef58c09350c6b0a92 --- /dev/null +++ b/tasks/chen1999/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A facility must schedule a set of jobs across a set of parallel machines. Each job has a known weight representing its priority or importance, and each job must be processed on exactly one machine without preemption. All jobs are available for processing at time zero. The machines may be identical, uniform, or unrelated. When machines are identical, every job has the same processing time regardless of which machine it is assigned to. When machines are uniform, each machine has a characteristic speed, and the processing time of a job on a given machine equals the job's base processing time divided by that machine's speed. When machines are unrelated, the processing time of each job on each machine is an independent value with no structured relationship across machines. + +Two scheduling objectives are considered, and each instance specifies which one applies. In the first variant, the goal is to minimize the total weighted completion time, defined as the sum over all jobs of each job's weight multiplied by its completion time. The completion time of a job equals the sum of the processing times of all jobs that finish no later than it on the same machine, including itself. Any sequencing of the jobs on a machine is feasible; the planner is free to choose any order. + +In the second variant, each job additionally has a due date, and a job is considered tardy if its completion time exceeds its due date. The goal is to minimize the weighted number of tardy jobs, defined as the sum of the weights of all tardy jobs. Any sequencing of jobs on each machine is feasible; the planner decides which jobs to complete on time and in what order, with all other jobs left tardy and contributing their weight to the objective. + +The input data for each instance specifies the number of jobs, the number of machines, the weight of each job, and the processing time of each job on each machine. For uniform machines the input additionally provides the base processing times and machine speeds. For the tardy-jobs variant the input additionally provides a due date for each job and a congestion parameter that was used to generate those due dates. + +The scheduler must assign every job to exactly one machine and determine the processing order of the jobs on each machine. Each machine processes at most one job at a time, and each machine's workload forms a single contiguous sequence starting from time zero. The completion time of the first job on a machine equals its processing time on that machine; the completion time of each subsequent job equals the completion time of the preceding job on that machine plus the current job's processing time on that machine. At most one schedule (possibly empty) is selected per machine. In the first variant, every job appears in exactly one machine's schedule. In the second variant, each job is either included in exactly one machine's on-time schedule or is designated as tardy; only on-time jobs appear in machine schedules and contribute to completion-time accounting. diff --git a/tasks/chen1999/solution_logger.py b/tasks/chen1999/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/chen1999/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/chen1999/solution_schema.json b/tasks/chen1999/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c09934d97a9a03f586df5ace7d06f2f957aed651 --- /dev/null +++ b/tasks/chen1999/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Total weighted completion time of all jobs, or total weight of tardy jobs, depending on which scheduling objective the instance specifies.", + "schedule": " Ordered list of job indices assigned to each machine, in the sequence they are processed starting from time zero (present for the weighted completion time variant; lists only on-time jobs for the tardy variant).", + "completion_times": " Time at which each scheduled job finishes processing on its assigned machine.", + "tardy_jobs": " Indices of the jobs left tardy in the weighted tardy jobs variant.", + "on_time_jobs": " Indices of the jobs completed by their due dates in the weighted tardy jobs variant." +} diff --git a/tasks/cherkesly2015/feasibility_check.py b/tasks/cherkesly2015/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..090ec7097d1bb9bd02b7d70ea2397219e7d63bf0 --- /dev/null +++ b/tasks/cherkesly2015/feasibility_check.py @@ -0,0 +1,721 @@ +""" +Feasibility checker for PDPTWL (Pickup and Delivery Problem with Time Windows +and Last-in-First-Out Loading). + +Based on: Cherkesly, Desaulniers, and Laporte (2015), Transportation Science. + +Checks constraints (2)-(13) from the mathematical formulation, plus +constraint (14) -- objective-consistency check (Tier C defense against +LLM score-gaming exploits that fabricate objective_value). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + 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_instance(data): + """Preprocess instance data into convenient structures.""" + n = data["n_requests"] + n_nodes = data["n_nodes"] + Q = data["vehicle_capacity"] + + nodes = {} + for nd in data["nodes"]: + nodes[nd["node_id"]] = nd + + P = set(range(1, n + 1)) + D = set(range(n + 1, 2 * n + 1)) + depot_o = 0 + depot_d = 2 * n + 1 + + arc_cost = {} + arc_time = {} + arc_set = set() + for arc in data["arcs"]: + i, j = arc["from"], arc["to"] + arc_set.add((i, j)) + arc_cost[(i, j)] = arc["cost"] + arc_time[(i, j)] = arc["travel_time"] + + return { + "n": n, + "n_nodes": n_nodes, + "Q": Q, + "nodes": nodes, + "P": P, + "D": D, + "depot_o": depot_o, + "depot_d": depot_d, + "arc_set": arc_set, + "arc_cost": arc_cost, + "arc_time": arc_time, + "vehicle_fixed_cost": data.get("vehicle_fixed_cost", 0), + } + + +def check_feasibility(inst, solution): + """ + Check all hard constraints (2)-(13) from the formulation plus + constraint (14) objective-consistency check. + Returns (feasible, violated_constraints, violations, violation_magnitudes). + """ + tol = 1e-5 + eps = 1e-5 + + n = inst["n"] + Q = inst["Q"] + P = inst["P"] + D = inst["D"] + depot_o = inst["depot_o"] + depot_d = inst["depot_d"] + nodes = inst["nodes"] + arc_set = inst["arc_set"] + arc_cost = inst["arc_cost"] + arc_time = inst["arc_time"] + + routes = solution["routes"] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs, rhs, op): + """Record a constraint violation with normalized magnitude.""" + if op == "eq": + violation_amount = abs(lhs - rhs) + elif op in ("le", "lt"): + violation_amount = lhs - rhs + elif op in ("ge", "gt"): + violation_amount = rhs - lhs + else: + violation_amount = 0.0 + + if violation_amount > tol: + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ========================================================================= + # Build route structures: for each vehicle k, extract x^k, and later T^k, Q^k + # ========================================================================= + # Each route is a sequence [depot_o, ..., depot_d]. + # x^k_{ij} = 1 iff arc (i,j) is consecutive in route k. + + vehicle_routes = [] # list of dicts with route info + for route_data in routes: + seq = route_data["route_sequence"] + arcs_used = set() + for idx in range(len(seq) - 1): + arcs_used.add((seq[idx], seq[idx + 1])) + vehicle_routes.append({ + "seq": seq, + "arcs": arcs_used, + "vehicle_id": route_data["vehicle_id"], + }) + + num_vehicles = len(vehicle_routes) + + # ========================================================================= + # Constraint (2): Each pickup visited exactly once + # sum_{k in K} sum_{j in N} x^k_{ij} = 1, for all i in P + # ========================================================================= + pickup_visit_count = {i: 0 for i in P} + for vr in vehicle_routes: + seq = vr["seq"] + for node in seq: + if node in P: + pickup_visit_count[node] += 1 + + for i in sorted(P): + count = pickup_visit_count[i] + if abs(count - 1) > tol: + record_violation( + 2, + f"Constraint (2): Pickup node {i} visited {count} time(s) (expected exactly 1)", + float(count), 1.0, "eq" + ) + + # ========================================================================= + # Constraint (3): Pairing - pickup i and delivery n+i on same vehicle + # sum_{j} x^k_{ij} - sum_{j} x^k_{n+i,j} = 0, for all i in P, k in K + # ========================================================================= + for vr in vehicle_routes: + seq = vr["seq"] + vid = vr["vehicle_id"] + nodes_in_route = set(seq) + for i in sorted(P): + pickup_in = 1 if i in nodes_in_route else 0 + delivery_in = 1 if (n + i) in nodes_in_route else 0 + diff = pickup_in - delivery_in + if abs(diff) > tol: + record_violation( + 3, + f"Constraint (3): Vehicle {vid} has pickup {i} (present={pickup_in}) " + f"but delivery {n + i} (present={delivery_in})", + float(pickup_in), float(delivery_in), "eq" + ) + + # ========================================================================= + # Constraint (4): Each vehicle leaves the origin depot + # sum_{j in N} x^k_{0,j} = 1, for all k in K + # ========================================================================= + for vr in vehicle_routes: + seq = vr["seq"] + vid = vr["vehicle_id"] + if len(seq) < 2 or seq[0] != depot_o: + count_from_depot = 0 + else: + # Count arcs from depot_o used by this vehicle + count_from_depot = sum(1 for (a, b) in vr["arcs"] if a == depot_o) + if abs(count_from_depot - 1) > tol: + record_violation( + 4, + f"Constraint (4): Vehicle {vid} has {count_from_depot} arc(s) from " + f"origin depot (expected 1)", + float(count_from_depot), 1.0, "eq" + ) + + # ========================================================================= + # Constraint (5): Flow conservation at P ∪ D nodes + # sum_{j} x^k_{ji} - sum_{j} x^k_{ij} = 0, for all i in P ∪ D, k in K + # ========================================================================= + for vr in vehicle_routes: + vid = vr["vehicle_id"] + seq = vr["seq"] + # Count in-degree and out-degree for each node in P ∪ D + in_deg = {} + out_deg = {} + for (a, b) in vr["arcs"]: + out_deg[a] = out_deg.get(a, 0) + 1 + in_deg[b] = in_deg.get(b, 0) + 1 + + all_nodes_in_route = set(seq) + for node in sorted(all_nodes_in_route): + if node in P or node in D: + ind = in_deg.get(node, 0) + outd = out_deg.get(node, 0) + diff = ind - outd + if abs(diff) > tol: + record_violation( + 5, + f"Constraint (5): Vehicle {vid}, node {node}: " + f"in-degree={ind}, out-degree={outd} (should be equal)", + float(ind), float(outd), "eq" + ) + + # ========================================================================= + # Constraint (6): Each vehicle enters destination depot + # sum_{i in N} x^k_{i,2n+1} = 1, for all k in K + # ========================================================================= + for vr in vehicle_routes: + vid = vr["vehicle_id"] + count_to_depot = sum(1 for (a, b) in vr["arcs"] if b == depot_d) + if abs(count_to_depot - 1) > tol: + record_violation( + 6, + f"Constraint (6): Vehicle {vid} has {count_to_depot} arc(s) to " + f"destination depot (expected 1)", + float(count_to_depot), 1.0, "eq" + ) + + # ========================================================================= + # Constraint (7): LIFO loading constraints + # The LIFO policy requires that deliveries happen in reverse order of + # pickups. If pickup i is picked up after pickup j on the same route, + # then i must be delivered before j. + # ========================================================================= + for vr in vehicle_routes: + vid = vr["vehicle_id"] + seq = vr["seq"] + # Track pickup order using a stack + stack = [] + for node in seq: + if node in P: + stack.append(node) + elif node in D: + req = node - n + if req in stack: + if stack[-1] != req: + # LIFO violation: req is not on top of stack + # Find its position + pos = stack.index(req) + top = stack[-1] + # The LHS is the number of arcs used in the infeasible + # sub-path; RHS is |N(R)| - 2. We approximate the + # violation: LHS = 1 (violation exists), RHS = 0 (should + # not happen). + record_violation( + 7, + f"Constraint (7): Vehicle {vid}, LIFO violation: " + f"request {req} delivered but request {top} " + f"(picked up later) is still on board", + 1.0, 0.0, "le" + ) + # Remove from stack wherever it is + stack.remove(req) + + # ========================================================================= + # Compute T^k_i and Q^k_i for each vehicle route + # We simulate the route to get arrival times and loads. + # ========================================================================= + route_times = [] # list of dicts: node_id -> arrival time + route_loads = [] # list of dicts: node_id -> load upon leaving + + for vr in vehicle_routes: + seq = vr["seq"] + vid = vr["vehicle_id"] + times = {} + loads = {} + + current_time = nodes[depot_o]["tw_early"] + current_load = 0 + times[seq[0]] = current_time + loads[seq[0]] = current_load # load upon leaving depot is 0 + + for idx in range(1, len(seq)): + prev = seq[idx - 1] + curr = seq[idx] + s_prev = nodes[prev]["service_time"] + t_arc = arc_time.get((prev, curr), None) + + if t_arc is None: + # Compute Euclidean distance as fallback + xi, yi = nodes[prev]["x"], nodes[prev]["y"] + xj, yj = nodes[curr]["x"], nodes[curr]["y"] + t_arc = math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2) + + arrival = current_time + s_prev + t_arc + # Respect earliest time window + service_start = max(arrival, nodes[curr]["tw_early"]) + times[curr] = service_start + + current_load += nodes[curr]["load"] + loads[curr] = current_load + current_time = service_start + + route_times.append(times) + route_loads.append(loads) + + # ========================================================================= + # Constraint (8): Load propagation + # Q^k_j >= Q^k_i + q_j (when arc (i,j) is used by vehicle k) + # Linearized: Q^k_j >= Q^k_i + q_j - M*(1 - x^k_{ij}) + # When x^k_{ij} = 1: Q^k_j >= Q^k_i + q_j + # ========================================================================= + for k, vr in enumerate(vehicle_routes): + seq = vr["seq"] + vid = vr["vehicle_id"] + for idx in range(len(seq) - 1): + i_node = seq[idx] + j_node = seq[idx + 1] + Qk_i = route_loads[k].get(i_node, 0) + Qk_j = route_loads[k].get(j_node, 0) + q_j = nodes[j_node]["load"] + rhs_val = Qk_i + q_j + # Qk_j >= rhs_val + if rhs_val - Qk_j > tol: + record_violation( + 8, + f"Constraint (8): Vehicle {vid}, arc ({i_node},{j_node}): " + f"Q[{j_node}]={Qk_j} < Q[{i_node}]+q[{j_node}]={rhs_val}", + float(Qk_j), float(rhs_val), "ge" + ) + + # ========================================================================= + # Constraint (9): Load bounds + # max(0, q_i) <= Q^k_i <= min(Q, Q + q_i), for all i in N, k in K + # ========================================================================= + for k, vr in enumerate(vehicle_routes): + seq = vr["seq"] + vid = vr["vehicle_id"] + for node in seq: + Qk_i = route_loads[k].get(node, 0) + q_i = nodes[node]["load"] + lb = max(0, q_i) + ub = min(Q, Q + q_i) + if Qk_i < lb - tol: + record_violation( + 9, + f"Constraint (9): Vehicle {vid}, node {node}: " + f"load={Qk_i} < lower bound={lb}", + float(Qk_i), float(lb), "ge" + ) + if Qk_i > ub + tol: + record_violation( + 9, + f"Constraint (9): Vehicle {vid}, node {node}: " + f"load={Qk_i} > upper bound={ub}", + float(Qk_i), float(ub), "le" + ) + + # ========================================================================= + # Constraint (10): Time propagation + # T^k_j >= T^k_i + s_i + t_{ij} (when arc (i,j) is used by vehicle k) + # Linearized: T^k_j >= T^k_i + s_i + t_{ij} - M*(1 - x^k_{ij}) + # When x^k_{ij} = 1: T^k_j >= T^k_i + s_i + t_{ij} + # ========================================================================= + for k, vr in enumerate(vehicle_routes): + seq = vr["seq"] + vid = vr["vehicle_id"] + for idx in range(len(seq) - 1): + i_node = seq[idx] + j_node = seq[idx + 1] + Tk_i = route_times[k].get(i_node, 0) + Tk_j = route_times[k].get(j_node, 0) + s_i = nodes[i_node]["service_time"] + t_ij = arc_time.get((i_node, j_node), None) + if t_ij is None: + xi, yi = nodes[i_node]["x"], nodes[i_node]["y"] + xj, yj = nodes[j_node]["x"], nodes[j_node]["y"] + t_ij = math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2) + rhs_val = Tk_i + s_i + t_ij + if rhs_val - Tk_j > tol: + record_violation( + 10, + f"Constraint (10): Vehicle {vid}, arc ({i_node},{j_node}): " + f"T[{j_node}]={Tk_j:.2f} < T[{i_node}]+s[{i_node}]+t({i_node},{j_node})={rhs_val:.2f}", + float(Tk_j), float(rhs_val), "ge" + ) + + # ========================================================================= + # Constraint (11): Time window bounds + # w_i <= T^k_i <= w_bar_i, for all i in N, k in K + # ========================================================================= + for k, vr in enumerate(vehicle_routes): + seq = vr["seq"] + vid = vr["vehicle_id"] + for node in seq: + Tk_i = route_times[k].get(node, 0) + w_early = nodes[node]["tw_early"] + w_late = nodes[node]["tw_late"] + if Tk_i < w_early - tol: + record_violation( + 11, + f"Constraint (11): Vehicle {vid}, node {node}: " + f"T={Tk_i:.2f} < earliest={w_early}", + float(Tk_i), float(w_early), "ge" + ) + if Tk_i > w_late + tol: + record_violation( + 11, + f"Constraint (11): Vehicle {vid}, node {node}: " + f"T={Tk_i:.2f} > latest={w_late}", + float(Tk_i), float(w_late), "le" + ) + + # ========================================================================= + # Constraint (12): Pickup before delivery with minimum travel time + # T^k_i + s_i + t_{i,n+i} <= T^k_{n+i}, for all i in P, k in K + # (Only applies on vehicles that serve request i) + # ========================================================================= + for k, vr in enumerate(vehicle_routes): + seq = vr["seq"] + vid = vr["vehicle_id"] + nodes_in_route = set(seq) + for i in sorted(P): + if i in nodes_in_route and (n + i) in nodes_in_route: + Tk_i = route_times[k].get(i, 0) + Tk_ni = route_times[k].get(n + i, 0) + s_i = nodes[i]["service_time"] + t_i_ni = arc_time.get((i, n + i), None) + if t_i_ni is None: + xi, yi = nodes[i]["x"], nodes[i]["y"] + xj, yj = nodes[n + i]["x"], nodes[n + i]["y"] + t_i_ni = math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2) + lhs_val = Tk_i + s_i + t_i_ni + rhs_val = Tk_ni + if lhs_val - rhs_val > tol: + record_violation( + 12, + f"Constraint (12): Vehicle {vid}, request {i}: " + f"T[{i}]+s[{i}]+t({i},{n + i})={lhs_val:.2f} > T[{n + i}]={rhs_val:.2f}", + float(lhs_val), float(rhs_val), "le" + ) + + # ========================================================================= + # Constraint (13): Integrality / arc validity + # x^k_{ij} in {0, 1}, for all (i,j) in A, k in K + # Since the solution provides route sequences, x values are implicitly + # binary. We check that all arcs used actually belong to A. + # ========================================================================= + for vr in vehicle_routes: + vid = vr["vehicle_id"] + seq = vr["seq"] + for idx in range(len(seq) - 1): + i_node = seq[idx] + j_node = seq[idx + 1] + if (i_node, j_node) not in arc_set: + record_violation( + 13, + f"Constraint (13): Vehicle {vid} uses arc ({i_node},{j_node}) " + f"which is not in the arc set A", + 1.0, 0.0, "le" + ) + + # ========================================================================= + # Constraint (14): Objective-consistency check (Tier C defense). + # The objective (1) is min sum_{k} sum_{(i,j) in A} c_{ij} * x^k_{ij}. + # Every variable that determines this sum (the per-vehicle route + # sequences) is present in the solution, so we can do a FULL recompute. + # For arcs not in arc_cost we fall back to Euclidean distance with the + # vehicle-fixed-cost surcharge on depot-out arcs, mirroring how the + # instance generator builds c_{ij}; this only kicks in if a route uses + # an arc not in A, which constraint (13) would already flag. + # ========================================================================= + 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: + vehicle_fixed_cost = float(inst.get("vehicle_fixed_cost", 0) or 0) + # vehicle_fixed_cost lives on the raw instance dict; pull it from + # the build_instance input via a stash on inst if available, + # otherwise default to 0 (the cost is already embedded in + # arc_cost for arcs in A, so the fallback only matters for + # missing arcs). + true_obj = 0.0 + for vr in vehicle_routes: + seq = vr["seq"] + for idx in range(len(seq) - 1): + a, b = seq[idx], seq[idx + 1] + c = arc_cost.get((a, b)) + if c is None: + xi, yi = nodes[a]["x"], nodes[a]["y"] + xj, yj = nodes[b]["x"], nodes[b]["y"] + c = math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2) + if a == depot_o: + c += vehicle_fixed_cost + true_obj += float(c) + 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: + record_violation( + 14, + f"Constraint (14): Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_k sum_(i,j) c[i,j]*x^k[i,j]={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol:.3g})", + float(reported), float(true_obj), "eq" + ) + + # ========================================================================= + # Compile results + # ========================================================================= + sorted_violated = sorted(violated_constraints) + feasible = len(sorted_violated) == 0 + + return feasible, sorted_violated, violations, violation_magnitudes + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for PDPTWL solutions" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the instance JSON file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the candidate solution JSON file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the feasibility result JSON file") + args = parser.parse_args() + + 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 + inst = build_instance(data) + + feasible, violated_constraints, violations, violation_magnitudes = \ + check_feasibility(inst, solution) + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility: {feasible}") + if not feasible: + print(f"Violated constraints: {violated_constraints}") + for v in violations: + print(f" - {v}") + print(f"Result written to: {args.result_path}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/cherkesly2015/gurobi_code.py b/tasks/cherkesly2015/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..903ca4b253e6afaacbd94c0812ed8bd8292168cb --- /dev/null +++ b/tasks/cherkesly2015/gurobi_code.py @@ -0,0 +1,460 @@ +""" +Gurobi implementation of the PDPTWL (Pickup and Delivery Problem with Time Windows +and LIFO Loading) compact three-index formulation. + +Based on: Cherkesly, Desaulniers, and Laporte (2015), Transportation Science. +Formulation: Constraints (1)-(13) from the paper. + +Assumptions (inferred): + - Travel costs c_{ij} = Euclidean distance (NOT SPECIFIED IN PAPER whether rounded). + We use the costs provided in the instance JSON directly. + - Travel times t_{ij} provided in the instance JSON directly. + - Vehicle fixed cost is included in c_{0,j} arcs (already in instance data). + - Big-M linearization used for constraints (8) and (10). + +Full LIFO is enforced by exact lazy separation of every incumbent route that +contains a pickup/pickup/delivery pattern inconsistent with stack order. +""" + +import argparse +import json +import math +import time +from itertools import combinations + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load problem instance from JSON file.""" + with open(path, "r") as f: + data = json.load(f) + return data + + +def lifo_lazy_callback(model, where): + """Separate a minimal infeasible path for every observed LIFO violation.""" + if where != GRB.Callback.MIPSOL: + return + values = model.cbGetSolution(model._lifo_x) + for vehicle in model._lifo_vehicles: + successor = { + i: j + for (i, j) in model._lifo_arcs + if values[vehicle, i, j] > 0.5 + } + sequence = [model._lifo_origin] + while sequence[-1] in successor and len(sequence) <= model._lifo_node_count: + sequence.append(successor[sequence[-1]]) + if sequence[-1] == model._lifo_destination: + break + stack = [] + pickup_position = {} + for position, node in enumerate(sequence): + if 1 <= node <= model._lifo_request_count: + stack.append(node) + pickup_position[node] = position + continue + if not (model._lifo_request_count < node <= 2 * model._lifo_request_count): + continue + request = node - model._lifo_request_count + if request not in stack: + continue + if stack[-1] != request: + first = pickup_position[request] + path = list(zip(sequence[first:position], sequence[first + 1:position + 1])) + model.cbLazy( + gp.quicksum(model._lifo_x[vehicle, i, j] for i, j in path) + <= len(path) - 1 + ) + stack.remove(request) + + +def build_model(data, time_limit): + """Build the PDPTWL compact formulation Gurobi model.""" + + n = data["n_requests"] + n_nodes = data["n_nodes"] # 2n + 2 + Q = data["vehicle_capacity"] + planning_horizon = data["planning_horizon"] + + # Build node data + nodes = {} + for node_data in data["nodes"]: + nid = node_data["node_id"] + nodes[nid] = node_data + + P = list(range(1, n + 1)) # Pickup nodes + D = list(range(n + 1, 2 * n + 1)) # Delivery nodes + depot_o = 0 + depot_d = 2 * n + 1 + N = list(range(n_nodes)) # All nodes + + # Build arc set from instance data + arc_set = set() + arc_cost = {} + arc_time = {} + for arc in data["arcs"]: + i, j = arc["from"], arc["to"] + arc_set.add((i, j)) + arc_cost[(i, j)] = arc["cost"] + arc_time[(i, j)] = arc["travel_time"] + + A = list(arc_set) + + # Determine number of vehicles K (upper bound: n vehicles) + # The paper says K is unrestricted; we use n as an upper bound + K_size = n + K = list(range(K_size)) + + # Big-M values for linearization + M_time = planning_horizon[1] + max( + node["service_time"] for node in data["nodes"] + ) + max(arc["travel_time"] for arc in data["arcs"]) + M_load = Q + + # --- Create model --- + model = gp.Model("PDPTWL") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + model.setParam("LazyConstraints", 1) + + # --- Decision variables --- + # x[k,i,j] binary: vehicle k uses arc (i,j) + x = {} + for k in K: + for (i, j) in A: + x[k, i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{k}_{i}_{j}") + + # T[k,i] continuous: service start time at node i for vehicle k + T = {} + for k in K: + for i in N: + lb = nodes[i]["tw_early"] + ub = nodes[i]["tw_late"] + T[k, i] = model.addVar(lb=lb, ub=ub, vtype=GRB.CONTINUOUS, + name=f"T_{k}_{i}") + + # Q_var[k,i] continuous: load of vehicle k upon leaving node i + Q_var = {} + for k in K: + for i in N: + q_i = nodes[i]["load"] + lb = max(0, q_i) + ub = min(Q, Q + q_i) + Q_var[k, i] = model.addVar(lb=lb, ub=ub, vtype=GRB.CONTINUOUS, + name=f"Q_{k}_{i}") + + model.update() + + # --- Objective (1): minimize total cost --- + model.setObjective( + gp.quicksum(arc_cost[(i, j)] * x[k, i, j] + for k in K for (i, j) in A), + GRB.MINIMIZE + ) + + # --- Constraints --- + + # (2) Each pickup visited exactly once + for i in P: + outgoing = [(i, j) for (ii, j) in A if ii == i] + model.addConstr( + gp.quicksum(x[k, i, j] for k in K for (_, j) in outgoing) == 1, + name=f"visit_{i}" + ) + + # (3) Pairing: if vehicle k visits pickup i, it must visit delivery n+i + for i in P: + ni = n + i # delivery node for request i + for k in K: + out_pickup = [(i, j) for (ii, j) in A if ii == i] + out_delivery = [(ni, j) for (ii, j) in A if ii == ni] + model.addConstr( + gp.quicksum(x[k, i, j] for (_, j) in out_pickup) + - gp.quicksum(x[k, ni, j] for (_, j) in out_delivery) == 0, + name=f"pair_{i}_{k}" + ) + + # (4) Each vehicle leaves origin depot exactly once + out_depot = [(depot_o, j) for (ii, j) in A if ii == depot_o] + for k in K: + model.addConstr( + gp.quicksum(x[k, depot_o, j] for (_, j) in out_depot) == 1, + name=f"depot_out_{k}" + ) + + # (5) Flow conservation at pickup and delivery nodes + for i in P + D: + in_arcs = [(ii, i) for (ii, jj) in A if jj == i] + out_arcs = [(i, j) for (ii, j) in A if ii == i] + for k in K: + model.addConstr( + gp.quicksum(x[k, ii, i] for (ii, _) in in_arcs) + - gp.quicksum(x[k, i, j] for (_, j) in out_arcs) == 0, + name=f"flow_{i}_{k}" + ) + + # (6) Each vehicle arrives at destination depot exactly once + in_depot = [(i, depot_d) for (i, jj) in A if jj == depot_d] + for k in K: + model.addConstr( + gp.quicksum(x[k, i, depot_d] for (i, _) in in_depot) == 1, + name=f"depot_in_{k}" + ) + + # (8) Load constraints (linearized with big-M) + # Q_var[k,j] >= Q_var[k,i] + q_j - M*(1 - x[k,i,j]) + for k in K: + for (i, j) in A: + q_j = nodes[j]["load"] + model.addConstr( + Q_var[k, j] >= Q_var[k, i] + q_j - M_load * (1 - x[k, i, j]), + name=f"load_{k}_{i}_{j}" + ) + + # (9) Load bounds are set via variable bounds already + + # (10) Time constraints (linearized with big-M) + # T[k,j] >= T[k,i] + s_i + t_{ij} - M*(1 - x[k,i,j]) + for k in K: + for (i, j) in A: + s_i = nodes[i]["service_time"] + t_ij = arc_time[(i, j)] + model.addConstr( + T[k, j] >= T[k, i] + s_i + t_ij - M_time * (1 - x[k, i, j]), + name=f"time_{k}_{i}_{j}" + ) + + # (11) Time window bounds are set via variable bounds already + + # (12) Precedence: T[k,i] + s_i + t_{i,n+i} <= T[k,n+i] + for i in P: + ni = n + i + s_i = nodes[i]["service_time"] + if (i, ni) in arc_time: + t_i_ni = arc_time[(i, ni)] + else: + # Compute Euclidean distance if arc not in set + # INFERRED ASSUMPTION: direct travel time between pickup and delivery + xi, yi = nodes[i]["x"], nodes[i]["y"] + xni, yni = nodes[ni]["x"], nodes[ni]["y"] + t_i_ni = math.sqrt((xi - xni) ** 2 + (yi - yni) ** 2) + for k in K: + model.addConstr( + T[k, i] + s_i + t_i_ni <= T[k, ni], + name=f"prec_{i}_{k}" + ) + + # --- LIFO constraints (7) --- + # We add LIFO constraints via infeasible path inequalities. + # For a compact formulation, we enumerate short LIFO-violating patterns. + # A LIFO violation occurs when pickup i is visited before pickup j, + # but delivery n+j is visited before delivery n+i (i.e., j is delivered + # before i, violating the "last picked up, first delivered" rule). + # + # For each pair (i, j) in P x P with i != j, the LIFO constraint says: + # If vehicle k picks up i then j (in that order), it must deliver j before i. + # + # We enforce: for each vehicle k, for each pair i,j in P: + # x[k,i,j] = 1 implies n+j must be delivered before n+i + # This is implicitly handled by the arc structure (no arcs from pickup i + # to delivery n+j for j != i), but we add explicit LIFO ordering constraints. + # + # The arc set already excludes (i, n+j) for i in P, j in P, j != i, + # which handles direct pickup-to-wrong-delivery violations. + # For indirect violations, we add constraints for delivery ordering: + # If both i and j are onboard (picked up), then n+j must come before n+i + # if j was picked up after i. We model this with time-based constraints: + # T[k,n+j] <= T[k,n+i] + M*(2 - x[k,i,j] - (sum of x indicating j picked after i)) + # + # INFERRED ASSUMPTION: The arc structure already restricts most LIFO violations. + # For the compact formulation, the paper notes that the explicit LIFO + # constraints (7) involve exponentially many subsets. We add pairwise + # LIFO constraints as a practical compromise for the compact model. + for i in P: + for j in P: + if i == j: + continue + ni = n + i + nj = n + j + # If arc (i,j) exists (pickup i then pickup j), then delivery j + # must happen before delivery i: T[k,nj] <= T[k,ni] + if (i, j) in arc_set: + for k in K: + model.addConstr( + T[k, nj] <= T[k, ni] + M_time * (1 - x[k, i, j]), + name=f"lifo_{i}_{j}_{k}" + ) + + # --- Symmetry breaking --- + # Break symmetry between identical vehicles by ordering their first pickup + # INFERRED ASSUMPTION: Standard symmetry-breaking technique + for k in range(len(K) - 1): + # Vehicle k's departure time from depot <= vehicle k+1's departure time + model.addConstr( + T[k, depot_o] <= T[k + 1, depot_o], + name=f"sym_{k}" + ) + + model.update() + model._lifo_x = gp.tupledict(x) + model._lifo_arcs = A + model._lifo_vehicles = K + model._lifo_origin = depot_o + model._lifo_destination = depot_d + model._lifo_request_count = n + model._lifo_node_count = len(N) + return model, x, T, Q_var, A, K, N, P, D, n, depot_o, depot_d, nodes + + +def extract_solution(model, x, T, Q_var, A, K, N, P, D, n, depot_o, depot_d, nodes): + """Extract solution from solved model.""" + if model.SolCount == 0: + return None + + obj_val = model.ObjVal + + routes = [] + for k in K: + route_arcs = [] + for (i, j) in A: + if x[k, i, j].X > 0.5: + route_arcs.append((i, j)) + + if not route_arcs: + continue + + # Build route sequence from arcs + # Check if this is a non-empty route (not just depot->depot path) + visits_customer = any(i in P or i in D or j in P or j in D + for (i, j) in route_arcs) + if not visits_customer: + continue + + # Build adjacency + adj = {} + for (i, j) in route_arcs: + adj[i] = j + + # Trace route from depot_o + route = [depot_o] + current = depot_o + visited_count = 0 + while current in adj and visited_count < len(N): + nxt = adj[current] + route.append(nxt) + current = nxt + visited_count += 1 + if current == depot_d: + break + + # Get timing and load info + route_detail = [] + for node_id in route: + detail = { + "node_id": node_id, + "arrival_time": round(T[k, node_id].X, 2), + "load_after": round(Q_var[k, node_id].X, 2) + } + route_detail.append(detail) + + route_cost = sum( + model.getAttr("Obj", [x[k, i, j]])[0] * x[k, i, j].X + for (i, j) in route_arcs + ) + + routes.append({ + "vehicle_id": k, + "route_sequence": route, + "route_details": route_detail, + }) + + solution = { + "objective_value": round(obj_val, 2), + "num_vehicles": len(routes), + "status": model.Status, + "status_description": { + GRB.OPTIMAL: "optimal", + GRB.TIME_LIMIT: "time_limit", + GRB.INFEASIBLE: "infeasible", + GRB.INF_OR_UNBD: "infeasible_or_unbounded", + }.get(model.Status, f"other_{model.Status}"), + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + "best_bound": model.ObjBound if model.SolCount > 0 else None, + "lifo_enforcement": "exact_lazy_infeasible_path_separation", + "solve_time": model.Runtime, + "routes": routes, + } + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="PDPTWL Gurobi compact formulation solver" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the instance JSON file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print(f"Loading instance from: {args.instance_path}") + data = load_instance(args.instance_path) + + print(f"Building model for {data['n_requests']} requests...") + model, x, T, Q_var, A, K, N, P, D, n, depot_o, depot_d, nodes = \ + build_model(data, args.time_limit) + + print(f"Solving with time limit = {args.time_limit}s...") + model.optimize(lifo_lazy_callback) + + print(f"Status: {model.Status}, Solutions found: {model.SolCount}") + + if model.SolCount > 0: + solution = extract_solution( + model, x, T, Q_var, A, K, N, P, D, n, depot_o, depot_d, nodes + ) + print(f"Objective value: {solution['objective_value']}") + print(f"Number of vehicles: {solution['num_vehicles']}") + else: + solution = { + "objective_value": None, + "num_vehicles": None, + "status": model.Status, + "status_description": "no_solution_found", + "mip_gap": None, + "best_bound": None, + "lifo_enforcement": "exact_lazy_infeasible_path_separation", + "solve_time": model.Runtime, + "routes": [], + } + print("No feasible solution found.") + + 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 saved to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/cherkesly2015/gurobi_feasi_result/large_feasi_result_1.json b/tasks/cherkesly2015/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cherkesly2015/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/cherkesly2015/gurobi_feasi_result/large_feasi_result_2.json b/tasks/cherkesly2015/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cherkesly2015/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/cherkesly2015/gurobi_feasi_result/large_feasi_result_3.json b/tasks/cherkesly2015/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cherkesly2015/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/cherkesly2015/gurobi_feasi_result/large_feasi_result_4.json b/tasks/cherkesly2015/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cherkesly2015/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/cherkesly2015/gurobi_feasi_result/large_feasi_result_5.json b/tasks/cherkesly2015/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cherkesly2015/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/cherkesly2015/gurobi_feasi_result/tiny_feasi_result.json b/tasks/cherkesly2015/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cherkesly2015/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/cherkesly2015/gurobi_solution/large_solution_1.json b/tasks/cherkesly2015/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..957c834c9b65124831da737757aaa27ec81292bf --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6707448a8a875f0edee860e816fb940c3af4b27a7fef7d81535bc1e2d0e6559 +size 40811 diff --git a/tasks/cherkesly2015/gurobi_solution/large_solution_2.json b/tasks/cherkesly2015/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..015d348e52c018ba492240b3d045a7d821d0e69b --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6cb9a43c75273aa4fae824e3d403e01f47861b050b7e27151e2cb88abb77ac7 +size 40750 diff --git a/tasks/cherkesly2015/gurobi_solution/large_solution_3.json b/tasks/cherkesly2015/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8d3320745abbd96ec62d14e8eec11c15c5c113c6 --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:978ba6ee9a3ed208b5e049bd7d494c55b0a09ffeeebc15129a07770ebc6ff998 +size 40873 diff --git a/tasks/cherkesly2015/gurobi_solution/large_solution_4.json b/tasks/cherkesly2015/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..84b94e88a0b5a3419dc2e926519f5a963be2d90a --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c95e569cab0f88718ceb213a419b8214dc0a09ef7182008a70b62caefadaaa8 +size 40888 diff --git a/tasks/cherkesly2015/gurobi_solution/large_solution_5.json b/tasks/cherkesly2015/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e71f4d9bf6520a35554d7c2d663252062129c2d1 --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94102c08d3df759be8ccf9a3808b0e5af18cb9fb7f4078332f70226ded65031e +size 40733 diff --git a/tasks/cherkesly2015/gurobi_solution/tiny_solution.json b/tasks/cherkesly2015/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..e850499cc9ff4da2a7f8cb4e05b09363f649c6c7 --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99c0a308375334c116bc1aa7ed0d042cb8ca22baf8dbac0ff9facf60776d88e1 +size 17513 diff --git a/tasks/cherkesly2015/gurobi_solution_log/large_log_1.jsonl b/tasks/cherkesly2015/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..140b19bddf209ffb997cf991433bf40f15f18aa7 --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f044fe9168538145742bc213cbb94b0e2978824bc2aa323471189f1b341892b +size 46 diff --git a/tasks/cherkesly2015/gurobi_solution_log/large_log_2.jsonl b/tasks/cherkesly2015/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f79db219b87356055dfaec723c691bef73ebfafa --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a494a3fb4ed5df4bf911582d304d96fbcc7e94e979c3d0f60590f4b4809a6101 +size 114 diff --git a/tasks/cherkesly2015/gurobi_solution_log/large_log_3.jsonl b/tasks/cherkesly2015/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7540d3e54043f50db7d2d3f952e5cf1a8fe2fa84 --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d22b1fcd42e43dcf7ece2ac5e2f2d4eab520405aefa92c84509800d3a5ee7372 +size 46 diff --git a/tasks/cherkesly2015/gurobi_solution_log/large_log_4.jsonl b/tasks/cherkesly2015/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9afb51c326a600776de761a70562260736fba90d --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1661306a0bb1d4f3fea2ee9161f5ed7423b20c5908085282ceb44442a2e594b6 +size 46 diff --git a/tasks/cherkesly2015/gurobi_solution_log/large_log_5.jsonl b/tasks/cherkesly2015/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..349236e259ac6cd78f368f4562c34d80e7be2b64 --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3509e5434403275558c1439d0947ae5102c8ff3d309547c0a0ec9db64e106d1 +size 103 diff --git a/tasks/cherkesly2015/gurobi_solution_log/tiny_log.jsonl b/tasks/cherkesly2015/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ea7f59f6877e97cad45133fa9eba65399fa1c913 --- /dev/null +++ b/tasks/cherkesly2015/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afe1f1986a5442d05956479e9eae0ae9a4cfe980f37ed86a4d8d39f845271c8a +size 45 diff --git a/tasks/cherkesly2015/instance/large_instance_1.json b/tasks/cherkesly2015/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c69decfab780bd8cd62a7def8614d07736b3b221 --- /dev/null +++ b/tasks/cherkesly2015/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b72734d1917fc3bbca66e714f135e3618f319590c84fb7db9bed9facc773602f +size 1493201 diff --git a/tasks/cherkesly2015/instance/large_instance_2.json b/tasks/cherkesly2015/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6ac8307b82cc91c2e274afdd7c5551c57e80e2bd --- /dev/null +++ b/tasks/cherkesly2015/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fec924a23b850fb919d447bc3cdb5871f21421474d6348e4f5d8e36c601358e +size 1403844 diff --git a/tasks/cherkesly2015/instance/large_instance_3.json b/tasks/cherkesly2015/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..71daf497d12d1520c3ba4a96ae27863aa0ec48ac --- /dev/null +++ b/tasks/cherkesly2015/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2d54cab4bcbac4530031ea190e1ad6c95519e9b6a8c1a71b24bfc4b7e9c04b9 +size 1403757 diff --git a/tasks/cherkesly2015/instance/large_instance_4.json b/tasks/cherkesly2015/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..64c53ebfe8375ae9e37e549a8429b5a40fdd85e6 --- /dev/null +++ b/tasks/cherkesly2015/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fca252ba0efdd2af2434beb448cd32095147871e361f7ba84b56ab7878efd63e +size 1403607 diff --git a/tasks/cherkesly2015/instance/large_instance_5.json b/tasks/cherkesly2015/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a4bd82d65b453800df4e8cc4a8fd03f312ee86af --- /dev/null +++ b/tasks/cherkesly2015/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c2149486088cdeb8686e5e345f42f2f267b0c7694767c51a2c715159a418bad +size 1404287 diff --git a/tasks/cherkesly2015/instance/tiny_instance.json b/tasks/cherkesly2015/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..1ff5fc9e9e80a478958f5f45ef13456e47ee9cb7 --- /dev/null +++ b/tasks/cherkesly2015/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2f90d7f68bdc84e641876537644336549dc866ce434eb6a9a7d48dd4741747d +size 280504 diff --git a/tasks/cherkesly2015/instance_schema.json b/tasks/cherkesly2015/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f85f1925eee039a54d5c99a2c108ee7267eca814 --- /dev/null +++ b/tasks/cherkesly2015/instance_schema.json @@ -0,0 +1,29 @@ +{ + "n_requests": " Number of transportation requests, each requiring pickup at one location and delivery to another.", + "n_nodes": " Total number of nodes in the network, equal to 2 * n_requests + 2 (pickups, deliveries, and two depot copies).", + "vehicle_capacity": " Maximum carrying capacity of each identical vehicle.", + "planning_horizon": " Earliest and latest times defining the operational planning window.", + "vehicle_fixed_cost": " Fixed cost incurred for each vehicle used, added to arcs leaving the origin depot.", + "nodes": [ + { + "node_id": " Unique identifier for this node in the network.", + "node_type": " Role of the node: 'depot_origin', 'pickup', 'delivery', or 'depot_destination'.", + "request_id": " Identifier of the transportation request this node belongs to, or null for depot nodes.", + "x": " Horizontal geographic coordinate of the node.", + "y": " Vertical geographic coordinate of the node.", + "load": " Quantity of goods picked up (positive) or delivered (negative) at this node, zero at depots.", + "service_time": " Duration of the service operation performed at this node.", + "tw_early": " Earliest time at which service may begin at this node.", + "tw_late": " Latest time at which service may begin at this node." + } + ], + "n_arcs": " Total number of directed arcs in the network.", + "arcs": [ + { + "from": " Node identifier where this arc originates.", + "to": " Node identifier where this arc terminates.", + "cost": " Travel cost of traversing this arc, including the vehicle fixed cost for arcs leaving the origin depot.", + "travel_time": " Travel time required to traverse this arc." + } + ] +} \ No newline at end of file diff --git a/tasks/cherkesly2015/mathematical_formulation.md b/tasks/cherkesly2015/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d55d1f0400093d8719f53c0582c05bded4dc66c4 --- /dev/null +++ b/tasks/cherkesly2015/mathematical_formulation.md @@ -0,0 +1,65 @@ +# Original Formulation: Pickup and Delivery Problem with Time Windows and LIFO Loading (PDPTWL) + +*Source: Branch-Price-and-Cut Algorithms for the Pickup and Delivery Problem with Time Windows and Last-In-First-Out Loading, Cherkesly, Desaulniers, and Laporte, 2015.* + +## Sets and Parameters + +- $n$: number of requests. + +- $G = (N, A)$: directed graph with $N = \{0, 1, \dots, 2n, 2n+1\}$; node $0$ is the origin depot and $2n+1$ the destination depot. + +- $P = \{1, \dots, n\}$: set of pickup nodes; $D = \{n+1, \dots, 2n\}$: set of delivery nodes. Request $i \in P$ is paired with delivery node $n+i$. + +- $A$: arc set, consisting of (i) $(0,j)$ for $j \in P$; (ii) $(i,2n+1)$ for $i \in D$; (iii) $(i,j)$ with $i \in P$, $j \in P \cup \{n+i\}$; (iv) $(i,j)$ with $i \in D$, $j \in (D \cup P) \setminus \{i-n\}$. In particular, arcs $(i, n+j)$ with $i \in P$, $j \in P \setminus \{i\}$ are *excluded* (they violate LIFO a priori). + +- $K$: unrestricted set of identical vehicles. + +- For each $i \in P$: $\Omega_i$ is the set of subsets $S \subseteq N$ such that $\{0, 2n+1, i, n+i\} \not\subseteq S$ and there exists a request $j$ with $(j \in S,\, n+j \notin S)$ or $(j \notin S,\, n+j \in S)$. + +- $q_i$: load picked up or delivered at $i$; $q_0 = q_{2n+1} = 0$, $q_i > 0$ for $i \in P$, $q_{n+i} = -q_i$ for $i \in P$. + +- $s_i$: service duration at $i$ ($s_0 = s_{2n+1} = 0$). $[w_i, \overline{w}_i]$: time window at node $i$. + +- $Q$: (identical) vehicle capacity; $c_{ij}$: nonnegative travel cost on arc $(i,j)$; $t_{ij}$: nonnegative travel time on $(i,j)$. + +## Decision Variables + +- $x^{k}_{ij} \in \{0,1\}$ for $(i,j) \in A$, $k \in K$: $=1$ iff vehicle $k$ uses arc $(i,j)$. + +- $T^{k}_{i} \geq 0$ for $i \in N$, $k \in K$: time at which vehicle $k$ begins service at node $i$. + +- $Q^{k}_{i} \geq 0$ for $i \in N$, $k \in K$: load of vehicle $k$ upon leaving node $i$. + +## Objective + +$$\begin{equation} +\min \;\; \sum_{k \in K} \sum_{(i,j) \in A} c_{ij}\, x^{k}_{ij} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{k \in K} \sum_{j \in N} x^{k}_{ij} &= 1, & \forall i \in P \tag{2} \\[2pt] +\sum_{j \in N} x^{k}_{ij} \;-\; \sum_{j \in N} x^{k}_{\,n+i,\,j} &= 0, & \forall i \in P,\; k \in K \tag{3} \\[2pt] +\sum_{j \in N} x^{k}_{0 j} &= 1, & \forall k \in K \tag{4} \\[2pt] +\sum_{j \in N} x^{k}_{j i} \;-\; \sum_{j \in N} x^{k}_{i j} &= 0, & \forall i \in P \cup D,\; k \in K \tag{5} \\[2pt] +\sum_{i \in N} x^{k}_{i,\, 2n+1} &= 1, & \forall k \in K \tag{6} +\end{align}$$ + +LIFO constraint (exponential family of infeasible-subset cuts): $$\begin{align} +\sum_{\substack{(i,j) \in A \\ j \in S}} x^{k}_{ij} + \;+\; \sum_{\substack{(l,j) \in A \\ l,j \in S}} x^{k}_{lj} + \;+\; \sum_{\substack{(j,\,n+i) \in A \\ j \in S}} x^{k}_{j,\,n+i} + &\;\leq\; |S|, & \forall S \in \Omega_i,\; i \in P,\; k \in K \tag{7} +\end{align}$$ + +Load and time constraints (stated in their original nonlinear form): $$\begin{align} +Q^{k}_{j} &\;\geq\; Q^{k}_{i} + q_{j}\, x^{k}_{ij}, & \forall (i,j) \in A,\; k \in K \tag{8} \\[2pt] +\max\{0,\, q_i\} \;\leq\; Q^{k}_{i} &\;\leq\; \min\{Q,\, Q + q_i\}, & \forall i \in N,\; k \in K \tag{9} \\[2pt] +T^{k}_{j} &\;\geq\; T^{k}_{i} + s_{i} + t_{ij}\, x^{k}_{ij}, & \forall (i,j) \in A,\; k \in K \tag{10} \\[2pt] +w_{i} \;\leq\; T^{k}_{i} &\;\leq\; \overline{w}_{i}, & \forall i \in N,\; k \in K \tag{11} \\[2pt] +T^{k}_{i} + t_{i,\,n+i} + s_{i} &\;\leq\; T^{k}_{n+i}, & \forall i \in P \tag{12} \\[2pt] +x^{k}_{ij} &\;\in\; \{0,1\}, & \forall (i,j) \in A,\; k \in K \tag{13} +\end{align}$$ + +Constraints (8) and (10) are nonlinear (bilinear) and are written as given in the paper; they may be linearized via standard big-$M$ constraints. diff --git a/tasks/cherkesly2015/problem_description.txt b/tasks/cherkesly2015/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..2719f932bc535b34bac17158d6552d67ffc9abce --- /dev/null +++ b/tasks/cherkesly2015/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A fleet of identical vehicles based at a single depot must fulfill a set of transportation requests. Each request specifies that a certain quantity of goods must be picked up at one location and delivered to a different location. The problem is defined on a directed graph whose nodes comprise an origin depot numbered zero, one pickup node for each request numbered sequentially from one to the total number of requests, one delivery node for each request numbered sequentially from one more than the total number of requests to twice the total number of requests, and a destination depot numbered one more than twice the total number of requests that is a copy of the origin depot representing the return. The delivery node corresponding to each request is numbered by adding the total number of requests to that request's pickup node number. The fleet size is unlimited; any number of identical vehicles may be used, each with the same carrying capacity. + +The input data specifies the following for each node: its geographic coordinates, the quantity of goods picked up or delivered there (positive at pickup nodes, negative at delivery nodes, zero at both depot copies), a service duration (positive at pickup and delivery nodes, zero at the depots), and a time window defined by an earliest and latest time at which service may begin. The depot nodes have unconstraining time windows spanning the full planning horizon. For each pair of nodes connected by an arc, the data provides a nonnegative travel cost and a nonnegative travel time, both satisfying the triangle inequality. The travel cost of each arc leaving the origin depot to a pickup node includes a fixed cost for using a vehicle; this fixed cost is large so that the solution first seeks to minimize the number of vehicles employed and then minimizes total travel distance. + +The planning decisions are which arcs each vehicle traverses (forming a route), the time at which each vehicle begins service at each node it visits, and the load carried by each vehicle upon departing each node it visits. + +Every pickup node must be visited exactly once across all vehicles, and whenever a vehicle visits a pickup node for a given request, the same vehicle must also visit the corresponding delivery node. Each vehicle's route must begin at the origin depot and end at the destination depot, and at every pickup or delivery node the number of times a vehicle arrives must equal the number of times it departs. The vehicle's load after visiting any node must be at least zero and at most the vehicle capacity; specifically, the load at each node must lie between the greater of zero and the node's load change on one hand, and the lesser of the vehicle capacity and the vehicle capacity plus the node's load change on the other. When a vehicle traverses an arc from one node to another, its load at the destination node must be at least its load at the origin node plus the load change at the destination node. Similarly, the service start time at the destination node of any traversed arc must be at least the service start time at the origin node plus the service duration at the origin node plus the travel time of that arc. Service at every node must begin within the node's time window. For every request, the pickup must be completed before the delivery begins: the service start time at the pickup node plus the service duration there plus the direct travel time from the pickup to the delivery node must not exceed the service start time at the delivery node. + +The vehicles maintain a last-in-first-out (LIFO) loading policy, meaning that goods are stacked in the vehicle in the order they are picked up, and a delivery can only be performed when the corresponding goods are on top of the stack. This is enforced structurally in two ways. First, the set of permissible arcs excludes any arc from a pickup node of one request directly to the delivery node of a different request, because traversing such an arc would require delivering an item that is not on top of the stack. Second, for each request and each subset of nodes that excludes both depot nodes and also excludes both the pickup and delivery nodes of that request, where the subset splits at least one other request by containing that other request's pickup but not its delivery or vice versa, the number of times each vehicle enters that subset, traverses arcs within it, or exits it toward the delivery node of the request in question cannot exceed the number of nodes in the subset. This prevents any route from interleaving pickups and deliveries in an order that would violate the stack discipline. + +The goal is to minimize total cost, defined as the sum of travel costs over all arcs traversed by all vehicles, where the travel cost on arcs leaving the origin depot includes the per-vehicle fixed cost. diff --git a/tasks/cherkesly2015/solution_logger.py b/tasks/cherkesly2015/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/cherkesly2015/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/cherkesly2015/solution_schema.json b/tasks/cherkesly2015/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fea86bcd6e1ae0a4da704645d364a78b9a8556af --- /dev/null +++ b/tasks/cherkesly2015/solution_schema.json @@ -0,0 +1,16 @@ +{ + "objective_value": " Total travel cost across all vehicles, including the per-vehicle fixed cost embedded in arcs leaving the origin depot.", + "routes": [ + { + "vehicle_id": " Identifier of the vehicle performing this route.", + "route_sequence": " Ordered sequence of nodes visited by the vehicle, starting at the origin depot and ending at the destination depot.", + "route_details": [ + { + "node_id": " Node visited at this step of the route.", + "arrival_time": " Time at which the vehicle begins service at this node.", + "load_after": " Quantity of goods on board the vehicle upon departing this node." + } + ] + } + ] +} diff --git a/tasks/colombi2017/feasibility_check.py b/tasks/colombi2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a4547c33b63c62534661b55eac8d6c26d4307fe7 --- /dev/null +++ b/tasks/colombi2017/feasibility_check.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the DPRPP-IC (Directed Profitable Rural Postman Problem +with Incompatibility Constraints) using Formulation (A) from Colombi et al. (2017). + +Checks constraints (1)-(10) as listed in math_model.txt, plus constraint (11): +objective-value consistency between the reported objective_value and a +recomputation from x/y/u (Tier C defense against LLM score-gaming). +""" + +import json +import argparse +import math +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'served_arcs', 'tour_arcs') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------------- + # Parse instance + # ------------------------------------------------------------------------- + num_nodes = instance["num_nodes"] + depot = instance["depot"] + + arc_cost = {} + for arc in instance["arcs"]: + arc_cost[(arc[0], arc[1])] = arc[2] + all_arcs = set(arc_cost.keys()) + + arc_profit = {} + for pa in instance["profitable_arcs"]: + arc_profit[(pa[0], pa[1])] = pa[2] + profitable_arcs = set(arc_profit.keys()) + + vi_nodes = set(instance.get("VI_nodes", [])) + if not vi_nodes: + vi_nodes = set(i for (i, _) in profitable_arcs) + + strong_incomp = [(e[0], e[1]) for e in instance["strong_incompatibilities"]] + weak_incomp = [] + weak_penalty = {} + + val = defaultdict(float) + for (i, j), p in arc_profit.items(): + c = arc_cost.get((i, j), 0) + val[i] += (p - c) + + gamma = instance.get("generation_parameters", {}).get("gamma", 0.01) + + for edge in instance["weak_incompatibilities"]: + i, j = edge[0], edge[1] + if len(edge) >= 3: + c_bar = edge[2] + else: + c_bar = math.ceil(gamma * (val[i] + val[j])) + weak_incomp.append((i, j)) + weak_penalty[(i, j)] = c_bar + + v_bar = set() + for (i, j) in strong_incomp: + v_bar.add(i) + v_bar.add(j) + for (i, j) in weak_incomp: + v_bar.add(i) + v_bar.add(j) + + profitable_from = defaultdict(list) + for (i, j) in profitable_arcs: + profitable_from[i].append((i, j)) + + nodes = set(range(num_nodes)) + + outgoing = defaultdict(list) + incoming = defaultdict(list) + for (i, j) in all_arcs: + outgoing[i].append((i, j)) + incoming[j].append((i, j)) + + # ------------------------------------------------------------------------- + # Parse solution: reconstruct x, y, z, u variables + # ------------------------------------------------------------------------- + # x[i,j]: number of times arc (i,j) is traversed + x = defaultdict(int) + for ta in solution.get("tour_arcs", []): + key = (ta["from"], ta["to"]) + x[key] = ta["count"] + + # y[i,j]: 1 if profitable arc is served + y = {} + for (i, j) in profitable_arcs: + y[(i, j)] = 0 + for sa in solution.get("served_arcs", []): + key = (sa["from"], sa["to"]) + if key in profitable_arcs: + y[key] = 1 + + # z[i]: 1 if at least one profitable arc leaving node i (in V_bar) is served + z = {} + for i in v_bar: + z[i] = 0 + for (i, j) in profitable_arcs: + if y.get((i, j), 0) == 1 and i in v_bar: + z[i] = 1 + + # u[i,j]: 1 if weak incompatibility penalty between i,j is paid + # u should be 1 when both z[i]=1 and z[j]=1 (otherwise the constraint is violated) + u = {} + for (i, j) in weak_incomp: + # Infer u: if both nodes are active, the penalty must be paid + if z.get(i, 0) == 1 and z.get(j, 0) == 1: + u[(i, j)] = 1 + else: + u[(i, j)] = 0 + + # ------------------------------------------------------------------------- + # Helper to record a violation + # ------------------------------------------------------------------------- + def record_violation(constraint_idx, message, lhs, rhs, violation_amount): + violations.append((constraint_idx, message)) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio) + }) + + # ========================================================================= + # Constraint (1): x_ij >= y_ij for (i,j) in R + # ========================================================================= + for (i, j) in profitable_arcs: + lhs = x[(i, j)] + rhs = y[(i, j)] + # This is a >= constraint: violation_amount = max(rhs - lhs, 0) + violation_amount = max(rhs - lhs, 0) + if violation_amount > tol: + record_violation( + 1, + f"Constraint (1): Served arc ({i},{j}) has y=1 but x={lhs} (arc not traversed)", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (2): flow conservation at each node j in V + # sum_{(j,i) in delta+(j)} x_ji = sum_{(i,j) in delta-(j)} x_ij + # ========================================================================= + for j in nodes: + out_flow = sum(x[(jj, k)] for (jj, k) in outgoing[j]) + in_flow = sum(x[(k, jj)] for (k, jj) in incoming[j]) + lhs = out_flow + rhs = in_flow + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 2, + f"Constraint (2): Flow imbalance at node {j}: outflow={out_flow}, inflow={in_flow}", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (3): connectivity + # sum_{(i,j) in delta+(S)} x_ij >= y_ks for S subset V\{0}, (k,s) in R(S) + # Check: if y_ks=1, the tour must connect S to the depot. + # We check by finding connected components of the tour graph and verifying + # that every served arc is in the component containing the depot. + # ========================================================================= + # Build directed graph from tour arcs + adj = defaultdict(set) + active_nodes = set() + for (i, j), count in x.items(): + if count > 0: + adj[i].add(j) + adj[j].add(i) + active_nodes.add(i) + active_nodes.add(j) + + # Find weakly connected components via BFS + visited = set() + depot_component = set() + components = [] + for node in active_nodes: + if node in visited: + continue + comp = set() + queue = [node] + while queue: + n = queue.pop() + if n in visited: + continue + visited.add(n) + comp.add(n) + for nb in adj[n]: + if nb not in visited: + queue.append(nb) + if comp: + if depot in comp: + depot_component = comp + components.append(comp) + + # Also add depot to its own component if it has no arcs + if depot not in active_nodes: + depot_component = {depot} + + # Check each served profitable arc: both endpoints must be in the depot component + for (k, s) in profitable_arcs: + if y[(k, s)] != 1: + continue + # S = V \ {depot component} that contains k and s + if k not in depot_component or s not in depot_component: + # The served arc is disconnected from the depot + # The cut value (arcs leaving the component containing k,s) is 0 + # LHS of constraint (3) = 0, RHS = y_ks = 1 + record_violation( + 3, + f"Constraint (3): Served arc ({k},{s}) is disconnected from depot (not in depot's connected component)", + 0.0, 1.0, 1.0 + ) + + # ========================================================================= + # Constraint (4): y_ij <= z_i for i in V_bar, (i,j) in R + # ========================================================================= + for i in v_bar: + for (ii, j) in profitable_from.get(i, []): + lhs = y[(ii, j)] + rhs = z.get(i, 0) + # This is a <= constraint: violation_amount = max(lhs - rhs, 0) + violation_amount = max(lhs - rhs, 0) + if violation_amount > tol: + record_violation( + 4, + f"Constraint (4): y_{{{ii},{j}}}={lhs} > z_{i}={rhs}", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (5): z_i + z_j <= 1 for {i,j} in E_1 (strong incompatibility) + # ========================================================================= + for (i, j) in strong_incomp: + lhs = z.get(i, 0) + z.get(j, 0) + rhs = 1 + violation_amount = max(lhs - rhs, 0) + if violation_amount > tol: + record_violation( + 5, + f"Constraint (5): Strong incompatibility violated: z_{i}={z.get(i,0)} + z_{j}={z.get(j,0)} = {lhs} > 1", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (6): z_i + z_j - u_ij <= 1 for {i,j} in E_2 (weak incompatibility) + # ========================================================================= + for (i, j) in weak_incomp: + lhs = z.get(i, 0) + z.get(j, 0) - u.get((i, j), 0) + rhs = 1 + violation_amount = max(lhs - rhs, 0) + if violation_amount > tol: + record_violation( + 6, + f"Constraint (6): Weak incompatibility violated: z_{i}+z_{j}-u_{{{i},{j}}} = {lhs} > 1", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (7): x_ij >= 0 integer for (i,j) in A + # ========================================================================= + for (i, j) in all_arcs: + val_x = x[(i, j)] + # Check non-negativity + if val_x < -tol: + violation_amount = abs(val_x) + record_violation( + 7, + f"Constraint (7): x_{{{i},{j}}}={val_x} is negative", + val_x, 0, violation_amount + ) + # Check integrality + rounded = round(val_x) + int_violation = abs(val_x - rounded) + if int_violation > tol: + record_violation( + 7, + f"Constraint (7): x_{{{i},{j}}}={val_x} is not integer", + val_x, rounded, int_violation + ) + + # Also check that tour arcs are valid arcs in the instance + for (i, j), count in x.items(): + if count > 0 and (i, j) not in all_arcs: + record_violation( + 7, + f"Constraint (7): Tour arc ({i},{j}) does not exist in the instance arc set", + count, 0, float(count) + ) + + # ========================================================================= + # Constraint (8): y_ij in {0,1} for (i,j) in R + # ========================================================================= + for (i, j) in profitable_arcs: + val_y = y[(i, j)] + if val_y not in (0, 1): + violation_amount = min(abs(val_y), abs(val_y - 1)) + record_violation( + 8, + f"Constraint (8): y_{{{i},{j}}}={val_y} is not binary", + val_y, round(val_y), violation_amount + ) + + # Also check that served arcs are valid profitable arcs + for sa in solution.get("served_arcs", []): + key = (sa["from"], sa["to"]) + if key not in profitable_arcs: + record_violation( + 8, + f"Constraint (8): Served arc ({key[0]},{key[1]}) is not a profitable arc in the instance", + 1, 0, 1.0 + ) + + # ========================================================================= + # Constraint (9): z_i in {0,1} for i in V_bar + # ========================================================================= + for i in v_bar: + val_z = z.get(i, 0) + if val_z not in (0, 1): + violation_amount = min(abs(val_z), abs(val_z - 1)) + record_violation( + 9, + f"Constraint (9): z_{i}={val_z} is not binary", + val_z, round(val_z), violation_amount + ) + + # ========================================================================= + # Constraint (10): u_ij in {0,1} for {i,j} in E_2 + # ========================================================================= + for (i, j) in weak_incomp: + val_u = u.get((i, j), 0) + if val_u not in (0, 1): + violation_amount = min(abs(val_u), abs(val_u - 1)) + record_violation( + 10, + f"Constraint (10): u_{{{i},{j}}}={val_u} is not binary", + val_u, round(val_u), violation_amount + ) + + # ========================================================================= + # Constraint (11): objective-value consistency (Tier C defense). + # The reported objective_value must equal the recomputed + # sum_{(i,j) in R} p_ij * y_ij + # - sum_{(i,j) in A} c_ij * x_ij + # - sum_{{i,j} in E_2} c_bar_ij * u_ij + # within a 0.1% relative tolerance (with a 1e-3 absolute floor). + # ========================================================================= + 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): + profit_term = sum(arc_profit[(i, j)] * y[(i, j)] for (i, j) in profitable_arcs) + # Use arc_cost.get(...) so x entries on non-instance arcs (already + # flagged by constraint 7) don't crash the recompute. + cost_term = sum(arc_cost.get((i, j), 0) * count for (i, j), count in x.items()) + penalty_term = sum(weak_penalty[(i, j)] * u[(i, j)] for (i, j) in weak_incomp) + true_obj = float(profit_term - cost_term - penalty_term) + abs_diff = abs(reported - true_obj) + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + record_violation( + 11, + f"Constraint (11): Objective consistency violated: " + f"reported objective_value={reported} differs from recomputed " + f"sum(p*y) - sum(c*x) - sum(cbar*u) = {true_obj} " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported, true_obj, abs_diff, + ) + elif reported is not None and not math.isfinite(reported): + # Non-finite reported objectives (inf/nan) are definitionally inconsistent + # with any feasible solution's finite objective. + record_violation( + 11, + f"Constraint (11): Objective consistency violated: " + f"reported objective_value={reported} is not finite", + reported, 0.0, float("inf"), + ) + + # ------------------------------------------------------------------------- + # Build output + # ------------------------------------------------------------------------- + violated_indices = sorted(set(c for c, _ in violations)) + violation_messages = [] + for idx in violated_indices: + msgs = [msg for c, msg in violations if c == idx] + violation_messages.append("; ".join(msgs)) + + feasible = len(violated_indices) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_indices, + "violations": violation_messages, + "violation_magnitudes": violation_magnitudes + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for DPRPP-IC (Colombi et al. 2017, Formulation A)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print("Solution is INFEASIBLE.") + print(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/colombi2017/gurobi_code.py b/tasks/colombi2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a02199976ed1f3599b7de4b94dde74c7f370f3d9 --- /dev/null +++ b/tasks/colombi2017/gurobi_code.py @@ -0,0 +1,402 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the DPRPP-IC (Directed Profitable Rural Postman Problem +with Incompatibility Constraints) using Formulation (A) from Colombi et al. (2017). + +Branch-and-cut with dynamically separated connectivity constraints (3). +Variables z and u are relaxed to continuous [0,1] per Proposition 1. + +The paper uses CPLEX 12.6.2; here we use Gurobi as the solver. +""" + +import json +import argparse +import math +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path) as f: + return json.load(f) + + +def build_adjacency(nodes, arcs): + """Build outgoing and incoming adjacency lists.""" + outgoing = defaultdict(list) + incoming = defaultdict(list) + for (i, j) in arcs: + outgoing[i].append((i, j)) + incoming[j].append((i, j)) + return outgoing, incoming + + +def find_weakly_connected_components(nodes_set, arc_vals, arcs, threshold): + """ + Find weakly connected components of the subgraph induced by arcs + with value > threshold. + """ + # Build undirected adjacency for arcs above threshold + adj = defaultdict(set) + active_nodes = set() + for (i, j) in arcs: + if arc_vals.get((i, j), 0) > threshold + 1e-9: + adj[i].add(j) + adj[j].add(i) + active_nodes.add(i) + active_nodes.add(j) + + visited = set() + components = [] + for node in active_nodes: + if node in visited: + continue + # BFS + comp = set() + queue = [node] + while queue: + n = queue.pop() + if n in visited: + continue + visited.add(n) + comp.add(n) + for nb in adj[n]: + if nb not in visited: + queue.append(nb) + if comp: + components.append(comp) + return components + + +def solve_dprpp_ic(instance, time_limit): + """ + Solve the DPRPP-IC using Formulation (A) with Gurobi. + Connectivity constraints (3) are separated dynamically via callbacks. + """ + num_nodes = instance["num_nodes"] + depot = instance["depot"] + + # --- Build arc data --- + arc_cost = {} + for arc in instance["arcs"]: + i, j, c = arc[0], arc[1], arc[2] + arc_cost[(i, j)] = c + all_arcs = list(arc_cost.keys()) + + # --- Build profitable arc data --- + arc_profit = {} + for pa in instance["profitable_arcs"]: + i, j, p = pa[0], pa[1], pa[2] + arc_profit[(i, j)] = p + profitable_arcs = list(arc_profit.keys()) + + # --- V_I nodes (initial nodes of profitable arcs) --- + vi_nodes = set(instance.get("VI_nodes", [])) + if not vi_nodes: + vi_nodes = set(i for (i, j) in profitable_arcs) + + # --- Incompatibility edges --- + strong_incomp = [] + for edge in instance["strong_incompatibilities"]: + strong_incomp.append((edge[0], edge[1])) + + weak_incomp = [] + weak_penalty = {} + + # Compute val(q) = sum_{(q,s) in R} (p_qs - c_qs) for penalty computation + val = defaultdict(float) + for (i, j), p in arc_profit.items(): + c = arc_cost.get((i, j), 0) + val[i] += (p - c) + + gamma = instance.get("generation_parameters", {}).get("gamma", 0.01) + + for edge in instance["weak_incompatibilities"]: + i, j = edge[0], edge[1] + if len(edge) >= 3: + c_bar = edge[2] + else: + # **INFERRED ASSUMPTION**: Penalty computed as ceil(gamma * (val(i) + val(j))) + # as described in Section 6.1 of the paper. + c_bar = math.ceil(gamma * (val[i] + val[j])) + weak_incomp.append((i, j)) + weak_penalty[(i, j)] = c_bar + + # --- V_bar: nodes appearing in incompatibility edges --- + v_bar = set() + for (i, j) in strong_incomp: + v_bar.add(i) + v_bar.add(j) + for (i, j) in weak_incomp: + v_bar.add(i) + v_bar.add(j) + + # Map profitable arcs leaving each node + profitable_from = defaultdict(list) + for (i, j) in profitable_arcs: + profitable_from[i].append((i, j)) + + # Adjacency + nodes = set(range(num_nodes)) + outgoing, incoming = build_adjacency(nodes, all_arcs) + + # ========== Build Gurobi Model ========== + model = gp.Model("DPRPP_IC_FormA") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("LazyConstraints", 1) + # Suppress output for cleaner runs + model.setParam("OutputFlag", 1) + + # --- Decision Variables --- + # x[i,j] >= 0 integer: number of times arc (i,j) is traversed + x = {} + for (i, j) in all_arcs: + x[(i, j)] = model.addVar(vtype=GRB.INTEGER, lb=0, name=f"x_{i}_{j}") + + # y[i,j] in {0,1}: 1 if profitable arc (i,j) is served + y = {} + for (i, j) in profitable_arcs: + y[(i, j)] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}_{j}") + + # z[i] in [0,1]: 1 if at least one profitable arc leaving i is served + # Per Proposition 1, z can be relaxed to continuous [0,1] + z = {} + for i in v_bar: + z[i] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, ub=1.0, name=f"z_{i}") + + # u[i,j] in [0,1]: 1 if weak incompatibility penalty is paid + # Per Proposition 1, u can be relaxed to continuous [0,1] + u = {} + for (i, j) in weak_incomp: + u[(i, j)] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, ub=1.0, name=f"u_{i}_{j}") + + model.update() + + # --- Objective Function --- + # max sum p_ij * y_ij - sum c_ij * x_ij - sum c_bar_ij * u_ij + obj = gp.LinExpr() + for (i, j) in profitable_arcs: + obj += arc_profit[(i, j)] * y[(i, j)] + for (i, j) in all_arcs: + obj -= arc_cost[(i, j)] * x[(i, j)] + for (i, j) in weak_incomp: + obj -= weak_penalty[(i, j)] * u[(i, j)] + model.setObjective(obj, GRB.MAXIMIZE) + + # --- Constraint (1): x_ij >= y_ij for (i,j) in R --- + for (i, j) in profitable_arcs: + model.addConstr(x[(i, j)] >= y[(i, j)], name=f"serve_{i}_{j}") + + # --- Constraint (2): flow conservation at each node --- + for j in nodes: + out_expr = gp.LinExpr() + in_expr = gp.LinExpr() + for (jj, k) in outgoing[j]: + out_expr += x[(jj, k)] + for (k, jj) in incoming[j]: + in_expr += x[(k, jj)] + model.addConstr(out_expr == in_expr, name=f"flow_{j}") + + # --- Constraint (4): y_ij <= z_i for i in V_bar, (i,j) in R --- + for i in v_bar: + for (ii, j) in profitable_from.get(i, []): + model.addConstr(y[(ii, j)] <= z[i], name=f"link_{ii}_{j}") + + # --- Constraint (5): z_i + z_j <= 1 for {i,j} in E_1 --- + for (i, j) in strong_incomp: + if i in z and j in z: + model.addConstr(z[i] + z[j] <= 1, name=f"strong_{i}_{j}") + + # --- Constraint (6): z_i + z_j - u_ij <= 1 for {i,j} in E_2 --- + for (i, j) in weak_incomp: + if i in z and j in z: + model.addConstr(z[i] + z[j] - u[(i, j)] <= 1, name=f"weak_{i}_{j}") + + # --- Constraint (3): connectivity - separated lazily --- + # For S ⊆ V\{0}, (k,s) ∈ R(S): sum_{(i,j) ∈ δ+(S)} x_ij >= y_ks + + # Store references for callback closure + cb_data = { + "x": x, "y": y, + "all_arcs": all_arcs, "profitable_arcs": profitable_arcs, + "outgoing": outgoing, "depot": depot, "nodes": nodes, + } + + def connectivity_callback(model, where): + if where == GRB.Callback.MIPSOL: + # Separate connectivity constraints on integer solutions + x_val = {} + for (i, j) in cb_data["all_arcs"]: + x_val[(i, j)] = model.cbGetSolution(cb_data["x"][(i, j)]) + y_val = {} + for (i, j) in cb_data["profitable_arcs"]: + y_val[(i, j)] = model.cbGetSolution(cb_data["y"][(i, j)]) + + _separate_and_add(model, x_val, y_val, is_integer=True) + + elif where == GRB.Callback.MIPNODE: + # Separate connectivity constraints on fractional solutions + if model.cbGet(GRB.Callback.MIPNODE_STATUS) != GRB.OPTIMAL: + return + x_val = {} + for (i, j) in cb_data["all_arcs"]: + x_val[(i, j)] = model.cbGetNodeRel(cb_data["x"][(i, j)]) + y_val = {} + for (i, j) in cb_data["profitable_arcs"]: + y_val[(i, j)] = model.cbGetNodeRel(cb_data["y"][(i, j)]) + + _separate_and_add(model, x_val, y_val, is_integer=False) + + def _separate_and_add(model, x_val, y_val, is_integer): + """ + Heuristic separation for connectivity constraints (3). + For each epsilon in {0, 0.25, 0.5}, compute connected components + of graph induced by arcs with x > epsilon. For components not + containing the depot, check for violated constraints. + """ + dep = cb_data["depot"] + out = cb_data["outgoing"] + pa = cb_data["profitable_arcs"] + x_vars = cb_data["x"] + y_vars = cb_data["y"] + + cuts_added = 0 + for eps in [0.0, 0.25, 0.5]: + components = find_weakly_connected_components( + cb_data["nodes"], x_val, cb_data["all_arcs"], eps + ) + + for comp in components: + if dep in comp: + continue + + # Check each profitable arc (k,s) with both endpoints in comp + for (k, s) in pa: + if k not in comp or s not in comp: + continue + + y_ks_val = y_val[(k, s)] + tol = 0.5 if is_integer else 1e-4 + if y_ks_val < tol: + continue + + # Compute cut value: sum x_ij for arcs leaving comp + cut_val = 0.0 + cut_expr = gp.LinExpr() + for node_in_S in comp: + for (ii, jj) in out[node_in_S]: + if jj not in comp: + cut_val += x_val[(ii, jj)] + cut_expr += x_vars[(ii, jj)] + + if cut_val < y_ks_val - 1e-4: + if is_integer: + model.cbLazy(cut_expr >= y_vars[(k, s)]) + else: + model.cbCut(cut_expr >= y_vars[(k, s)]) + cuts_added += 1 + + # ========== Solve ========== + model.optimize(connectivity_callback) + + # ========== Extract Solution ========== + result = {"objective_value": None} + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + + served_arcs = [] + for (i, j) in profitable_arcs: + if y[(i, j)].X > 0.5: + served_arcs.append({ + "from": i, "to": j, + "profit": arc_profit[(i, j)], + "cost": arc_cost.get((i, j), 0) + }) + result["served_arcs"] = served_arcs + + tour_arcs = [] + for (i, j) in all_arcs: + count = int(round(x[(i, j)].X)) + if count > 0: + tour_arcs.append({ + "from": i, "to": j, + "count": count, + "cost": arc_cost[(i, j)] + }) + result["tour_arcs"] = tour_arcs + + result["total_profit"] = sum( + arc_profit[(i, j)] for (i, j) in profitable_arcs if y[(i, j)].X > 0.5 + ) + result["total_travel_cost"] = sum( + arc_cost[(i, j)] * int(round(x[(i, j)].X)) + for (i, j) in all_arcs if x[(i, j)].X > 0.5 + ) + result["total_penalty"] = sum( + weak_penalty[(i, j)] * u[(i, j)].X + for (i, j) in weak_incomp + ) if weak_incomp else 0.0 + + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + result["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + else: + # No feasible solution found: null solution (stay at depot, no profit) + result["objective_value"] = 0.0 + result["served_arcs"] = [] + result["tour_arcs"] = [] + result["total_profit"] = 0.0 + result["total_travel_cost"] = 0.0 + result["total_penalty"] = 0.0 + result["status"] = "no_solution" + result["mip_gap"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="DPRPP-IC Solver using Gurobi - Formulation (A) (Colombi et al. 2017)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path 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) + + instance = load_instance(args.instance_path) + result = solve_dprpp_ic(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']}") + if result.get("mip_gap") is not None: + print(f"MIP gap: {result['mip_gap']:.4f}") + + +if __name__ == "__main__": + main() diff --git a/tasks/colombi2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/colombi2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/colombi2017/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/colombi2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/colombi2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/colombi2017/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/colombi2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/colombi2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/colombi2017/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/colombi2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/colombi2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/colombi2017/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/colombi2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/colombi2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/colombi2017/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/colombi2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/colombi2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/colombi2017/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/colombi2017/gurobi_solution/large_solution_1.json b/tasks/colombi2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..dbea58076293bbbd15804b5dfbf25b0edf46cdb1 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93d2f42aaa67920f9baf7b5e6be6f50aa260910ca61f89c6006fbd584868165e +size 101874 diff --git a/tasks/colombi2017/gurobi_solution/large_solution_2.json b/tasks/colombi2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..5e47735260f9a4c353cfcb64e72d82e72fae51fe --- /dev/null +++ b/tasks/colombi2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f503e96352c626403251c13ee10bef22fc6cc7f965ea162e98631bf4cd07bd9 +size 48880 diff --git a/tasks/colombi2017/gurobi_solution/large_solution_3.json b/tasks/colombi2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1102b2dff5bc248ed98dc8e17cb8b3646f68ce14 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4d6c50fb355ded152b3619c08a455a54e57091bc7dadd1af641eab9e7a8a35e +size 68633 diff --git a/tasks/colombi2017/gurobi_solution/large_solution_4.json b/tasks/colombi2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d4d4d4ced486b9391a8c3da22b7263cbd56e389e --- /dev/null +++ b/tasks/colombi2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06707cbb26c344ed16e2e9f92883ed55d8dfb02b6ffaf7cac549f879f8301ca6 +size 99098 diff --git a/tasks/colombi2017/gurobi_solution/large_solution_5.json b/tasks/colombi2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ad847653ba85640b70fe6ae901047a6c7313268c --- /dev/null +++ b/tasks/colombi2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e68907c3a5a9495ca0c80fae386504aa4ac4b6dbfff210e987715b450626f161 +size 172574 diff --git a/tasks/colombi2017/gurobi_solution/tiny_solution.json b/tasks/colombi2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..49f122c038937d03ab327a6e321de12db5cb2a56 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f3c1a7711c98288b2932789b22c49d46a3d6bd71efb7341625fe926b6303ff5 +size 6148 diff --git a/tasks/colombi2017/gurobi_solution_log/large_log_1.jsonl b/tasks/colombi2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6df85aa5dd8863a12caa5fe51a603a6f9a105e67 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eaf964540d0be19ea1027533ce529e2a2185f4a80f7a9b48c0a56ec55370658 +size 41 diff --git a/tasks/colombi2017/gurobi_solution_log/large_log_2.jsonl b/tasks/colombi2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..02892fdadfe159c33aa1f307d3b245eca9481685 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db301e03410cf473194ea900beee51e315db11806336e92f78215cb308ecd04a +size 41 diff --git a/tasks/colombi2017/gurobi_solution_log/large_log_3.jsonl b/tasks/colombi2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..01692ed7b8ed6db8a4ae0739a82cd7fdc28e9840 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7527ee267d22261f5e4c8858a69baedb3c99ede4cf04e823d315a398da0d7978 +size 41 diff --git a/tasks/colombi2017/gurobi_solution_log/large_log_4.jsonl b/tasks/colombi2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..70124add3e0f7ac436b263ed7e355c1a1fefc173 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a37c153a4c5322a5992eb58b0a7f11750c595867e510c20987031095e7c89b34 +size 41 diff --git a/tasks/colombi2017/gurobi_solution_log/large_log_5.jsonl b/tasks/colombi2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..589352a50ca04fe15e01ecfe9f78e9d70c923bae --- /dev/null +++ b/tasks/colombi2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6672148f1237563a137ce620185ce0d7cd3fe9f576594bb60d403338d1e1af83 +size 41 diff --git a/tasks/colombi2017/gurobi_solution_log/tiny_log.jsonl b/tasks/colombi2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fcdd9611b8836b660669bb62caff6ee20262b451 --- /dev/null +++ b/tasks/colombi2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2b2232268ff36a91dd811013647cca2b11de4217e0e235a8d3009cb1da18e31 +size 41 diff --git a/tasks/colombi2017/instance/large_instance_1.json b/tasks/colombi2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a95311edcd626f3758913be5fc007e67eabe75fb --- /dev/null +++ b/tasks/colombi2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:728d702c6bb8bc8cca5e7626b38d91be3187e9d210f8930ca3c833b3e9f570f2 +size 353651 diff --git a/tasks/colombi2017/instance/large_instance_2.json b/tasks/colombi2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..729c02459fbdfd4f763de80acafa4871ce7c5766 --- /dev/null +++ b/tasks/colombi2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8c610a277db648e4088145484f4b5bc952f48c8cf9243b7c582590893db69ca +size 300138 diff --git a/tasks/colombi2017/instance/large_instance_3.json b/tasks/colombi2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..493b6fd28a4961ccc2df292b7d947d7a0f132bb4 --- /dev/null +++ b/tasks/colombi2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:feb69b129db844a2433b909e8102957818c518bc00bcdae874fdc1c5a4610c99 +size 326488 diff --git a/tasks/colombi2017/instance/large_instance_4.json b/tasks/colombi2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ac2528d73b9e0d0b153e5c8d5d2f8e722076dd65 --- /dev/null +++ b/tasks/colombi2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbf66bbb70e5b043ece556cf5bcec527f8fb57d51855c72f954b4464d95551b6 +size 157916 diff --git a/tasks/colombi2017/instance/large_instance_5.json b/tasks/colombi2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5d5f1911d96dca5309af2b8c7cd428419ecf32f5 --- /dev/null +++ b/tasks/colombi2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad7e2f2fff571efc70c6ab3307b4b0ad939c0de76a30d6dca4d28c106ae8623e +size 169034 diff --git a/tasks/colombi2017/instance/tiny_instance.json b/tasks/colombi2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..ff744d953d5f9dadbb805eea277eacab7978bf22 --- /dev/null +++ b/tasks/colombi2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbceae331cc99b5f81b6fad7e85b8d6937a5248d01e2ce31ebf7d87087ee4037 +size 6394 diff --git a/tasks/colombi2017/instance_schema.json b/tasks/colombi2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..4489d9925f3007d0bed79db9a3bcb01918aa69b3 --- /dev/null +++ b/tasks/colombi2017/instance_schema.json @@ -0,0 +1,14 @@ +{ + "num_nodes": " Total number of nodes in the directed road network.", + "depot": " Node index where the hauler's tour must start and end.", + "num_arcs": " Total number of directed arcs in the road network.", + "num_profitable_arcs": " Number of arcs that yield a profit when served.", + "num_VI_nodes": " Number of starting nodes that appear in the incompatibility graph.", + "num_strong_incompatibilities": " Number of strong incompatibility edges between starting nodes.", + "num_weak_incompatibilities": " Number of weak incompatibility edges between starting nodes.", + "arcs": " Each entry [i, j, cost] defines a directed arc from node i to node j with its traveling cost.", + "profitable_arcs": " Each entry [i, j, profit] defines a profitable arc from node i to node j with its collectible profit.", + "VI_nodes": " Nodes that are starting nodes of profitable arcs and appear in the incompatibility graph.", + "strong_incompatibilities": " Each entry [i, j] defines a pair of starting nodes that cannot both have their profitable arcs served.", + "weak_incompatibilities": " Each entry [i, j, penalty] defines a pair of starting nodes that can both have their profitable arcs served only if the associated penalty cost is paid." +} diff --git a/tasks/colombi2017/mathematical_formulation.md b/tasks/colombi2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..5a5cdb773f8b784811df7a541e966556a1932361 --- /dev/null +++ b/tasks/colombi2017/mathematical_formulation.md @@ -0,0 +1,58 @@ +# Original Formulation: Directed Profitable Rural Postman Problem with Incompatibility Constraints (DPRPP-IC), Formulation (A) + +*Source: The Rural Postman Problem with Incompatibility Constraints, Colombi, Corberán, Mansini, Plana, and Sanchis, 2017.* + +## Sets and Parameters + +- $G(V, A)$: strongly-connected directed graph with node set $V = \{0, 1, \dots, n\}$ (node $0$ is the depot) and arc set $A$. + +- $R \subseteq A$: subset of profitable arcs (arcs that require service and yield positive profit). + +- $V_I \subset V$: set of nodes $i \in V$ with at least one arc $(i,j) \in R$. + +- $\bar{G}(\bar{V},\, E_1 \cup E_2)$: incompatibility graph with $\bar{V} \subseteq V_I$; edges $E_1$ are strong incompatibilities and $E_2$ are weak (removable via penalty) incompatibilities. + +- $\delta^{+}(S)$, $\delta^{-}(S)$: arc cutsets leaving / entering $S \subseteq V$. $R(S)$: profitable arcs with both endpoints in $S$. + +- $c_{ij}$: traveling cost on arc $(i,j) \in A$. + +- $p_{ij}$: positive profit on each profitable arc $(i,j) \in R$ (collected once per arc, the first time it is traversed). + +- $\bar{c}_{ij}$: penalty cost to remove a weak incompatibility $\{i,j\} \in E_2$. + +## Decision Variables + +- $x_{ij} \geq 0$, integer, for $(i,j) \in A$: number of times arc $(i,j)$ is traversed. + +- $y_{ij} \in \{0,1\}$ for $(i,j) \in R$: $=1$ iff profitable arc $(i,j)$ is served. + +- $z_i \in \{0,1\}$ for $i \in \bar{V}$: $=1$ iff at least one profitable arc leaving $i$ is served. + +- $u_{ij} \in \{0,1\}$ for $\{i,j\} \in E_2$: $=1$ iff the weak-incompatibility penalty between $i$ and $j$ is paid. + +## Objective + +$$\begin{equation} +w \;=\; \max \;\; \sum_{(i,j) \in R} p_{ij}\, y_{ij} + \;-\; \sum_{(i,j) \in A} c_{ij}\, x_{ij} + \;-\; \sum_{\{i,j\} \in E_2} \bar{c}_{ij}\, u_{ij} +\tag{A} +\end{equation}$$ + +## Constraints + +$$\begin{align} +x_{ij} & \;\geq\; y_{ij}, & (i,j) \in R \tag{1} \\[2pt] +\sum_{(j,i) \in \delta^{+}(j)} x_{ji} + \;-\; \sum_{(i,j) \in \delta^{-}(j)} x_{ij} & \;=\; 0, & j \in V \tag{2} \\[2pt] +\sum_{(i,j) \in \delta^{+}(S)} x_{ij} & \;\geq\; y_{ks}, & S \subseteq V \setminus \{0\},\; (k,s) \in R(S) \tag{3} \\[2pt] +y_{ij} & \;\leq\; z_{i}, & i \in \bar{V},\; (i,j) \in R \tag{4} \\[2pt] +z_i + z_j & \;\leq\; 1, & \{i,j\} \in E_1 \tag{5} \\[2pt] +z_i + z_j - u_{ij} & \;\leq\; 1, & \{i,j\} \in E_2 \tag{6} \\[2pt] +x_{ij} & \;\geq\; 0, \text{ integer}, & (i,j) \in A \tag{7} \\[2pt] +y_{ij} & \;\in\; \{0,1\}, & (i,j) \in R \tag{8} \\[2pt] +z_{i} & \;\in\; \{0,1\}, & i \in \bar{V} \tag{9} \\[2pt] +u_{ij} & \;\in\; \{0,1\}, & \{i,j\} \in E_2 \tag{10} +\end{align}$$ + +By Proposition 1 of the paper, constraints (9)–(10) may be relaxed to $z_i \in [0,1]$ and $u_{ij} \in [0,1]$ without loss of optimality. diff --git a/tasks/colombi2017/problem_description.txt b/tasks/colombi2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..8750b8b06e0c10e0ee944fd368586804c14ae4b0 --- /dev/null +++ b/tasks/colombi2017/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A hauler operates on a strongly-connected directed road network consisting of a set of nodes and a set of directed arcs, where one distinguished node serves as the depot. Each arc has an associated traveling cost. A designated subset of arcs are profitable arcs, each yielding a positive profit that can be collected at most once, specifically the first time the arc is traversed in a tour. The hauler must plan a closed tour that starts and ends at the depot, selecting which profitable arcs to serve so as to maximize net profit. + +Certain nodes in the network are the starting nodes (tail nodes) of profitable arcs. Among pairs of these starting nodes, incompatibility relationships may exist, which come in two forms: strong and weak. These incompatibilities are described by an incompatibility graph whose nodes are a subset of the profitable-arc starting nodes and whose edges are partitioned into two sets representing strong and weak incompatibilities respectively. Starting nodes that do not appear in the incompatibility graph are compatible with every other node and their profitable arcs may be freely selected. + +The input data specifies the number of nodes and the depot node, the full set of directed arcs with their traveling costs, the set of profitable arcs with their profits, the set of starting nodes that appear in the incompatibility graph, and the two sets of incompatibility edges (strong and weak) among those starting nodes. Each weak incompatibility edge also carries a penalty cost that must be paid to override that incompatibility. + +The hauler must decide which profitable arcs to serve, how many times each arc in the network is traversed, and which weak incompatibilities to override by paying their penalties. A profitable arc can only be served if it is traversed at least once. The number of arcs entering any node must equal the number of arcs leaving that node. The tour must be connected: for any subset of nodes not containing the depot, if a profitable arc with both endpoints in that subset is served, then at least one arc must leave that subset. If any profitable arc leaving a given starting node in the incompatibility graph is served, that node is considered active. Two nodes connected by a strong incompatibility edge cannot both be active, meaning no profitable arc leaving one and no profitable arc leaving the other may both be served. Two nodes connected by a weak incompatibility edge may both be active only if the associated penalty is paid. The number of times any arc is traversed is a nonnegative integer. + +The goal is to maximize the net profit, defined as the total profit collected from all served profitable arcs, minus the total traveling cost summed over all arc traversals (counting each traversal separately), minus the total penalty cost paid to override weak incompatibilities. diff --git a/tasks/colombi2017/solution_logger.py b/tasks/colombi2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/colombi2017/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/colombi2017/solution_schema.json b/tasks/colombi2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f17c95c188ce2dc9fad9c666d149873e35ae5a5a --- /dev/null +++ b/tasks/colombi2017/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Net profit of the tour, equal to total collected profit minus total traveling cost minus total penalty cost paid to override weak incompatibilities.", + "served_arcs": " Profitable arcs selected to be served in the tour, with fields 'from' (starting node of the profitable arc), 'to' (ending node of the profitable arc), 'profit' (profit collected from serving this arc), and 'cost' (traveling cost of this arc).", + "tour_arcs": " Arcs traversed at least once in the closed tour starting and ending at the depot, with fields 'from' (starting node of the traversed arc), 'to' (ending node of the traversed arc), 'count' (number of times this arc is traversed in the tour), and 'cost' (traveling cost per traversal of this arc)." +} diff --git a/tasks/contreras2011/feasibility_check.py b/tasks/contreras2011/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..73876d3d085319d462a28dd3c7895a81c7a803f0 --- /dev/null +++ b/tasks/contreras2011/feasibility_check.py @@ -0,0 +1,497 @@ +""" +Feasibility checker for the Capacitated Hub Location Problem with Single Assignment (CHLPSA). + +Mathematical model from: + Contreras, Diaz, and Fernandez (2011), + "Branch and Price for Large-Scale Capacitated Hub Location Problems with Single Assignment", + INFORMS Journal on Computing, 23(1), pp. 41-55. + +Constraints are numbered 1-8 corresponding to equations (2)-(9) in the paper, +counting strictly from top to bottom in the formulation section. + +Constraint 9 (Tier-C, added in this _new variant): objective-value consistency. + The reported `objective_value` must match the recomputed objective from the + solution variables (hubs + assignment), since hubs+assignment fully determine + z_{kk}, z_{ik} and (via constraints 4-5) x_{ijkm}, and therefore the full + objective in Eq. (1). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'hubs', '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 load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + # Handle missing or empty solution data + if (not solution.get("hubs") and not solution.get("assignment")) or \ + (not solution.get("assignment")): + return { + "feasible": None, + "violated_constraints": [], + "violations": ["No solution data in solution file"], + "violation_magnitudes": [], + } + + n = instance["n"] + N = range(n) + O = instance["outgoing_flow"] + D = instance["total_flow_D"] + b = instance["capacities"] + + hubs = solution["hubs"] + assignment = solution["assignment"] + + hub_set = set(hubs) + + # z_{ik} = 1 iff assignment[i] == k + # x_{ijkm} = 1 iff assignment[i] == k and assignment[j] == m + + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs, rhs, operator): + """Record a violation with normalized magnitude.""" + if operator == "eq": + violation_amount = abs(lhs - rhs) + elif operator in ("leq", "lt"): + violation_amount = max(lhs - rhs, 0.0) + elif operator in ("geq", "gt"): + violation_amount = max(rhs - lhs, 0.0) + else: + violation_amount = 0.0 + + if violation_amount > tol: + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append((constraint_idx, msg)) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ========================================================================= + # Constraint 1 (Eq. 2): sum_{k,m} x_{ijkm} = 1, for all i,j in N + # ========================================================================= + # x_{ijkm} = 1 iff assignment[i]==k and assignment[j]==m. + # For each (i,j), exactly one (k,m) pair satisfies this (k=assignment[i], + # m=assignment[j]), so sum = 1 iff assignment[i] and assignment[j] are + # valid node indices in {0,...,n-1}. Check this for all i,j. + for i in N: + ai = assignment[i] + if ai < 0 or ai >= n: + # sum would be 0 for any j + for j in N: + record_violation(1, + f"Constraint 1 (Eq.2) violated: sum_km x[{i},{j},k,m] = 0 != 1 " + f"(node {i} has invalid assignment {ai})", + 0.0, 1.0, "eq") + continue + for j in N: + aj = assignment[j] + if aj < 0 or aj >= n: + record_violation(1, + f"Constraint 1 (Eq.2) violated: sum_km x[{i},{j},k,m] = 0 != 1 " + f"(node {j} has invalid assignment {aj})", + 0.0, 1.0, "eq") + + # ========================================================================= + # Constraint 2 (Eq. 3): z_{ik} <= z_{kk}, for all i,k in N + # ========================================================================= + # z_{ik}=1 only when assignment[i]==k. z_{kk}=1 only when assignment[k]==k. + # Violation: assignment[i]==k but assignment[k]!=k (i assigned to a non-hub). + for i in N: + k = assignment[i] + if 0 <= k < n and assignment[k] != k: + record_violation(2, + f"Constraint 2 (Eq.3) violated: z[{i},{k}]=1 > z[{k},{k}]=0 " + f"(node {i} assigned to non-hub {k})", + 1.0, 0.0, "leq") + + # ========================================================================= + # Constraint 3 (Eq. 4): sum_{m} x_{ijkm} = z_{ik}, for all i,j,k in N + # ========================================================================= + # For fixed i,j,k: + # LHS = sum_m x_{ijkm}. x_{ijkm}=1 requires assignment[i]==k AND + # assignment[j]==m. If assignment[i]==k, exactly one m works + # (m=assignment[j]), so LHS=1. If assignment[i]!=k, LHS=0. + # RHS = z_{ik} = 1 if assignment[i]==k, else 0. + # So LHS always equals RHS as long as assignments are valid indices. + # Violations only occur if assignment[i] is out of range (already caught + # in Constraint 1) or assignment[j] is out of range. In the latter case, + # when assignment[i]==k, LHS=0 but RHS=1. + for i in N: + ai = assignment[i] + if ai < 0 or ai >= n: + continue # already reported in constraint 1 + k = ai # only k=assignment[i] gives z_{ik}=1 + for j in N: + aj = assignment[j] + if aj < 0 or aj >= n: + # LHS = 0 (no valid m), RHS = z_{ik} = 1 + record_violation(3, + f"Constraint 3 (Eq.4) violated: sum_m x[{i},{j},{k},m]=0 != z[{i},{k}]=1 " + f"(node {j} has invalid assignment {aj})", + 0.0, 1.0, "eq") + + # ========================================================================= + # Constraint 4 (Eq. 5): sum_{k} x_{ijkm} = z_{jm}, for all i,j,m in N + # ========================================================================= + # Symmetric to Constraint 3. For fixed i,j,m: + # LHS = sum_k x_{ijkm}. x_{ijkm}=1 requires assignment[j]==m AND + # assignment[i]==k. If assignment[j]==m, LHS=1 (k=assignment[i]). + # If assignment[j]!=m, LHS=0. + # RHS = z_{jm} = 1 if assignment[j]==m, else 0. + # Again LHS==RHS unless assignments are invalid. + for j in N: + aj = assignment[j] + if aj < 0 or aj >= n: + continue # already reported + m = aj + for i in N: + ai = assignment[i] + if ai < 0 or ai >= n: + record_violation(4, + f"Constraint 4 (Eq.5) violated: sum_k x[{i},{j},k,{m}]=0 != z[{j},{m}]=1 " + f"(node {i} has invalid assignment {ai})", + 0.0, 1.0, "eq") + + # ========================================================================= + # Constraint 5 (Eq. 6): sum_{i} O_i * z_{ik} <= b_k * z_{kk}, for all k in N + # ========================================================================= + for k in N: + lhs = sum(O[i] for i in N if assignment[i] == k) + z_kk = 1.0 if assignment[k] == k else 0.0 + rhs = b[k] * z_kk + if lhs - rhs > tol: + record_violation(5, + f"Constraint 5 (Eq.6) violated: hub {k} capacity exceeded: " + f"incoming flow {lhs:.4f} > capacity {rhs:.4f}", + lhs, rhs, "leq") + + # ========================================================================= + # Constraint 6 (Eq. 7): sum_{k} b_k * z_{kk} >= D + # ========================================================================= + lhs = sum(b[k] for k in N if assignment[k] == k) + rhs = D + if rhs - lhs > tol: + record_violation(6, + f"Constraint 6 (Eq.7) violated: total hub capacity {lhs:.4f} < total demand {rhs:.4f}", + lhs, rhs, "geq") + + # ========================================================================= + # Constraint 7 (Eq. 8): x_{ijkm} >= 0, for all i,j,k,m in N + # ========================================================================= + # All x values are 0 or 1 by construction (from integer assignment), so + # non-negativity is always satisfied. We verify this holds. + # The only non-zero x values are x[i,j,assignment[i],assignment[j]] = 1. + # All others are 0. Both 0 and 1 are >= 0. + # No violation possible with valid binary construction. + for i in N: + for j in N: + k = assignment[i] + m = assignment[j] + x_val = 1.0 # by construction + if x_val < -tol: + record_violation(7, + f"Constraint 7 (Eq.8) violated: x[{i},{j},{k},{m}]={x_val} < 0", + x_val, 0.0, "geq") + + # ========================================================================= + # Constraint 8 (Eq. 9): z_{ik} in {0, 1}, for all i,k in N + # ========================================================================= + # z values are exactly 0 or 1 by construction from integer assignment. + # Verify assignments produce valid binary values. + for i in N: + ai = assignment[i] + if not isinstance(ai, int) or ai < 0 or ai >= n: + # z values cannot be properly defined + record_violation(8, + f"Constraint 8 (Eq.9) violated: node {i} has invalid assignment {ai}, " + f"z variables not properly binary", + float('nan'), 0.0, "eq") + + # ========================================================================= + # Constraint 9 (Tier-C, objective consistency): the reported + # objective_value must equal the recomputed total cost of the solution. + # + # Recompute (Eq. 1): + # obj = sum_{k in hubs} f_k + # + sum_{i,j in N} W_{ij} + # * (chi * d[i][a[i]] + alpha * d[a[i]][a[j]] + delta * d[a[j]][j]) + # where a[i] = assignment[i]. + # + # This is only meaningful if the assignment indices are valid (otherwise + # the existing constraints 1/3/4/8 already capture infeasibility). + # Tolerance: max(1e-3 absolute, 1e-3 * |recomputed|) -> 0.1% relative. + # ========================================================================= + 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: + flow = instance["flow_matrix"] + dist = instance["distance_matrix"] + f_setup = instance["setup_costs"] + cp = instance["cost_parameters"] + chi = float(cp["collection_cost_chi"]) + alpha = float(cp["transfer_cost_alpha"]) + delta = float(cp["distribution_cost_delta"]) + + # Verify assignment indices are valid before recomputing. + indices_valid = all( + isinstance(assignment[i], int) and 0 <= assignment[i] < n + for i in N + ) + + if indices_valid: + setup_total = 0.0 + for k in hubs: + if isinstance(k, int) and 0 <= k < n: + setup_total += float(f_setup[k]) + + routing_total = 0.0 + for i in N: + ai = assignment[i] + d_i_ai = float(dist[i][ai]) + for j in N: + aj = assignment[j] + wij = float(flow[i][j]) + if wij == 0.0: + continue + cost_per_unit = ( + chi * d_i_ai + + alpha * float(dist[ai][aj]) + + delta * float(dist[aj][j]) + ) + routing_total += wij * cost_per_unit + + true_obj = setup_total + routing_total + 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: + record_violation(9, + f"Constraint 9 (obj consistency) violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_k f_k z_kk + sum_ij W_ij*(chi*d_i_ai + alpha*d_ai_aj + delta*d_aj_j)" + f"={true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported, true_obj, "eq") + except (KeyError, IndexError, TypeError, ValueError): + # Instance data missing or malformed; skip obj check. + pass + + # Aggregate results + violated_constraint_indices = sorted(set(v[0] for v in violations)) + violation_messages = [] + for idx in violated_constraint_indices: + msgs = [v[1] for v in violations if v[0] == idx] + if len(msgs) == 1: + violation_messages.append(msgs[0]) + else: + violation_messages.append(f"{msgs[0]} (and {len(msgs)-1} more similar violations)") + + feasible = len(violated_constraint_indices) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_constraint_indices, + "violations": violation_messages, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for CHLPSA (Contreras et al. 2011)" + ) + 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 for the output feasibility result JSON file") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"] is None: + print(f"Solution could not be checked.") + for msg in result["violations"]: + print(f" - {msg}") + elif result["feasible"]: + print(f"Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE.") + print(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/contreras2011/gurobi_code.py b/tasks/contreras2011/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4da48c63bab206763493c4bcb08aa83a21c5772f --- /dev/null +++ b/tasks/contreras2011/gurobi_code.py @@ -0,0 +1,218 @@ +""" +Gurobi MIP solver for the Capacitated Hub Location Problem with Single Assignment (CHLPSA). + +Implements the four-index formulation (MP) from: + Contreras, Diaz, and Fernandez (2011), + "Branch and Price for Large-Scale Capacitated Hub Location Problems with Single Assignment", + INFORMS Journal on Computing, 23(1), pp. 41-55. + +Formulation: + min sum_k f_k * z_{kk} + sum_{i,j,k,m} F_{ijkm} * x_{ijkm} (1) + s.t. + sum_{k,m} x_{ijkm} = 1 for all i,j (2) + z_{ik} <= z_{kk} for all i,k (3) + sum_m x_{ijkm} = z_{ik} for all i,j,k (4) + sum_k x_{ijkm} = z_{jm} for all i,j,m (5) + sum_i O_i * z_{ik} <= b_k * z_{kk} for all k (6) + sum_k b_k * z_{kk} >= D (7) + x_{ijkm} >= 0 for all i,j,k,m (8) + z_{ik} in {0,1} for all i,k (9) +""" + +import argparse +import json +import time +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, 'r') as f: + data = json.load(f) + return data + + +def solve_chlpsa(instance, time_limit): + n = instance["n"] + N = range(n) + + W = instance["flow_matrix"] + d = instance["distance_matrix"] + f_cost = instance["setup_costs"] + b = instance["capacities"] + O = instance["outgoing_flow"] + D = instance["total_flow_D"] + + chi = instance["cost_parameters"]["collection_cost_chi"] + alpha = instance["cost_parameters"]["transfer_cost_alpha"] + delta = instance["cost_parameters"]["distribution_cost_delta"] + + # Precompute routing costs F_{ijkm} + F = {} + for i in N: + for j in N: + for k in N: + for m in N: + F[i, j, k, m] = W[i][j] * (chi * d[i][k] + alpha * d[k][m] + delta * d[m][j]) + + # Create model + model = gp.Model("CHLPSA") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # z[i,k] = 1 if node i is assigned to hub k + z = {} + for i in N: + for k in N: + z[i, k] = model.addVar(vtype=GRB.BINARY, name=f"z_{i}_{k}") + + # x[i,j,k,m] >= 0: flow from i to j routed via hubs k and m + x = {} + for i in N: + for j in N: + for k in N: + for m in N: + x[i, j, k, m] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0.0, name=f"x_{i}_{j}_{k}_{m}" + ) + + model.update() + + # Objective (1): minimize setup costs + routing costs + obj = gp.quicksum(f_cost[k] * z[k, k] for k in N) + \ + gp.quicksum(F[i, j, k, m] * x[i, j, k, m] for i in N for j in N for k in N for m in N) + model.setObjective(obj, GRB.MINIMIZE) + + # Constraint (2): exactly one path for each (i,j) pair + for i in N: + for j in N: + model.addConstr( + gp.quicksum(x[i, j, k, m] for k in N for m in N) == 1, + name=f"path_{i}_{j}" + ) + + # Constraint (3): assignment only to open hubs + for i in N: + for k in N: + model.addConstr(z[i, k] <= z[k, k], name=f"assign_{i}_{k}") + + # Constraint (4): linking x and z (origin side) + for i in N: + for j in N: + for k in N: + model.addConstr( + gp.quicksum(x[i, j, k, m] for m in N) == z[i, k], + name=f"link_orig_{i}_{j}_{k}" + ) + + # Constraint (5): linking x and z (destination side) + for i in N: + for j in N: + for m in N: + model.addConstr( + gp.quicksum(x[i, j, k, m] for k in N) == z[j, m], + name=f"link_dest_{i}_{j}_{m}" + ) + + # Constraint (6): hub capacity + for k in N: + model.addConstr( + gp.quicksum(O[i] * z[i, k] for i in N) <= b[k] * z[k, k], + name=f"capacity_{k}" + ) + + # Constraint (7): total capacity must cover total demand + model.addConstr( + gp.quicksum(b[k] * z[k, k] for k in N) >= D, + name="total_capacity" + ) + + # Optimize + model.optimize() + + # Extract solution + result = {} + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + + # Extract hub locations + hubs = [k for k in N if z[k, k].X > 0.5] + result["hubs"] = hubs + + # Extract assignments + assignment = [] + for i in N: + for k in N: + if z[i, k].X > 0.5: + assignment.append(k) + break + result["assignment"] = assignment + + result["status"] = model.Status + if model.Status == GRB.OPTIMAL: + result["status_text"] = "OPTIMAL" + elif model.Status == GRB.TIME_LIMIT: + result["status_text"] = "TIME_LIMIT" + else: + result["status_text"] = f"STATUS_{model.Status}" + + result["mip_gap"] = model.MIPGap + result["runtime"] = model.Runtime + else: + result["objective_value"] = None + result["status"] = model.Status + result["status_text"] = "NO_SOLUTION" + result["hubs"] = [] + result["assignment"] = [] + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi MIP solver for CHLPSA (Contreras et al. 2011)" + ) + 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) + + instance = load_instance(args.instance_path) + result = solve_chlpsa(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"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']:.2f}") + print(f"Hubs: {result['hubs']}") + print(f"Assignment: {result['assignment']}") + print(f"Status: {result['status_text']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/contreras2011/gurobi_feasi_result/large_feasi_result_1.json b/tasks/contreras2011/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/contreras2011/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/contreras2011/gurobi_feasi_result/large_feasi_result_2.json b/tasks/contreras2011/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/contreras2011/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/contreras2011/gurobi_feasi_result/large_feasi_result_3.json b/tasks/contreras2011/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/contreras2011/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/contreras2011/gurobi_feasi_result/large_feasi_result_4.json b/tasks/contreras2011/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/contreras2011/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/contreras2011/gurobi_feasi_result/large_feasi_result_5.json b/tasks/contreras2011/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/contreras2011/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/contreras2011/gurobi_feasi_result/tiny_feasi_result.json b/tasks/contreras2011/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/contreras2011/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/contreras2011/gurobi_solution/large_solution_1.json b/tasks/contreras2011/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..251c663856948879e8da5e3b232efc17b64a9acf --- /dev/null +++ b/tasks/contreras2011/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d2ca7535dc2351705e5d28745627f9240231b329112e975064efcd572adfcf0 +size 526 diff --git a/tasks/contreras2011/gurobi_solution/large_solution_2.json b/tasks/contreras2011/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e8f0fc5078f014ee3d946289e12d688be98168fd --- /dev/null +++ b/tasks/contreras2011/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7c456eddfce56a644431a27c608c67178b70d06d954134c220336a9a431001f +size 518 diff --git a/tasks/contreras2011/gurobi_solution/large_solution_3.json b/tasks/contreras2011/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..59c27b0ca996c4688ee806f7236d17e1b59bb8d6 --- /dev/null +++ b/tasks/contreras2011/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad30915f2eb11f5582a02dd4b569c1524460016a9903cafc04d484e51f1ca4d9 +size 516 diff --git a/tasks/contreras2011/gurobi_solution/large_solution_4.json b/tasks/contreras2011/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..594927d37608285601aec9c2f6dab3b27004443a --- /dev/null +++ b/tasks/contreras2011/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:91aa2cc0f1d7ad1dcf36f18f5face04fc7f24c107a525c24b340fafb6053ad16 +size 526 diff --git a/tasks/contreras2011/gurobi_solution/large_solution_5.json b/tasks/contreras2011/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c7b258cb3797370baa040a5865676da475df8afb --- /dev/null +++ b/tasks/contreras2011/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f22b27ea41f9dfb4fd0575264a32ee9bcdea76f6df5c29f7b0374b94e67414e2 +size 517 diff --git a/tasks/contreras2011/gurobi_solution/tiny_solution.json b/tasks/contreras2011/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2521a7cb997fab15f224dad0ba1d6f2a647f1226 --- /dev/null +++ b/tasks/contreras2011/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55d0171f67e69a93e40f765b25cddd1e45b438ee161eb60cd1c603750e08802b +size 253 diff --git a/tasks/contreras2011/gurobi_solution_log/large_log_1.jsonl b/tasks/contreras2011/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fadb62aea703fae4e737433fe966f825b215cce1 --- /dev/null +++ b/tasks/contreras2011/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef111d87f938f3f502c8dd6e5e6ee955c932388dc63c4d077cd185ad7ce8a0a1 +size 505 diff --git a/tasks/contreras2011/gurobi_solution_log/large_log_2.jsonl b/tasks/contreras2011/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..baabee06eb2282ca58db42d84edf8444c96d1cbd --- /dev/null +++ b/tasks/contreras2011/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a2e9cd12b8c4070f0fea118958cf36b04b80e823490cc4674f9927937aaf47b +size 223 diff --git a/tasks/contreras2011/gurobi_solution_log/large_log_3.jsonl b/tasks/contreras2011/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9bc545b24006869fd2c9a6c357133df83bc5227f --- /dev/null +++ b/tasks/contreras2011/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2724c5aa29bbaafbc025db1ccc4aa535816c7e37eb01668ea85e19b27033c868 +size 169 diff --git a/tasks/contreras2011/gurobi_solution_log/large_log_4.jsonl b/tasks/contreras2011/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..03ee88022e797bfd91f006b9d1165090fc149061 --- /dev/null +++ b/tasks/contreras2011/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbaf0eb8c5612199251d861dbc0bdb0dbf8e13d854d2b55d8689508e2cc5de44 +size 502 diff --git a/tasks/contreras2011/gurobi_solution_log/large_log_5.jsonl b/tasks/contreras2011/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b67e1a2359c36be7eece1376c2b41b2c8d7b555f --- /dev/null +++ b/tasks/contreras2011/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78dc37795ac80e81e5af1f924f0bdb7245df4a139e1c35507a2b2d81f5e9eebf +size 168 diff --git a/tasks/contreras2011/gurobi_solution_log/tiny_log.jsonl b/tasks/contreras2011/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b69ca628454dcc8a26c2a2cdc70045e3ba88806a --- /dev/null +++ b/tasks/contreras2011/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:561e942fb17811a5b803de1e8f13101089b418e0540f1328c1217af95c0d2205 +size 53 diff --git a/tasks/contreras2011/instance/large_instance_1.json b/tasks/contreras2011/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f6c87b3e4f6ebbfba26ccfc441efe9b9d5002621 --- /dev/null +++ b/tasks/contreras2011/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:638421f246c1a51fb1d475e04906f87004279fba3cf56e95c1193972b34583c2 +size 56477 diff --git a/tasks/contreras2011/instance/large_instance_2.json b/tasks/contreras2011/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..289c9a193d46f49c249416f1d24784787c2d2e3a --- /dev/null +++ b/tasks/contreras2011/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acc1d19d5022c3818fab8cc4e0c4ad34243e77d624e3a237f52b0d59921a707b +size 56440 diff --git a/tasks/contreras2011/instance/large_instance_3.json b/tasks/contreras2011/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..04c77405d79679ddfcf262929a96608601d65a64 --- /dev/null +++ b/tasks/contreras2011/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e0702625620e3ffc80b89fd1ffa0bb2798218f38b05c3b931aa5453f13ff02d +size 56446 diff --git a/tasks/contreras2011/instance/large_instance_4.json b/tasks/contreras2011/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..36629ed91a8f2d524d8e7ba30b06e2db915a3e34 --- /dev/null +++ b/tasks/contreras2011/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be5675f1fd2bf54f45c62eec56d4396a898394a8d04be860488d7ef3fb64840e +size 56425 diff --git a/tasks/contreras2011/instance/large_instance_5.json b/tasks/contreras2011/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..1cf68c0100e943a2bb2971fb80f04c0e18f0bec3 --- /dev/null +++ b/tasks/contreras2011/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72be5d02ebfab4ce14387dfeb48111a90d2818b6a66511dfc86949e407d0dd06 +size 56551 diff --git a/tasks/contreras2011/instance/tiny_instance.json b/tasks/contreras2011/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..2ffe0a0ddb9ea8017d4ab894d0190b416eb87b56 --- /dev/null +++ b/tasks/contreras2011/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bd80e116d3ae47ad5df251f760289bd2d7482c69e89d8b82a25592359723ab8 +size 5656 diff --git a/tasks/contreras2011/instance_schema.json b/tasks/contreras2011/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5fe184ed3866d9a00dc319d1c13bb1a27d80f88c --- /dev/null +++ b/tasks/contreras2011/instance_schema.json @@ -0,0 +1,16 @@ +{ + "n": " Number of nodes in the logistics network, each serving as both a potential hub location and a source or destination of commodity flow.", + "cost_parameters": { + "collection_cost_chi": " Per-unit-distance cost rate for transporting flow from an origin node to its assigned hub.", + "transfer_cost_alpha": " Discounted per-unit-distance cost rate for transporting consolidated flow between two hubs.", + "distribution_cost_delta": " Per-unit-distance cost rate for transporting flow from a destination's assigned hub to the destination node.", + "routing_cost_formula": " Formula expressing the routing cost for sending flow from origin i to destination j via hubs k and m." + }, + "total_flow_D": " Total outgoing flow across all nodes in the network.", + "coordinates": " Geographic x and y coordinates of each node.", + "flow_matrix": " Quantity of commodity flow originating at node i and destined for node j.", + "distance_matrix": " Euclidean distance between each pair of nodes, scaled by a factor of 1/1000.", + "outgoing_flow": " Total flow originating at each node, summed over all destinations.", + "setup_costs": " Fixed cost incurred for opening a hub at each node.", + "capacities": " Maximum total incoming flow that each node can handle if opened as a hub." +} diff --git a/tasks/contreras2011/mathematical_formulation.md b/tasks/contreras2011/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f56f68b07808cbe21ab82164fdd1b59ac9833e26 --- /dev/null +++ b/tasks/contreras2011/mathematical_formulation.md @@ -0,0 +1,50 @@ +# Original Formulation: Capacitated Hub Location Problem with Single Assignment (CHLPSA), Formulation (MP) + +*Source: Branch and Price for Large-Scale Capacitated Hub Location Problems with Single Assignment, Contreras, Díaz, and Fernández, 2011.* + +## Sets and Parameters + +- $G = (N, A)$: complete digraph; $N = \{1,\dots,n\}$ is the set of nodes (potential hub locations). + +- Indices $(i,j) \in N \times N$ denote origin/destination pairs; $(k,m) \in N \times N$ denote hub pairs. + +- $W_{ij}$: flow with origin $i$ and destination $j$. + +- $d_{ij}$: distance from $i$ to $j$ (satisfies the triangle inequality). + +- $F_{ijkm} = W_{ij}(\chi\, d_{ik} + \alpha\, d_{km} + \delta\, d_{mj})$: cost of routing $W_{ij}$ along path $i \to k \to m \to j$, where $\chi,\alpha,\delta$ are collection, transfer, and distribution coefficients. + +- $f_k$: fixed setup cost of locating a hub at node $k$. + +- $b_k$: capacity of hub $k$ (upper bound on total incoming flow). + +- $O_i = \sum_{j \in N} W_{ij}$: total outgoing flow at node $i$. + +- $D = \sum_{i \in N} O_i$: total flow in the graph. + +## Decision Variables + +- $z_{ik} \in \{0,1\}$, $i,k \in N$: $=1$ iff node $i$ is assigned to hub $k$; $z_{kk} = 1$ indicates a hub is located at $k$. + +- $x_{ijkm} \geq 0$, $i,j,k,m \in N$: $=1$ iff the flow from $i$ to $j$ is routed via hubs $k$ and $m$ (integrality is implied by the binary $z$ variables together with (4) and (5)). + +## Objective + +$$\begin{equation} +\min \;\; \sum_{k \in N} f_k\, z_{kk} + \;+\; \sum_{i \in N} \sum_{j \in N} \sum_{k \in N} \sum_{m \in N} F_{ijkm}\, x_{ijkm} +\tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{k \in N} \sum_{m \in N} x_{ijkm} &= 1, & \forall\, i, j \in N \tag{2} \\[2pt] +z_{ik} &\;\leq\; z_{kk}, & \forall\, i, k \in N \tag{3} \\[2pt] +\sum_{m \in N} x_{ijkm} &= z_{ik}, & \forall\, i, j, k \in N \tag{4} \\[2pt] +\sum_{k \in N} x_{ijkm} &= z_{jm}, & \forall\, i, j, m \in N \tag{5} \\[2pt] +\sum_{i \in N} O_i\, z_{ik} &\;\leq\; b_k\, z_{kk}, & \forall\, k \in N \tag{6} \\[2pt] +\sum_{k \in N} b_k\, z_{kk} &\;\geq\; D, \tag{7} \\[2pt] +x_{ijkm} &\;\geq\; 0, & \forall\, i, j, k, m \in N \tag{8} \\[2pt] +z_{ik} &\;\in\; \{0,1\}, & \forall\, i, k \in N \tag{9} +\end{align}$$ diff --git a/tasks/contreras2011/problem_description.txt b/tasks/contreras2011/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b8e98941fadf49bb781640a02f82adacb740d45 --- /dev/null +++ b/tasks/contreras2011/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A logistics network consists of a given number of nodes, each of which is both a potential hub location and a source or destination of commodity flow. Every ordered pair of nodes has an associated flow quantity representing the amount of commodity originating at the first node and destined for the second. The Euclidean distance between every pair of nodes is known and satisfies the triangle inequality. Each node has a fixed setup cost that must be paid if that node is selected as a hub, and each potential hub has a capacity that limits the total incoming flow it can handle. + +The company must decide which nodes to open as hubs and must assign every node to exactly one open hub, where each open hub is assigned to itself. All commodity flow between an origin node and a destination node is routed along a three-leg path: from the origin to the origin's assigned hub, then between hubs (from the origin's hub to the destination's hub), and finally from the destination's hub to the destination. The cost of routing the flow for a given origin-destination pair through a given pair of hubs equals the flow quantity multiplied by the sum of three distance-based components: the collection cost rate times the distance from the origin to its hub, the inter-hub transfer cost rate times the distance between the two hubs, and the distribution cost rate times the distance from the destination's hub to the destination. The collection cost rate, inter-hub transfer cost rate, and distribution cost rate are given constants (in standard benchmark instances these are 3, 0.75, and 2, respectively), where the discounted inter-hub transfer rate reflects economies of scale on consolidated hub-to-hub links. + +Each node must be assigned to exactly one hub, and a node may only be assigned to a hub that is open. For every origin-destination pair, exactly one routing path (defined by a pair of hubs) must be selected. The routing must be consistent with the hub assignments: if the origin is assigned to a particular hub, then all flow originating at that node must depart through that hub regardless of destination, and symmetrically, if the destination is assigned to a particular hub, then all flow arriving at that node must arrive through that hub regardless of origin. The total outgoing flow of a node is defined as the sum of flows from that node to every other node (including itself). The total outgoing flow of all nodes assigned to a given hub must not exceed that hub's capacity, and this capacity restriction applies only when the hub is open. Additionally, the combined capacity of all opened hubs must be at least as large as the total flow generated across the entire network. + +The goal is to minimize the total cost, which is the sum of the fixed setup costs of all opened hubs plus the routing costs for all origin-destination pairs across their assigned hub paths. diff --git a/tasks/contreras2011/solution_logger.py b/tasks/contreras2011/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/contreras2011/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/contreras2011/solution_schema.json b/tasks/contreras2011/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f43b527608e1318c6d854a815f351cca5344debc --- /dev/null +++ b/tasks/contreras2011/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total cost of the solution, comprising hub setup costs and all routing costs.", + "hubs": " Indices of nodes selected to operate as hubs.", + "assignment": " Index of the hub to which each node is assigned for sending and receiving all its flow." +} diff --git a/tasks/cordeau2006/feasibility_check.py b/tasks/cordeau2006/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f0072b6cd154433493d221a019f4e1f8898772f1 --- /dev/null +++ b/tasks/cordeau2006/feasibility_check.py @@ -0,0 +1,776 @@ +""" +Feasibility checker for the Dial-a-Ride Problem (DARP). +Based on: Cordeau (2006), "A Branch-and-Cut Algorithm for the Dial-a-Ride Problem", +Operations Research 54(3), pp. 573-586. + +Checks constraints (2)-(14) from the mathematical formulation, plus +constraint (15) -- objective consistency: the reported objective_value +must match the recomputed routing cost (sum of Euclidean distances along +all arcs in the routes), which is the deterministic objective of (1). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'ride_times', 'routes', 'service_times') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('ride_times', 'service_times') +_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 euclidean_distance(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance_path, solution_path, result_path): + tol = 1e-5 + eps = 1e-5 + + data = load_json(instance_path) + sol = load_json(solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return _frontieror_contract_result + + n = data["num_users"] + K_size = data["num_vehicles"] + Q = data["vehicle_capacity"] + L_max = data["maximum_ride_time"] + T_max = data["maximum_route_duration"] + num_nodes = data["num_nodes"] + + origin_depot = 0 + dest_depot = 2 * n + 1 + + P = list(range(1, n + 1)) + D = list(range(n + 1, 2 * n + 1)) + N_all = list(range(num_nodes)) + K = list(range(K_size)) + + # Extract node data + nodes_by_id = {} + for node in data["nodes"]: + nodes_by_id[node["node_id"]] = node + + x_coord = {} + y_coord = {} + e = {} + l_tw = {} + d_serv = {} + q = {} + for nid, node in nodes_by_id.items(): + x_coord[nid] = node["x"] + y_coord[nid] = node["y"] + e[nid] = node["earliest_time"] + l_tw[nid] = node["latest_time"] + d_serv[nid] = node["service_duration"] + q[nid] = node["load"] + + # Travel times / costs (Euclidean distance) + t_matrix = {} + for i in N_all: + for j in N_all: + if i != j: + t_matrix[i, j] = euclidean_distance( + x_coord[i], y_coord[i], x_coord[j], y_coord[j] + ) + + # ========================================================================= + # Parse solution + # ========================================================================= + if "routes" not in sol or sol["routes"] is None: + result = { + "feasible": None, + "violated_constraints": [], + "violations": ["No solution data in solution file"], + "violation_magnitudes": [], + } + with open(result_path, "w") as f: + json.dump(result, f, indent=2) + print("No solution data in solution file") + print(f"Result written to {result_path}") + return result + + routes = {} + for k_str, route in sol["routes"].items(): + routes[int(k_str)] = route + + service_times = {} + for key, val in sol["service_times"].items(): + service_times[key] = val + + ride_times = {} + if "ride_times" in sol: + for key, val in sol["ride_times"].items(): + ride_times[key] = val + + assignments = {} + if "assignments" in sol: + for key, val in sol["assignments"].items(): + assignments[int(key)] = val + + # Build B (service begin times) for each node + B = {} + for i in P + D: + key = str(i) + if key in service_times: + B[i] = service_times[key] + + B_depot_start = {} + B_depot_end = {} + for k in K: + ds_key = f"depot_start_{k}" + de_key = f"depot_end_{k}" + if ds_key in service_times: + B_depot_start[k] = service_times[ds_key] + if de_key in service_times: + B_depot_end[k] = service_times[de_key] + + # Build x (binary routing variables) from routes + x_var = {} + for k in K: + route = routes.get(k, []) + for idx in range(len(route) - 1): + i_node = route[idx] + j_node = route[idx + 1] + x_var[k, i_node, j_node] = 1 + + # Build load at each node by traversing routes + Q_var = {} + for k in K: + route = routes.get(k, []) + load = 0 + for node in route: + load += q.get(node, 0) + Q_var[k, node] = load + + # Build ride times from solution or compute from B + L_var = {} + for i in P: + key = str(i) + if key in ride_times: + L_var[i] = ride_times[key] + elif i in B and (n + i) in B: + L_var[i] = B[n + i] - (B[i] + d_serv[i]) + + violations = [] + violated_constraints = set() + violation_magnitudes = [] + + def add_violation(constraint_idx, message, lhs, rhs, violation_amount): + violated_constraints.add(constraint_idx) + violations.append(message) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # A partial timing map is not a valid witness: all timing checks below use + # dictionary lookups, so missing keys must be rejected before those checks + # can legitimately use their defensive `continue` branches. + expected_route_keys = set(K) + if set(routes) != expected_route_keys: + add_violation( + 1, + "Route map must contain exactly one route for every vehicle: " + f"expected={sorted(expected_route_keys)}, got={sorted(routes)}", + float(len(routes)), float(len(expected_route_keys)), + float(len(set(routes) ^ expected_route_keys)), + ) + + expected_service_keys = {str(i) for i in P + D} + expected_service_keys.update(f"depot_start_{k}" for k in K) + expected_service_keys.update(f"depot_end_{k}" for k in K) + actual_service_keys = set(service_times) + if actual_service_keys != expected_service_keys: + missing = sorted(expected_service_keys - actual_service_keys) + extra = sorted(actual_service_keys - expected_service_keys) + add_violation( + 7, + "service_times must exactly cover every request node and both " + f"depot endpoints per vehicle; missing={missing[:10]}, extra={extra[:10]}", + float(len(actual_service_keys)), float(len(expected_service_keys)), + float(len(actual_service_keys ^ expected_service_keys)), + ) + + expected_ride_keys = {str(i) for i in P} + actual_ride_keys = set(ride_times) + if actual_ride_keys != expected_ride_keys: + missing = sorted(expected_ride_keys - actual_ride_keys) + extra = sorted(actual_ride_keys - expected_ride_keys) + add_violation( + 9, + "ride_times must exactly cover every pickup request; " + f"missing={missing[:10]}, extra={extra[:10]}", + float(len(actual_ride_keys)), float(len(expected_ride_keys)), + float(len(actual_ride_keys ^ expected_ride_keys)), + ) + + # ========================================================================= + # Constraint (2): Each request served exactly once + # sum_{k in K} sum_{j in N} x^k_{ij} = 1 for all i in P + # ========================================================================= + for i in P: + total = sum( + x_var.get((k, i, j), 0) for k in K for j in N_all if j != i + ) + violation_amount = abs(total - 1) + if violation_amount > tol: + add_violation( + 2, + f"Constraint (2): Pickup node {i} (user {i}) served {total} times instead of exactly 1", + total, 1.0, violation_amount, + ) + + # ========================================================================= + # Constraint (3): Same vehicle serves pickup and dropoff + # sum_{j in N} x^k_{ij} - sum_{j in N} x^k_{n+i,j} = 0 + # for all i in P, k in K + # ========================================================================= + for i in P: + for k in K: + out_pickup = sum( + x_var.get((k, i, j), 0) for j in N_all if j != i + ) + out_dropoff = sum( + x_var.get((k, n + i, j), 0) for j in N_all if j != n + i + ) + diff = out_pickup - out_dropoff + violation_amount = abs(diff) + if violation_amount > tol: + add_violation( + 3, + f"Constraint (3): User {i}, vehicle {k}: pickup outflow={out_pickup}, dropoff outflow={out_dropoff}, diff={diff}", + diff, 0.0, violation_amount, + ) + + # ========================================================================= + # Constraint (4): Each vehicle route starts at origin depot + # sum_{j in N} x^k_{0,j} = 1 for all k in K + # ========================================================================= + for k in K: + total = sum( + x_var.get((k, origin_depot, j), 0) for j in N_all if j != origin_depot + ) + violation_amount = abs(total - 1) + if violation_amount > tol: + add_violation( + 4, + f"Constraint (4): Vehicle {k} has {total} arcs leaving origin depot instead of 1", + total, 1.0, violation_amount, + ) + + # ========================================================================= + # Constraint (5): Flow conservation at pickup and dropoff nodes + # sum_{j in N} x^k_{j,i} - sum_{j in N} x^k_{i,j} = 0 + # for all i in P union D, k in K + # ========================================================================= + for i in P + D: + for k in K: + inflow = sum( + x_var.get((k, j, i), 0) for j in N_all if j != i + ) + outflow = sum( + x_var.get((k, i, j), 0) for j in N_all if j != i + ) + diff = inflow - outflow + violation_amount = abs(diff) + if violation_amount > tol: + add_violation( + 5, + f"Constraint (5): Node {i}, vehicle {k}: inflow={inflow}, outflow={outflow}, diff={diff}", + diff, 0.0, violation_amount, + ) + + # ========================================================================= + # Constraint (6): Each vehicle route ends at destination depot + # sum_{i in N} x^k_{i,2n+1} = 1 for all k in K + # ========================================================================= + for k in K: + total = sum( + x_var.get((k, i, dest_depot), 0) for i in N_all if i != dest_depot + ) + violation_amount = abs(total - 1) + if violation_amount > tol: + add_violation( + 6, + f"Constraint (6): Vehicle {k} has {total} arcs entering destination depot instead of 1", + total, 1.0, violation_amount, + ) + + # ========================================================================= + # Constraint (7): Time consistency + # B^k_j >= (B^k_i + d_i + t_{ij}) * x^k_{ij} + # for all i in N, j in N, k in K + # Only active when x^k_{ij} = 1. + # ========================================================================= + for k in K: + route = routes.get(k, []) + for idx in range(len(route) - 1): + i_node = route[idx] + j_node = route[idx + 1] + # Get B values + if i_node == origin_depot: + B_i = B_depot_start.get(k, 0) + elif i_node == dest_depot: + B_i = B_depot_end.get(k, 0) + else: + B_i = B.get(i_node) + if j_node == origin_depot: + B_j = B_depot_start.get(k, 0) + elif j_node == dest_depot: + B_j = B_depot_end.get(k, 0) + else: + B_j = B.get(j_node) + + if B_i is None or B_j is None: + continue + if (i_node, j_node) not in t_matrix: + continue + + required = B_i + d_serv[i_node] + t_matrix[i_node, j_node] + violation_amount = required - B_j + if violation_amount > tol: + add_violation( + 7, + f"Constraint (7): Vehicle {k}, arc ({i_node}->{j_node}): B[{j_node}]={B_j:.6f} < {required:.6f} (B[{i_node}]+d+t)", + B_j, required, violation_amount, + ) + + # ========================================================================= + # Constraint (8): Load consistency + # Q^k_j >= (Q^k_i + q_j) * x^k_{ij} + # for all i in N, j in N, k in K + # Only active when x^k_{ij} = 1. + # ========================================================================= + for k in K: + route = routes.get(k, []) + for idx in range(len(route) - 1): + i_node = route[idx] + j_node = route[idx + 1] + Q_i = Q_var.get((k, i_node)) + Q_j = Q_var.get((k, j_node)) + if Q_i is None or Q_j is None: + continue + required = Q_i + q.get(j_node, 0) + violation_amount = required - Q_j + if violation_amount > tol: + add_violation( + 8, + f"Constraint (8): Vehicle {k}, arc ({i_node}->{j_node}): Q[{j_node}]={Q_j} < {required} (Q[{i_node}]+q[{j_node}])", + Q_j, required, violation_amount, + ) + + # ========================================================================= + # Constraint (9): Ride time definition + # L^k_i = B^k_{n+i} - (B^k_i + d_i) for all i in P, k in K + # ========================================================================= + for i in P: + if i not in B or (n + i) not in B: + continue + expected = B[n + i] - (B[i] + d_serv[i]) + actual = L_var.get(i) + if actual is not None: + violation_amount = abs(actual - expected) + if violation_amount > tol: + add_violation( + 9, + f"Constraint (9): User {i}: ride time L={actual:.6f} != B[{n+i}]-B[{i}]-d={expected:.6f}", + actual, expected, violation_amount, + ) + + # ========================================================================= + # Constraint (10): Maximum route duration + # B^k_{2n+1} - B^k_0 <= T_k for all k in K + # ========================================================================= + for k in K: + if k not in B_depot_start or k not in B_depot_end: + continue + duration = B_depot_end[k] - B_depot_start[k] + rhs = T_max + violation_amount = duration - rhs + if violation_amount > tol: + add_violation( + 10, + f"Constraint (10): Vehicle {k}: route duration={duration:.6f} > T_max={rhs}", + duration, rhs, violation_amount, + ) + + # ========================================================================= + # Constraint (11): Time windows + # e_i <= B^k_i <= l_i for all i in N, k in K + # ========================================================================= + # Check non-depot nodes + for i in P + D: + if i not in B: + continue + # Lower bound: e_i <= B_i + lb_violation = e[i] - B[i] + if lb_violation > tol: + add_violation( + 11, + f"Constraint (11): Node {i}: B={B[i]:.6f} < earliest={e[i]:.6f}", + B[i], e[i], lb_violation, + ) + # Upper bound: B_i <= l_i + ub_violation = B[i] - l_tw[i] + if ub_violation > tol: + add_violation( + 11, + f"Constraint (11): Node {i}: B={B[i]:.6f} > latest={l_tw[i]:.6f}", + B[i], l_tw[i], ub_violation, + ) + # Check depot nodes + for k in K: + if k in B_depot_start: + lb_viol = e[origin_depot] - B_depot_start[k] + if lb_viol > tol: + add_violation( + 11, + f"Constraint (11): Vehicle {k} origin depot: B={B_depot_start[k]:.6f} < earliest={e[origin_depot]:.6f}", + B_depot_start[k], e[origin_depot], lb_viol, + ) + ub_viol = B_depot_start[k] - l_tw[origin_depot] + if ub_viol > tol: + add_violation( + 11, + f"Constraint (11): Vehicle {k} origin depot: B={B_depot_start[k]:.6f} > latest={l_tw[origin_depot]:.6f}", + B_depot_start[k], l_tw[origin_depot], ub_viol, + ) + if k in B_depot_end: + lb_viol = e[dest_depot] - B_depot_end[k] + if lb_viol > tol: + add_violation( + 11, + f"Constraint (11): Vehicle {k} dest depot: B={B_depot_end[k]:.6f} < earliest={e[dest_depot]:.6f}", + B_depot_end[k], e[dest_depot], lb_viol, + ) + ub_viol = B_depot_end[k] - l_tw[dest_depot] + if ub_viol > tol: + add_violation( + 11, + f"Constraint (11): Vehicle {k} dest depot: B={B_depot_end[k]:.6f} > latest={l_tw[dest_depot]:.6f}", + B_depot_end[k], l_tw[dest_depot], ub_viol, + ) + + # ========================================================================= + # Constraint (12): Ride time bounds + # t_{i,n+i} <= L^k_i <= L for all i in P, k in K + # ========================================================================= + for i in P: + if i not in L_var: + continue + ride = L_var[i] + t_direct = t_matrix[i, n + i] + # Lower bound: t_{i,n+i} <= L_i + lb_violation = t_direct - ride + if lb_violation > tol: + add_violation( + 12, + f"Constraint (12): User {i}: ride time={ride:.6f} < direct travel time={t_direct:.6f}", + ride, t_direct, lb_violation, + ) + # Upper bound: L_i <= L + ub_violation = ride - L_max + if ub_violation > tol: + add_violation( + 12, + f"Constraint (12): User {i}: ride time={ride:.6f} > max ride time={L_max}", + ride, float(L_max), ub_violation, + ) + + # ========================================================================= + # Constraint (13): Capacity bounds + # max{0, q_i} <= Q^k_i <= min{Q_k, Q_k + q_i} + # for all i in N, k in K + # ========================================================================= + for k in K: + route = routes.get(k, []) + for node in route: + Q_node = Q_var.get((k, node)) + if Q_node is None: + continue + lb = max(0, q.get(node, 0)) + ub = min(Q, Q + q.get(node, 0)) + lb_violation = lb - Q_node + if lb_violation > tol: + add_violation( + 13, + f"Constraint (13): Vehicle {k}, node {node}: load={Q_node} < lower bound={lb}", + float(Q_node), float(lb), lb_violation, + ) + ub_violation = Q_node - ub + if ub_violation > tol: + add_violation( + 13, + f"Constraint (13): Vehicle {k}, node {node}: load={Q_node} > upper bound={ub} (capacity={Q})", + float(Q_node), float(ub), ub_violation, + ) + + # ========================================================================= + # Constraint (14): Binary variables + # x^k_{ij} in {0, 1} for all i in N, j in N, k in K + # Since we reconstruct x from routes as 0/1, check that each arc is used + # at most once and values are binary. + # ========================================================================= + for key, val in x_var.items(): + violation_amount = abs(val - round(val)) + if violation_amount > tol: + k, i_node, j_node = key + add_violation( + 14, + f"Constraint (14): x[{k},{i_node},{j_node}]={val} is not binary", + val, round(val), violation_amount, + ) + + # ========================================================================= + # Constraint (15): Objective consistency + # The reported objective_value must equal the recomputed routing cost, + # which is sum_{k in K} sum_{(i,j) in route_k} c_{ij} where + # c_{ij} = t_{ij} = Euclidean distance between nodes i and j + # (per math_model.txt reproduction note 1; cost = travel time for all + # computational experiments). Full recompute applies because the route + # variables fully determine which arcs are traversed. + # ========================================================================= + reported_obj = sol.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + for k in K: + route = routes.get(k, []) + for idx in range(len(route) - 1): + i_node = route[idx] + j_node = route[idx + 1] + if (i_node, j_node) in t_matrix: + true_obj += t_matrix[i_node, j_node] + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor. + tol_obj = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + add_violation( + 15, + f"Constraint (15): Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum of arc Euclidean distances=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol_obj:.6g})", + reported, true_obj, abs_diff, + ) + + # ========================================================================= + # Compile results + # ========================================================================= + unique_violated = sorted(violated_constraints) + feasible = len(unique_violated) == 0 + + # Deduplicate violation messages per constraint + seen_messages = set() + unique_violations = [] + for msg in violations: + if msg not in seen_messages: + seen_messages.add(msg) + unique_violations.append(msg) + + result = { + "feasible": feasible, + "violated_constraints": unique_violated, + "violations": unique_violations, + "violation_magnitudes": violation_magnitudes if not feasible else [], + } + + with open(result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasibility: {'FEASIBLE' if feasible else 'INFEASIBLE'}") + if not feasible: + print(f"Violated constraints: {unique_violated}") + for msg in unique_violations: + print(f" - {msg}") + print(f"Result written to {result_path}") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for DARP (Cordeau 2006)" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance." + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution." + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result." + ) + args = parser.parse_args() + check_feasibility(args.instance_path, args.solution_path, 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/cordeau2006/gurobi_code.py b/tasks/cordeau2006/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..5cf86bad4975664a277b30ebc5ccab818d9bc30f --- /dev/null +++ b/tasks/cordeau2006/gurobi_code.py @@ -0,0 +1,429 @@ +""" +Gurobi implementation of the Dial-a-Ride Problem (DARP) +Based on: Cordeau (2006), "A Branch-and-Cut Algorithm for the Dial-a-Ride Problem", +Operations Research 54(3), pp. 573-586. + +Uses the aggregate formulation (constraints 17-24) as described in the paper. +""" + +import argparse +import json +import math +import time +import sys +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("ERROR: gurobipy is not installed. Please install Gurobi.") + sys.exit(1) + + +def euclidean_distance(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def load_instance(instance_path): + """Load a DARP instance from JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(instance_path, solution_path, time_limit): + """Build and solve the DARP model using Gurobi.""" + data = load_instance(instance_path) + + n = data["num_users"] # number of users + K_size = data["num_vehicles"] + Q = data["vehicle_capacity"] + L = data["maximum_ride_time"] + T_max = data["maximum_route_duration"] + + nodes = data["nodes"] + num_nodes = data["num_nodes"] # = 2n + 2 + + # Node indices: + # 0: origin depot + # 1..n: pickup nodes (P) + # n+1..2n: dropoff nodes (D) + # 2n+1: destination depot + origin_depot = 0 + dest_depot = 2 * n + 1 + + P = list(range(1, n + 1)) + D = list(range(n + 1, 2 * n + 1)) + N = list(range(num_nodes)) # all nodes including depots + K = list(range(K_size)) + + # Extract node data + x_coord = {} + y_coord = {} + e = {} # earliest time + l = {} # latest time + d = {} # service duration + q = {} # load + + for node in nodes: + nid = node["node_id"] + x_coord[nid] = node["x"] + y_coord[nid] = node["y"] + e[nid] = node["earliest_time"] + l[nid] = node["latest_time"] + d[nid] = node["service_duration"] + q[nid] = node["load"] + + # Compute travel times/costs (Euclidean distance) + t = {} + c = {} + for i in N: + for j in N: + if i != j: + dist = euclidean_distance(x_coord[i], y_coord[i], x_coord[j], y_coord[j]) + t[i, j] = dist + c[i, j] = dist + + # ========================================================================= + # ARC ELIMINATION (Section 5.1.2) + # ========================================================================= + # Build the set of feasible arcs A + A = [] + for i in N: + for j in N: + if i == j: + continue + # Remove arcs (0, n+i) for i in P: depot directly to dropoff + if i == origin_depot and j in D: + continue + # Remove arcs (i, 2n+1) for i in P: pickup directly to dest depot + if i in P and j == dest_depot: + continue + # Remove arcs (n+i, i) for i in P: dropoff back to own pickup + if i in D and j in P and i == j + n: + continue + # Remove arc (i,j) if e_i + d_i + t_ij > l_j + if e[i] + d[i] + t[i, j] > l[j] + 1e-9: + continue + # Remove arcs between depot nodes that don't make sense + if i == dest_depot: + continue # no arcs out of destination depot + if j == origin_depot: + continue # no arcs into origin depot + A.append((i, j)) + + A_set = set(A) + + # ========================================================================= + # BUILD GUROBI MODEL + # ========================================================================= + model = gp.Model("DARP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # --- Decision Variables --- + # x[k,i,j]: binary, vehicle k traverses arc (i,j) + x = {} + for k in K: + for (i, j) in A: + x[k, i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{k}_{i}_{j}") + + # B_i: aggregate time variable for non-depot nodes + B = {} + for i in P + D: + B[i] = model.addVar(lb=e[i], ub=l[i], vtype=GRB.CONTINUOUS, name=f"B_{i}") + + # B_k_0, B_k_{2n+1}: per-vehicle time at depots + B_depot_start = {} + B_depot_end = {} + for k in K: + B_depot_start[k] = model.addVar(lb=e[origin_depot], ub=l[origin_depot], + vtype=GRB.CONTINUOUS, name=f"B_{k}_0") + B_depot_end[k] = model.addVar(lb=e[dest_depot], ub=l[dest_depot], + vtype=GRB.CONTINUOUS, name=f"B_{k}_{dest_depot}") + + # Q_i: aggregate load for non-depot nodes (homogeneous fleet) + Qvar = {} + for i in P + D: + lb_q = max(0, q[i]) + ub_q = min(Q, Q + q[i]) + Qvar[i] = model.addVar(lb=lb_q, ub=ub_q, vtype=GRB.CONTINUOUS, name=f"Q_{i}") + + # Q_k_0, Q_k_{2n+1}: per-vehicle load at depots + Q_depot_start = {} + Q_depot_end = {} + for k in K: + Q_depot_start[k] = model.addVar(lb=0, ub=0, vtype=GRB.CONTINUOUS, + name=f"Q_{k}_0") + Q_depot_end[k] = model.addVar(lb=0, ub=0, vtype=GRB.CONTINUOUS, + name=f"Q_{k}_{dest_depot}") + + # L_i: aggregate ride time for users + L_var = {} + for i in P: + t_direct = t[i, n + i] + L_var[i] = model.addVar(lb=t_direct, ub=L, vtype=GRB.CONTINUOUS, + name=f"L_{i}") + + model.update() + + # --- Objective (1): minimize total routing cost --- + model.setObjective( + gp.quicksum(c[i, j] * x[k, i, j] + for k in K for (i, j) in A if (k, i, j) in x), + GRB.MINIMIZE + ) + + # --- Constraint (2): each request served exactly once --- + for i in P: + model.addConstr( + gp.quicksum(x[k, i, j] for k in K for j in N + if (i, j) in A_set and (k, i, j) in x) == 1, + name=f"serve_{i}" + ) + + # --- Constraint (3): same vehicle for pickup and dropoff --- + for i in P: + for k in K: + model.addConstr( + gp.quicksum(x[k, i, j] for j in N if (i, j) in A_set and (k, i, j) in x) - + gp.quicksum(x[k, n + i, j] for j in N if (n + i, j) in A_set and (k, n + i, j) in x) == 0, + name=f"pair_{i}_{k}" + ) + + # --- Constraint (4): each vehicle starts at origin depot --- + for k in K: + model.addConstr( + gp.quicksum(x[k, origin_depot, j] for j in N + if (origin_depot, j) in A_set and (k, origin_depot, j) in x) == 1, + name=f"start_{k}" + ) + + # --- Constraint (5): flow conservation at pickup and dropoff nodes --- + for i in P + D: + for k in K: + model.addConstr( + gp.quicksum(x[k, j, i] for j in N if (j, i) in A_set and (k, j, i) in x) - + gp.quicksum(x[k, i, j] for j in N if (i, j) in A_set and (k, i, j) in x) == 0, + name=f"flow_{i}_{k}" + ) + + # --- Constraint (6): each vehicle ends at destination depot --- + for k in K: + model.addConstr( + gp.quicksum(x[k, i, dest_depot] for i in N + if (i, dest_depot) in A_set and (k, i, dest_depot) in x) == 1, + name=f"end_{k}" + ) + + # --- Constraint (17): time from depot to non-depot node --- + # B_j >= (B_k_0 + d_0 + t_{0,j}) * x^k_{0,j} + # Linearized: B_j >= B_k_0 + d[0] + t[0,j] - M*(1 - x^k_{0,j}) + for j in P + D: + for k in K: + if (origin_depot, j) in A_set and (k, origin_depot, j) in x: + M_val = max(0, l[origin_depot] + d[origin_depot] + t[origin_depot, j] - e[j]) + model.addConstr( + B[j] >= B_depot_start[k] + d[origin_depot] + t[origin_depot, j] + - M_val * (1 - x[k, origin_depot, j]), + name=f"time_depot_to_{j}_{k}" + ) + + # --- Constraint (18): time consistency between non-depot nodes --- + # B_j >= (B_i + d_i + t_{ij}) * sum_k x^k_{ij} + # Linearized: B_j >= B_i + d_i + t_{ij} - M_{ij}*(1 - sum_k x^k_{ij}) + for i in P + D: + for j in P + D: + if i == j: + continue + if (i, j) not in A_set: + continue + sum_x = gp.quicksum(x[k, i, j] for k in K if (k, i, j) in x) + M_val = max(0, l[i] + d[i] + t[i, j] - e[j]) + if M_val > 0: + model.addConstr( + B[j] >= B[i] + d[i] + t[i, j] - M_val * (1 - sum_x), + name=f"time_{i}_{j}" + ) + + # --- Constraint (19): time from non-depot node to dest depot --- + # B^k_{2n+1} >= (B_i + d_i + t_{i,2n+1}) * x^k_{i,2n+1} + # Linearized: B^k_{2n+1} >= B_i + d_i + t_{i,2n+1} - M*(1 - x^k_{i,2n+1}) + for i in P + D: + for k in K: + if (i, dest_depot) in A_set and (k, i, dest_depot) in x: + M_val = max(0, l[i] + d[i] + t[i, dest_depot] - e[dest_depot]) + model.addConstr( + B_depot_end[k] >= B[i] + d[i] + t[i, dest_depot] + - M_val * (1 - x[k, i, dest_depot]), + name=f"time_to_depot_{i}_{k}" + ) + + # --- Constraint (20): ride time definition --- + # L_i = B_{n+i} - (B_i + d_i) for i in P + for i in P: + model.addConstr(L_var[i] == B[n + i] - B[i] - d[i], + name=f"ridetime_{i}") + + # --- Constraint (10): maximum route duration --- + # B^k_{2n+1} - B^k_0 <= T_k + for k in K: + model.addConstr(B_depot_end[k] - B_depot_start[k] <= T_max, + name=f"duration_{k}") + + # --- Constraint (21): load from depot to non-depot node --- + # Q_j >= (Q^k_0 + q_j) * x^k_{0,j} + # Since Q^k_0 = 0: Q_j >= q_j * x^k_{0,j} + # Linearized: Q_j >= q_j - W*(1 - x^k_{0,j}) + for j in P + D: + for k in K: + if (origin_depot, j) in A_set and (k, origin_depot, j) in x: + W_val = min(Q, Q + q[origin_depot]) # = Q since q_0 = 0 + model.addConstr( + Qvar[j] >= q[j] - W_val * (1 - x[k, origin_depot, j]), + name=f"load_depot_to_{j}_{k}" + ) + + # --- Constraint (24): lifted load constraints between non-depot nodes --- + # Q_j >= Q_i + q_j - W_{ij}*(1 - sum_k x^k_{ij}) + (W_{ij} - q_i - q_j)*sum_k x^k_{ji} + for i in P + D: + for j in P + D: + if i == j: + continue + if (i, j) not in A_set: + continue + W_ij = min(Q, Q + q[i]) + sum_x_ij = gp.quicksum(x[k, i, j] for k in K if (k, i, j) in x) + sum_x_ji = gp.LinExpr(0) + if (j, i) in A_set: + sum_x_ji = gp.quicksum(x[k, j, i] for k in K if (k, j, i) in x) + model.addConstr( + Qvar[j] >= Qvar[i] + q[j] - W_ij * (1 - sum_x_ij) + + (W_ij - q[i] - q[j]) * sum_x_ji, + name=f"load_{i}_{j}" + ) + + # --- Constraint (23): load from non-depot node to dest depot --- + # Q^k_{2n+1} >= (Q_i + q_{2n+1}) * x^k_{i,2n+1} + # Since q_{2n+1}=0 and Q^k_{2n+1}=0, this is always satisfied when load + # must be 0 at dest depot. We add it for correctness. + # Actually Q_depot_end is fixed at 0, so this constrains Q_i to be <= 0 when + # x^k_{i,2n+1} = 1, but Q_i >= 0 so Q_i = 0 at the last stop before depot. + # This is automatically handled by the load bounds and flow. + + # ========================================================================= + # 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.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + }.get(model.Status, f"STATUS_{model.Status}") + result["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + + # Extract routes + routes = {} + for k in K: + route = [] + current = origin_depot + visited = set() + while current != dest_depot and current not in visited: + visited.add(current) + route.append(current) + found_next = False + for j in N: + if (current, j) in A_set and (k, current, j) in x: + if x[k, current, j].X > 0.5: + current = j + found_next = True + break + if not found_next: + break + route.append(dest_depot) + routes[k] = route + + result["routes"] = {str(k): routes[k] for k in K} + + # Extract service times + service_times = {} + for i in P + D: + service_times[str(i)] = B[i].X + for k in K: + service_times[f"depot_start_{k}"] = B_depot_start[k].X + service_times[f"depot_end_{k}"] = B_depot_end[k].X + result["service_times"] = service_times + + # Extract ride times + ride_times = {} + for i in P: + ride_times[str(i)] = L_var[i].X + result["ride_times"] = ride_times + + else: + result["objective_value"] = None + result["status"] = model.Status + result["status_description"] = "NO_SOLUTION_FOUND" + + result["solve_time_seconds"] = model.Runtime + result["num_variables"] = model.NumVars + result["num_constraints"] = model.NumConstrs + + # Write solution + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']:.2f}") + print(f"Solver status: {result['status_description']}") + print(f"Solve time: {result['solve_time_seconds']:.2f}s") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for the Dial-a-Ride Problem (DARP) - Cordeau (2006)" + ) + 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 solution JSON file will be written.") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + build_and_solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/cordeau2006/gurobi_feasi_result/large_feasi_result_1.json b/tasks/cordeau2006/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2006/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/cordeau2006/gurobi_feasi_result/large_feasi_result_2.json b/tasks/cordeau2006/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2006/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/cordeau2006/gurobi_feasi_result/large_feasi_result_3.json b/tasks/cordeau2006/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2006/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/cordeau2006/gurobi_feasi_result/large_feasi_result_4.json b/tasks/cordeau2006/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2006/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/cordeau2006/gurobi_feasi_result/large_feasi_result_5.json b/tasks/cordeau2006/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2006/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/cordeau2006/gurobi_feasi_result/tiny_feasi_result.json b/tasks/cordeau2006/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2006/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/cordeau2006/gurobi_solution/large_solution_1.json b/tasks/cordeau2006/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..aff0d41ec7bb903eb59259c1d499aa6856e857bd --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:645d995c56740394b9718a9f40dcd24ba75a031d1ea69ed71ed4da1903eba281 +size 4177 diff --git a/tasks/cordeau2006/gurobi_solution/large_solution_2.json b/tasks/cordeau2006/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e2cb2940fca275815c1e9b82efe81ddec7d047b8 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:192787bef26c222969ed317ac7b06b579d22dfe94790ed1b52016c1ba45a1f5b +size 4203 diff --git a/tasks/cordeau2006/gurobi_solution/large_solution_3.json b/tasks/cordeau2006/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b3550c6fe0a426e5621e4483ca64f7d51bb60b5e --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65ce52802bd6a626d48f1ea12e367feb357a51c226968215e9973ce0ec797487 +size 4224 diff --git a/tasks/cordeau2006/gurobi_solution/large_solution_4.json b/tasks/cordeau2006/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..889a1f45f395ab123d97e5bbac7d418784034514 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee9894427845792818634805267fdddd9994b80c96dd38a72a34a67b9450256d +size 4109 diff --git a/tasks/cordeau2006/gurobi_solution/large_solution_5.json b/tasks/cordeau2006/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c81775e117a2b69d47a66c80aefb1b5f5f999c67 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e9d53433a7ae83facd4a4283c2b413e6eece03d4949e50c1967ddad582661c1 +size 2276 diff --git a/tasks/cordeau2006/gurobi_solution/tiny_solution.json b/tasks/cordeau2006/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..4f95e14e6e02bc7522ec1b7367b14282345dc7fc --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4ced029d7d3e05e6723912ba04ddb28e0aff61bbac80f2e855085c101eee16f +size 1995 diff --git a/tasks/cordeau2006/gurobi_solution_log/large_log_1.jsonl b/tasks/cordeau2006/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..56637f49a86587b24bd37404629525639414d594 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5755683e2997a5aab8a6d2874f0b762c8dacb0c716c5ff1637a0b94bb611ca9 +size 626 diff --git a/tasks/cordeau2006/gurobi_solution_log/large_log_2.jsonl b/tasks/cordeau2006/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c6bb4b5d888e6e732a9f8af4fb0bc86bd87bc4a6 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b3de617f31a14f6f98ff723ceaff054340f6b4a84953ff413f7746278fc944e +size 1303 diff --git a/tasks/cordeau2006/gurobi_solution_log/large_log_3.jsonl b/tasks/cordeau2006/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d95756b664a4a7e14f19b9576a21fa145ff77ff3 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85897015109140324f1c3db344fa55aef2a00c1da5008e8d72f3937b4c1f820f +size 107 diff --git a/tasks/cordeau2006/gurobi_solution_log/large_log_4.jsonl b/tasks/cordeau2006/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..091de772986ccad9570f13e9d1b575c7d62e9f87 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42e5a3285b4d0ee8ff4e3d383259b5b06029cf2900c8698e53fe0a928e501895 +size 1530 diff --git a/tasks/cordeau2006/gurobi_solution_log/large_log_5.jsonl b/tasks/cordeau2006/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..64a937599a4698b27767e9e9a9deb384bb4526ef --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aca6ba67a944c9ada07a0813305f5caddfb5fb17e9573887571209c478d2f838 +size 671 diff --git a/tasks/cordeau2006/gurobi_solution_log/tiny_log.jsonl b/tasks/cordeau2006/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fffc397695f5db776c47463c16717499040dd0b1 --- /dev/null +++ b/tasks/cordeau2006/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:337f6599f97599856e55ac065574e293beb8310473aee30ced76055a518b3151 +size 108 diff --git a/tasks/cordeau2006/instance/large_instance_1.json b/tasks/cordeau2006/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..2c1de486b3d875c4fe9f1ea7f0e758fe181650ad --- /dev/null +++ b/tasks/cordeau2006/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e201c205b0c534a085c6b5f17cfd1b8c0ce58b8182e0f61d09bad80f2d14e6dc +size 22553 diff --git a/tasks/cordeau2006/instance/large_instance_2.json b/tasks/cordeau2006/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..06ce6169a99e737a66e4581cd6518fe6038fe2dd --- /dev/null +++ b/tasks/cordeau2006/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba7fff30e4f3da3821333708f77698625c4b039ff2d7aa7cdeff82ddff625d28 +size 22558 diff --git a/tasks/cordeau2006/instance/large_instance_3.json b/tasks/cordeau2006/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..45b4ff0d801d2e3d07f034cf393b68464c669e9a --- /dev/null +++ b/tasks/cordeau2006/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69670442e3f9f4d416c8bd63100a649505816cca7e4566db6cb81ccbd29ef679 +size 22225 diff --git a/tasks/cordeau2006/instance/large_instance_4.json b/tasks/cordeau2006/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d0acd160b08cc6f2040f9494a3a501fce36bc261 --- /dev/null +++ b/tasks/cordeau2006/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcf601ea11208a992fc01f3663b032b1d970a5df4afcef878e692c94fa67bdf4 +size 22539 diff --git a/tasks/cordeau2006/instance/large_instance_5.json b/tasks/cordeau2006/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3b9b7b87267eb42fa9698febcb88b56cb9289190 --- /dev/null +++ b/tasks/cordeau2006/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95d7323393b34bed49ac03905b01ea500f314452862f097f9dbb799879be6ec0 +size 10543 diff --git a/tasks/cordeau2006/instance/tiny_instance.json b/tasks/cordeau2006/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..326ff5e305a378245a72c03cec9fa82cd764682c --- /dev/null +++ b/tasks/cordeau2006/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e9d4ea8891848e9d987e3c402814820d6b603b3d7c586a6a3c37cb60c470b62 +size 10978 diff --git a/tasks/cordeau2006/instance_schema.json b/tasks/cordeau2006/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7a85ac7b7875d61f41a86ebf22041226b8fcd740 --- /dev/null +++ b/tasks/cordeau2006/instance_schema.json @@ -0,0 +1,23 @@ +{ + "num_vehicles": " Number of vehicles available in the dial-a-ride fleet.", + "num_users": " Number of users requesting transportation service.", + "vehicle_capacity": " Maximum number of passengers that each vehicle can carry simultaneously.", + "maximum_ride_time": " Maximum time any user may spend aboard a vehicle from pickup to drop-off.", + "num_nodes": " Total number of nodes in the service network, equal to 2 * num_users + 2 (one pickup and one drop-off per user, plus origin and destination depots).", + "nodes": [ + { + "node_id": " Unique identifier for this node, ranging from 0 (origin depot) to num_nodes - 1 (destination depot).", + "x": " Horizontal coordinate of this node's location.", + "y": " Vertical coordinate of this node's location.", + "earliest_time": " Earliest time at which service may begin at this node.", + "latest_time": " Latest time at which service may begin at this node.", + "service_duration": " Time required to board or alight passengers at this node.", + "load": " Change in vehicle occupancy when visiting this node (positive at pickups, negative at drop-offs, zero at depots).", + "node_type": " Role of this node: 'origin_depot', 'destination_depot', 'pickup', or 'dropoff'.", + "user_id": " Identifier of the user associated with this pickup or drop-off node (present only for pickup and dropoff nodes).", + "paired_node": " Node identifier of the corresponding drop-off node for a pickup, or the corresponding pickup node for a drop-off (present only for pickup and dropoff nodes).", + "request_type": " Whether this user's trip is 'outbound' (from home to a destination) or 'inbound' (from an origin back home) (present only for pickup and dropoff nodes)." + } + ], + "maximum_route_duration": " Maximum total duration of any single vehicle's route from depot departure to depot return." +} \ No newline at end of file diff --git a/tasks/cordeau2006/mathematical_formulation.md b/tasks/cordeau2006/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..2c0b8a539da8b413e2c6c97125886953b7218d06 --- /dev/null +++ b/tasks/cordeau2006/mathematical_formulation.md @@ -0,0 +1,65 @@ +# Original Formulation: Dial-a-Ride Problem (DARP), Per-Vehicle Model + +*Source: A Branch-and-Cut Algorithm for the Dial-a-Ride Problem, Cordeau, 2006.* + +## Sets and Parameters + +- $n$: number of users (requests). + +- $G = (N, A)$: complete directed graph with $N = P \cup D \cup \{0, 2n+1\}$. + +- $P = \{1, \dots, n\}$: pick-up nodes; $D = \{n+1, \dots, 2n\}$: drop-off nodes; node $0$ is the origin depot and $2n+1$ the destination depot. User $i \in P$ has origin $i$ and destination $n+i$. + +- $K$: set of vehicles. + +- $Q_k$: capacity of vehicle $k \in K$. + +- $T_k$: maximum route duration for vehicle $k \in K$. + +- $q_i$: load at node $i$; $q_0 = q_{2n+1} = 0$ and $q_i = -q_{n+i}$ for $i = 1,\dots,n$. + +- $d_i \geq 0$: service duration at node $i$; $d_0 = d_{2n+1} = 0$. + +- $[e_i, l_i]$: time window at node $i$. + +- $c^{k}_{ij}$: routing cost on arc $(i,j)$ (potentially vehicle-dependent). + +- $t_{ij}$: travel time on arc $(i,j)$. + +- $L$: maximum ride time of a user. + +## Decision Variables (Per-Vehicle) + +- $x^{k}_{ij} \in \{0,1\}$, $(i,j) \in A$, $k \in K$: $=1$ iff vehicle $k$ traverses arc $(i,j)$. + +- $B^{k}_{i} \geq 0$, $i \in N$, $k \in K$: time at which vehicle $k$ begins service at node $i$. + +- $Q^{k}_{i} \geq 0$, $i \in N$, $k \in K$: load of vehicle $k$ after visiting node $i$. + +- $L^{k}_{i} \geq 0$, $i \in P$, $k \in K$: ride time of user $i$ on vehicle $k$. + +## Objective + +$$\begin{equation} +\min \;\; \sum_{k \in K} \sum_{i \in N} \sum_{j \in N} c^{k}_{ij}\, x^{k}_{ij} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{k \in K} \sum_{j \in N} x^{k}_{ij} &= 1, & \forall i \in P \tag{2} \\[2pt] +\sum_{j \in N} x^{k}_{ij} \;-\; \sum_{j \in N} x^{k}_{\,n+i,\,j} &= 0, & \forall i \in P,\; k \in K \tag{3} \\[2pt] +\sum_{j \in N} x^{k}_{0 j} &= 1, & \forall k \in K \tag{4} \\[2pt] +\sum_{j \in N} x^{k}_{j i} \;-\; \sum_{j \in N} x^{k}_{i j} &= 0, & \forall i \in P \cup D,\; k \in K \tag{5} \\[2pt] +\sum_{i \in N} x^{k}_{i,\, 2n+1} &= 1, & \forall k \in K \tag{6} \\[2pt] +B^{k}_{j} &\;\geq\; \bigl(B^{k}_{i} + d_{i} + t_{ij}\bigr)\, x^{k}_{ij}, & \forall i, j \in N,\; k \in K \tag{7} \\[2pt] +Q^{k}_{j} &\;\geq\; \bigl(Q^{k}_{i} + q_{j}\bigr)\, x^{k}_{ij}, & \forall i, j \in N,\; k \in K \tag{8} \\[2pt] +L^{k}_{i} &\;=\; B^{k}_{n+i} - \bigl(B^{k}_{i} + d_{i}\bigr), & \forall i \in P,\; k \in K \tag{9} \\[2pt] +B^{k}_{2n+1} - B^{k}_{0} &\;\leq\; T_{k}, & \forall k \in K \tag{10} \\[2pt] +e_{i} \;\leq\; B^{k}_{i} &\;\leq\; l_{i}, & \forall i \in N,\; k \in K \tag{11} \\[2pt] +t_{i,\,n+i} \;\leq\; L^{k}_{i} &\;\leq\; L, & \forall i \in P,\; k \in K \tag{12} \\[2pt] +\max\{0,\, q_i\} \;\leq\; Q^{k}_{i} &\;\leq\; \min\{Q_k,\, Q_k + q_i\}, & \forall i \in N,\; k \in K \tag{13} \\[2pt] +x^{k}_{ij} &\;\in\; \{0,1\}, & \forall i, j \in N,\; k \in K \tag{14} +\end{align}$$ + +Constraints (7) and (8) are bilinear in their original form; they may be linearized via standard big-$M$ constraints. diff --git a/tasks/cordeau2006/problem_description.txt b/tasks/cordeau2006/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..61a7e7840bf8e884d39d79f83fc5d5141ec6fc27 --- /dev/null +++ b/tasks/cordeau2006/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A dial-a-ride service operates a fleet of vehicles to transport users between specified origins and destinations. There are n users, each requesting transportation from a pickup location to a drop-off location, and a fleet of vehicles, all based at a single depot. The service network contains a direct connection from every node to every other node. The nodes comprise one pickup node and one drop-off node for each user, plus an origin depot node and a destination depot node representing the start and end of each vehicle's route. The first half of users formulate outbound requests (from home to a destination) and the second half formulate inbound requests (from an origin back home). Each node has a two-dimensional coordinate, and the routing cost and travel time for every pair of nodes equal the Euclidean distance between them. + +Each vehicle has a passenger capacity and a maximum route duration. Every node has an associated load value: pickup nodes carry a positive load equal to the number of passengers boarding, drop-off nodes carry the corresponding negative load, and both depot nodes carry zero load. Every node also has a service duration representing the time needed to board or alight passengers, with zero service duration at the depots. A time window is specified at each node, giving the earliest and latest times at which service may begin. For outbound users the time window is specified at the destination (drop-off) node and then tightened at the origin (pickup) node using the maximum ride time and direct travel time; for inbound users the time window is specified at the origin (pickup) node and then tightened at the destination (drop-off) node analogously. The depot time windows are derived from the tightest user time windows and the planning horizon. A global maximum ride time limits how long any user may spend traveling aboard a vehicle from pickup to drop-off. + +The service must decide, for each vehicle, which sequence of pickup and drop-off nodes to visit, thereby determining every vehicle's route and schedule. Specifically, the planner must determine which direct connections each vehicle traverses between nodes, the time at which each vehicle begins service at each node it visits, the onboard load of each vehicle after visiting each node, and the ride time experienced by each user. + +Every user request must be served exactly once, meaning exactly one vehicle visits that user's pickup node. The same vehicle that picks up a user must also deliver that user, so the pickup and drop-off of each user appear on the same vehicle's route. Every vehicle's route must begin at the origin depot and end at the destination depot. At every pickup and drop-off node, the number of times a vehicle arrives at that node must equal the number of times it departs. If a vehicle travels directly from one node to another, the time at which service begins at the second node must be no earlier than the service-start time at the first node plus the service duration at the first node plus the travel time between them. Similarly, if a vehicle travels directly from one node to another, the vehicle's load after visiting the second node must be at least the load after visiting the first node plus the load associated with the second node. Each user's ride time equals the difference between the time service begins at that user's drop-off node and the sum of the time service begins at that user's pickup node plus the service duration at the pickup node. The total duration of each vehicle's route, measured as the difference between the service-start time at the destination depot and the service-start time at the origin depot, must not exceed that vehicle's maximum route duration. Service at every node must begin within the node's time window. Each user's ride time must be at least the direct travel time from that user's pickup to drop-off and must not exceed the global maximum ride time. After visiting any node, a vehicle's load must be at least the greater of zero and that node's load value, and at most the lesser of the vehicle's capacity and the vehicle's capacity plus that node's load value. + +The goal is to minimize the total routing cost, computed as the sum of the travel costs on all connections traversed by all vehicles. diff --git a/tasks/cordeau2006/solution_logger.py b/tasks/cordeau2006/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/cordeau2006/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/cordeau2006/solution_schema.json b/tasks/cordeau2006/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..97607e9f0bfaf766583529dfdbb81811922b902c --- /dev/null +++ b/tasks/cordeau2006/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Total routing cost across all vehicles, computed as the sum of Euclidean distances of all arcs traversed.", + "routes": " Ordered sequence of node identifiers visited by each vehicle, starting at the origin depot (node 0) and ending at the destination depot (node 2 * num_users + 1).", + "service_times": " Time at which service begins at each pickup or drop-off node, and the departure and return times at the depot for each vehicle.", + "ride_times": " Time each user spends aboard the vehicle from the end of pickup service to the beginning of drop-off service." +} \ No newline at end of file diff --git a/tasks/cordeau2014/feasibility_check.py b/tasks/cordeau2014/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..74f27b84f78d3059d9aeba8071d11d1beb28cf0f --- /dev/null +++ b/tasks/cordeau2014/feasibility_check.py @@ -0,0 +1,736 @@ +""" +Feasibility checker for the Time-Dependent Travelling Salesman Problem (TDTSP). + +Verifies a candidate solution against the mathematical formulation in +Cordeau, Ghiani, and Guerriero (2014), Transportation Science 48(1), pp. 46-58. + +Constraints checked (original TDTSP core only): + Constraint 2 (eq 14): In-degree = 1 for every vertex + Constraint 3 (eq 15): Out-degree = 1 for every vertex + Constraint 4 (eq 16): Subtour elimination (Hamiltonian tour) + Constraint 5 (eq 17): Binary domain x_{ij} in {0,1} + Constraint 15 (obj): Objective consistency: reported objective_value must + equal the TDTSP tour duration recomputed from the + tour and instance data (full recompute, eq 12). + +Skipped (valid inequalities / period-decomposition reformulation): + Constraint 1 (eq 13): Path-based lower-bound linking (VI) + Constraints 6-11 (eqs 20-25): Period-decomposition VIs on z_h, y_h + Constraint 12 (eq 26): sum y_h = 1 (reformulation-only) + Constraint 13 (eq 27): z_h >= 0, y_h in {0,1} (reformulation vars) + Constraint 14 (eq 31): z >= z_bar(c*) (initial LB, not an original constraint) +These involve auxiliary variables z_h, y_h and path-based lower bounds that +a generated algorithm operating on the original (x_ij, z) space need not +produce; checking them would only verify the paper's cutting-plane bounds, +not the underlying TDTSP feasibility. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'tour') +_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 + + + +# ============================================================================ +# Tolerance constants +# ============================================================================ +TOL = 1e-5 +EPS = 1e-5 + + +# ============================================================================ +# Algorithm 1: Travel Time Computation (from the paper) +# ============================================================================ + +def compute_travel_time_on_arc(L_ij, speeds_for_periods, departure_time, + period_boundaries): + """Compute travel time on arc (i,j) departing at departure_time.""" + if L_ij <= 1e-12: + return 0.0 + + H = len(speeds_for_periods) + t = departure_time + + # Find starting period k such that T_k <= t <= T_{k+1}. + k = H - 1 + for h in range(H): + if period_boundaries[h] <= t <= period_boundaries[h + 1] + 1e-12: + k = h + break + + d = L_ij + speed = speeds_for_periods[k] + if speed <= 1e-15: + return float('inf') + + t_prime = t + d / speed + + while t_prime > period_boundaries[k + 1] + 1e-12 and k < H - 1: + d -= speed * (period_boundaries[k + 1] - t) + t = period_boundaries[k + 1] + k += 1 + speed = speeds_for_periods[k] + if speed <= 1e-15: + return float('inf') + t_prime = t + d / speed + + return t_prime - departure_time + + +# ============================================================================ +# Tour / Path Evaluation +# ============================================================================ + +def evaluate_tour_td(tour, distances, speeds_v_ijh, period_boundaries): + """Evaluate TDTSP tour duration starting at time 0.""" + current_time = 0.0 + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + L_ij = distances[i][j] + speeds = speeds_v_ijh[i][j] + tt = compute_travel_time_on_arc(L_ij, speeds, current_time, + period_boundaries) + if tt == float('inf'): + return float('inf') + current_time += tt + return current_time + + +def evaluate_tour_common_congestion(tour, distances, max_speeds, b_h, + period_boundaries): + """Evaluate tour under common congestion: v_{ijh} = b_h * u_{ij}.""" + current_time = 0.0 + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + L_ij = distances[i][j] + u_ij = max_speeds[i][j] + speeds = [bh * u_ij for bh in b_h] + tt = compute_travel_time_on_arc(L_ij, speeds, current_time, + period_boundaries) + if tt == float('inf'): + return float('inf') + current_time += tt + return current_time + + +def evaluate_path_td(path, distances, speeds_v_ijh, period_boundaries): + """Evaluate TDTSP traversal time of a path starting at time 0.""" + current_time = 0.0 + for idx in range(len(path) - 1): + a = path[idx] + b = path[idx + 1] + L_ab = distances[a][b] + speeds = speeds_v_ijh[a][b] + tt = compute_travel_time_on_arc(L_ab, speeds, current_time, + period_boundaries) + if tt == float('inf'): + return float('inf') + current_time += tt + return current_time + + +def compute_atsp_cost_of_path(path, distances, max_speeds): + """Compute z_bar_bar(p) = sum of L_{ab}/u_{ab} along the path.""" + cost = 0.0 + for idx in range(len(path) - 1): + a = path[idx] + b = path[idx + 1] + if max_speeds[a][b] <= 1e-15: + return float('inf') + cost += distances[a][b] / max_speeds[a][b] + return cost + + +def compute_lb_p(path, distances, max_speeds, speeds_v_ijh, b_h, + period_boundaries, z_bar_bar_c_star): + """Compute LB_p (Algorithm 2 from the paper).""" + z_p = evaluate_path_td(path, distances, speeds_v_ijh, period_boundaries) + if z_p == float('inf'): + return float('inf') + + z_bar_bar_p = compute_atsp_cost_of_path(path, distances, max_speeds) + if z_bar_bar_p == float('inf'): + return float('inf') + + if z_bar_bar_c_star < z_bar_bar_p: + return z_p + else: + remaining_length = z_bar_bar_c_star - z_bar_bar_p + if remaining_length <= 1e-12: + return z_p + tau = compute_travel_time_on_arc( + remaining_length, b_h, z_p, period_boundaries) + if tau == float('inf'): + return float('inf') + return z_p + tau + + +# ============================================================================ +# Compute z_h and y_h from the tour under common congestion +# ============================================================================ + +def compute_zh_yh_from_tour(tour, distances, max_speeds, b_h, + period_boundaries): + """ + Compute the z_h and y_h auxiliary variable values from a tour. + + z_h represents the portion of tour duration attributable to time period h + under common congestion (v_{ijh} = b_h * u_{ij}). + + y_h = 1 iff the tour completion time under common congestion falls in + period h, i.e., T_h <= z_bar(c) <= T_{h+1}. + """ + H = len(b_h) + + # First compute the common-congestion tour time z_bar(c) and track + # how much time is spent in each period. + z_h_vals = [0.0] * H + current_time = 0.0 + + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + L_ij = distances[i][j] + u_ij = max_speeds[i][j] + + if L_ij <= 1e-12: + continue + + speeds = [bh * u_ij for bh in b_h] + + # Simulate Algorithm 1 tracking time per period + t = current_time + k = H - 1 + for h in range(H): + if period_boundaries[h] <= t <= period_boundaries[h + 1] + 1e-12: + k = h + break + + d = L_ij + speed = speeds[k] + if speed <= 1e-15: + break + + t_prime = t + d / speed + + while t_prime > period_boundaries[k + 1] + 1e-12 and k < H - 1: + time_in_period = period_boundaries[k + 1] - t + z_h_vals[k] += speed * time_in_period / u_ij if u_ij > 1e-15 else 0.0 + d -= speed * time_in_period + t = period_boundaries[k + 1] + k += 1 + speed = speeds[k] + if speed <= 1e-15: + break + t_prime = t + d / speed + + if speed > 1e-15: + time_in_final = t_prime - t + z_h_vals[k] += speed * time_in_final / u_ij if u_ij > 1e-15 else 0.0 + + current_time_new = current_time + compute_travel_time_on_arc( + L_ij, speeds, current_time, period_boundaries) + current_time = current_time_new + + # z_bar(c) = common congestion tour time + z_bar_c = current_time + + # Determine y_h: which period does z_bar(c) fall in? + y_h_vals = [0] * H + for h in range(H): + if period_boundaries[h] - TOL <= z_bar_c <= period_boundaries[h + 1] + TOL: + y_h_vals[h] = 1 + break + else: + # If beyond all periods, assign to last + if z_bar_c > period_boundaries[H]: + y_h_vals[H - 1] = 1 + + # z_h values: under common congestion, the traversal time per period h + # is sum of L_ij/u_ij for time spent in period h, scaled by b_h. + # Actually, z_h represents the sum of (L_ij/u_ij) contributions that fall + # within period h. Let's recompute properly. + # + # The z_h auxiliary variables satisfy: + # z_bar(c) = sum_h z_h / b_h (from constraint 20) + # where z_h = b_h * (time spent in period h under common congestion) + # equivalently z_h / b_h = time in period h, so z_h = b_h * (time in period h). + # + # We track the actual time spent in each period under common congestion. + z_h_time = [0.0] * H + current_time = 0.0 + + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + L_ij = distances[i][j] + u_ij = max_speeds[i][j] + + if L_ij <= 1e-12: + continue + + speeds = [bh * u_ij for bh in b_h] + + t = current_time + k = H - 1 + for h in range(H): + if period_boundaries[h] <= t <= period_boundaries[h + 1] + 1e-12: + k = h + break + + d = L_ij + speed = speeds[k] + if speed <= 1e-15: + break + + t_prime = t + d / speed + + while t_prime > period_boundaries[k + 1] + 1e-12 and k < H - 1: + time_in_period = period_boundaries[k + 1] - t + z_h_time[k] += time_in_period + d -= speed * time_in_period + t = period_boundaries[k + 1] + k += 1 + speed = speeds[k] + if speed <= 1e-15: + break + t_prime = t + d / speed + + if speed > 1e-15: + time_in_final = t_prime - t + z_h_time[k] += time_in_final + + current_time += compute_travel_time_on_arc( + L_ij, speeds, current_time, period_boundaries) + + # z_h = b_h * (time spent in period h) + z_h_final = [b_h[h] * z_h_time[h] for h in range(H)] + + return z_h_final, y_h_vals, z_bar_c + + +# ============================================================================ +# ATSP helpers +# ============================================================================ + +def compute_atsp_tour_cost(tour, distances, max_speeds): + """Compute z_bar_bar(c) = sum L_ij/u_ij along the tour.""" + cost = 0.0 + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + if max_speeds[i][j] <= 1e-15: + return float('inf') + cost += distances[i][j] / max_speeds[i][j] + return cost + + +# ============================================================================ +# Violation recording helper +# ============================================================================ + +def record_violation(constraint_idx, lhs, rhs, op, violations_list, + violated_set, messages_list, message): + """Check if a constraint is violated and record it.""" + if op == '>=': + violation_amount = rhs - lhs + elif op == '<=': + violation_amount = lhs - rhs + elif op == '=': + violation_amount = abs(lhs - rhs) + else: + violation_amount = 0.0 + + if violation_amount > TOL: + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations_list.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + violated_set.add(constraint_idx) + messages_list.append(message) + return True + return False + + +# ============================================================================ +# Main feasibility check +# ============================================================================ + +def check_feasibility(instance_data, solution_data): + """ + Check feasibility of a candidate TDTSP solution. + + Returns a dict with feasibility results. + """ + violations_list = [] # list of violation magnitude dicts + violated_set = set() # set of violated constraint indices + messages_list = [] # human-readable violation messages + + # Parse instance + params = instance_data["parameters"] + n = params["total_vertices"] + H = params["H"] + b_h = params["b_h"] + period_boundaries = params["period_boundaries"] + distances = instance_data["arcs"]["distances"] + max_speeds = instance_data["arcs"]["max_speeds_u_ij"] + speeds_v_ijh = instance_data["arcs"]["speeds_v_ijh"] + + # Parse solution + tour = solution_data["tour"] + z_reported = solution_data["objective_value"] + + if z_reported is None or not tour: + return { + "feasible": False, + "violated_constraints": [2, 3, 4], + "violations": ["Solution is empty or has no objective value"], + "violation_magnitudes": [], + } + + # Derive x_{ij} from tour + x = {} + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + x[i, j] = 1 + + # ----------------------------------------------------------------------- + # Constraint 2 (eq 14): In-degree = 1 for each vertex in V u {0} + # sum_{i in V\{j}} x_{ij} = 1 for all j in V u {0} + # ----------------------------------------------------------------------- + in_degree = [0] * n + for (i, j) in x: + if 0 <= j < n: + in_degree[j] += 1 + + for j in range(n): + lhs = in_degree[j] + rhs = 1.0 + record_violation(2, float(lhs), rhs, '=', violations_list, + violated_set, messages_list, + f"In-degree of vertex {j} is {lhs}, expected 1") + + # ----------------------------------------------------------------------- + # Constraint 3 (eq 15): Out-degree = 1 for each vertex in V u {0} + # sum_{j in V\{i}} x_{ij} = 1 for all i in V u {0} + # ----------------------------------------------------------------------- + out_degree = [0] * n + for (i, j) in x: + if 0 <= i < n: + out_degree[i] += 1 + + for i in range(n): + lhs = out_degree[i] + rhs = 1.0 + record_violation(3, float(lhs), rhs, '=', violations_list, + violated_set, messages_list, + f"Out-degree of vertex {i} is {lhs}, expected 1") + + # ----------------------------------------------------------------------- + # Constraint 4 (eq 16): Subtour elimination — tour must be Hamiltonian + # The tour must visit all n vertices exactly once and form a single cycle + # starting and ending at depot 0. + # ----------------------------------------------------------------------- + # Check tour starts and ends at depot + tour_valid = True + if tour[0] != 0 or tour[-1] != 0: + record_violation(4, 0.0, 1.0, '>=', violations_list, + violated_set, messages_list, + f"Tour does not start and end at depot 0: " + f"starts at {tour[0]}, ends at {tour[-1]}") + tour_valid = False + + # Check all vertices visited + visited = set(tour[:-1]) # exclude final depot duplicate + if len(visited) != n: + missing = set(range(n)) - visited + extra = visited - set(range(n)) + # Compute a violation amount: how many vertices are missing + lhs = float(len(visited)) + rhs = float(n) + record_violation(4, lhs, rhs, '=', violations_list, + violated_set, messages_list, + f"Tour visits {len(visited)} vertices but should visit {n}. " + f"Missing: {sorted(missing)}, Extra: {sorted(extra)}") + tour_valid = False + + # Check for repeated vertices (subtour) + interior = tour[1:-1] + if len(interior) != len(set(interior)): + from collections import Counter + counts = Counter(interior) + duplicates = {v: c for v, c in counts.items() if c > 1} + record_violation(4, 0.0, 1.0, '>=', violations_list, + violated_set, messages_list, + f"Tour has repeated vertices (subtour): {duplicates}") + tour_valid = False + + # ----------------------------------------------------------------------- + # Constraint 5 (eq 17): Binary domain x_{ij} in {0,1} + # Since x is derived from tour arcs (always 0 or 1), this is + # automatically satisfied. We verify arc indices are valid. + # ----------------------------------------------------------------------- + for (i, j) in x: + if i < 0 or i >= n or j < 0 or j >= n or i == j: + record_violation(5, 0.0, 1.0, '>=', violations_list, + violated_set, messages_list, + f"Invalid arc ({i},{j}) in tour: vertex index " + f"out of range [0,{n-1}] or self-loop") + + # If the tour is not structurally valid, skip objective-related checks + if not tour_valid: + return _build_result(violated_set, messages_list, violations_list) + + # ----------------------------------------------------------------------- + # Compute derived quantities needed for remaining constraints + # ----------------------------------------------------------------------- + + # Actual TDTSP tour duration + z_actual = evaluate_tour_td(tour, distances, speeds_v_ijh, + period_boundaries) + + # ----------------------------------------------------------------------- + # Constraint 15 (obj, eq 12): Objective consistency. + # The TDTSP objective is z = total tour duration. Since the tour is fully + # in the solution and travel times are deterministic given the speed law, + # we can recompute z exactly via evaluate_tour_td and reject solutions + # whose reported objective_value disagrees beyond tolerance. + # ----------------------------------------------------------------------- + try: + reported = float(z_reported) + except (TypeError, ValueError): + reported = None + if reported is not None and math.isfinite(z_actual): + abs_diff = abs(reported - z_actual) + tol = max(1e-3, 1e-3 * abs(z_actual)) # 0.1% relative, 1e-3 absolute floor + if abs_diff > tol: + record_violation(15, reported, z_actual, '=', violations_list, + violated_set, messages_list, + f"Objective consistency violated: reported " + f"objective_value={reported} differs from " + f"recomputed tour duration={z_actual} " + f"(|diff|={abs_diff:.3g}, tol={tol:.3g})") + + # Constraints 1, 6-14 SKIPPED: path-based LB (VI) and period-decomposition + # reformulation constraints on z_h, y_h, plus initial z_bar(c*) LB (eq 31). + # A generated algorithm operating on the original (x_ij, z) space does not + # produce z_h, y_h and need not satisfy the paper's cutting-plane bounds — + # they only tighten the LP relaxation, not TDTSP integer feasibility. + + return _build_result(violated_set, messages_list, violations_list) + + +def _build_result(violated_set, messages_list, violations_list): + """Build the output result dictionary.""" + feasible = len(violated_set) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": messages_list, + "violation_magnitudes": violations_list, + } + + +# ============================================================================ +# Main +# ============================================================================ + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for TDTSP solutions " + "(Cordeau, Ghiani, Guerriero 2014).") + 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("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/cordeau2014/gurobi_code.py b/tasks/cordeau2014/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a6d84f6de08a1c2b8a374ef20ba5bec5e794941d --- /dev/null +++ b/tasks/cordeau2014/gurobi_code.py @@ -0,0 +1,1209 @@ +#!/usr/bin/env python3 +""" +TDTSP (Time-Dependent Travelling Salesman Problem) Branch-and-Cut Solver +Based on: Cordeau, Ghiani, and Guerriero (2014) + "Analysis and Branch-and-Cut Algorithm for the Time-Dependent + Travelling Salesman Problem" + Transportation Science 48(1), pp. 46-58. + +This implementation uses Gurobi with lazy constraint callbacks for +subtour elimination (16) and path-based lower bound constraints (13). +""" + +import argparse +import heapq +import json +import math +import sys +import time +from collections import defaultdict +from itertools import combinations + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +# ============================================================================ +# Algorithm 1: Travel time computation +# ============================================================================ + +def compute_travel_time(i, j, t0, L, v_ijh, period_boundaries, H): + """ + Algorithm 1 from the paper. + Compute travel time on arc (i,j) departing at time t0. + + Parameters + ---------- + i, j : int + Origin and destination vertex indices. + t0 : float + Departure time. + L : 2D list/array + Distance matrix L[i][j]. + v_ijh : 3D list/array + Speed array v_ijh[i][j][h]. + period_boundaries : list + Period boundary times [T_0, T_1, ..., T_H]. + H : int + Number of time periods. + + Returns + ------- + float + Travel time tau_{ij}(t0). + """ + if i == j: + return 0.0 + + dist = L[i][j] + if dist <= 0: + return 0.0 + + # Find period k0 such that T_{k0} <= t0 <= T_{k0+1} + k = 0 + for h in range(H): + if period_boundaries[h] <= t0 <= period_boundaries[h + 1]: + k = h + break + else: + # t0 is at or beyond the last boundary; use the last period + k = H - 1 + + t = t0 + d = dist + speed = v_ijh[i][j][k] + if speed <= 1e-12: + # Speed is essentially zero; return a very large travel time + return 1e15 + + t_prime = t + d / speed + + while t_prime > period_boundaries[k + 1] + 1e-12 and k < H - 1: + # Distance covered in current period k + d = d - speed * (period_boundaries[k + 1] - t) + t = period_boundaries[k + 1] + k = k + 1 + speed = v_ijh[i][j][k] + if speed <= 1e-12: + return 1e15 + t_prime = t + d / speed + + return t_prime - t0 + + +def compute_travel_time_common_congestion(i, j, t0, L, u_ij, b_h, + period_boundaries, H): + """ + Compute travel time on arc (i,j) under common congestion model: + speed = b_h * u_{ij} in each period h. + + Uses Algorithm 1 logic with v_{ijh} = b_h * u_{ij}. + """ + if i == j: + return 0.0 + + dist = L[i][j] + if dist <= 0: + return 0.0 + + u = u_ij[i][j] + if u <= 1e-12: + return 1e15 + + # Find period k0 + k = 0 + for h in range(H): + if period_boundaries[h] <= t0 <= period_boundaries[h + 1]: + k = h + break + else: + k = H - 1 + + t = t0 + d = dist + speed = b_h[k] * u + if speed <= 1e-12: + return 1e15 + + t_prime = t + d / speed + + while t_prime > period_boundaries[k + 1] + 1e-12 and k < H - 1: + d = d - speed * (period_boundaries[k + 1] - t) + t = period_boundaries[k + 1] + k = k + 1 + speed = b_h[k] * u + if speed <= 1e-12: + return 1e15 + t_prime = t + d / speed + + return t_prime - t0 + + +def compute_dummy_travel_time(length, start_time, b_h, period_boundaries, H): + """ + Compute travel time of a 'dummy arc' with given length and speed b_h + in each period h. Used in Algorithm 2 (LB_p computation). + + This is Algorithm 1 with L = length and v_h = b_h for all h. + """ + if length <= 1e-12: + return 0.0 + + # Find period k0 + k = 0 + for h in range(H): + if period_boundaries[h] <= start_time <= period_boundaries[h + 1]: + k = h + break + else: + k = H - 1 + + t = start_time + d = length + speed = b_h[k] + if speed <= 1e-12: + return 1e15 + + t_prime = t + d / speed + + while t_prime > period_boundaries[k + 1] + 1e-12 and k < H - 1: + d = d - speed * (period_boundaries[k + 1] - t) + t = period_boundaries[k + 1] + k = k + 1 + speed = b_h[k] + if speed <= 1e-12: + return 1e15 + t_prime = t + d / speed + + return t_prime - start_time + + +# ============================================================================ +# Tour evaluation functions +# ============================================================================ + +def evaluate_tour_tdtsp(tour, L, v_ijh, period_boundaries, H): + """ + Evaluate a tour under the actual TDTSP speed model. + tour: list of vertices starting and ending at depot 0. + Returns z(c) = total tour duration. + """ + current_time = 0.0 + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + tt = compute_travel_time(i, j, current_time, L, v_ijh, + period_boundaries, H) + current_time += tt + return current_time + + +def evaluate_tour_common_congestion(tour, L, u_ij, b_h, + period_boundaries, H): + """ + Evaluate a tour under the common congestion speed model: + v_{ijh} = b_h * u_{ij}. + Returns z_underline(c). + """ + current_time = 0.0 + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + tt = compute_travel_time_common_congestion(i, j, current_time, L, + u_ij, b_h, + period_boundaries, H) + current_time += tt + return current_time + + +def evaluate_tour_atsp(tour, L, u_ij): + """ + Evaluate a tour under ATSP costs: L_{ij}/u_{ij}. + Returns z_bar_bar(c). + """ + total = 0.0 + for idx in range(len(tour) - 1): + i = tour[idx] + j = tour[idx + 1] + if u_ij[i][j] > 1e-12: + total += L[i][j] / u_ij[i][j] + return total + + +# ============================================================================ +# Path evaluation for LB_p (Algorithm 2) +# ============================================================================ + +def evaluate_path_tdtsp(path, L, v_ijh, period_boundaries, H): + """ + Evaluate actual TDTSP traversal time of a path starting at time 0. + Returns z(p). + """ + current_time = 0.0 + for idx in range(len(path) - 1): + i = path[idx] + j = path[idx + 1] + tt = compute_travel_time(i, j, current_time, L, v_ijh, + period_boundaries, H) + current_time += tt + return current_time + + +def evaluate_path_atsp(path, L, u_ij): + """ + Evaluate ATSP cost of a path: sum of L_{ab}/u_{ab} for (a,b) in path. + Returns z_bar_bar(p). + """ + total = 0.0 + for idx in range(len(path) - 1): + a = path[idx] + b = path[idx + 1] + if u_ij[a][b] > 1e-12: + total += L[a][b] / u_ij[a][b] + return total + + +def compute_LB_p(path, atsp_lower_bound, L, u_ij, v_ijh, b_h, + period_boundaries, H): + """ + Algorithm 2: Compute lower bound LB_p for a path p. + + Parameters + ---------- + path : list of int + Simple path from depot 0 to some vertex i. + atsp_lower_bound : float + Certified lower bound on the optimal ATSP value. + L, u_ij, v_ijh, b_h, period_boundaries, H : instance data. + + Returns + ------- + float + LB_p. + """ + z_p = evaluate_path_tdtsp(path, L, v_ijh, period_boundaries, H) + zbar_p = evaluate_path_atsp(path, L, u_ij) + + if atsp_lower_bound < zbar_p: + return z_p + else: + remaining_length = atsp_lower_bound - zbar_p + tau_val = compute_dummy_travel_time(remaining_length, z_p, b_h, + period_boundaries, H) + return z_p + tau_val + + +# ============================================================================ +# ATSP solver (Step 1) +# ============================================================================ + +def solve_atsp(n_total, L, u_ij, time_limit=600): + """ + Solve the ATSP with arc costs L_{ij}/u_{ij} using Gurobi with + lazy subtour elimination constraints. + + Parameters + ---------- + n_total : int + Total number of vertices (n_customers + 1, including depot 0). + L : 2D list + Distance matrix. + u_ij : 2D list + Max speed matrix. + time_limit : int + Time limit in seconds. + + Returns + ------- + tour : list of int + Optimal tour as a sequence of vertices (starting and ending at 0). + atsp_incumbent : float + Best ATSP tour value found. + atsp_bound : float + Certified lower bound on the ATSP optimum. + atsp_status : int + Gurobi termination status for the ATSP subproblem. + """ + vertices = list(range(n_total)) + arcs = [(i, j) for i in vertices for j in vertices if i != j] + + # Arc costs + cost = {} + for i, j in arcs: + if u_ij[i][j] > 1e-12: + cost[i, j] = L[i][j] / u_ij[i][j] + else: + cost[i, j] = 1e15 # effectively prohibit + + model = gp.Model("ATSP") + model.setParam("Threads", 1) + model.Params.OutputFlag = 0 + model.Params.TimeLimit = time_limit + model.Params.LazyConstraints = 1 + + # Binary variables + x = model.addVars(arcs, vtype=GRB.BINARY, name="x") + + # Objective + model.setObjective(gp.quicksum(cost[i, j] * x[i, j] + for i, j in arcs), GRB.MINIMIZE) + + # Degree constraints + for j in vertices: + model.addConstr( + gp.quicksum(x[i, j] for i in vertices if i != j) == 1, + name=f"indeg_{j}") + for i in vertices: + model.addConstr( + gp.quicksum(x[i, j] for j in vertices if j != i) == 1, + name=f"outdeg_{i}") + + def subtour_callback(model, where): + if where == GRB.Callback.MIPSOL: + x_val = model.cbGetSolution(x) + # Build adjacency from solution + adj = {} + for i, j in arcs: + if x_val[i, j] > 0.5: + adj[i] = j + + # Find connected components (subtours) + visited = set() + subtours = [] + for start in vertices: + if start in visited: + continue + tour = [] + current = start + while current not in visited: + visited.add(current) + tour.append(current) + current = adj.get(current, start) + if len(tour) < n_total: + subtours.append(tour) + + # Add SEC for each subtour not containing all vertices + for S in subtours: + if len(S) < n_total: + S_set = set(S) + model.cbLazy( + gp.quicksum(x[i, j] + for i in S_set + for j in vertices + if j not in S_set and i != j) >= 1) + + model.optimize(subtour_callback) + + if model.Status == GRB.OPTIMAL or model.SolCount > 0: + # Extract tour + adj = {} + for i, j in arcs: + if x[i, j].X > 0.5: + adj[i] = j + + tour = [0] + current = adj[0] + while current != 0: + tour.append(current) + current = adj[current] + tour.append(0) + + return tour, model.ObjVal, model.ObjBound, model.Status + else: + print("ATSP solve failed. Status:", model.Status) + sys.exit(1) + + +# ============================================================================ +# Shortest path for constraint (13) separation +# ============================================================================ + +def dijkstra_from_source(source, n_total, arc_costs): + """ + Dijkstra's algorithm from a single source with given arc costs. + Returns (dist, pred) where dist[v] is shortest distance and + pred[v] is the predecessor on the shortest path. + """ + INF = float('inf') + dist = [INF] * n_total + pred = [-1] * n_total + dist[source] = 0.0 + visited = [False] * n_total + pq = [(0.0, source)] + + while pq: + d, u = heapq.heappop(pq) + if visited[u]: + continue + visited[u] = True + for v in range(n_total): + if v == u: + continue + w = arc_costs.get((u, v), INF) + if d + w < dist[v]: + dist[v] = d + w + pred[v] = u + heapq.heappush(pq, (dist[v], v)) + + return dist, pred + + +def reconstruct_path(pred, target): + """Reconstruct path from source to target using predecessor array.""" + path = [] + v = target + while v != -1: + path.append(v) + v = pred[v] + path.reverse() + return path + + +# ============================================================================ +# Connected components for subtour detection +# ============================================================================ + +def find_connected_components(n_total, edges): + """ + Find connected components in an undirected graph. + edges: list of (i, j, weight) tuples. + Returns list of sets, each set being a connected component. + """ + adj = defaultdict(set) + active_nodes = set() + for i, j, w in edges: + if w > 1e-6: + adj[i].add(j) + adj[j].add(i) + active_nodes.add(i) + active_nodes.add(j) + + visited = set() + components = [] + for start in range(n_total): + if start in visited: + continue + if start not in active_nodes: + # Isolated node; add as single component + visited.add(start) + components.append({start}) + continue + # BFS + comp = set() + queue = [start] + while queue: + node = queue.pop() + if node in visited: + continue + visited.add(node) + comp.add(node) + for neighbor in adj[node]: + if neighbor not in visited: + queue.append(neighbor) + components.append(comp) + + return components + + +def find_subtours_integer(n_total, x_vals): + """ + Given integer x values, find subtours by following arcs. + Returns list of subtours (each a list of vertices). + """ + adj = {} + for (i, j), val in x_vals.items(): + if val > 0.5: + adj[i] = j + + visited = set() + subtours = [] + for start in range(n_total): + if start in visited: + continue + tour = [] + current = start + while current not in visited: + visited.add(current) + tour.append(current) + if current not in adj: + break + current = adj[current] + subtours.append(tour) + + return subtours + + +def find_min_cut_subtour(n_total, x_vals): + """ + Find violated subtour elimination constraints from fractional solution. + Uses a simple approach: build undirected support graph, find min cut + via connected components for integer solutions, or use flow-based + approach for fractional. + + For fractional solutions, we check all subsets S containing depot 0 + and look for x(S, V\\S) < 1. In practice, we use a max-flow / min-cut + heuristic. + + Returns list of violated subsets S (each a set of vertex indices). + """ + # Build undirected support graph capacity + capacity = defaultdict(float) + for (i, j), val in x_vals.items(): + if val > 1e-6: + capacity[i, j] += val + + violated = [] + + # For each vertex t != 0, compute min s-t cut from 0 to t + for t in range(1, n_total): + # Use BFS-based max-flow (Edmonds-Karp) + flow_val, S_set = max_flow_min_cut(0, t, n_total, capacity) + if flow_val < 1.0 - 1e-6: + violated.append(S_set) + + return violated + + +def max_flow_min_cut(s, t, n, capacity): + """ + Edmonds-Karp (BFS-based) max-flow algorithm. + Returns (max_flow_value, S_set) where S_set is the source side + of the min cut. + """ + # Build residual graph + residual = defaultdict(float) + for (i, j), cap in capacity.items(): + residual[i, j] += cap + + total_flow = 0.0 + + while True: + # BFS to find augmenting path + parent = {s: None} + visited = {s} + queue = [s] + found = False + while queue and not found: + u = queue.pop(0) + for v in range(n): + if v not in visited and residual.get((u, v), 0) > 1e-10: + parent[v] = u + visited.add(v) + if v == t: + found = True + break + queue.append(v) + + if not found: + break + + # Find bottleneck + bottleneck = float('inf') + v = t + while parent[v] is not None: + u = parent[v] + bottleneck = min(bottleneck, residual[u, v]) + v = u + if bottleneck <= 1e-10: + break + + # Update residual + v = t + while parent[v] is not None: + u = parent[v] + residual[u, v] -= bottleneck + residual[v, u] += bottleneck + v = u + + total_flow += bottleneck + + # Find S-side of min cut (reachable from s in residual) + S_set = set() + visited_final = {s} + queue = [s] + while queue: + u = queue.pop(0) + S_set.add(u) + for v in range(n): + if v not in visited_final and residual.get((u, v), 0) > 1e-10: + visited_final.add(v) + queue.append(v) + + return total_flow, S_set + + +# ============================================================================ +# Main TDTSP Branch-and-Cut Model +# ============================================================================ + +def solve_tdtsp(instance_path, solution_path, time_limit): + """ + Main function: load instance, solve ATSP for initialization, + build and solve the TDTSP branch-and-cut model. + """ + # ------------------------------------------------------------------ + # 1. Load instance data + # ------------------------------------------------------------------ + with open(instance_path, 'r') as f: + data = json.load(f) + + params = data["parameters"] + n_customers = params["n_customers"] + n_total = params["total_vertices"] # n_customers + 1 (depot) + H = params["H"] + b_h = params["b_h"] + T = params["time_horizon_T"] + period_boundaries = params["period_boundaries"] + + L = data["arcs"]["distances"] + u_ij = data["arcs"]["max_speeds_u_ij"] + v_ijh = data["arcs"]["speeds_v_ijh"] + + vertices = list(range(n_total)) + arcs = [(i, j) for i in vertices for j in vertices if i != j] + + # Precompute ATSP arc costs: L_{ij}/u_{ij} + atsp_cost = {} + for i, j in arcs: + if u_ij[i][j] > 1e-12: + atsp_cost[i, j] = L[i][j] / u_ij[i][j] + else: + atsp_cost[i, j] = 1e15 + + print("=" * 70) + print("TDTSP Branch-and-Cut Solver") + print(f"Instance: {instance_path}") + print(f"Vertices: {n_total} (depot + {n_customers} customers)") + print(f"Time periods: {H}, b_h = {b_h}") + print(f"Time horizon: {T:.6f}") + print(f"Period boundaries: {period_boundaries}") + print("=" * 70) + + # ------------------------------------------------------------------ + # 2. Solve ATSP to get optimal tour c* + # ------------------------------------------------------------------ + print("\n--- Step 1: Solving ATSP ---") + atsp_time_limit = max(60, time_limit // 4) + atsp_tour, atsp_incumbent, atsp_bound, atsp_status = solve_atsp( + n_total, L, u_ij, atsp_time_limit + ) + print(f"ATSP incumbent tour: {atsp_tour}") + print(f"ATSP incumbent value = {atsp_incumbent:.6f}") + print(f"ATSP certified lower bound = {atsp_bound:.6f}") + + # ------------------------------------------------------------------ + # 3. Compute initial bounds + # ------------------------------------------------------------------ + print("\n--- Step 2: Computing initial bounds ---") + + # z_bar_bar(c*) = ATSP value (already computed) + # Path lower bounds must use a certified bound. Treating a time-limited + # incumbent as the ATSP optimum can invalidate every downstream cut. + zbarbar_cstar = atsp_bound + + # z(c*) = evaluate tour under actual TDTSP speeds (upper bound) + z_cstar = evaluate_tour_tdtsp(atsp_tour, L, v_ijh, period_boundaries, H) + print(f"TDTSP evaluation z(c*) = {z_cstar:.6f} (upper bound)") + + # z_underline(c*) = evaluate tour under common congestion (lower bound) + # Under common congestion, normalized arc lengths L_ij/u_ij are traversed + # at the shared speed b_h. Applying that time transform to the certified + # ATSP bound yields a valid initial lower bound even when the ATSP + # subproblem stops with only an incumbent. + z_underline_cstar = compute_dummy_travel_time( + atsp_bound, 0.0, b_h, period_boundaries, H + ) + print(f"Certified common-congestion lower bound = " + f"{z_underline_cstar:.6f}") + + initial_gap = (z_cstar - z_underline_cstar) / z_cstar * 100 + print(f"Initial gap: {initial_gap:.2f}%") + + # ------------------------------------------------------------------ + # 4. Build the main TDTSP ILP model + # ------------------------------------------------------------------ + print("\n--- Step 3: Building TDTSP ILP model ---") + + model = gp.Model("TDTSP") + model.setParam("Threads", 1) + model.Params.OutputFlag = 1 + model.Params.TimeLimit = time_limit + model.Params.LazyConstraints = 1 + # Use Gurobi's default settings for other parameters + + # --- Decision Variables --- + + # x_{ij} binary arc variables + x = model.addVars(arcs, vtype=GRB.BINARY, name="x") + + # z: total tour duration (continuous) + z = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name="z") + + # z_h: auxiliary variables for valid inequalities, h = 0,...,H-1 + z_h = model.addVars(H, vtype=GRB.CONTINUOUS, lb=0.0, name="z_h") + + # y_h: binary variables, h = 0,...,H-1 + y_h = model.addVars(H, vtype=GRB.BINARY, name="y_h") + + # --- Objective (12): minimize z --- + model.setObjective(z, GRB.MINIMIZE) + + # --- Degree constraints (14): in-degree --- + for j in vertices: + model.addConstr( + gp.quicksum(x[i, j] for i in vertices if i != j) == 1, + name=f"indeg_{j}") + + # --- Degree constraints (15): out-degree --- + for i in vertices: + model.addConstr( + gp.quicksum(x[i, j] for j in vertices if j != i) == 1, + name=f"outdeg_{i}") + + # --- Initial lower bound (31): z >= z_underline(c*) --- + model.addConstr(z >= z_underline_cstar, name="init_lb") + + # --- Set initial upper bound via cutoff --- + model.Params.Cutoff = z_cstar + 1e-6 + + # --- Provide the ATSP tour as a MIP start --- + for i, j in arcs: + x[i, j].Start = 0.0 + for idx in range(len(atsp_tour) - 1): + ai = atsp_tour[idx] + aj = atsp_tour[idx + 1] + x[ai, aj].Start = 1.0 + + # --- Valid inequalities (20)-(27) --- + + # Precompute: ATSP_sum = sum of (L_{ij}/u_{ij}) * x_{ij} over all arcs + atsp_sum_expr = gp.quicksum(atsp_cost[i, j] * x[i, j] + for i, j in arcs) + + # (20) z >= sum_{h=0}^{H-1} z_h / b_h + model.addConstr( + z >= gp.quicksum(z_h[h] / b_h[h] for h in range(H)), + name="vi_20") + + # (21) z_0 >= ATSP_sum - sum_{l=1}^{H-1} z_l + if H >= 1: + model.addConstr( + z_h[0] >= atsp_sum_expr + - gp.quicksum(z_h[l] for l in range(1, H)), + name="vi_21") + + # (22) z_h >= ATSP_sum - sum_{l=0}^{h-1} b_l*(T_{l+1}-T_l) + # - sum_{l=h+1}^{H-1} z_l + # for h = 1, ..., H-2 + for h in range(1, H - 1): + sum_periods = sum(b_h[l] * (period_boundaries[l + 1] + - period_boundaries[l]) + for l in range(h)) + model.addConstr( + z_h[h] >= atsp_sum_expr - sum_periods + - gp.quicksum(z_h[l] for l in range(h + 1, H)), + name=f"vi_22_{h}") + + # (23) z_{H-1} >= ATSP_sum - sum_{l=0}^{H-2} b_l*(T_{l+1}-T_l) + if H >= 2: + sum_periods_all = sum(b_h[l] * (period_boundaries[l + 1] + - period_boundaries[l]) + for l in range(H - 1)) + model.addConstr( + z_h[H - 1] >= atsp_sum_expr - sum_periods_all, + name="vi_23") + + # (24) z_h <= b_h*(T_{h+1}-T_h) * sum_{l=h}^{H-1} y_l + # for h = 0,...,H-1 + for h in range(H): + period_len = period_boundaries[h + 1] - period_boundaries[h] + model.addConstr( + z_h[h] <= b_h[h] * period_len + * gp.quicksum(y_h[l] for l in range(h, H)), + name=f"vi_24_{h}") + + # (25) z_h >= b_h*(T_{h+1}-T_h) * sum_{l=h+1}^{H-1} y_l + # for h = 0,...,H-2 + for h in range(H - 1): + period_len = period_boundaries[h + 1] - period_boundaries[h] + model.addConstr( + z_h[h] >= b_h[h] * period_len + * gp.quicksum(y_h[l] for l in range(h + 1, H)), + name=f"vi_25_{h}") + + # (26) sum_{h=0}^{H-1} y_h = 1 + model.addConstr( + gp.quicksum(y_h[h] for h in range(H)) == 1, + name="vi_26") + + # (27) z_h >= 0 (already set as lb=0), y_h binary (already set) + + # ------------------------------------------------------------------ + # 5. Callback for lazy constraints + # ------------------------------------------------------------------ + callback_data = { + 'n_total': n_total, + 'vertices': vertices, + 'arcs': arcs, + 'L': L, + 'u_ij': u_ij, + 'v_ijh': v_ijh, + 'b_h': b_h, + 'period_boundaries': period_boundaries, + 'H': H, + 'atsp_lower_bound': zbarbar_cstar, + 'atsp_cost': atsp_cost, + 'x': x, + 'z': z, + 'sec_count': 0, + 'path_count': 0, + 'best_obj': z_cstar, + } + + def tdtsp_callback(model, where): + if where == GRB.Callback.MIPSOL: + # Integer solution found: check for subtours and update bound + _separate_integer(model, callback_data) + elif where == GRB.Callback.MIPNODE: + # At a node: separate fractional cuts + status = model.cbGet(GRB.Callback.MIPNODE_STATUS) + if status == GRB.OPTIMAL: + _separate_fractional(model, callback_data) + + def _separate_integer(model, cb): + """Separate subtour elimination at integer solutions.""" + x = cb['x'] + z_var = cb['z'] + n = cb['n_total'] + verts = cb['vertices'] + + x_val = {} + for i, j in cb['arcs']: + x_val[i, j] = model.cbGetSolution(x[i, j]) + + z_val = model.cbGetSolution(z_var) + + # Check subtours + subtours = find_subtours_integer(n, x_val) + + if len(subtours) > 1: + # Multiple subtours found: add SEC for each + for S in subtours: + if len(S) < n: + S_set = set(S) + model.cbLazy( + gp.quicksum(x[i, j] + for i in S_set + for j in verts + if j not in S_set and i != j) >= 1) + cb['sec_count'] += 1 + else: + # Single tour (Hamiltonian): check if we can update best + # Extract the tour + adj = {} + for (i, j), val in x_val.items(): + if val > 0.5: + adj[i] = j + tour = [0] + current = adj.get(0, 0) + while current != 0 and len(tour) <= n: + tour.append(current) + current = adj.get(current, 0) + tour.append(0) + + # Evaluate actual TDTSP value + actual_z = evaluate_tour_tdtsp( + tour, cb['L'], cb['v_ijh'], + cb['period_boundaries'], cb['H']) + + # The constraint z >= actual_z should hold for this tour + if actual_z > z_val + 1e-6: + # The current z is too low; add path constraint for this tour + # We add it as a constraint on the full tour + num_arcs = len(tour) - 1 + model.cbLazy( + z_var >= actual_z * ( + gp.quicksum( + x[tour[idx], tour[idx + 1]] + for idx in range(num_arcs) + ) - num_arcs + 1 + )) + cb['path_count'] += 1 + + if actual_z < cb['best_obj']: + cb['best_obj'] = actual_z + + def _separate_fractional(model, cb): + """Separate subtour elimination and path constraints at + fractional nodes.""" + x = cb['x'] + z_var = cb['z'] + n = cb['n_total'] + verts = cb['vertices'] + + x_val = {} + for i, j in cb['arcs']: + x_val[i, j] = model.cbGetNodeRel(x[i, j]) + + z_val = model.cbGetNodeRel(z_var) + + # --- Subtour elimination separation --- + # Build directed capacity for min-cut + capacity = defaultdict(float) + for (i, j), val in x_val.items(): + if val > 1e-6: + capacity[i, j] = val + + sec_found = False + for t in range(1, n): + flow_val, S_set = max_flow_min_cut(0, t, n, capacity) + if flow_val < 1.0 - 1e-4: + # Violated SEC + S_bar = set(verts) - S_set + model.cbCut( + gp.quicksum(x[i, j] + for i in S_set + for j in S_bar + if i != j and (i, j) in x) >= 1) + cb['sec_count'] += 1 + sec_found = True + + if sec_found: + return # Try SECs again in next round + + # --- Path constraint (13) separation --- + # Arc costs: (1 - x_hat_{ij}) + arc_costs_sp = {} + for i, j in cb['arcs']: + arc_costs_sp[i, j] = max(0.0, 1.0 - x_val[i, j]) + + # Dijkstra from vertex 0 + dist, pred = dijkstra_from_source(0, n, arc_costs_sp) + + path_found = False + for target in range(1, n): + if dist[target] < 1.0 - 1e-6: + # Violated path constraint + path = reconstruct_path(pred, target) + + if len(path) < 2: + continue + + # Compute LB_p + LB_p = compute_LB_p( + path, cb['atsp_lower_bound'], + cb['L'], cb['u_ij'], cb['v_ijh'], + cb['b_h'], cb['period_boundaries'], cb['H']) + + if LB_p <= 1e-6: + continue + + # Constraint (13): + # z >= LB_p * (1 - sum_{(a,b) in p} (1 - x_{ab})) + # = LB_p * (sum x_{ab} - m + 1), m = #arcs in path. + # It is active when every path arc is selected and relaxes as + # soon as an arc is absent. + num_arcs_in_path = len(path) - 1 + rhs_val = LB_p * ( + sum(x_val[path[k], path[k + 1]] + for k in range(num_arcs_in_path)) + - num_arcs_in_path + 1 + ) + + if rhs_val > z_val + 1e-6: + path_arcs_sum = gp.quicksum( + x[path[k], path[k + 1]] + for k in range(num_arcs_in_path)) + model.cbCut( + z_var >= LB_p * ( + path_arcs_sum - num_arcs_in_path + 1)) + cb['path_count'] += 1 + path_found = True + + # If path constraints were found, the next iteration will + # re-examine SECs + + # ------------------------------------------------------------------ + # 6. Optimize + # ------------------------------------------------------------------ + print("\n--- Step 4: Solving TDTSP model ---") + start_time = time.time() + model.optimize(tdtsp_callback) + solve_time = time.time() - start_time + + print(f"\nSolve time: {solve_time:.2f} seconds") + print(f"SECs added: {callback_data['sec_count']}") + print(f"Path constraints added: {callback_data['path_count']}") + + # ------------------------------------------------------------------ + # 7. Extract solution + # ------------------------------------------------------------------ + result = { + "instance_path": instance_path, + "solver": "gurobi", + "model": "TDTSP_BranchAndCut", + "time_limit": time_limit, + "solve_time": solve_time, + "status": model.Status, + "status_name": _status_name(model.Status), + "atsp_status": atsp_status, + "atsp_status_name": _status_name(atsp_status), + "atsp_incumbent": atsp_incumbent, + "atsp_certified_bound": atsp_bound, + } + + if model.SolCount > 0: + # Extract tour from x values + adj = {} + for i, j in arcs: + if x[i, j].X > 0.5: + adj[i] = j + + tour = [0] + current = adj.get(0, -1) + max_steps = n_total + 1 + steps = 0 + while current != 0 and current != -1 and steps < max_steps: + tour.append(current) + current = adj.get(current, -1) + steps += 1 + tour.append(0) + + # Model objective (z variable value) + model_obj = z.X + + # Evaluate actual TDTSP tour time + actual_obj = evaluate_tour_tdtsp( + tour, L, v_ijh, period_boundaries, H) + + # The true objective is the actual TDTSP evaluation of the best tour. + # Use the better of the MIP solution tour and the initial ATSP tour. + if actual_obj <= z_cstar: + final_obj = actual_obj + else: + final_obj = z_cstar + tour = atsp_tour + + result.update({ + "objective_value": final_obj, + "model_z_value": model_obj, + "actual_tdtsp_value": actual_obj, + "atsp_upper_bound": z_cstar, + "initial_lower_bound": z_underline_cstar, + "tour": tour, + "n_customers": n_customers, + "n_vertices": n_total, + "mip_gap": model.MIPGap if hasattr(model, 'MIPGap') else None, + "best_bound": model.ObjBound if hasattr(model, 'ObjBound') + else None, + "node_count": int(model.NodeCount), + }) + + print(f"\nModel z value: {model_obj:.6f}") + print(f"Actual TDTSP evaluation: {actual_obj:.6f}") + print(f"ATSP heuristic UB: {z_cstar:.6f}") + print(f"Final objective: {final_obj:.6f}") + print(f"Tour: {tour}") + if hasattr(model, 'MIPGap'): + try: + print(f"MIP gap: {model.MIPGap * 100:.4f}%") + except Exception: + pass + else: + # No feasible solution found; use ATSP heuristic + print("\nNo MIP solution found. Using ATSP heuristic solution.") + result.update({ + "objective_value": z_cstar, + "model_z_value": None, + "actual_tdtsp_value": z_cstar, + "atsp_upper_bound": z_cstar, + "initial_lower_bound": z_underline_cstar, + "tour": atsp_tour, + "n_customers": n_customers, + "n_vertices": n_total, + "mip_gap": None, + "best_bound": None, + "node_count": 0, + }) + + # ------------------------------------------------------------------ + # 8. 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}") + + return result + + +def _status_name(status): + """Convert Gurobi status code to name.""" + status_map = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.CUTOFF: "CUTOFF", + GRB.ITERATION_LIMIT: "ITERATION_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.INTERRUPTED: "INTERRUPTED", + GRB.NUMERIC: "NUMERIC", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + } + return status_map.get(status, f"UNKNOWN({status})") + + +# ============================================================================ +# CLI Entry Point +# ============================================================================ + +def main(): + parser = argparse.ArgumentParser( + description="TDTSP Branch-and-Cut solver using Gurobi. " + "Based on Cordeau, Ghiani, Guerriero (2014).") + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the TDTSP instance JSON file.") + parser.add_argument( + "--solution_path", type=str, default="gurobi_solution_1.json", + help="Output path for the solution JSON (default: " + "gurobi_solution_1.json).") + parser.add_argument( + "--time_limit", type=int, default=3600, + help="Gurobi time limit in seconds (default: 3600).") + + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + result = solve_tdtsp(args.instance_path, args.solution_path, + args.time_limit) + + print("\n" + "=" * 70) + print("SUMMARY") + print("=" * 70) + print(f"Status: {result['status_name']}") + print(f"Objective value: {result['objective_value']:.6f}") + print(f"Solve time: {result['solve_time']:.2f}s") + print(f"Tour: {result['tour']}") + print("=" * 70) + + +if __name__ == "__main__": + main() diff --git a/tasks/cordeau2014/gurobi_feasi_result/large_feasi_result_1.json b/tasks/cordeau2014/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2014/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/cordeau2014/gurobi_feasi_result/large_feasi_result_2.json b/tasks/cordeau2014/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2014/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/cordeau2014/gurobi_feasi_result/large_feasi_result_3.json b/tasks/cordeau2014/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2014/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/cordeau2014/gurobi_feasi_result/large_feasi_result_4.json b/tasks/cordeau2014/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2014/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/cordeau2014/gurobi_feasi_result/large_feasi_result_5.json b/tasks/cordeau2014/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2014/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/cordeau2014/gurobi_feasi_result/tiny_feasi_result.json b/tasks/cordeau2014/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2014/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/cordeau2014/gurobi_solution/large_solution_1.json b/tasks/cordeau2014/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6fb6b7113eead8f7420a7db504575f749c00ddf6 --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96b161feb229fb4e20c040cf880c35fbe979c68aebb00163f14e2ba6eea7d70c +size 2389 diff --git a/tasks/cordeau2014/gurobi_solution/large_solution_2.json b/tasks/cordeau2014/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6748a023915598938907999a931b68d64e52ad7c --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3ccb81a014b259c746bad7acd992af961f3b5b1110de15e0c838a0b1e33f764 +size 2535 diff --git a/tasks/cordeau2014/gurobi_solution/large_solution_3.json b/tasks/cordeau2014/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6f06d55d16a1bef6059046f4271d16caffd8582e --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4d06d3b5d037ebb0448375d85a1a3e3fe5ecbe45554436987da838ac13572b4 +size 2393 diff --git a/tasks/cordeau2014/gurobi_solution/large_solution_4.json b/tasks/cordeau2014/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..410130c0ccad3b84932558fc59edcd6af6de1b3d --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f5ad8fe5f966b253c85603621e4e5ee1035b6594982ae259cdd6bad4cdf552e +size 2490 diff --git a/tasks/cordeau2014/gurobi_solution/large_solution_5.json b/tasks/cordeau2014/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..89312edc2f382384f6e2942c835a47846236876b --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:473e6f6a40c275f72ad8e619e5ac496dcbb4b085d24289dad3bf68aabfe6ecd5 +size 2359 diff --git a/tasks/cordeau2014/gurobi_solution/tiny_solution.json b/tasks/cordeau2014/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..4276ff1dd216fd1949b6d23c31014856090231fe --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c12c7cb835db1ab6e56f23c15b3cde1a671bc76ed9f0d2afa554f9310ea65ab4 +size 781 diff --git a/tasks/cordeau2014/gurobi_solution_log/large_log_1.jsonl b/tasks/cordeau2014/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..009fa98d6e7dd3afa5a8dea4bf4fc467ccb9b6fd --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a700dd57373dd67dfc4a4d92bf3b1e551a829d3a07df641475db1d60f133f6f +size 109 diff --git a/tasks/cordeau2014/gurobi_solution_log/large_log_2.jsonl b/tasks/cordeau2014/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fe9dcc3626b81edb61d62c11de11168273b116d3 --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2b194294bd519c1f39cb85b3b46c84953ca131379b3407d7e166bfbe047e7a4 +size 110 diff --git a/tasks/cordeau2014/gurobi_solution_log/large_log_3.jsonl b/tasks/cordeau2014/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bf7a9d921823b915231373e761df23d2fe089666 --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec1df9f7f2c669b762b17719951402353d8874fb3fc6af0bee8e809f0031b6be +size 273 diff --git a/tasks/cordeau2014/gurobi_solution_log/large_log_4.jsonl b/tasks/cordeau2014/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..914872bc3f36673b34ccdd21317d734bfe7177b3 --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d818aea6953a3ba55b4587263779f88e99e33989ca7c140f09d0350fbba0a2e7 +size 106 diff --git a/tasks/cordeau2014/gurobi_solution_log/large_log_5.jsonl b/tasks/cordeau2014/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..856e084da9b054814a2210229f9c6845ab7523f2 --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:409279529f55a64ca184656a0b3e1d453acd0b55feef6d8477aa4723bdfd4a36 +size 109 diff --git a/tasks/cordeau2014/gurobi_solution_log/tiny_log.jsonl b/tasks/cordeau2014/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1768fdc02ed1d1702e92adc10b916557e9e769d6 --- /dev/null +++ b/tasks/cordeau2014/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aff47c1697e2b77dd21772846f21b4f8f9e2b73fb7f245d6a005c8619bccef49 +size 55 diff --git a/tasks/cordeau2014/instance/large_instance_1.json b/tasks/cordeau2014/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ce85e8891ba0c0a4238643be6f07f7bebe5e4d07 --- /dev/null +++ b/tasks/cordeau2014/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44f08103c1b2c90095c10beb153ccf80ad1ee0755225efcb5dfeb0a09bca12cf +size 7092033 diff --git a/tasks/cordeau2014/instance/large_instance_2.json b/tasks/cordeau2014/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e58356e7fd247095beea0ac06c2f1d92779799f6 --- /dev/null +++ b/tasks/cordeau2014/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fe64d2ed23798859e4f3e646586d135b9d67380261191c595f833181f9a705c +size 7045302 diff --git a/tasks/cordeau2014/instance/large_instance_3.json b/tasks/cordeau2014/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1e04e5dccb77cebd74857c503bac65983cd85ccd --- /dev/null +++ b/tasks/cordeau2014/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e6d6ffe1ba4babbecdcb297f025b474313a8a906b696c0c78fdd336d4d6f2bd +size 7052838 diff --git a/tasks/cordeau2014/instance/large_instance_4.json b/tasks/cordeau2014/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..dccbf5399f31dca0ff3488258d11c6c078a87bb9 --- /dev/null +++ b/tasks/cordeau2014/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:690c422cab3c2a1b49d7f80d2ee86de5f541d94db746c1682d0dc60bc604cfaa +size 7723688 diff --git a/tasks/cordeau2014/instance/large_instance_5.json b/tasks/cordeau2014/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..52f40c3d4ad6f08043e184b5a0138f9b410266ec --- /dev/null +++ b/tasks/cordeau2014/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db124cd9030bcd3b1a404f616fffd00ce61634e90e26ee79dcbbf38e39517e29 +size 7630891 diff --git a/tasks/cordeau2014/instance/tiny_instance.json b/tasks/cordeau2014/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..57df70680b0e926bcbf94f95acd6f3b65f432904 --- /dev/null +++ b/tasks/cordeau2014/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63b08f008e259aaf5648ed356552ac76af33c75fc67d053ef1c400e6b1fffa98 +size 52698 diff --git a/tasks/cordeau2014/instance_schema.json b/tasks/cordeau2014/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b6bc7f30d1b158df720bcd0254421073f1c61840 --- /dev/null +++ b/tasks/cordeau2014/instance_schema.json @@ -0,0 +1,26 @@ +{ + "parameters": { + "n_customers": " Number of customers to be visited by the vehicle.", + "total_vertices": " Total number of vertices in the graph, including the depot and all customers.", + "H": " Number of consecutive time periods that partition the planning horizon.", + "b_h": " Global congestion factor for each time period, representing the lightest congestion level on the network during that period.", + "time_horizon_T": " End time of the planning horizon, within which the vehicle must complete its tour.", + "period_boundaries": " Start and end times of each time period, from time zero to the end of the horizon." + }, + "depot": { + "index": " Index of the depot vertex in the vertex list.", + "x": " X-coordinate of the depot location.", + "y": " Y-coordinate of the depot location." + }, + "vertices": { + "count": " Total number of vertices including the depot.", + "coordinates": " X and Y coordinates of each vertex, starting with the depot at index 0 followed by each customer.", + "zones": " Concentric traffic zone assignment for each vertex based on its distance from the depot." + }, + "arcs": { + "distances": " Euclidean travel distance from vertex i to vertex j for every ordered pair of vertices.", + "max_speeds_u_ij": " Maximum achievable travel speed on the arc from vertex i to vertex j across all time periods.", + "speeds_v_ijh": " Travel speed on the arc from vertex i to vertex j during each time period.", + "delta_ijh": " Arc-specific congestion degradation factor for the arc from vertex i to vertex j during each time period." + } +} diff --git a/tasks/cordeau2014/mathematical_formulation.md b/tasks/cordeau2014/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..4950af6d0a53a19c7aa3a926d9a939d159c9d073 --- /dev/null +++ b/tasks/cordeau2014/mathematical_formulation.md @@ -0,0 +1,78 @@ +# Original Formulation: Time-Dependent Travelling Salesman Problem (TDTSP) + +*Source: Analysis and Branch-and-Cut for the Time-Dependent Travelling Salesman Problem, Cordeau, Ghiani, and Guerriero, 2014.* + +## Sets and Parameters + +- $G = (V \cup \{0\}, A)$: complete directed graph with $V = \{1,\dots,n\}$ and depot $0$. + +- $[0, T]$: time horizon partitioned into $H$ subintervals $[T_h, T_{h+1}]$, $h = 0,\dots,H-1$, with $T_0 = 0$ and $T_H = T$. + +- $L_{ij}$: length of arc $(i,j) \in A$. + +- $u_{ij} = \max_{h} v_{ijh}$: maximum (free-flow) speed on arc $(i,j)$. + +- $v_{ijh} = \delta_{ijh}\, b_h\, u_{ij}$: actual speed on $(i,j)$ during period $h$, where $b_h \in [0,1]$ is the common congestion factor and $\delta_{ijh} \in [0,1]$ is an arc-specific degradation. + +- $\mathcal{P}_i$: set of simple paths $\{i_0, i_1, \dots, i_m\}$ on $G$ with $i_0 = 0$ and $i_m = i$. + +- $LB_{\mathfrak{p}}$: lower bound on total tour duration when path $\mathfrak{p} \in \mathcal{P}_i$ is a prefix of the tour (computed via Algorithm 2 of the paper). + +- $\underline{z}(\underline{c}^{*})$: lower bound given by the optimal ATSP tour with arc costs $L_{ij}/u_{ij}$ (speed law $v_{ijh} = b_h u_{ij}$). + +## Decision Variables + +- $x_{ij} \in \{0,1\}$, $(i,j) \in A$: $=1$ iff arc $(i,j)$ is in the tour. + +- $z \in \mathbb{R}$: total tour duration. + +- $z_h \geq 0$, $h = 0,\dots,H-1$: auxiliary continuous variable representing the portion of tour duration attributable to period $h$ (under the common-congestion speed law). + +- $y_h \in \{0,1\}$, $h = 0,\dots,H-1$: $=1$ iff the tour completion time lies in $[T_{h-1}, T_h]$. + +## Objective + +$$\begin{equation} +\min \;\; z \tag{12} +\end{equation}$$ + +## Constraints (Core Model, Section 4) + +$$\begin{align} +z &\;\geq\; LB_{\mathfrak{p}} \Bigl( 1 - \sum_{(a,b) \in \mathfrak{p}} (1 - x_{ab}) \Bigr), + & \forall i \in V \cup \{0\},\; \mathfrak{p} \in \mathcal{P}_i \tag{13} \\[2pt] +\sum_{i \in V \cup \{0\} \setminus \{j\}} x_{ij} &= 1, & \forall j \in V \cup \{0\} \tag{14} \\[2pt] +\sum_{j \in V \cup \{0\} \setminus \{i\}} x_{ij} &= 1, & \forall i \in V \cup \{0\} \tag{15} \\[2pt] +\sum_{i \in S} \sum_{j \notin S} x_{ij} &\;\geq\; 1, + & \forall S \subset V \cup \{0\},\; |S| \geq 2 \tag{16} \\[2pt] +x_{ij} &\;\in\; \{0,1\}, & \forall (i,j) \in A \tag{17} +\end{align}$$ + +## Valid Inequalities (Section 4.1) + +$$\begin{align} +z &\;\geq\; \sum_{h=0}^{H-1} \frac{z_h}{b_h} \tag{20} \\[2pt] +z_0 &\;\geq\; \sum_{(i,j) \in A} \frac{L_{ij}}{u_{ij}}\, x_{ij} + \;-\; \sum_{\ell=1}^{H-1} z_\ell \tag{21} \\[2pt] +z_h &\;\geq\; \sum_{(i,j) \in A} \frac{L_{ij}}{u_{ij}}\, x_{ij} + \;-\; \sum_{\ell=0}^{h-1} b_\ell\,(T_\ell - T_{\ell-1}) + \;-\; \sum_{\ell=h+1}^{H-1} z_\ell, + & h = 1, \dots, H-2 \tag{22} \\[2pt] +z_{H-1} &\;\geq\; \sum_{(i,j) \in A} \frac{L_{ij}}{u_{ij}}\, x_{ij} + \;-\; \sum_{\ell=0}^{H-2} b_\ell\,(T_\ell - T_{\ell-1}) \tag{23} \\[2pt] +z_h &\;\leq\; b_h\,(T_h - T_{h-1}) \sum_{\ell=h}^{H-1} y_\ell, + & h = 0, \dots, H-1 \tag{24} \\[2pt] +z_h &\;\geq\; b_h\,(T_h - T_{h-1}) \sum_{\ell=h+1}^{H-1} y_\ell, + & h = 0, \dots, H-2 \tag{25} \\[2pt] +\sum_{h=0}^{H-1} y_h &= 1 \tag{26} \\[2pt] +z_h \;\geq\; 0, \;\; y_h &\;\in\; \{0,1\}, + & h = 0, \dots, H-1 \tag{27} +\end{align}$$ + +## Initial Bound (eq. 31) + +$$\begin{equation} +z \;\geq\; \underline{z}(\underline{c}^{*}) \tag{31} +\end{equation}$$ + +Constraints (13) and (16) are exponential in size and are separated dynamically (shortest-path separation for (13); min-cut separation for (16)). Valid inequalities (20)–(27), together with (31), are added up-front as the total count $3H + 1$ is small. diff --git a/tasks/cordeau2014/problem_description.txt b/tasks/cordeau2014/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..60104a6b34dc75f8c21ae26d05e0d15c8a956386 --- /dev/null +++ b/tasks/cordeau2014/problem_description.txt @@ -0,0 +1,15 @@ +# Problem Description + +A single vehicle must depart from a depot, visit each customer exactly once, and return to the depot, forming a single closed route through all locations. The underlying network is a directed graph in which a directed connection exists from every location to every other location, where the locations consist of the depot and all customers. The travel time on each connection depends on the time of day at which the vehicle begins traversing that connection, making this a time-dependent travelling salesman problem. The vehicle departs the depot at time zero, and the planning horizon spans from time zero to a known end time. + +The time horizon is divided into consecutive time periods, with boundary times starting at zero and ending at the horizon's end time, so that each period covers the interval between two consecutive boundary times. Each connection from one location to another has a fixed travel distance that is at least zero and a maximum travel speed, defined as the highest speed achievable on that connection across all time periods. For each connection and each time period, the travel speed is the product of three quantities: a degradation factor for that connection during that period (between zero and one), a global congestion factor for that period (between zero and one, representing the lightest congestion on the entire network during that period), and the maximum speed for that connection. The speed is constant within each period but may change at period boundaries. + +When the vehicle begins traversing a connection during one time period, it may not finish within that same period. In that case, the remaining distance is covered at the speed applicable to the next period, and this process continues across as many period boundaries as necessary until the connection is fully traversed. Specifically, the travel time for a connection when departing at a given time is computed as follows: let the remaining distance initially equal the connection's full travel distance and let the current period be the one containing the departure time. The tentative arrival time is the current time plus the remaining distance divided by the speed for that connection during the current period. If this tentative arrival time falls within the current period, the traversal is complete and the travel time equals the tentative arrival time minus the departure time. Otherwise, the vehicle travels at the current period's speed until the end of that period, the remaining distance is reduced by the distance covered during that portion, the current time advances to the start of the next period, and the computation repeats with the updated period and remaining distance. + +The input data for each instance specifies the number of customers, the coordinates of the depot and each customer, the number of time periods and their boundary times, the global congestion factor for each period, the travel distance for every ordered pair of locations, the maximum speed for every ordered pair of locations, and the speed or equivalently the degradation factor for every ordered pair of locations and every time period. + +The planner must determine the order in which to visit the customers, which is equivalent to choosing exactly one outgoing connection and one incoming connection at every location (including the depot) such that the selected connections form a single tour visiting all locations. Every location, including the depot, must have exactly one selected connection entering it and exactly one selected connection leaving it. The selected connections must not form disconnected loops: the chosen connections must form one single connected route rather than multiple disjoint loops. + +The tour duration is the total elapsed time from the vehicle's departure at the depot at time zero until it returns to the depot, computed by applying the time-dependent travel time procedure connection by connection along the chosen route. Because travel speeds vary by time period, the tour duration depends not just on which connections are selected but on the cumulative departure times at each location along the route. + +The goal is to find the tour that minimizes total tour duration. diff --git a/tasks/cordeau2014/solution_logger.py b/tasks/cordeau2014/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/cordeau2014/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/cordeau2014/solution_schema.json b/tasks/cordeau2014/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2a7efde8c191674f415de744296bbc2fc6dc3f92 --- /dev/null +++ b/tasks/cordeau2014/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total tour duration from the vehicle's departure at the depot until its return, computed under time-dependent travel speeds.", + "tour": " Ordered sequence of vertex indices visited by the vehicle, starting and ending at the depot." +} diff --git a/tasks/cordeau2019/feasibility_check.py b/tasks/cordeau2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee1dc7d179fde9bab8f304a894e29a2656f5455 --- /dev/null +++ b/tasks/cordeau2019/feasibility_check.py @@ -0,0 +1,694 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for PSCLP and MCLP solutions from: +Cordeau, Furini, and Ljubic (2019) - "Benders decomposition for very large +scale partial set covering and maximal covering location problems." + +Constraints numbered top-to-bottom across both formulations: + PSCLP: + Constraint 1: sum_{i in I(j)} y_i >= z_j, for all j in J (linking) + Constraint 2: sum_{j in J} d_j z_j >= D (demand coverage) + Constraint 3: y_i in {0,1}, for all i in I (binary y) + Constraint 4: z_j in {0,1}, for all j in J (binary z) + MCLP: + Constraint 5: sum_{i in I} f_i y_i <= B (budget) + Constraint 6: sum_{i in I(j)} y_i >= z_j, for all j in J (linking) + Constraint 7: y_i in {0,1}, for all i in I (binary y) + Constraint 8: z_j in {0,1}, for all j in J (binary z) + Both: + Constraint 9: objective-value consistency (anti-gaming) + The self-reported objective_value must equal the objective recomputed + from `open_facilities`: + PSCLP objective (1): total opening cost = sum_{i in I} f_i y_i + MCLP objective (6): total covered demand = sum_{j in J} d_j z_j + Both objectives are fully determined by `open_facilities` (z_j is + derived from coverage), so a full recompute is possible. This is a + Tier C defense against candidates that fabricate objective_value while + keeping the routes/decisions technically feasible. Constraint 9 is only + ever ADDED to a verdict; constraints 1-8 are checked by the unmodified + `check_feasibility` and never altered here. + +This is the obj-recompute variant of `feasibility_check.py`. `check_feasibility` +is byte-identical to the original; the objective consistency check lives +entirely in `main()`, just before the overall feasibility decision. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'primary_problem_type', 'results') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('results',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, problem_type, open_facilities): + """Check feasibility of a solution for a given problem type. + + Returns (violated_constraints, violations, violation_magnitudes). + """ + tol = 1e-5 + eps = 1e-5 + + num_facilities = instance["num_facilities"] + num_customers = instance["num_customers"] + customer_demands = instance["customer_demands"] + facility_cost = instance["facility_cost"] + cust_to_fac = instance["customer_to_facilities_coverage"] + + violated_constraints = [] + violations = [] + violation_magnitudes = [] + + # Build y vector + y = [0] * num_facilities + for i in open_facilities: + y[i] = 1 + + # Derive z: z_j = 1 if any facility in I(j) is open, else 0 + open_set = set(open_facilities) + z = [0] * num_customers + for j in range(num_customers): + I_j = cust_to_fac.get(str(j), []) + for i in I_j: + if i in open_set: + z[j] = 1 + break + + if problem_type == "PSCLP": + D = instance["covering_demand_D"] + + # Constraint 1: sum_{i in I(j)} y_i >= z_j for all j + # Since z_j is derived as 1 only when sum >= 1, check explicitly + c1_violated = False + for j in range(num_customers): + I_j = cust_to_fac.get(str(j), []) + lhs = sum(y[i] for i in I_j) + rhs = z[j] + violation_amount = rhs - lhs # >= constraint: violation if rhs > lhs + if violation_amount > tol: + if not c1_violated: + c1_violated = True + violated_constraints.append(1) + violations.append( + f"Linking constraint violated: customer {j} has z_j={rhs} " + f"but sum of y_i over I(j) = {lhs}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Constraint 2: sum_{j in J} d_j z_j >= D + covered_demand = sum(customer_demands[j] * z[j] for j in range(num_customers)) + violation_amount = D - covered_demand # >= constraint + if violation_amount > tol: + violated_constraints.append(2) + violations.append( + f"Demand coverage violated: covered demand = {covered_demand}, " + f"required D = {D}, shortfall = {violation_amount}" + ) + normalizer = max(abs(D), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(covered_demand), + "rhs": float(D), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Constraint 3: y_i in {0,1} + c3_violated = False + for i in range(num_facilities): + if y[i] not in (0, 1): + if not c3_violated: + c3_violated = True + violated_constraints.append(3) + violations.append( + f"Binary constraint on y violated: y_{i} = {y[i]}" + ) + val = y[i] + violation_amount = min(abs(val), abs(val - 1)) + normalizer = max(1.0, eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(val), + "rhs": float(round(val)), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Constraint 4: z_j in {0,1} + c4_violated = False + for j in range(num_customers): + if z[j] not in (0, 1): + if not c4_violated: + c4_violated = True + violated_constraints.append(4) + violations.append( + f"Binary constraint on z violated: z_{j} = {z[j]}" + ) + val = z[j] + violation_amount = min(abs(val), abs(val - 1)) + normalizer = max(1.0, eps) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(val), + "rhs": float(round(val)), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Also check validity of facility indices + for i in open_facilities: + if i < 0 or i >= num_facilities: + if 3 not in violated_constraints: + violated_constraints.append(3) + violations.append( + f"Invalid facility index: {i} not in [0, {num_facilities-1}]" + ) + + elif problem_type == "MCLP": + B = instance["budget_B"] + + # Constraint 5: sum_{i in I} f_i y_i <= B + total_cost = sum(facility_cost[i] * y[i] for i in range(num_facilities)) + violation_amount = total_cost - B # <= constraint: violation if lhs > rhs + if violation_amount > tol: + violated_constraints.append(5) + violations.append( + f"Budget constraint violated: total cost = {total_cost}, " + f"budget B = {B}, excess = {violation_amount}" + ) + normalizer = max(abs(B), eps) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(total_cost), + "rhs": float(B), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Constraint 6: sum_{i in I(j)} y_i >= z_j for all j + c6_violated = False + for j in range(num_customers): + I_j = cust_to_fac.get(str(j), []) + lhs = sum(y[i] for i in I_j) + rhs = z[j] + violation_amount = rhs - lhs + if violation_amount > tol: + if not c6_violated: + c6_violated = True + violated_constraints.append(6) + violations.append( + f"Linking constraint violated: customer {j} has z_j={rhs} " + f"but sum of y_i over I(j) = {lhs}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Constraint 7: y_i in {0,1} + c7_violated = False + for i in range(num_facilities): + if y[i] not in (0, 1): + if not c7_violated: + c7_violated = True + violated_constraints.append(7) + violations.append( + f"Binary constraint on y violated: y_{i} = {y[i]}" + ) + val = y[i] + violation_amount = min(abs(val), abs(val - 1)) + normalizer = max(1.0, eps) + violation_magnitudes.append({ + "constraint": 7, + "lhs": float(val), + "rhs": float(round(val)), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Constraint 8: z_j in {0,1} + c8_violated = False + for j in range(num_customers): + if z[j] not in (0, 1): + if not c8_violated: + c8_violated = True + violated_constraints.append(8) + violations.append( + f"Binary constraint on z violated: z_{j} = {z[j]}" + ) + val = z[j] + violation_amount = min(abs(val), abs(val - 1)) + normalizer = max(1.0, eps) + violation_magnitudes.append({ + "constraint": 8, + "lhs": float(val), + "rhs": float(round(val)), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Check validity of facility indices + for i in open_facilities: + if i < 0 or i >= num_facilities: + if 7 not in violated_constraints: + violated_constraints.append(7) + violations.append( + f"Invalid facility index: {i} not in [0, {num_facilities-1}]" + ) + + feasible = len(violated_constraints) == 0 + return feasible, violated_constraints, violations, violation_magnitudes + + +def compute_true_objective(instance, problem_type, open_facilities): + """Recompute the true objective from the solution's `open_facilities`. + + PSCLP objective (1): total opening cost = sum_{i in I} f_i y_i + MCLP objective (6): total covered demand = sum_{j in J} d_j z_j + + Both are full recomputes: `open_facilities` is the only decision variable + carried in the solution, and z_j is derived from coverage exactly as + `check_feasibility` derives it. Stray (out-of-range) indices are skipped + so this recompute can never crash. + """ + num_facilities = instance["num_facilities"] + num_customers = instance["num_customers"] + facility_cost = instance["facility_cost"] + customer_demands = instance["customer_demands"] + cust_to_fac = instance["customer_to_facilities_coverage"] + + # y vector / open set restricted to valid facility indices. + y = [0] * num_facilities + open_set = set() + for i in open_facilities: + if 0 <= i < num_facilities: + y[i] = 1 + open_set.add(i) + + if problem_type == "PSCLP": + # total opening cost of the selected facilities + return float(sum(facility_cost[i] * y[i] for i in range(num_facilities))) + + # MCLP: total covered demand; z_j = 1 if any facility in I(j) is open + total = 0 + for j in range(num_customers): + for i in cust_to_fac.get(str(j), []): + if i in open_set: + total += customer_demands[j] + break + return float(total) + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for PSCLP/MCLP (Cordeau et al. 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() + + 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 + + expected_problem_types = set(instance.get("problem_types", [])) + results = solution.get("results") + primary = solution.get("primary_problem_type") + result_contract_errors = [] + if not isinstance(results, dict) or set(results) != expected_problem_types: + result_contract_errors.append( + "results must exactly cover the instance problem_types: " + f"expected={sorted(expected_problem_types)}, " + f"got={sorted(results) if isinstance(results, dict) else type(results).__name__}" + ) + if primary not in expected_problem_types: + result_contract_errors.append( + f"primary_problem_type={primary!r} is not declared by the instance" + ) + if isinstance(results, dict): + for problem_type in expected_problem_types: + result = results.get(problem_type) + if not isinstance(result, dict): + result_contract_errors.append( + f"results.{problem_type} must be an object" + ) + continue + if result.get("problem_type") != problem_type: + result_contract_errors.append( + f"results.{problem_type}.problem_type must equal {problem_type}" + ) + facilities = result.get("open_facilities") + if not isinstance(facilities, list) or not facilities: + result_contract_errors.append( + f"results.{problem_type}.open_facilities must be a nonempty list" + ) + elif len(facilities) != len(set(facilities)): + result_contract_errors.append( + f"results.{problem_type}.open_facilities contains duplicates" + ) + nested_objective = result.get("objective_value") + if ( + isinstance(nested_objective, bool) + or not isinstance(nested_objective, (int, float)) + or not math.isfinite(float(nested_objective)) + ): + result_contract_errors.append( + f"results.{problem_type}.objective_value must be finite" + ) + if result_contract_errors: + with open(args.result_path, "w") as result_handle: + json.dump( + { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": result_contract_errors, + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + return + + all_violated_constraints = [] + all_violations = [] + all_violation_magnitudes = [] + + # --- Constraint 9: objective-value consistency (Tier C anti-gaming) ---- + # Recompute the objective from `open_facilities` and flag a violation when + # the self-reported objective_value disagrees. Objectives here are + # integer-valued (unit facility costs, integer customer demands) and well + # within float64's exact-integer range, so a tight tolerance is correct: + # any off-by-one or larger lie fires; genuine values pass exactly. + OBJ_IDX = 9 + OBJ_TOL = 0.5 + + # Recomputed true objective per problem type, reused by the top-level check. + true_obj_by_ptype = {} + + def flag_obj(reported_raw, true_obj, label): + """Append a constraint-9 violation if reported_raw disagrees with + true_obj. A missing / non-numeric objective_value is left to the + upstream eval pipeline (it rejects those independently).""" + if reported_raw is None: + return + try: + reported = float(reported_raw) + except (TypeError, ValueError): + return + abs_diff = abs(reported - true_obj) + if abs_diff > OBJ_TOL: + all_violated_constraints.append(OBJ_IDX) + all_violations.append( + f"Objective consistency violated ({label}): reported " + f"objective_value={reported} differs from recomputed " + f"objective={true_obj} (|diff|={abs_diff:.6g}, tol={OBJ_TOL})" + ) + normalizer = max(abs(true_obj), 1e-5) + all_violation_magnitudes.append({ + "constraint": OBJ_IDX, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + # Detect solution format + if "results" in solution: + # Gurobi format: has results dict with sub-problems + for ptype, result in solution["results"].items(): + open_facs = result.get("open_facilities", []) + feasible, vc, vi, vm = check_feasibility(instance, ptype, open_facs) + all_violated_constraints.extend(vc) + all_violations.extend(vi) + all_violation_magnitudes.extend(vm) + + # Objective consistency for this sub-problem's reported value. + true_obj = compute_true_objective(instance, ptype, open_facs) + true_obj_by_ptype[ptype] = true_obj + flag_obj(result.get("objective_value"), true_obj, f"results.{ptype}") + + # Top-level objective_value: the eval pipeline reads THIS field, so it + # is the primary anti-gaming target. It reports the "primary problem + # variant". Compare it precisely against the primary variant's + # recompute when `primary_problem_type` is given; otherwise require it + # to match at least one variant's recomputed objective. + top_obj = solution.get("objective_value") + if top_obj is not None and true_obj_by_ptype: + if primary in true_obj_by_ptype: + flag_obj( + top_obj, true_obj_by_ptype[primary], + f"top-level objective_value (primary={primary})", + ) + else: + try: + top_val = float(top_obj) + except (TypeError, ValueError): + top_val = None + if top_val is not None and not any( + abs(top_val - t) <= OBJ_TOL + for t in true_obj_by_ptype.values() + ): + nearest = min( + true_obj_by_ptype.values(), + key=lambda t: abs(top_val - t), + ) + flag_obj( + top_obj, nearest, + "top-level objective_value (primary unknown; " + "matched no problem variant)", + ) + else: + # Efficient algorithm format: flat structure + open_facs = solution.get("open_facilities", []) + # Determine problem type from instance + problem_types = instance.get("problem_types", []) + if "PSCLP" in problem_types: + ptype = "PSCLP" + elif "MCLP" in problem_types: + ptype = "MCLP" + else: + ptype = problem_types[0] if problem_types else "PSCLP" + + feasible, vc, vi, vm = check_feasibility(instance, ptype, open_facs) + all_violated_constraints.extend(vc) + all_violations.extend(vi) + all_violation_magnitudes.extend(vm) + + # Objective consistency for the flat solution's reported value. + true_obj = compute_true_objective(instance, ptype, open_facs) + flag_obj( + solution.get("objective_value"), true_obj, + f"top-level objective_value ({ptype})", + ) + + # Deduplicate constraint indices + unique_violated = sorted(set(all_violated_constraints)) + overall_feasible = len(unique_violated) == 0 + + output = { + "feasible": overall_feasible, + "violated_constraints": unique_violated, + "violations": all_violations, + "violation_magnitudes": all_violation_magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(output, f, indent=2) + + status = "FEASIBLE" if overall_feasible else "INFEASIBLE" + print(f"Result: {status}") + if not overall_feasible: + print(f"Violated constraints: {unique_violated}") + for v in all_violations: + print(f" - {v}") + print(f"Result written to {args.result_path}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/cordeau2019/gurobi_code.py b/tasks/cordeau2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c3490f92171bed456dff104f5f89718ac521dd90 --- /dev/null +++ b/tasks/cordeau2019/gurobi_code.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of PSCLP and MCLP models from: +Cordeau, Furini, and Ljubic (2019) - "Benders decomposition for very large +scale partial set covering and maximal covering location problems." + +Usage: + python gurobi_code.py --instance_path instance_1.json --solution_path gurobi_solution_1.json --time_limit 3600 +""" + +import argparse +import json +import os +import time + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, "r") as f: + return json.load(f) + + +def solve_psclp(instance, time_limit): + """ + Partial Set Covering Location Problem (PSCLP). + + min sum_{i in I} f_i * y_i + s.t. sum_{i in I(j)} y_i >= z_j, for all j in J + sum_{j in J} d_j * z_j >= D + y_i in {0,1}, i in I + z_j in [0,1], j in J (relaxed per Property 1) + """ + n_facilities = instance["num_facilities"] + n_customers = instance["num_customers"] + facility_cost = instance["facility_cost"] + customer_demands = instance["customer_demands"] + D = instance["covering_demand_D"] + cust_to_fac = instance["customer_to_facilities_coverage"] + + model = gp.Model("PSCLP") + model.Params.TimeLimit = time_limit + model.Params.Threads = 1 + + # Decision variables + y = model.addVars(n_facilities, vtype=GRB.BINARY, name="y") + z = model.addVars(n_customers, vtype=GRB.CONTINUOUS, lb=0.0, ub=1.0, name="z") + + # Objective: minimize total facility cost + model.setObjective( + gp.quicksum(facility_cost[i] * y[i] for i in range(n_facilities)), + GRB.MINIMIZE, + ) + + # Coverage constraints: z_j <= sum_{i in I(j)} y_i + for j in range(n_customers): + I_j = cust_to_fac.get(str(j), []) + model.addConstr( + gp.quicksum(y[i] for i in I_j) >= z[j], + name=f"cover_{j}", + ) + + # Demand constraint: sum_j d_j * z_j >= D + model.addConstr( + gp.quicksum(customer_demands[j] * z[j] for j in range(n_customers)) >= D, + name="demand", + ) + + start = time.time() + model.optimize() + wall_time = time.time() - start + + result = { + "problem_type": "PSCLP", + "status": model.Status, + "status_name": _status_name(model.Status), + "wall_time": wall_time, + "time_limit": time_limit, + "num_facilities": n_facilities, + "num_customers": n_customers, + "covering_demand_D": D, + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["mip_gap"] = model.MIPGap + result["open_facilities"] = [i for i in range(n_facilities) if y[i].X > 0.5] + result["num_open_facilities"] = len(result["open_facilities"]) + covered_demand = sum( + customer_demands[j] * z[j].X for j in range(n_customers) + ) + result["covered_demand"] = covered_demand + else: + result["objective_value"] = None + result["best_bound"] = None + result["mip_gap"] = None + result["open_facilities"] = [] + result["num_open_facilities"] = 0 + result["covered_demand"] = 0.0 + + model.dispose() + return result + + +def solve_mclp(instance, time_limit): + """ + Maximal Covering Location Problem (MCLP). + + max sum_{j in J} d_j * z_j + s.t. sum_{i in I} f_i * y_i <= B + sum_{i in I(j)} y_i >= z_j, for all j in J + y_i in {0,1}, i in I + z_j in [0,1], j in J (relaxed per Property 1) + """ + n_facilities = instance["num_facilities"] + n_customers = instance["num_customers"] + facility_cost = instance["facility_cost"] + customer_demands = instance["customer_demands"] + B = instance["budget_B"] + cust_to_fac = instance["customer_to_facilities_coverage"] + + model = gp.Model("MCLP") + model.Params.TimeLimit = time_limit + model.Params.Threads = 1 + + # Decision variables + y = model.addVars(n_facilities, vtype=GRB.BINARY, name="y") + z = model.addVars(n_customers, vtype=GRB.CONTINUOUS, lb=0.0, ub=1.0, name="z") + + # Objective: maximize covered demand + model.setObjective( + gp.quicksum(customer_demands[j] * z[j] for j in range(n_customers)), + GRB.MAXIMIZE, + ) + + # Budget constraint: sum_i f_i * y_i <= B + model.addConstr( + gp.quicksum(facility_cost[i] * y[i] for i in range(n_facilities)) <= B, + name="budget", + ) + + # Coverage constraints: z_j <= sum_{i in I(j)} y_i + for j in range(n_customers): + I_j = cust_to_fac.get(str(j), []) + model.addConstr( + gp.quicksum(y[i] for i in I_j) >= z[j], + name=f"cover_{j}", + ) + + start = time.time() + model.optimize() + wall_time = time.time() - start + + result = { + "problem_type": "MCLP", + "status": model.Status, + "status_name": _status_name(model.Status), + "wall_time": wall_time, + "time_limit": time_limit, + "num_facilities": n_facilities, + "num_customers": n_customers, + "budget_B": B, + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["mip_gap"] = model.MIPGap + result["open_facilities"] = [i for i in range(n_facilities) if y[i].X > 0.5] + result["num_open_facilities"] = len(result["open_facilities"]) + result["covered_demand"] = model.ObjVal + else: + result["objective_value"] = None + result["best_bound"] = None + result["mip_gap"] = None + result["open_facilities"] = [] + result["num_open_facilities"] = 0 + result["covered_demand"] = 0.0 + + model.dispose() + return result + + +def _status_name(status): + mapping = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.INTERRUPTED: "INTERRUPTED", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + } + return mapping.get(status, f"UNKNOWN_{status}") + + +def main(): + parser = argparse.ArgumentParser( + description="Solve PSCLP/MCLP using Gurobi (Cordeau et al. 2019)" + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to instance JSON file", + ) + parser.add_argument( + "--solution_path", + type=str, + default=None, + help="Path for solution JSON output. Defaults to gurobi_solution_{i}.json", + ) + parser.add_argument( + "--time_limit", + type=int, + default=3600, + help="Time limit in seconds (default: 3600)", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + instance_id = instance["instance_id"] + problem_types = instance["problem_types"] + + # Determine output directory (same as instance file) + out_dir = os.path.dirname(os.path.abspath(args.instance_path)) + + results = {} + + # Solve PSCLP if listed + if "PSCLP" in problem_types: + print(f"{'='*60}") + print(f"Solving PSCLP for instance {instance_id}") + print(f"{'='*60}") + results["PSCLP"] = solve_psclp(instance, args.time_limit) + + # Solve MCLP if listed + if "MCLP" in problem_types: + print(f"{'='*60}") + print(f"Solving MCLP for instance {instance_id}") + print(f"{'='*60}") + results["MCLP"] = solve_mclp(instance, args.time_limit) + + # Determine primary objective_value (first problem type solved) + primary_type = problem_types[0] + primary_result = results.get(primary_type, {}) + primary_obj = primary_result.get("objective_value", None) + + sol_path = args.solution_path if args.solution_path else os.path.join( + out_dir, f"gurobi_solution_{instance_id}.json" + ) + + solution = { + "instance_id": instance_id, + "objective_value": primary_obj, + "solver": "gurobi", + "primary_problem_type": primary_type, + "results": results, + } + with open(sol_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + print(f"\nSolution written to {sol_path}") + + # Print summary + for ptype, res in results.items(): + print(f"\n--- {ptype} Summary ---") + print(f" Status: {res['status_name']}") + print(f" Objective: {res['objective_value']}") + if res.get("best_bound") is not None: + print(f" Best bound: {res['best_bound']}") + if res.get("mip_gap") is not None: + print(f" MIP gap: {res['mip_gap']:.6f}") + print(f" Open facilities: {res['num_open_facilities']}") + print(f" Wall time: {res['wall_time']:.2f}s") + + +if __name__ == "__main__": + main() diff --git a/tasks/cordeau2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/cordeau2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2019/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/cordeau2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/cordeau2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2019/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/cordeau2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/cordeau2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2019/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/cordeau2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/cordeau2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2019/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/cordeau2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/cordeau2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2019/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/cordeau2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/cordeau2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cordeau2019/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/cordeau2019/gurobi_solution/large_solution_1.json b/tasks/cordeau2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..bc119d923ed58060c50334288a2c6eb08ca810df --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e5578a0a8d8c31b7b6db1a06443a67489ed6f0bd5138c380f5bfaf0d3cec89e +size 1196 diff --git a/tasks/cordeau2019/gurobi_solution/large_solution_2.json b/tasks/cordeau2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..871995a3e0b97dfb39c94a42deda2ef6d0a5603f --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56c8af87e871fb86d9a43aa10d0c6dc0f39c79c5d73cf1b4f45f34ab00da8a9d +size 1208 diff --git a/tasks/cordeau2019/gurobi_solution/large_solution_3.json b/tasks/cordeau2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1c77d99574efc66d8a6b4f7dbb6dfe6dc3248732 --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78b75d336ff6222d817ddffe361210ebf31baf58b39a1c90bdcfd1d4fae1f3f4 +size 1207 diff --git a/tasks/cordeau2019/gurobi_solution/large_solution_4.json b/tasks/cordeau2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c45c115ac63fa9a7a374566ac694f5578e75991f --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:097f085fdebcae48f800bf5b1543b73de185284361d8d5e6f90d8913322fe985 +size 1196 diff --git a/tasks/cordeau2019/gurobi_solution/large_solution_5.json b/tasks/cordeau2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d6be3a5c398dcb95cb7d326408dbd17ef1565b5d --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfbbef31401f67523b8dd0a489c5b38699f3bd38be631a3f26027eaf82e0020a +size 1315 diff --git a/tasks/cordeau2019/gurobi_solution/tiny_solution.json b/tasks/cordeau2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..b4a072e72344d63ade5db90a9f6b0c30b4f2b4d5 --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0cd4a41942ffa664652600ea8abf8604e1b2d38c5d235537710bd645ebb811c4 +size 1199 diff --git a/tasks/cordeau2019/gurobi_solution_log/large_log_1.jsonl b/tasks/cordeau2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e0789afa48fef3fc5328bf2a20793186463abc35 --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1a31d72d2dfdfebef6c4d551c184f4bffa8cca4343a70b6c827921055b40989 +size 252 diff --git a/tasks/cordeau2019/gurobi_solution_log/large_log_2.jsonl b/tasks/cordeau2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e7d83c458373e2b93adcbe1c11a40fbb39fc761d --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:310f3a6901fc780988b91a2d29a4128a322a867161f7d38b7a4a016ae18747e1 +size 295 diff --git a/tasks/cordeau2019/gurobi_solution_log/large_log_3.jsonl b/tasks/cordeau2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92bcd97ee20d4cadccd1d6082aba3c49494adde0 --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e0393ec920512da621d79195433801f3ce18a68a11dcebefdcc5cb41a163a11 +size 211 diff --git a/tasks/cordeau2019/gurobi_solution_log/large_log_4.jsonl b/tasks/cordeau2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3af311b3d77421c3d923454aef55d6150278fc83 --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17eca955780456049bba9dc0b2365f1c96f277adcdd6c1efcbd1e402870ffe82 +size 168 diff --git a/tasks/cordeau2019/gurobi_solution_log/large_log_5.jsonl b/tasks/cordeau2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..321c97f091dfb7c64300cde2718303106317cf60 --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0baa845add86e3eb8f81b5075e452744ad9327660a3f0bb1a7c01e3ae1ef396c +size 252 diff --git a/tasks/cordeau2019/gurobi_solution_log/tiny_log.jsonl b/tasks/cordeau2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..266567ffe76fb94115c34abc11e1a2379b1f1ee2 --- /dev/null +++ b/tasks/cordeau2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bcfddd4ec8fe184daabdfa1397cf5431de2998045e9832257e4c9210d61f59b4 +size 163 diff --git a/tasks/cordeau2019/instance/large_instance_1.json b/tasks/cordeau2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..2a8584318eb4ceacf53ef8a8d621293519b4dff4 --- /dev/null +++ b/tasks/cordeau2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6338452b94bc3d0fb08a8a2ea2402e90764077872fa964c8cbbeed2dbb7e9da9 +size 12562666 diff --git a/tasks/cordeau2019/instance/large_instance_2.json b/tasks/cordeau2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6b1eac1afe33b8bbbb405c7a97229af1124cf3d5 --- /dev/null +++ b/tasks/cordeau2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96a8e5dfb3839a3076d1596f7f0627644cddfb1694ed55d761f6cce33885a971 +size 11245263 diff --git a/tasks/cordeau2019/instance/large_instance_3.json b/tasks/cordeau2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..4985eb273fde9605b236e050bee6914e70312754 --- /dev/null +++ b/tasks/cordeau2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48025224557147f9ad526523781283acacc6462b109acb18de2c85d22c59dce8 +size 12173023 diff --git a/tasks/cordeau2019/instance/large_instance_4.json b/tasks/cordeau2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2ad7175f94f124082309a8e8e76d18715b6aadba --- /dev/null +++ b/tasks/cordeau2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4653996036b69520918f504a5bcb135a83af8cd248ef97ce19e93908af973806 +size 13529387 diff --git a/tasks/cordeau2019/instance/large_instance_5.json b/tasks/cordeau2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9b35c51292a11200c0eeb29d63f718fc68494c70 --- /dev/null +++ b/tasks/cordeau2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37388a3885b82efd5ba4ef17ecf7ada1192cbfd58b1879d41d9575866de01a17 +size 8961994 diff --git a/tasks/cordeau2019/instance/tiny_instance.json b/tasks/cordeau2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..3b60f8e13e8b8fed52fe37dec26fe3f0971d4210 --- /dev/null +++ b/tasks/cordeau2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f418bde54e2073fdeae171485acbabaafd9969ccf43be5c7c7f0487dd0d9fd7 +size 1011703 diff --git a/tasks/cordeau2019/instance_schema.json b/tasks/cordeau2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d5027bf392548a66a820bfeb37c217ca14b911d7 --- /dev/null +++ b/tasks/cordeau2019/instance_schema.json @@ -0,0 +1,15 @@ +{ + "num_facilities": " Total number of potential facility locations that may be opened.", + "num_customers": " Total number of customers to be served.", + "budget_B": " Maximum total opening cost allowed when selecting facilities in the Maximal Covering Location Problem.", + "covering_demand_fraction": " Fraction of total demand that must be covered in the Partial Set Covering Location Problem.", + "covering_demand_D": " Minimum total covered demand required in the Partial Set Covering Location Problem.", + "total_demand_D_bar": " Sum of all customer demands across the entire customer set.", + "radius_of_coverage": " Maximum Euclidean distance between a facility and a customer for the facility to cover that customer.", + "facility_cost": " Cost of opening each facility.", + "facility_coordinates": " Two-dimensional coordinates (x, y) of each potential facility location.", + "customer_coordinates": " Two-dimensional coordinates (x, y) of each customer location.", + "customer_demands": " Demand quantity associated with each customer.", + "facility_to_customers_coverage": " List of customer indices that each facility can cover, where coverage means the Euclidean distance is within the coverage radius.", + "customer_to_facilities_coverage": " List of facility indices that can cover each customer, where coverage means the Euclidean distance is within the coverage radius." +} diff --git a/tasks/cordeau2019/mathematical_formulation.md b/tasks/cordeau2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..a872ed7c9e67a17077a5175ca2b74a9d35980316 --- /dev/null +++ b/tasks/cordeau2019/mathematical_formulation.md @@ -0,0 +1,65 @@ +# Original Formulation: Partial Set Covering Location Problem (PSCLP) and Maximal Covering Location Problem (MCLP) + +*Source: Benders Decomposition for Very Large Scale Partial Set Covering and Maximal Covering Location Problems, Jean-François Cordeau, Fabio Furini, and Ivana Ljubić, 2019.* + +## Sets and Parameters + +- $I$: set of potential facility locations, indexed by $i$. + +- $J$: set of customers (demand points), indexed by $j$. + +- $I(j) \subseteq I$: subset of facilities that can cover customer $j$ (i.e., those within the coverage radius $\hat{R}$ of $j$). + +- $J(i) \subseteq J$: subset of customers that can be covered by facility $i$. + +- $f_i \ge 0$: opening cost of facility $i \in I$. + +- $d_j \ge 0$: demand of customer $j \in J$. + +- $D > 0$: minimum total demand that must be covered (PSCLP parameter). + +- $B > 0$: budget available for opening facilities (MCLP parameter). + +## Decision Variables + +- $y_i \in \{0,1\}$, $i \in I$: 1 if facility $i$ is open, 0 otherwise. + +- $z_j \in \{0,1\}$, $j \in J$: 1 if customer $j$ is covered by at least one open facility, 0 otherwise. + +## 3.1 The Partial Set Covering Location Problem (PSCLP) + +### Objective + +$$\begin{align} +\min \quad & \sum_{i \in I} f_i\, y_i \tag{1} +\end{align}$$ + +### Constraints + +$$\begin{align} +\sum_{i \in I(j)} y_i &\ge z_j, & \forall j \in J, \tag{2}\\ +\sum_{j \in J} d_j\, z_j &\ge D, \tag{3}\\ +y_i &\in \{0,1\}, & \forall i \in I, \tag{4}\\ +z_j &\in \{0,1\}, & \forall j \in J. \tag{5} +\end{align}$$ + +The objective (1) minimizes the total cost of open facilities. Constraints (2) are linking constraints: customer $j$ can be counted as covered only if at least one facility in $I(j)$ is open. Constraint (3) forces the total covered demand to be at least $D$. Constraints (4)–(5) are binary restrictions. + +## 3.2 The Maximal Covering Location Problem (MCLP) + +### Objective + +$$\begin{align} +\max \quad & \sum_{j \in J} d_j\, z_j \tag{6} +\end{align}$$ + +### Constraints + +$$\begin{align} +\sum_{i \in I} f_i\, y_i &\le B, \tag{7}\\ +\sum_{i \in I(j)} y_i &\ge z_j, & \forall j \in J, \tag{2}\\ +y_i &\in \{0,1\}, & \forall i \in I, \tag{4}\\ +z_j &\in \{0,1\}, & \forall j \in J. \tag{5} +\end{align}$$ + +The objective (6) maximizes the total covered customer demand. The knapsack-like constraint (7) ensures that the available budget $B$ for opening the facilities is not exceeded. The remaining constraints (2),(4),(5) are the same as for the PSCLP. diff --git a/tasks/cordeau2019/problem_description.txt b/tasks/cordeau2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..a1bb83c090af940ed6b5c84950a7710b2b1a2e14 --- /dev/null +++ b/tasks/cordeau2019/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A service provider must decide which facilities to open from a set of potential facility locations in order to cover nearby customers. Each potential facility location has known two-dimensional coordinates and an associated opening cost that is at least zero. Each customer also has known two-dimensional coordinates and a demand that is at least zero. A customer is said to be covered by a facility if the Euclidean distance between them is at most a given coverage radius; consequently, each customer has a known subset of facilities that can cover it, and each facility has a known subset of customers it can cover. The provider must choose a subset of facilities to open and, as a result, determine which customers are covered, where a customer counts as covered if at least one of the facilities capable of covering it is opened. + +Two variants of this problem are considered, both using the same data. In the first variant, called the Partial Set Covering Location Problem, the provider is given a minimum total demand threshold that must be covered. The sum of the demands of all covered customers must be at least this threshold. The goal is to minimize the total opening cost of the selected facilities while ensuring that the covered demand meets or exceeds the threshold. In the second variant, called the Maximal Covering Location Problem, the provider is given a budget that limits the total opening cost of selected facilities. The sum of opening costs of all opened facilities must not exceed this budget. The goal is to maximize the total demand of all covered customers subject to this spending limit. + +In both variants, the coverage-linking rule is the same: a customer may only be counted as covered if at least one facility from its coverage neighborhood is open. The input data specifies the number of potential facility locations, the number of customers, the opening cost of each facility, the demand of each customer, the two-dimensional coordinates of every facility and every customer, the coverage radius, and, for the Partial Set Covering variant, the minimum demand threshold, or for the Maximal Covering variant, the available budget. The coverage relationships between facilities and customers are derived from the coordinates and the radius: a facility can cover a customer precisely when their Euclidean distance does not exceed the radius. diff --git a/tasks/cordeau2019/solution_logger.py b/tasks/cordeau2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/cordeau2019/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/cordeau2019/solution_schema.json b/tasks/cordeau2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..63992e70e86987e562470ba6e89637d564bfa9b6 --- /dev/null +++ b/tasks/cordeau2019/solution_schema.json @@ -0,0 +1,16 @@ +{ + "objective_value": " Objective value of the primary problem variant solved for this instance: total opening cost of selected facilities for the Partial Set Covering Location Problem, or total covered demand for the Maximal Covering Location Problem.", + "primary_problem_type": " Variant whose value is reported by objective_value; must be one of the instance problem_types.", + "results": { + "PSCLP": { + "objective_value": " Minimum total opening cost of the selected facilities such that the covered demand meets the required threshold.", + "open_facilities": " Indices of facilities selected to be opened in the Partial Set Covering Location Problem.", + "covered_demand": " Total demand of the customers counted as covered by the selected facilities." + }, + "MCLP": { + "objective_value": " Maximum total demand of customers counted as covered by the selected facilities while respecting the opening budget.", + "open_facilities": " Indices of facilities selected to be opened in the Maximal Covering Location Problem.", + "covered_demand": " Total demand of the customers counted as covered by the selected facilities." + } + } +} diff --git a/tasks/cote2018/feasibility_check.py b/tasks/cote2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7b8da3b243c7f1304ee891322b4da4919fb35afe --- /dev/null +++ b/tasks/cote2018/feasibility_check.py @@ -0,0 +1,445 @@ +""" +Feasibility checker for the Cutting Stock Problem (CSP) arc-flow formulation +from Côté & Iori (2018). + +Checks the candidate solution (objective value z = number of bins) against +the hard constraints of the arc-flow formulation (eqs 11-14): + + Constraint 1 (eq 12): Flow conservation — z must be non-negative and + sufficient for a valid flow to exist (z >= continuous lower bound). + Constraint 2 (eq 13): Demand satisfaction — total bin capacity z*W must + accommodate all items; each item must fit in a bin (w_i <= W). + Constraint 3 (eq 14): Non-negativity and integrality — z must be a + non-negative integer. + +The candidate contains the complete sparse arc-flow vector. Missing model +variables are interpreted as zero. The checker substitutes that vector into +trusted offline model coefficients; it does not invoke an optimizer. +""" + +import json +import argparse +import math +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from solverless_witness import require_linked_variables, validate_complete_witness + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('model_variables', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('model_variables',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_instance(path): + with open(path, 'r') as f: + return json.load(f) + + +def load_solution(path): + with open(path, 'r') as f: + return json.load(f) + + +def check_feasibility(instance, solution, instance_path=None): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violated_constraints = set() + violation_magnitudes = [] + + W = instance["bin_capacity"] + items = instance["items"] + + z = solution.get("objective_value") + + # --- Constraint 3 (eq 14): Non-negativity and integrality --- + # x_{pq} >= 0, integer; z >= 0, integer + # Check z is a valid non-negative integer. + + if z is None: + violated_constraints.add(3) + violations.append( + "Constraint 3: objective_value is None (no feasible solution reported)." + ) + # Cannot check further constraints without a valid z + result = { + "feasible": False, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + # Check z >= 0 + if z < -tol: + violation_amount = abs(z) + rhs = 0.0 + normalizer = max(abs(rhs), eps) + violated_constraints.add(3) + violations.append( + f"Constraint 3: z = {z} is negative (must be >= 0)." + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(z), + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Check z is integer + if abs(z - round(z)) > tol: + violation_amount = abs(z - round(z)) + rhs = round(z) + normalizer = max(abs(rhs), eps) + violated_constraints.add(3) + violations.append( + f"Constraint 3: z = {z} is not integer (nearest integer is {round(z)})." + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(z), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + z_int = z if isinstance(z, int) else (round(z) if abs(z - round(z)) <= tol else z) + + # --- Constraint 2 (eq 13): Demand satisfaction --- + # sum_{(q, q+w_i) in A} x_{q,q+w_i} >= d_i for each item type i. + # Necessary conditions: + # (a) Each item must fit in a bin: w_i <= W + # (b) Total capacity must suffice: z * W >= sum(w_i * d_i) + # Equivalently: z >= ceil(sum(w_i * d_i) / W) + + # Check (a): each item fits + for item in items: + w_i = item["width"] + d_i = item["demand"] + if w_i > W: + violation_amount = w_i - W + rhs = float(W) + normalizer = max(abs(rhs), eps) + violated_constraints.add(2) + violations.append( + f"Constraint 2: Item type {item['type_id']} has width {w_i} " + f"exceeding bin capacity {W}; demand {d_i} cannot be satisfied." + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(w_i), + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Check (b): z >= ceil(sum(w_i * d_i) / W) + total_width = sum(item["width"] * item["demand"] for item in items) + lb_continuous = total_width / W + lb = math.ceil(lb_continuous - tol) # ceil with tolerance + + if z_int < lb - tol: + # LHS is z (number of bins), RHS is lb (minimum needed) + # This is a >= constraint: z >= lb, so violation = lb - z + violation_amount = lb - z_int + rhs = float(lb) + normalizer = max(abs(rhs), eps) + violated_constraints.add(2) + violations.append( + f"Constraint 2: z = {z_int} bins insufficient; need at least {lb} " + f"bins to satisfy total demand (total item width = {total_width}, " + f"bin capacity = {W})." + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(z_int), + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Tighter lower bound: items with w_i > W/2 cannot share a bin + large_item_bins = sum( + item["demand"] for item in items if item["width"] > W / 2 + ) + if z_int < large_item_bins - tol: + violation_amount = large_item_bins - z_int + rhs = float(large_item_bins) + normalizer = max(abs(rhs), eps) + if 2 not in violated_constraints or True: + # Only add if this gives a tighter bound + violated_constraints.add(2) + violations.append( + f"Constraint 2: z = {z_int} bins insufficient; at least " + f"{large_item_bins} bins needed for items with width > W/2." + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(z_int), + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # --- Constraint 1 (eq 12): Flow conservation --- + # At vertex 0: outflow - inflow = z (z >= 0) + # At vertex W: outflow - inflow = -z + # At other vertices: outflow - inflow = 0 + # Necessary condition: z >= 0 (already checked under constraint 3) + # Additional necessary condition from flow structure: + # A valid integral flow of value z through the network from 0 to W must + # exist that respects demand constraints. The continuous relaxation lower + # bound is ceil(sum(w_i * d_i) / W), already checked above. + # We also check that z does not exceed the trivial upper bound + # (one item per bin). + + total_items = sum(item["demand"] for item in items) + if z_int > total_items + tol: + # z exceeds the number of items — more bins than items + # This means the flow is sending more units 0->W than there are items, + # which violates flow conservation (arcs would need negative values + # or extra loss-only bins beyond what's needed). + # LHS = z, RHS = total_items, constraint type: <= + violation_amount = z_int - total_items + rhs = float(total_items) + normalizer = max(abs(rhs), eps) + violated_constraints.add(1) + violations.append( + f"Constraint 1: z = {z_int} exceeds total number of items " + f"{total_items}; flow conservation cannot hold with more bins " + f"than items." + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(z_int), + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # Validate the complete arc-flow witness without running a solver. + if not violated_constraints: + if instance_path is None: + witness_objective, witness_errors = None, ["instance_path is required for solverless validation"] + else: + witness_objective, witness_errors, _ = validate_complete_witness( + instance_path, solution, Path(__file__).resolve().parent + ) + witness_errors.extend(require_linked_variables(solution, {"z": float(z_int)})) + if witness_errors: + violated_constraints.add(1) + violations.extend(f"Constraint 1: {message}" for message in witness_errors) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(z_int), + "rhs": float(z_int), + "raw_excess": 1.0, + "normalizer": max(abs(float(z_int)), eps), + "ratio": 1.0 / max(abs(float(z_int)), eps), + }) + elif witness_objective is None or abs(float(z_int) - witness_objective) > tol: + violated_constraints.add(1) + difference = abs(float(z_int) - float(witness_objective or 0.0)) + violations.append( + f"Constraint 1: objective_value={z_int} does not equal the " + f"complete witness objective={witness_objective}." + ) + violation_magnitudes.append({ + "constraint": 1, "lhs": float(z_int), "rhs": witness_objective, + "raw_excess": difference, "normalizer": max(abs(float(witness_objective or 0.0)), eps), + "ratio": difference / max(abs(float(witness_objective or 0.0)), eps), + }) + + # 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 CSP arc-flow (Côté & Iori 2018)" + ) + 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_instance(args.instance_path) + solution = load_solution(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + result = check_feasibility(instance, solution, args.instance_path) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/cote2018/gurobi_code.py b/tasks/cote2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..6356df938b5cca4632306eeac3d9f79e9ef05fac --- /dev/null +++ b/tasks/cote2018/gurobi_code.py @@ -0,0 +1,268 @@ +""" +Gurobi implementation of the Arc-Flow formulation for the Cutting Stock Problem (CSP) +from Côté & Iori (2018) "The Meet-in-the-Middle Principle for Cutting and Packing Problems" + +_GUROBI_CODE_START_TIME = time.time() +This implements the arc-flow model (equations 11-14) using normal patterns (eq. 15) +for the arc set construction, as described in Section 4. +""" + +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/). +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, 'r') as f: + data = json.load(f) + W = data["bin_capacity"] + items = [] + for it in data["items"]: + items.append((it["width"], it["demand"])) + return W, items + + +def compute_normal_patterns_csp(widths, demands, W): + """ + Compute B'_i for each item type i using eq. (15). + Items are sorted by nonincreasing width. + For item type i, B'_i = { x = sum_{j=1}^{i} w_j * xi_j : 0 <= x <= W - w_i, + xi_j in {0,1,...,d_bar_j^i} } + where d_bar_j^i = d_j for j < i, d_bar_i^i = d_i - 1. + + We use dynamic programming (Algorithm 1 adapted for CSP). + """ + m = len(widths) + # B_prime[i] = set of positions for item type i + B_prime = [set() for _ in range(m)] + + # We compute all B'_i sets using DP. + # For each item i, we need combinations of items 1..i with modified demands. + # We do this incrementally: maintain a DP array that tracks reachable sums + # using items 1..i with their full demands, then for item i we use d_i - 1. + + # Actually, let's compute B'_i for each i separately using bounded knapsack DP. + # For efficiency, we do it incrementally. + + for i in range(m): + w_i = widths[i] + if w_i > W: + continue + cap = W - w_i + + # DP: can we reach sum x using items j=0..i with demands d_bar_j^i? + # d_bar_j^i = demands[j] for j < i, demands[i] - 1 for j = i + # We use a boolean array reachable[0..cap] + reachable = [False] * (cap + 1) + reachable[0] = True + + for j in range(i + 1): + w_j = widths[j] + if w_j > cap: + continue + d_bar = demands[j] if j < i else demands[i] - 1 + if d_bar <= 0: + continue + + # Bounded knapsack: add up to d_bar copies of w_j + # Use binary decomposition for efficiency + remaining = d_bar + k = 1 + while remaining > 0: + take = min(k, remaining) + weight = take * w_j + # Traverse from cap down to weight + for x in range(cap, weight - 1, -1): + if reachable[x - weight]: + reachable[x] = True + remaining -= take + k *= 2 + + B_prime[i] = {x for x in range(cap + 1) if reachable[x]} + + return B_prime + + +def build_arc_flow_model(W, widths, demands, B_prime, time_limit): + """ + Build the arc-flow MILP (eqs. 11-14) using normal patterns. + """ + m = len(widths) + w_min = min(widths) + + # Collect all vertices that appear as arc endpoints + # Item arcs: (p, p + w_i) for each item type i and p in B'_i + item_arcs = {} # (p, q) -> list of item types + arc_to_items = {} # (p, q) -> set of item type indices + + for i in range(m): + w_i = widths[i] + for p in B_prime[i]: + q = p + w_i + if q > W: + continue + key = (p, q) + if key not in arc_to_items: + arc_to_items[key] = set() + arc_to_items[key].add(i) + + # Items with w_i > W/2: force start position to 0 only + for i in range(m): + if widths[i] > W / 2: + B_prime[i] = {0} if 0 in B_prime[i] else set() + + # Rebuild item arcs after forcing large items to position 0 + item_arcs_list = [] # list of (p, q, item_type) + item_arc_set = set() # set of (p, q) that are item arcs + + for i in range(m): + w_i = widths[i] + for p in B_prime[i]: + q = p + w_i + if q > W: + continue + item_arcs_list.append((p, q, i)) + item_arc_set.add((p, q)) + + # Compute B' = union of all B'_i, plus endpoints of item arcs + all_vertices = set() + all_vertices.add(0) + all_vertices.add(W) + for p, q, _ in item_arcs_list: + all_vertices.add(p) + all_vertices.add(q) + + # Loss arcs: unit-width, connecting consecutive vertices in B' union endpoints, + # but only in interval [w_min, ..., W]. + # Also, a loss arc is removed if an item arc connects the same two vertices. + sorted_vertices = sorted(all_vertices) + + loss_arcs = [] + for idx in range(len(sorted_vertices) - 1): + p = sorted_vertices[idx] + q = sorted_vertices[idx + 1] + # Only in interval [w_min, W] + if p < w_min: + continue + # Remove if item arc exists + if (p, q) in item_arc_set: + continue + loss_arcs.append((p, q)) + + # Build Gurobi model + model = gp.Model("CSP_ArcFlow") + model.setParam("TimeLimit", time_limit) + model.setParam("Threads", 1) + + # Variable z: number of bins + z = model.addVar(vtype=GRB.INTEGER, name="z", lb=0) + + # Arc variables + # For item arcs, we group by (p, q) to allow multiple item types + all_arcs = set() + for p, q, _ in item_arcs_list: + all_arcs.add((p, q)) + for p, q in loss_arcs: + all_arcs.add((p, q)) + + x = {} + for (p, q) in all_arcs: + x[p, q] = model.addVar(vtype=GRB.INTEGER, name=f"x_{p}_{q}", lb=0) + + model.update() + + # Objective: minimize z + model.setObjective(z, GRB.MINIMIZE) + + # Flow conservation constraints (eq. 12) + # For each vertex q: sum of outgoing - sum of incoming = z (q=0), -z (q=W), 0 otherwise + for q in sorted_vertices: + outgoing = gp.LinExpr() + incoming = gp.LinExpr() + for (p2, q2) in all_arcs: + if p2 == q: + outgoing += x[p2, q2] + if q2 == q: + incoming += x[p2, q2] + + if q == 0: + model.addConstr(outgoing - incoming == z, name=f"flow_{q}") + elif q == W: + model.addConstr(outgoing - incoming == -z, name=f"flow_{q}") + else: + model.addConstr(outgoing - incoming == 0, name=f"flow_{q}") + + # Demand constraints (eq. 13) + # For each item type i: sum of x_{q, q+w_i} over all valid q >= d_i + for i in range(m): + w_i = widths[i] + demand_expr = gp.LinExpr() + for p in B_prime[i]: + q = p + w_i + if (p, q) in x: + demand_expr += x[p, q] + model.addConstr(demand_expr >= demands[i], name=f"demand_{i}") + + return model, z, x + + +def solve_and_output(model, z, solution_path): + model.optimize() + + result = {} + if model.SolCount > 0: + result["objective_value"] = round(model.ObjVal) + else: + result["objective_value"] = None + result["status"] = "no_feasible_solution" + + result["solver_status"] = model.Status + result["mip_gap"] = model.MIPGap if model.SolCount > 0 else None + + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + +def main(): + parser = argparse.ArgumentParser(description="CSP Arc-Flow with Gurobi") + parser.add_argument("--instance_path", type=str, required=True) + parser.add_argument("--solution_path", type=str, default="gurobi_solution_1.json") + parser.add_argument("--time_limit", type=int, default=1200) + 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) + + W, items = load_instance(args.instance_path) + + # Sort items by nonincreasing width (as required by the arc-flow formulation) + items.sort(key=lambda x: -x[0]) + widths = [it[0] for it in items] + demands = [it[1] for it in items] + + # Phase 1: Compute normal patterns B'_i for each item type + B_prime = compute_normal_patterns_csp(widths, demands, W) + + # Phase 2 & 3: Build and solve arc-flow MILP + model, z, x = build_arc_flow_model(W, widths, demands, B_prime, args.time_limit) + + # Solve and output + solve_and_output(model, z, args.solution_path) + + +if __name__ == "__main__": + main() diff --git a/tasks/cote2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/cote2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2018/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/cote2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/cote2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2018/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/cote2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/cote2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2018/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/cote2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/cote2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2018/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/cote2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/cote2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2018/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/cote2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/cote2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2018/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/cote2018/gurobi_solution/large_solution_1.json b/tasks/cote2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ca09ad77d8d64e4e7716b34fa99b83dcb69a7d3e --- /dev/null +++ b/tasks/cote2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ded8b39b887be74cc6403a99af52058a37a140efae4d592f03524549108d7b5 +size 28614 diff --git a/tasks/cote2018/gurobi_solution/large_solution_2.json b/tasks/cote2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..39d2b5afff4972010a56dba972f8004ac680bb3d --- /dev/null +++ b/tasks/cote2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9230d4097be24fec453eb91ecc77ce96194f86de2c269c65762c0a104e9aed54 +size 202011 diff --git a/tasks/cote2018/gurobi_solution/large_solution_3.json b/tasks/cote2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b73b2e48e22efde4cc31b34f2d6b6637c201db7f --- /dev/null +++ b/tasks/cote2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a84d691932c6e084971d265f37c434eca2a654cef2df9c071fcbb2f0c0b53254 +size 35363 diff --git a/tasks/cote2018/gurobi_solution/large_solution_4.json b/tasks/cote2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..0c65250b5e1e8d125ade735a3d6a8faea0685cfd --- /dev/null +++ b/tasks/cote2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc4f54da0c3c201dd8d16c7bdc5e96da09c8c79ba904d5681d9b58496dc9f616 +size 13812 diff --git a/tasks/cote2018/gurobi_solution/large_solution_5.json b/tasks/cote2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..68b657daab6d036b78f4a0c733a7633f957cb788 --- /dev/null +++ b/tasks/cote2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c51ffc782e8907154b5d8fa275d1e6fa316822edfaeab01ef5d56b13ba0f3b4 +size 8322 diff --git a/tasks/cote2018/gurobi_solution/tiny_solution.json b/tasks/cote2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..7fd7aa328f665c3bc00ea28d8a872b696a015b9c --- /dev/null +++ b/tasks/cote2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:959fa38897616ea87818bc4a5b103d758b39d138085b8bddfc80e5e1e7f02427 +size 893 diff --git a/tasks/cote2018/gurobi_solution_log/large_log_1.jsonl b/tasks/cote2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..77ec159ccb791188db49bde03e8e6ac579d2cac1 --- /dev/null +++ b/tasks/cote2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0e9327064f688be31e490f70e131445cda6608f34d8bb8ce4fa0aec9f58d547 +size 45 diff --git a/tasks/cote2018/gurobi_solution_log/large_log_2.jsonl b/tasks/cote2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dc577cb3ea843fc4fe36775e2121a58101e1ffda --- /dev/null +++ b/tasks/cote2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:466b6a1e023ee5f283452ca28448b85619221803946db6c4bb612252f614583e +size 86 diff --git a/tasks/cote2018/gurobi_solution_log/large_log_3.jsonl b/tasks/cote2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0ab68bd82636626b3d76918f345b51a49fa1db30 --- /dev/null +++ b/tasks/cote2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7368a92d9d021c8a74e813e98c0a02514390ccf1298d2551e26d6cfb661aa558 +size 42 diff --git a/tasks/cote2018/gurobi_solution_log/large_log_4.jsonl b/tasks/cote2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7386a94eef4b45a117fec82f178195e47b555b25 --- /dev/null +++ b/tasks/cote2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5505bfa81c397cb17ce2914c5c409263239ad2e9484618ed4f10dc681c312038 +size 42 diff --git a/tasks/cote2018/gurobi_solution_log/large_log_5.jsonl b/tasks/cote2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e72c229537bab9b7761390f5618019695cf36c22 --- /dev/null +++ b/tasks/cote2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:499f4133d40bcb02ec848ece42d6ae30022e4eaa0de14c85e581c3a00d26a4ac +size 129 diff --git a/tasks/cote2018/gurobi_solution_log/tiny_log.jsonl b/tasks/cote2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b9f4b0dd1a57a8c6297977cec9fe321871ea0a7 --- /dev/null +++ b/tasks/cote2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79309230fceb88913d0ef7e2fd6c527f87135361919b098fe5899313527df374 +size 41 diff --git a/tasks/cote2018/instance/large_instance_1.json b/tasks/cote2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..b58eb7fc7083886cad0b00482402583cf8719849 --- /dev/null +++ b/tasks/cote2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71dc5cb78f3a931c7a11cb9581c6256883d0e9ab99dc46d2ef87b57771823da1 +size 2732 diff --git a/tasks/cote2018/instance/large_instance_2.json b/tasks/cote2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..98c0e3dfafddb78a94223adc844bab527dea62f9 --- /dev/null +++ b/tasks/cote2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:288eda85666e6b6613f4ba67e2678c64e1a6c98fc9cf0e82d7f0aac7c2ff6167 +size 4009 diff --git a/tasks/cote2018/instance/large_instance_3.json b/tasks/cote2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..155cac34b19693aa22f64c4764401599a1d72418 --- /dev/null +++ b/tasks/cote2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:183897d39edee6713262ce9ea3a70ead89bf948ea2db801b5d68d9558b0c1ae4 +size 4009 diff --git a/tasks/cote2018/instance/large_instance_4.json b/tasks/cote2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..6e97399fbaa23dff21d69e620bfc086c9c0f5b56 --- /dev/null +++ b/tasks/cote2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f282400bbe6d469050be731e0dcbb7dec89d3339630001d88bb98e541a8b22ee +size 4009 diff --git a/tasks/cote2018/instance/large_instance_5.json b/tasks/cote2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8d3eb118dadf608aa1a5024a07cb6f1c021f5c8a --- /dev/null +++ b/tasks/cote2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:937fd967344c9b1d2e6e2c7db9ba86ed3e50a7ffb02a1c7114a1d7d8a40408f9 +size 2939 diff --git a/tasks/cote2018/instance/tiny_instance.json b/tasks/cote2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..826fc933a08f0782ee4184125883a6e9f7606628 --- /dev/null +++ b/tasks/cote2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7813c9cf1c3851a8f5584beebaccd068512c48aa5774b3570c880e93f1511479 +size 800 diff --git a/tasks/cote2018/instance_schema.json b/tasks/cote2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..520c7a16229572f0ae963d2e94f11a4214447548 --- /dev/null +++ b/tasks/cote2018/instance_schema.json @@ -0,0 +1,12 @@ +{ + "bin_capacity": " Maximum total width that can be packed into a single bin.", + "num_item_types": " Number of distinct item types to be cut.", + "total_num_items": " Total number of individual items to be produced across all types.", + "items": [ + { + "type_id": " Unique identifier for this item type.", + "width": " Width of each copy of this item type.", + "demand": " Number of copies of this item type that must be produced." + } + ] +} diff --git a/tasks/cote2018/mathematical_formulation.md b/tasks/cote2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d39d6dd2a0931793e606f3c79fece618f1afe572 --- /dev/null +++ b/tasks/cote2018/mathematical_formulation.md @@ -0,0 +1,45 @@ +# Original Formulation: One-Dimensional Cutting Stock Problem (CSP) + +*Source: The Meet-in-the-Middle Principle for Cutting and Packing Problems, Jean-François Côté and Manuel Iori, 2018.* + +## Sets and Parameters + +- $m$: number of item types; item type $i$ has integer width $w_i$ and integer demand $d_i$. + +- $n = \sum_{i=1}^{m} d_i$: total number of item copies. + +- $W$: integer capacity (width) of each identical bin. + +- $G = (V,A)$: digraph with vertex set $V = \{0,1,\ldots,W\}$ (a vertex $q$ is a partial bin filling). + +- $A$: set of arcs $(p,q)$, each representing either (i) the packing of an item of width $q-p$ starting at the partial filling $p$ (*item arc*), or (ii) an empty portion of the bin between fillings $p$ and $q$ (*loss arc*). + +- $\delta^-(q)$: set of arcs entering vertex $q$; $\delta^+(q)$: set of arcs leaving vertex $q$. + +## Decision Variables + +- $x_{pq} \in \mathbb{Z}_{\ge 0}$: number of times arc $(p,q)\in A$ is selected. + +- $z$: number of bins used, i.e. the amount of flow sent from vertex $0$ to vertex $W$ (each bin packing corresponds to a path from $0$ to $W$). + +## Objective + +$$\begin{align} + \min \quad & z \tag{11} +\end{align}$$ + +## Constraints + +$$\begin{align} + \text{s.t.} \quad + & \sum_{(q,r)\in\delta^+(q)} x_{qr} \;-\; \sum_{(p,q)\in\delta^-(q)} x_{pq} + = \begin{cases} + z & \text{if } q = 0, \\ + -z & \text{if } q = W, \\ + 0 & \text{if } q = 1,2,\ldots,W-1, + \end{cases} \tag{12} \\[4pt] + & \sum_{(q,\,q+w_i)\in A} x_{q,\,q+w_i} \;\ge\; d_i, \quad i = 1,2,\ldots,m, \tag{13} \\[4pt] + & x_{pq} \ge 0, \text{ integer}, \quad (p,q)\in A. \tag{14} +\end{align}$$ + +Constraints (12) impose flow conservation; constraints (13) state that all item demands must be fulfilled. Each possible packing of a bin is a path from $0$ to $W$, and the aim is to minimize the number $z$ of selected paths. The “$\ge$” in (13) (rather than “$=$”) allows over-production, which is admissible for the CSP. diff --git a/tasks/cote2018/problem_description.txt b/tasks/cote2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..0bf59e8a9c1a1f25ed48085c6d8c010f342e851b --- /dev/null +++ b/tasks/cote2018/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A company must produce a required quantity of one-dimensional pieces (items) by cutting them out of identical stock units (bins). Every stock unit has the same fixed integer capacity, representing the total length available in one unit. The order specifies several distinct item types; each type has a known integer width and a required number of copies (its demand) that must be produced. The company can use as many stock units as needed, but each individual stock unit can only hold a collection of items whose widths sum to no more than its capacity. The objective is to fulfill the demand for every item type while using as few stock units as possible. + +In operational terms, the company decides how to assign individual item copies to stock units so that (a) the total width of items placed in any single stock unit does not exceed the bin capacity, and (b) the number of copies of each item type placed across all used stock units is at least the demand for that type. The quantity to minimize is the total number of stock units that contain at least one item. + +Equivalently, this is the classical one-dimensional cutting-stock problem: given identical bins of integer capacity W and a list of item types with integer widths and integer demands, determine the minimum number of bins needed to pack all required item copies without exceeding any bin's capacity. diff --git a/tasks/cote2018/solution_logger.py b/tasks/cote2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/cote2018/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/cote2018/solution_schema.json b/tasks/cote2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e3b2d01bd08154d43d2faab72069d0fd4046d483 --- /dev/null +++ b/tasks/cote2018/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Number of stock units used by the submitted complete arc-flow witness.", + "model_variables": " Sparse complete arc-flow solution. Every omitted model variable is exactly zero; every listed value must be numeric." +} diff --git a/tasks/cote2018/solverless_models/183897d39edee6713262ce9ea3a70ead89bf948ea2db801b5d68d9558b0c1ae4.npz b/tasks/cote2018/solverless_models/183897d39edee6713262ce9ea3a70ead89bf948ea2db801b5d68d9558b0c1ae4.npz new file mode 100644 index 0000000000000000000000000000000000000000..387c3b89d0ac86e2a9aafab4f5ca6217c8c84b35 --- /dev/null +++ b/tasks/cote2018/solverless_models/183897d39edee6713262ce9ea3a70ead89bf948ea2db801b5d68d9558b0c1ae4.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67c4a297cc306c05475ca4320f0766f0107b387787dc406399f5ec37ea3bb672 +size 85489