diff --git a/tasks/cote2018/solverless_models/288eda85666e6b6613f4ba67e2678c64e1a6c98fc9cf0e82d7f0aac7c2ff6167.npz b/tasks/cote2018/solverless_models/288eda85666e6b6613f4ba67e2678c64e1a6c98fc9cf0e82d7f0aac7c2ff6167.npz new file mode 100644 index 0000000000000000000000000000000000000000..c43d65ecaa058ef93185ccea46ae8902fb8a1780 --- /dev/null +++ b/tasks/cote2018/solverless_models/288eda85666e6b6613f4ba67e2678c64e1a6c98fc9cf0e82d7f0aac7c2ff6167.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3483c782bd78786b182438bbdbfaa086aca2da4ad5786db7dbcec8e7cb2da6ad +size 371215 diff --git a/tasks/cote2018/solverless_models/71dc5cb78f3a931c7a11cb9581c6256883d0e9ab99dc46d2ef87b57771823da1.npz b/tasks/cote2018/solverless_models/71dc5cb78f3a931c7a11cb9581c6256883d0e9ab99dc46d2ef87b57771823da1.npz new file mode 100644 index 0000000000000000000000000000000000000000..cb095e80f0a041ef0d67241c1d86a087ebdba594 --- /dev/null +++ b/tasks/cote2018/solverless_models/71dc5cb78f3a931c7a11cb9581c6256883d0e9ab99dc46d2ef87b57771823da1.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:642ce28c399129051fcf522c36f60f789971b58f1257ee76e61c3a152d8821ad +size 1054069 diff --git a/tasks/cote2018/solverless_models/7813c9cf1c3851a8f5584beebaccd068512c48aa5774b3570c880e93f1511479.npz b/tasks/cote2018/solverless_models/7813c9cf1c3851a8f5584beebaccd068512c48aa5774b3570c880e93f1511479.npz new file mode 100644 index 0000000000000000000000000000000000000000..749f19a3a1dfb4790fdf9b82ad6549e1257cdfda --- /dev/null +++ b/tasks/cote2018/solverless_models/7813c9cf1c3851a8f5584beebaccd068512c48aa5774b3570c880e93f1511479.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c14f9b34e0c7cbc8fe73860eec50c3f20aef61f3d6c1136246fa327f9b75e92c +size 7754 diff --git a/tasks/cote2018/solverless_models/937fd967344c9b1d2e6e2c7db9ba86ed3e50a7ffb02a1c7114a1d7d8a40408f9.npz b/tasks/cote2018/solverless_models/937fd967344c9b1d2e6e2c7db9ba86ed3e50a7ffb02a1c7114a1d7d8a40408f9.npz new file mode 100644 index 0000000000000000000000000000000000000000..3e26cefe41795c1c6e34fdc4784cf15ef09cf8dc --- /dev/null +++ b/tasks/cote2018/solverless_models/937fd967344c9b1d2e6e2c7db9ba86ed3e50a7ffb02a1c7114a1d7d8a40408f9.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f94674d391847d6c139dda748288e9cd8f317bd2f1b025fafa6a419eb92bbb1 +size 342158 diff --git a/tasks/cote2018/solverless_models/f282400bbe6d469050be731e0dcbb7dec89d3339630001d88bb98e541a8b22ee.npz b/tasks/cote2018/solverless_models/f282400bbe6d469050be731e0dcbb7dec89d3339630001d88bb98e541a8b22ee.npz new file mode 100644 index 0000000000000000000000000000000000000000..dd49066bbda6480f88ffa1a079fa5a357a3adbec --- /dev/null +++ b/tasks/cote2018/solverless_models/f282400bbe6d469050be731e0dcbb7dec89d3339630001d88bb98e541a8b22ee.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c0fec752c51b6f28ab8a15f5d6fb741771a68e3a19c0006d8384e1e6b8bb640 +size 20938 diff --git a/tasks/cote2018/solverless_witness.py b/tasks/cote2018/solverless_witness.py new file mode 100644 index 0000000000000000000000000000000000000000..6e8d1c0a2a83a5aa314a7405d6b50f6d5dacaf8c --- /dev/null +++ b/tasks/cote2018/solverless_witness.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Solver-free validation of complete sparse optimization witnesses.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import Any + +import numpy as np + +WITNESS_FIELD = "model_variables" + + +def _digest(path: str | Path) -> str: + value = hashlib.sha256() + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + value.update(block) + return value.hexdigest() + + +def _strings(values: np.ndarray) -> list[str]: + return [str(value) for value in values.tolist()] + + +def validate_complete_witness( + instance_path: str | Path, + solution: dict[str, Any], + case_directory: str | Path, + *, + absolute_tolerance: float = 1e-5, + relative_tolerance: float = 1e-7, +) -> tuple[float | None, list[str], dict[str, float]]: + """Return recomputed objective, validation errors, and diagnostics.""" + errors: list[str] = [] + diagnostics: dict[str, float] = {} + witness = solution.get(WITNESS_FIELD) + if not isinstance(witness, dict): + return None, [f"{WITNESS_FIELD} must be an object"], diagnostics + + digest = _digest(instance_path) + snapshot = Path(case_directory) / "solverless_models" / f"{digest}.npz" + if not snapshot.is_file(): + return None, [f"no trusted solverless model for instance sha256={digest}"], diagnostics + + with np.load(snapshot, allow_pickle=False) as model: + if str(model["instance_sha256"].item()) != digest: + return None, ["trusted model instance digest mismatch"], diagnostics + names = _strings(model["var_names"]) + name_to_index = {name: index for index, name in enumerate(names)} + values = np.zeros(len(names), dtype=np.float64) + unknown: list[str] = [] + for name, raw in witness.items(): + index = name_to_index.get(str(name)) + if index is None: + if len(unknown) < 5: + unknown.append(str(name)) + continue + if isinstance(raw, bool) or not isinstance(raw, (int, float)): + errors.append(f"model variable {name!r} must be a finite number") + continue + value = float(raw) + if not np.isfinite(value): + errors.append(f"model variable {name!r} must be finite") + continue + values[index] = value + if unknown: + errors.append("unknown model variable(s): " + ", ".join(unknown)) + + lower = model["lower_bounds"] + upper = model["upper_bounds"] + scale = np.maximum(1.0, np.maximum(np.abs(lower), np.abs(upper))) + scale[~np.isfinite(scale)] = 1.0 + bound_tol = absolute_tolerance + relative_tolerance * scale + low_bad = np.flatnonzero(values < lower - bound_tol) + high_bad = np.flatnonzero(values > upper + bound_tol) + if low_bad.size: + diagnostics["max_lower_bound_violation"] = float(np.max(lower[low_bad] - values[low_bad])) + for index in low_bad[:5]: + errors.append(f"lower bound violated: {names[index]}={values[index]:.12g} < {lower[index]:.12g}") + if high_bad.size: + diagnostics["max_upper_bound_violation"] = float(np.max(values[high_bad] - upper[high_bad])) + for index in high_bad[:5]: + errors.append(f"upper bound violated: {names[index]}={values[index]:.12g} > {upper[index]:.12g}") + + integer_mask = model["integer_mask"].astype(bool) + integer_indices = np.flatnonzero(integer_mask) + fractionality = np.abs(values[integer_mask] - np.rint(values[integer_mask])) + bad_local = np.flatnonzero(fractionality > absolute_tolerance) + if bad_local.size: + diagnostics["max_integrality_violation"] = float(np.max(fractionality[bad_local])) + for local_index in bad_local[:5]: + index = integer_indices[local_index] + errors.append(f"integrality violated: {names[index]}={values[index]:.12g}") + + row_count = int(model["constraint_count"].item()) + rows = model["row_indices"] + columns = model["column_indices"] + coefficients = model["coefficients"] + activity = np.bincount(rows, weights=coefficients * values[columns], minlength=row_count) + absolute_activity = np.bincount(rows, weights=np.abs(coefficients * values[columns]), minlength=row_count) + rhs = model["rhs"] + senses = model["senses"] + row_tol = absolute_tolerance + relative_tolerance * np.maximum.reduce( + [np.ones(row_count), np.abs(rhs), absolute_activity] + ) + violation = np.zeros(row_count, dtype=np.float64) + violation[senses == -1] = np.maximum(0.0, activity[senses == -1] - rhs[senses == -1]) + violation[senses == 0] = np.abs(activity[senses == 0] - rhs[senses == 0]) + violation[senses == 1] = np.maximum(0.0, rhs[senses == 1] - activity[senses == 1]) + bad_rows = np.flatnonzero(violation > row_tol) + if bad_rows.size: + diagnostics["max_constraint_violation"] = float(np.max(violation[bad_rows])) + constraint_names = _strings(model["constraint_names"]) + sense_text = {-1: "<=", 0: "==", 1: ">="} + for row in bad_rows[:10]: + errors.append( + f"constraint violated: {constraint_names[row]}: {activity[row]:.12g} " + f"{sense_text[int(senses[row])]} {rhs[row]:.12g} (excess {violation[row]:.6g})" + ) + + objective = float(model["objective_constant"].item()) + objective += float(np.dot(model["linear_objective"], values)) + q_coefficients = model["quadratic_coefficients"] + if q_coefficients.size: + objective += float(np.sum( + q_coefficients * values[model["quadratic_rows"]] * values[model["quadratic_columns"]] + )) + diagnostics["recomputed_objective"] = objective + return objective, errors, diagnostics + + +def require_linked_variables( + solution: dict[str, Any], expected: dict[str, float], *, tolerance: float = 1e-6 +) -> list[str]: + """Ensure public fields and the complete vector describe one plan.""" + witness = solution.get(WITNESS_FIELD) + if not isinstance(witness, dict): + return [f"{WITNESS_FIELD} must be an object"] + errors: list[str] = [] + for name, expected_value in expected.items(): + raw = witness.get(name, 0.0) + try: + actual = float(raw) + except (TypeError, ValueError): + errors.append(f"linked model variable {name!r} is not numeric") + continue + if not np.isfinite(actual) or abs(actual - float(expected_value)) > tolerance: + errors.append( + f"public decision and model witness disagree for {name}: {expected_value} versus {actual}" + ) + if len(errors) >= 10: + break + return errors diff --git a/tasks/cote2019/feasibility_check.py b/tasks/cote2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..82b78da62aeb66f7c27efdb703fc3d0a91e9c543 --- /dev/null +++ b/tasks/cote2019/feasibility_check.py @@ -0,0 +1,853 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for S2L-CVRP (Stochastic 2D Loading CVRP). + +Checks hard constraints from the mathematical formulation: + Constraint 1 (Eq 2): depot degree = 2K + Constraint 2 (Eq 3): each customer has degree 2 + Constraint 3 (Eq 4): Rounded Capacity Inequalities (RCI) + Constraint 4 (Eq 5): Infeasible path inequalities + Constraint 5 (Eq 6): Binary integrality of edge variables + Constraint 6 (objective): reported objective must equal the routing cost + plus the scenario-weighted recourse cost recomputed from the routes. +""" + +import argparse +import json +import math +import itertools +from collections import defaultdict + +# 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 + + + +# --------------------------------------------------------------------------- +# Tolerance parameters +# --------------------------------------------------------------------------- +TOL = 1e-5 +EPS = 1e-5 + + +# --------------------------------------------------------------------------- +# Data helpers +# --------------------------------------------------------------------------- + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def compute_expected_area_weight(customers): + """ + Compute expected area a_tilde_j and expected weight q_tilde_j for each customer. + a_tilde_j = sum_{i in I_j} sum_r p_i^r * h_i^r * w_i^r + q_tilde_j = sum_{i in I_j} sum_r p_i^r * q_i^r + """ + result = {} + for cust in customers: + cid = cust["id"] + a_tilde = 0.0 + q_tilde = 0.0 + for item in cust["items"]: + for r in item["realizations"]: + p = r["probability"] + a_tilde += p * r["height"] * r["width"] + q_tilde += p * r["weight"] + result[cid] = (a_tilde, q_tilde) + return result + + +# --------------------------------------------------------------------------- +# Reconstruct edge variables from routes +# --------------------------------------------------------------------------- + +def reconstruct_edges(routes): + """ + Given routes (lists of customer IDs), reconstruct x_{jk} edge variables. + Each route is 0 -> c1 -> c2 -> ... -> cm -> 0. + Returns dict {(j,k): 1} with j < k. + """ + edges = {} + for route in routes: + full_path = [0] + list(route) + [0] + for i in range(len(full_path) - 1): + u, v = full_path[i], full_path[i + 1] + key = (min(u, v), max(u, v)) + edges[key] = edges.get(key, 0) + 1 + return edges + + +# --------------------------------------------------------------------------- +# Bottom-left heuristic for 2D packing with unloading constraints +# --------------------------------------------------------------------------- + +def bottom_left_heuristic_with_unloading(items_with_delivery_order, H, W): + """ + Bottom-left heuristic for 2OPP with unloading constraints. + + items_with_delivery_order: list of (item_h, item_w, delivery_position) + H: vehicle height, W: vehicle width. + + Items are packed in reverse delivery order (last delivered first, deepest). + Unloading from y=H end; later-delivered items must not block earlier ones. + + Returns True if all items packed feasibly. + """ + sorted_items = sorted(items_with_delivery_order, key=lambda t: -t[2]) + + placements = [] # (x, y, w, h, delivery_pos) + + for (ih, iw, dpos) in sorted_items: + if ih > H or iw > W: + return False + + placed = False + y_candidates = sorted(set([0] + [p[1] + p[3] for p in placements])) + x_candidates = sorted(set([0] + [p[0] + p[2] for p in placements])) + + best_pos = None + for y in y_candidates: + if y + ih > H: + continue + for x in x_candidates: + if x + iw > W: + continue + # Check no overlap + overlap = False + for (px, py, pw, ph, pd) in placements: + if x < px + pw and x + iw > px and y < py + ph and y + ih > py: + overlap = True + break + if overlap: + continue + + # Check unloading: items with delivery_pos > dpos are still on + # truck when dpos is delivered; they must not block from y=H exit. + unloading_ok = True + for (px, py, pw, ph, pd) in placements: + if pd > dpos: + if (px < x + iw and px + pw > x and + py + ph > y + ih and py < H): + unloading_ok = False + break + if not unloading_ok: + continue + + if best_pos is None or (y, x) < (best_pos[1], best_pos[0]): + best_pos = (x, y) + + if best_pos is not None and best_pos[1] == y: + break + + if best_pos is None: + return False + + placements.append((best_pos[0], best_pos[1], iw, ih, dpos)) + + return True + + +def check_packing_feasibility_heuristic(items_by_customer_ordered, H, W): + """ + Check packing feasibility with unloading using bottom-left heuristic. + items_by_customer_ordered: list of (customer_id, [(h, w)]) in delivery order. + Returns True if heuristic finds a feasible packing. + """ + if not items_by_customer_ordered: + return True + + total_area = sum(h * w for _, items in items_by_customer_ordered for h, w in items) + if total_area > H * W: + return False + + for _, items in items_by_customer_ordered: + for h, w in items: + if h > H or w > W: + return False + + # Build items with delivery positions + pack_items = [] + for pos_idx, (cid, cust_items) in enumerate(items_by_customer_ordered): + delivery_pos = pos_idx + 1 + for h, w in cust_items: + pack_items.append((h, w, delivery_pos)) + + return bottom_left_heuristic_with_unloading(pack_items, H, W) + + +def _solve_2opp_exact(pack_items, H, W): + """Existentially solve the omitted 2OPPUL placement variables. + + ``pack_items`` contains (height, width, delivery_position). This is the + same disjunctive placement model used by gurobi_code.py, expressed with + SciPy/HiGHS so that objective validation does not need a Gurobi licence. + """ + if not pack_items: + return True + try: + import numpy as np + from scipy.optimize import Bounds, LinearConstraint, milp + from scipy.sparse import coo_matrix + except ImportError as error: + raise RuntimeError(f"SciPy MILP unavailable: {error}") from error + + lower = [] + upper = [] + integrality = [] + + def variable(lb, ub, integer=False): + index = len(lower) + lower.append(float(lb)) + upper.append(float(ub)) + integrality.append(1 if integer else 0) + return index + + x_index = [variable(0.0, W - item[1]) for item in pack_items] + y_index = [variable(0.0, H - item[0]) for item in pack_items] + rows = [] + row_lower = [] + row_upper = [] + + def constraint(coefficients, lb=-float("inf"), ub=float("inf")): + rows.append(dict(coefficients)) + row_lower.append(float(lb)) + row_upper.append(float(ub)) + + for i in range(len(pack_items)): + hi, wi, delivery_i = pack_items[i] + for j in range(i + 1, len(pack_items)): + hj, wj, delivery_j = pack_items[j] + separated = [variable(0.0, 1.0, True) for _ in range(4)] + constraint( + {x_index[i]: 1.0, x_index[j]: -1.0, separated[0]: W}, + ub=W - wi, + ) + constraint( + {x_index[j]: 1.0, x_index[i]: -1.0, separated[1]: W}, + ub=W - wj, + ) + constraint( + {y_index[i]: 1.0, y_index[j]: -1.0, separated[2]: H}, + ub=H - hi, + ) + constraint( + {y_index[j]: 1.0, y_index[i]: -1.0, separated[3]: H}, + ub=H - hj, + ) + constraint({index: 1.0 for index in separated}, lb=1.0) + + # Unloading is through y=H. A later-delivered item may not sit + # between an earlier-delivered item and that exit. + if delivery_i < delivery_j: + upper[separated[2]] = 0.0 + elif delivery_j < delivery_i: + upper[separated[3]] = 0.0 + + row_indices = [] + column_indices = [] + values = [] + for row_index, coefficients in enumerate(rows): + for column_index, value in coefficients.items(): + row_indices.append(row_index) + column_indices.append(column_index) + values.append(value) + matrix = coo_matrix( + (values, (row_indices, column_indices)), + shape=(len(rows), len(lower)), + dtype=float, + ).tocsr() + result = milp( + c=np.zeros(len(lower), dtype=float), + integrality=np.asarray(integrality, dtype=int), + bounds=Bounds(np.asarray(lower), np.asarray(upper)), + constraints=LinearConstraint( + matrix, np.asarray(row_lower), np.asarray(row_upper) + ), + options={"presolve": True, "time_limit": 10.0}, + ) + return bool(result.success) + + +def _scenario_is_packable(scenario_items, H, W, Q): + """Check weight and exact 2OPPUL feasibility for one realization.""" + total_weight = sum( + weight for _, items in scenario_items for _, _, weight in items + ) + if total_weight > Q + TOL: + return False + + pack_items = [] + for delivery_position, (_, items) in enumerate(scenario_items, start=1): + for height, width, _ in items: + if height > H + TOL or width > W + TOL: + return False + pack_items.append((height, width, delivery_position)) + if sum(height * width for height, width, _ in pack_items) > H * W + TOL: + return False + if bottom_left_heuristic_with_unloading(pack_items, H, W): + return True + return _solve_2opp_exact(pack_items, H, W) + + +def _count_unserved(delivery_order, scenario_items, H, W, Q): + """Reproduce gurobi_code.py's largest-area greedy recourse rule.""" + by_customer = {customer: items for customer, items in scenario_items} + served = list(delivery_order) + for drop_count in range(1, len(delivery_order)): + to_drop = max( + served, + key=lambda customer: sum( + height * width for height, width, _ in by_customer[customer] + ), + ) + served.remove(to_drop) + remaining = [(customer, by_customer[customer]) for customer in served] + if _scenario_is_packable(remaining, H, W, Q): + return drop_count + return len(delivery_order) + + +def _route_recourse_for_ordering(delivery_order, customers_by_id, H, W, Q, cf): + deterministic = all( + len(item["realizations"]) == 1 + for customer in delivery_order + for item in customers_by_id[customer]["items"] + ) + scenarios = enumerate_scenarios_for_route(delivery_order, customers_by_id) + if deterministic: + return ( + 0.0 + if _scenario_is_packable(scenarios[0][1], H, W, Q) + else float(cf) * len(delivery_order) + ) + + recourse = 0.0 + for probability, scenario_items in scenarios: + if probability < 1e-15: + continue + if not _scenario_is_packable(scenario_items, H, W, Q): + recourse += ( + probability + * float(cf) + * _count_unserved( + delivery_order, scenario_items, H, W, Q + ) + ) + return recourse + + +def compute_route_recourse(route, customers_by_id, H, W, Q, cf): + """Recompute the model's recourse for both undirected route orders.""" + if not route: + return 0.0 + return min( + _route_recourse_for_ordering( + ordering, customers_by_id, H, W, Q, cf + ) + for ordering in (list(route), list(reversed(route))) + ) + + +# --------------------------------------------------------------------------- +# Scenario enumeration +# --------------------------------------------------------------------------- + +def enumerate_scenarios_for_route(route_customer_ids, customers_by_id): + """ + Enumerate all scenarios for customers on a route via Cartesian product + of item realizations. + Returns list of (probability, [(cust_id, [(h, w, weight)])]). + """ + item_realizations = [] + for cid in route_customer_ids: + cust = customers_by_id[cid] + for item in cust["items"]: + reals = [] + for r in item["realizations"]: + reals.append((r["height"], r["width"], r["weight"], + r["probability"], cid)) + item_realizations.append(reals) + + if not item_realizations: + return [(1.0, [])] + + scenarios = [] + for combo in itertools.product(*item_realizations): + prob = 1.0 + cust_items = defaultdict(list) + for h, w, weight, p, cid in combo: + prob *= p + cust_items[cid].append((h, w, weight)) + scenario_data = [(cid, cust_items[cid]) for cid in route_customer_ids + if cid in cust_items] + scenarios.append((prob, scenario_data)) + + return scenarios + + +def is_route_always_infeasible(route, customers_by_id, H, W, Q): + """ + Check if a route is in R^{inf}: infeasible under ALL scenarios and + both delivery orderings. + """ + # Cap scenario count to avoid exponential blowup + n_scenarios = 1 + for cid in route: + cust = customers_by_id[cid] + for item in cust["items"]: + n_scenarios *= len(item["realizations"]) + if n_scenarios > 50000: + return False # conservative: assume not always infeasible + + scenarios = enumerate_scenarios_for_route(route, customers_by_id) + + for prob, scenario_items in scenarios: + # Check weight + total_weight = sum(w for _, items in scenario_items for _, _, w in items) + if total_weight > Q: + continue # infeasible under this scenario due to weight + + # Check packing feasibility in both orderings + for ordering in [scenario_items, list(reversed(scenario_items))]: + items_ordered = [(cid, [(h, w) for h, w, _ in items]) + for cid, items in ordering] + if check_packing_feasibility_heuristic(items_ordered, H, W): + return False # at least one scenario is feasible + + return True # all scenarios infeasible + + +# --------------------------------------------------------------------------- +# Violation recording helpers +# --------------------------------------------------------------------------- + +def make_violation_entry(constraint_idx, lhs, rhs, violation_amount): + normalizer = max(abs(rhs), EPS) + return { + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + } + + +# --------------------------------------------------------------------------- +# Main feasibility check +# --------------------------------------------------------------------------- + +def check_feasibility(instance, solution): + customers = instance["customers"] + vehicle = instance["vehicle"] + H = vehicle["H"] + W = vehicle["W"] + Q = vehicle["Q"] + K = vehicle["K"] + n_customers = len(customers) + + customers_by_id = {c["id"]: c for c in customers} + customer_ids = set(c["id"] for c in customers) + expected = compute_expected_area_weight(customers) + + routes = solution["routes"] + + violations = [] + violation_magnitudes = [] + violated_constraint_set = set() + + # Reconstruct edges from routes + edges = reconstruct_edges(routes) + + # ----------------------------------------------------------------------- + # Constraint 1 (Eq 2): sum_{j in C} x_{0j} = 2K + # ----------------------------------------------------------------------- + depot_degree = 0 + for (j, k), val in edges.items(): + if j == 0 or k == 0: + depot_degree += val + rhs_c1 = 2 * K + violation_amount_c1 = abs(depot_degree - rhs_c1) + if violation_amount_c1 > TOL: + violated_constraint_set.add(1) + violations.append( + f"Constraint 1 (depot degree): depot degree = {depot_degree}, " + f"expected 2K = {rhs_c1}" + ) + violation_magnitudes.append( + make_violation_entry(1, depot_degree, rhs_c1, violation_amount_c1) + ) + + # ----------------------------------------------------------------------- + # Constraint 2 (Eq 3): degree = 2 for each customer j in C + # ----------------------------------------------------------------------- + # Count degree per customer from the edge set + degree = defaultdict(int) + for (j, k), val in edges.items(): + if j > 0: + degree[j] += val + if k > 0: + degree[k] += val + + # Check each customer + for cid in sorted(customer_ids): + deg = degree.get(cid, 0) + rhs_c2 = 2 + viol = abs(deg - rhs_c2) + if viol > TOL: + violated_constraint_set.add(2) + violations.append( + f"Constraint 2 (degree): customer {cid} has degree {deg}, " + f"expected 2" + ) + violation_magnitudes.append( + make_violation_entry(2, deg, rhs_c2, viol) + ) + + # Also check customers not appearing in any route + visited_customers = set() + for route in routes: + for c in route: + visited_customers.add(c) + missing = customer_ids - visited_customers + for cid in sorted(missing): + violated_constraint_set.add(2) + violations.append( + f"Constraint 2 (degree): customer {cid} not visited (degree 0), " + f"expected 2" + ) + violation_magnitudes.append( + make_violation_entry(2, 0, 2, 2.0) + ) + + # ----------------------------------------------------------------------- + # Constraint 3 (Eq 4): RCI for each route's customer set S + # sum_{j,k in S, j TOL: + violated_constraint_set.add(3) + reason_parts = [] + if area_vehicles > 1: + reason_parts.append( + f"expected area {sum_area:.1f} exceeds vehicle area {HW}" + ) + if weight_vehicles > 1: + reason_parts.append( + f"expected weight {sum_weight:.1f} exceeds vehicle capacity {Q}" + ) + reason = "; ".join(reason_parts) if reason_parts else "RCI violated" + violations.append( + f"Constraint 3 (RCI): route {route_idx + 1} with customers " + f"{sorted(S)}: LHS={lhs_c3}, RHS={rhs_c3} ({reason})" + ) + violation_magnitudes.append( + make_violation_entry(3, lhs_c3, rhs_c3, violation_amount_c3) + ) + + # ----------------------------------------------------------------------- + # Constraint 4 (Eq 5): Infeasible path inequalities + # No route should be in R^{inf} (always infeasible under all scenarios) + # ----------------------------------------------------------------------- + for route_idx, route in enumerate(routes): + if not route: + continue + + if is_route_always_infeasible(route, customers_by_id, H, W, Q): + # The route is in R^{inf}, violating constraint 5 + # LHS = sum of edges on route path, RHS = |R| - 1 + full_path = [0] + list(route) + [0] + route_edge_set = set() + for i in range(len(full_path) - 1): + u, v = full_path[i], full_path[i + 1] + route_edge_set.add((min(u, v), max(u, v))) + + lhs_c4 = sum(edges.get(e, 0) for e in route_edge_set) + rhs_c4 = len(route_edge_set) - 1 + violation_amount_c4 = lhs_c4 - rhs_c4 + + if violation_amount_c4 > TOL: + violated_constraint_set.add(4) + violations.append( + f"Constraint 4 (infeasible path): route {route_idx + 1} " + f"with customers {sorted(route)} is always infeasible " + f"(in R^{{inf}})" + ) + violation_magnitudes.append( + make_violation_entry(4, lhs_c4, rhs_c4, violation_amount_c4) + ) + + # ----------------------------------------------------------------------- + # Constraint 5 (Eq 6): x_{jk} in {0, 1} + # Check that no edge has value other than 0 or 1 + # ----------------------------------------------------------------------- + for (j, k), val in edges.items(): + if val != 0 and val != 1: + violated_constraint_set.add(5) + viol_amount = min(abs(val - 0), abs(val - 1)) + violations.append( + f"Constraint 5 (binary): edge ({j},{k}) has value {val}, " + f"expected 0 or 1" + ) + violation_magnitudes.append( + make_violation_entry(5, val, round(val), viol_amount) + ) + + # ----------------------------------------------------------------------- + # Constraint 6 (objective): bind the score to the complete route witness. + # The public solution omits scenario and packing variables, so the checker + # existentially reconstructs them with the same deterministic recourse + # calculation as gurobi_code.py. + # ----------------------------------------------------------------------- + reported = float(solution["objective_value"]) + dm = instance["distance_matrix"] + cf = instance["parameters"]["recourse_cost_cf"] + routing_cost = 0.0 + for route in routes: + full_path = [0] + list(route) + [0] + routing_cost += sum( + dm[u][v] for u, v in zip(full_path[:-1], full_path[1:]) + ) + recourse_cost = sum( + compute_route_recourse(route, customers_by_id, H, W, Q, cf) + for route in routes + ) + expected_objective = float(routing_cost) + recourse_cost + objective_difference = abs(reported - expected_objective) + objective_tolerance = max(1e-6, 1e-8 * abs(expected_objective)) + if objective_difference > objective_tolerance: + violated_constraint_set.add(6) + violations.append( + f"Constraint 6 (objective): reported objective_value={reported} " + f"does not match routing + recourse = {expected_objective} " + f"(routing={routing_cost}, recourse={recourse_cost}, " + f"|diff|={objective_difference:.3g}, " + f"tol={objective_tolerance:.3g})" + ) + violation_magnitudes.append( + make_violation_entry( + 6, reported, expected_objective, objective_difference + ) + ) + + # ----------------------------------------------------------------------- + # Build result + # ----------------------------------------------------------------------- + feasible = len(violated_constraint_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraint_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for S2L-CVRP solutions" + ) + parser.add_argument("--instance_path", required=True, + help="Path to instance JSON file") + parser.add_argument("--solution_path", required=True, + help="Path to candidate solution JSON file") + parser.add_argument("--result_path", required=True, + help="Path to write feasibility result JSON file") + args = parser.parse_args() + + 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("FEASIBLE: All hard constraints satisfied.") + else: + print(f"INFEASIBLE: Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/cote2019/gurobi_code.py b/tasks/cote2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..50d18d61053a7293e20e5bd1ce97aa1e538db158 --- /dev/null +++ b/tasks/cote2019/gurobi_code.py @@ -0,0 +1,939 @@ +#!/usr/bin/env python3 +""" +S2L-CVRP (Stochastic 2D Loading CVRP) solver using Gurobi. + +Implements the mathematical model from Côté, Gendreau, and Potvin (2020). +Branch-and-cut with lazy constraint callbacks for: + - Subtour elimination / rounded capacity inequalities (Eq 4) + - Infeasible path inequalities (Eq 5) + - Aggregated optimality cuts for recourse (Eq 43) + +Usage: + python gurobi_code.py --instance_path instance_1.json --solution_path sol.json --time_limit 3600 +""" + +import argparse +import json +import math +import time +from itertools import product as cartesian_product +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass# --------------------------------------------------------------------------- +# Instance loading +# --------------------------------------------------------------------------- + +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + return data + + +# --------------------------------------------------------------------------- +# Precomputation helpers +# --------------------------------------------------------------------------- + +def compute_expected_area_weight(customers): + """ + Compute expected area ã_j and expected weight q̃_j for each customer j. + ã_j = Σ_{i∈I_j} Σ_r p_i^r * h_i^r * w_i^r + q̃_j = Σ_{i∈I_j} Σ_r p_i^r * q_i^r + """ + expected = {} + for cust in customers: + cid = cust["id"] + a_tilde = 0.0 + q_tilde = 0.0 + for item in cust["items"]: + for r in item["realizations"]: + p = r["probability"] + a_tilde += p * r["height"] * r["width"] + q_tilde += p * r["weight"] + expected[cid] = (a_tilde, q_tilde) + return expected + + +def rhs_capacity_bound(subset_ids, expected, H, W, Q): + """ + Compute right-hand side of RCI (Eq 4): + |S| - max{ceil(Σ ã_j / (H*W)), ceil(Σ q̃_j / Q)} + """ + total_area = sum(expected[j][0] for j in subset_ids) + total_weight = sum(expected[j][1] for j in subset_ids) + area_vehicles = math.ceil(total_area / (H * W)) + weight_vehicles = math.ceil(total_weight / Q) + return len(subset_ids) - max(area_vehicles, weight_vehicles) + + +# --------------------------------------------------------------------------- +# Route extraction from edge solution +# --------------------------------------------------------------------------- + +def extract_routes(edge_vals, n): + """ + Given a dict {(j,k): value} of edge variables with value ~1, + extract routes as lists of customer IDs (not including depot 0). + Depot = 0, customers = 1..n. + """ + # Build adjacency list (only edges with value close to 1) + adj = defaultdict(list) + for (j, k), val in edge_vals.items(): + if val > 0.5: + adj[j].append(k) + adj[k].append(j) + + # Each route starts and ends at depot 0. + # Depot degree = 2K, so there are K routes. + visited_edges = set() + routes = [] + + # Find all neighbors of depot 0 + depot_neighbors = sorted(adj[0]) + + for start in depot_neighbors: + edge = (min(0, start), max(0, start)) + if edge in visited_edges: + continue + visited_edges.add(edge) + + route = [] + prev = 0 + cur = start + while cur != 0: + route.append(cur) + neighbors = adj[cur] + next_node = None + for nb in neighbors: + e = (min(cur, nb), max(cur, nb)) + if e not in visited_edges: + next_node = nb + break + if next_node is None: + # **INFERRED ASSUMPTION**: if stuck, route is malformed; break. + break + visited_edges.add((min(cur, next_node), max(cur, next_node))) + prev = cur + cur = next_node + + if route: + routes.append(route) + + return routes + + +# --------------------------------------------------------------------------- +# 2D Packing feasibility: Bottom-Left heuristic with unloading constraints +# --------------------------------------------------------------------------- + +def bottom_left_heuristic_with_unloading(items_with_delivery_order, H, W): + """ + Bottom-left heuristic for 2OPP with unloading constraints. + + items_with_delivery_order: list of (item_h, item_w, delivery_position) + sorted by delivery_position descending (last delivered packed first). + H: vehicle height (length along which items are unloaded from the top/rear). + W: vehicle width. + + Unloading constraint: items delivered earlier (higher delivery_position + numerically = later in delivery) must not block items delivered later + from being pulled out from the top (y-direction = H direction). + **INFERRED ASSUMPTION**: "top" means the open end at y=H; items are + unloaded by sliding out in the +y direction. An item i (delivered at + position a) is blocked by item j (delivered at position b, b>a meaning + j is delivered after i) if j overlaps i in x and j.y > i.y. Since j is + still on the truck when i is delivered, this is a conflict. We pack in + reverse delivery order (last-delivered = first packed, placed deepest). + + Returns True if all items packed feasibly, False otherwise. + """ + # Sort: last-delivered customers first (they go deepest in truck). + sorted_items = sorted(items_with_delivery_order, key=lambda t: -t[2]) + + placements = [] # (x, y, w, h, delivery_pos) + + for (ih, iw, dpos) in sorted_items: + placed = False + # Try all candidate positions in bottom-left order + # Candidate y positions: 0, and top edges of existing placements + # Candidate x positions: 0, and right edges of existing placements + y_candidates = sorted(set([0] + [p[1] + p[3] for p in placements])) + x_candidates = sorted(set([0] + [p[0] + p[2] for p in placements])) + + best_pos = None + for y in y_candidates: + if y + ih > H: + continue + for x in x_candidates: + if x + iw > W: + continue + # Check no overlap with existing placements + overlap = False + for (px, py, pw, ph, pd) in placements: + if x < px + pw and x + iw > px and y < py + ph and y + ih > py: + overlap = True + break + if overlap: + continue + + # Check unloading constraints: + # This item has delivery_pos = dpos. + # For every already-placed item with delivery_pos pd < dpos + # (delivered earlier, so still on truck when this item should + # be unloaded), that item must not be above this item + # in a way that blocks pulling this item out. + # **INFERRED ASSUMPTION**: unloading from y=H end. + # Item (x,y,iw,ih) is blocked by (px,py,pw,ph) if they + # overlap in x range AND py >= y+ih (the other item is + # further from the open end). Actually, the blocker is + # between this item and the exit. So item j blocks item i + # if j overlaps i in x and j is between i and exit (y=H). + # i.e., px < x+iw and px+pw > x and py >= y (some part of j + # is at or above y) but we need j to actually be between i + # and the exit. The precise constraint: j's y range overlaps + # (y+ih, H) in x-projection overlapping (x, x+iw). + # Simpler conservative check: if j has delivery_pos < dpos + # (j is delivered BEFORE this item, so j must be unloaded + # first), then j must be closer to exit (higher y) or + # non-overlapping in x. + # Actually let's be precise: when delivering customer at + # position dpos, all items of customers with position > dpos + # have already been delivered and removed. Items with position + # < dpos are still on the truck. So we need: no item with + # position < dpos blocks this item's removal from y=H. + # An item blocks if it overlaps in x and has y >= this item's + # y + ih (between this item and exit at y=H). + # Wait—items with smaller delivery position are delivered LATER. + # Delivery position 1 = first delivered, N = last delivered. + # When unloading customer at position p, customers p+1..N + # have not yet been delivered? No—delivery order is 1,2,3... + # Customer 1 is delivered first. When delivering customer 1, + # customers 2..N are still on truck. So items of customers + # 2..N must not block customer 1's items. + # So for this item (dpos), items with delivery_pos > dpos are + # still on truck during this item's delivery and could block. + unloading_ok = True + for (px, py, pw, ph, pd) in placements: + if pd > dpos: + # pd is delivered AFTER dpos, so pd's items are still + # on the truck when dpos is being delivered. + # Check if pd's item blocks this item from exit (y=H). + if (px < x + iw and px + pw > x and + py + ph > y + ih and py < H): + # pd's item occupies space between this item's top + # and the exit in overlapping x range → blocks. + # **INFERRED ASSUMPTION**: blocking means any part + # of the other item is above (closer to exit) this + # item in the same x column. + unloading_ok = False + break + if not unloading_ok: + continue + + # Valid position found (bottom-left preference) + if best_pos is None or (y, x) < (best_pos[1], best_pos[0]): + best_pos = (x, y) + + if best_pos is not None and best_pos[1] == y: + # Already found the bottom-most valid position at this y + break + + if best_pos is None: + return False + + placements.append((best_pos[0], best_pos[1], iw, ih, dpos)) + + return True + + +# --------------------------------------------------------------------------- +# 2OPP / 2OPPUL exact MIP solver +# --------------------------------------------------------------------------- + +def solve_2opp_exact(items_with_delivery_order, H, W, time_limit=30.0): + """ + Exact MIP for 2D Orthogonal Packing with Unloading constraints (2OPPUL). + + items_with_delivery_order: list of (item_h, item_w, delivery_position) + H, W: container dimensions + time_limit: seconds for Gurobi + + Returns True if feasible, False otherwise. + """ + n_items = len(items_with_delivery_order) + if n_items == 0: + return True + + env = gp.Env(empty=True) + env.setParam("OutputFlag", 0) + env.start() + m = gp.Model("2OPPUL", env=env) + m.setParam("Threads", 1) + m.setParam("TimeLimit", time_limit) + m.setParam("OutputFlag", 0) + + items = items_with_delivery_order # alias + + # Position variables + x = {} + y = {} + for i in range(n_items): + x[i] = m.addVar(lb=0, ub=W - items[i][1], vtype=GRB.CONTINUOUS, + name=f"x_{i}") + y[i] = m.addVar(lb=0, ub=H - items[i][0], vtype=GRB.CONTINUOUS, + name=f"y_{i}") + + # Non-overlap disjunction: for each pair (i,j), i delta1 + # x_j + w_j <= x_i (j left of i) -> delta2 + # y_i + h_i <= y_j (i below j) -> delta3 + # y_j + h_j <= y_i (j below i) -> delta4 + M_x = W + M_y = H + + delta = {} + for i in range(n_items): + for j in range(i + 1, n_items): + d = {} + for k in range(4): + d[k] = m.addVar(vtype=GRB.BINARY, name=f"d_{i}_{j}_{k}") + delta[(i, j)] = d + + hi, wi, di_pos = items[i] + hj, wj, dj_pos = items[j] + + # x_i + w_i <= x_j + M*(1 - delta1) + m.addConstr(x[i] + wi <= x[j] + M_x * (1 - d[0])) + # x_j + w_j <= x_i + M*(1 - delta2) + m.addConstr(x[j] + wj <= x[i] + M_x * (1 - d[1])) + # y_i + h_i <= y_j + M*(1 - delta3) + m.addConstr(y[i] + hi <= y[j] + M_y * (1 - d[2])) + # y_j + h_j <= y_i + M*(1 - delta4) + m.addConstr(y[j] + hj <= y[i] + M_y * (1 - d[3])) + + # At least one must hold + m.addConstr(d[0] + d[1] + d[2] + d[3] >= 1) + + # Unloading constraints: + # If di_pos < dj_pos: i is delivered before j. When delivering i, + # j is still on truck. j must not block i from exit (y=H). + # "j above i" = y_j + h_j > y_i + h_i with x-overlap. + # The "j below i" option (delta4: y_j + h_j <= y_i) means j is + # deeper than i. This is fine—j doesn't block i from exit. + # The "i below j" option (delta3: y_i + h_i <= y_j) means i is + # deeper and j is above i between i and exit. This blocks i. + # So we must forbid delta3 when di_pos < dj_pos. + # **INFERRED ASSUMPTION**: "above" in the unloading direction + # means higher y, and items are pulled out from y=H. + # When i is delivered before j (di_pos < dj_pos), j is still on + # truck. j must not be between i and exit. + # Forbid: delta3 (y_i + h_i <= y_j) because this puts j above i. + if di_pos < dj_pos: + m.addConstr(d[2] == 0) # forbid "i below j" + elif dj_pos < di_pos: + m.addConstr(d[3] == 0) # forbid "j below i" + # If same delivery position (same customer), no unloading constraint. + + m.setObjective(0, GRB.MINIMIZE) # feasibility problem + m.optimize() + + feasible = (m.Status == GRB.OPTIMAL or + (m.Status == GRB.TIME_LIMIT and m.SolCount > 0)) + m.dispose() + env.dispose() + return feasible + + +# --------------------------------------------------------------------------- +# Packing feasibility check (combined heuristic + exact) +# --------------------------------------------------------------------------- + +def check_packing_feasibility(items_with_delivery_order, H, W, Q): + """ + Check if items can be packed in the vehicle with unloading constraints. + + items_with_delivery_order: list of (height, width, weight, delivery_position) + H, W: vehicle dimensions + Q: vehicle weight capacity + + Returns True if feasible. + """ + if not items_with_delivery_order: + return True + + # Area bound + total_area = sum(h * w for h, w, wt, dp in items_with_delivery_order) + if total_area > H * W: + return False + + # Weight bound + total_weight = sum(wt for h, w, wt, dp in items_with_delivery_order) + if total_weight > Q: + return False + + # Individual item dimension check + for h, w, wt, dp in items_with_delivery_order: + # **NOT SPECIFIED IN PAPER**: Items cannot be rotated (stated in problem). + if h > H or w > W: + return False + + # Build list for packing (h, w, delivery_position) + pack_items = [(h, w, dp) for h, w, wt, dp in items_with_delivery_order] + + # Try bottom-left heuristic first (fast) + if bottom_left_heuristic_with_unloading(pack_items, H, W): + return True + + # Fall back to exact MIP + return solve_2opp_exact(pack_items, H, W, time_limit=10.0) + + +# --------------------------------------------------------------------------- +# Recourse computation for a single route +# --------------------------------------------------------------------------- + +def compute_route_recourse(route, customers_by_id, H, W, Q, cf): + """ + Compute the recourse cost F(R) for a route. + + route: list of customer IDs in delivery order. + Returns the minimum recourse over both delivery orderings (forward/reverse). + + F(R) = cf * Σ_{ω} p_ω * F(ω) + where F(ω) = number of unserved customers under scenario ω. + """ + if not route: + return 0.0 + + # **INFERRED ASSUMPTION**: Both orderings are checked since two-index + # formulation doesn't determine direction; use the better one. + best_recourse = float("inf") + + for delivery_order in [route, list(reversed(route))]: + recourse = _compute_recourse_for_ordering( + delivery_order, customers_by_id, H, W, Q, cf + ) + best_recourse = min(best_recourse, recourse) + + return best_recourse + + +def _compute_recourse_for_ordering(delivery_order, customers_by_id, H, W, Q, cf): + """ + Compute recourse for a specific delivery ordering. + Enumerate scenarios (Cartesian product of item realizations). + """ + # Collect all items on this route with their realizations. + # For each item, we have a list of (realization_data, probability). + # A scenario is one realization per item. + item_realizations = [] # list of lists of (h, w, weight, prob, customer_id, delivery_pos) + for pos_idx, cid in enumerate(delivery_order): + cust = customers_by_id[cid] + delivery_pos = pos_idx + 1 # 1-indexed delivery position + for item in cust["items"]: + reals = [] + for r in item["realizations"]: + reals.append(( + r["height"], r["width"], r["weight"], + r["probability"], cid, delivery_pos + )) + item_realizations.append(reals) + + # Check if all items are deterministic (1 realization each) + all_deterministic = all(len(reals) == 1 for reals in item_realizations) + + if all_deterministic: + # Single scenario with probability 1 + items = [(r[0], r[1], r[2], r[5]) for reals in item_realizations + for r in reals] + feasible = check_packing_feasibility(items, H, W, Q) + if feasible: + return 0.0 + else: + # Infeasible deterministic route: F(R) = infinity conceptually. + # In practice, all customers are unserved. + # **NOT SPECIFIED IN PAPER**: For a deterministic infeasible route, + # we return cf * n_customers (all unserved). The outer logic will + # add an infeasible path inequality instead. + return cf * len(delivery_order) + + # Enumerate all scenarios + # **NOT SPECIFIED IN PAPER**: For routes with very many scenarios, this + # could be exponential. We cap at a reasonable number. + n_scenarios = 1 + for reals in item_realizations: + n_scenarios *= len(reals) + + # If too many scenarios, use sampling + # **NOT SPECIFIED IN PAPER**: sampling threshold + MAX_SCENARIOS = 10000 + if n_scenarios > MAX_SCENARIOS: + return _compute_recourse_sampled( + delivery_order, item_realizations, customers_by_id, H, W, Q, cf, + MAX_SCENARIOS + ) + + total_recourse = 0.0 + + for scenario in cartesian_product(*item_realizations): + # scenario is a tuple of (h, w, weight, prob, cid, delivery_pos) per item + prob = 1.0 + for item_real in scenario: + prob *= item_real[3] + + if prob < 1e-15: + continue + + # Build item list: (h, w, weight, delivery_pos) + items_scenario = [(s[0], s[1], s[2], s[5]) for s in scenario] + + # Check full route feasibility + feasible = check_packing_feasibility(items_scenario, H, W, Q) + if feasible: + # F(ω) = 0 + continue + + # Not feasible: find max customers that can be served. + unserved = _count_unserved(delivery_order, scenario, H, W, Q) + total_recourse += prob * cf * unserved + + return total_recourse + + +def _compute_recourse_sampled(delivery_order, item_realizations, customers_by_id, + H, W, Q, cf, n_samples): + """Estimate recourse by sampling scenarios.""" + import random + total_recourse = 0.0 + + for _ in range(n_samples): + scenario = [] + for reals in item_realizations: + # Sample according to probabilities + r_val = random.random() + cumul = 0.0 + chosen = reals[0] + for real in reals: + cumul += real[3] + if r_val <= cumul: + chosen = real + break + scenario.append(chosen) + + items_scenario = [(s[0], s[1], s[2], s[5]) for s in scenario] + feasible = check_packing_feasibility(items_scenario, H, W, Q) + if not feasible: + unserved = _count_unserved(delivery_order, scenario, H, W, Q) + total_recourse += cf * unserved + + return total_recourse / n_samples + + +def _count_unserved(delivery_order, scenario, H, W, Q): + """ + Count unserved customers in a scenario. + Try dropping customers one at a time (greedy) to find the maximum number + that can be served. + + **NOT SPECIFIED IN PAPER**: Exact approach would try all subsets; we use + greedy removal of the customer whose items contribute most area, then + re-check feasibility. This is a heuristic for the recourse sub-problem. + """ + n_cust = len(delivery_order) + + # Group items by customer + cust_items = defaultdict(list) + for s in scenario: + cust_items[s[4]].append(s) # keyed by customer id + + # Try serving all customers first (already failed), then drop one at a time. + served = list(delivery_order) + + for drop_count in range(1, n_cust): + # Try dropping each remaining customer, pick the one that makes it feasible + # **INFERRED ASSUMPTION**: greedy drop by largest area contribution + best_to_drop = None + best_area = -1 + for cid in served: + area = sum(s[0] * s[1] for s in cust_items[cid]) + if area > best_area: + best_area = area + best_to_drop = cid + + served.remove(best_to_drop) + + # Rebuild item list with remaining customers + remaining_items = [] + for cid in served: + for s in cust_items[cid]: + # Recompute delivery_pos based on position in served list + dpos = served.index(cid) + 1 + remaining_items.append((s[0], s[1], s[2], dpos)) + + if check_packing_feasibility(remaining_items, H, W, Q): + return drop_count # number unserved + + # If even single customer can't be served (shouldn't happen normally) + return n_cust + + +# --------------------------------------------------------------------------- +# Check if route is infeasible under ALL scenarios +# --------------------------------------------------------------------------- + +def is_route_always_infeasible(route, customers_by_id, H, W, Q): + """ + Check if a route is infeasible under every possible scenario. + Used for infeasible path inequalities (Eq 5). + Both delivery orderings are checked. + """ + for delivery_order in [route, list(reversed(route))]: + item_realizations = [] + for pos_idx, cid in enumerate(delivery_order): + cust = customers_by_id[cid] + delivery_pos = pos_idx + 1 + for item in cust["items"]: + reals = [] + for r in item["realizations"]: + reals.append((r["height"], r["width"], r["weight"], + r["probability"], cid, delivery_pos)) + item_realizations.append(reals) + + # Check each scenario + n_scenarios = 1 + for reals in item_realizations: + n_scenarios *= len(reals) + + if n_scenarios > 10000: + # **NOT SPECIFIED IN PAPER**: too many scenarios to check all; + # conservatively say not always infeasible. + return False + + any_feasible = False + for scenario in cartesian_product(*item_realizations): + items_scenario = [(s[0], s[1], s[2], s[5]) for s in scenario] + if check_packing_feasibility(items_scenario, H, W, Q): + any_feasible = True + break + + if any_feasible: + return False + + return True + + +# --------------------------------------------------------------------------- +# Connected components from edges +# --------------------------------------------------------------------------- + +def find_connected_components(edge_vals, n): + """ + Find connected components from edges with value > 0.5. + Returns list of sets of node IDs. + """ + adj = defaultdict(set) + for (j, k), val in edge_vals.items(): + if val > 0.5: + adj[j].add(k) + adj[k].add(j) + + visited = set() + components = [] + + for node in range(n + 1): # 0..n + if node in visited or node not in adj: + continue + comp = set() + stack = [node] + while stack: + v = stack.pop() + if v in visited: + continue + visited.add(v) + comp.add(v) + for nb in adj[v]: + if nb not in visited: + stack.append(nb) + components.append(comp) + + return components + + +# --------------------------------------------------------------------------- +# Main solver +# --------------------------------------------------------------------------- + +def solve(args): + data = load_instance(args.instance_path) + + params = data["parameters"] + vehicle = data["vehicle"] + depot = data["depot"] + customers = data["customers"] + dist_matrix = data["distance_matrix"] + + n = params["n_customers"] + H = vehicle["H"] + W = vehicle["W"] + Q = vehicle["Q"] + K = vehicle["K"] + cf = params["recourse_cost_cf"] + + customers_by_id = {c["id"]: c for c in customers} + expected = compute_expected_area_weight(customers) + + # Node set: 0 = depot, 1..n = customers + C = list(range(1, n + 1)) # customer set + V = list(range(0, n + 1)) # all nodes + + # Edge set: (j, k) with j < k + edges = [] + for j in V: + for k in V: + if j < k: + edges.append((j, k)) + + # Distance / cost + c = {} + for j, k in edges: + c[(j, k)] = dist_matrix[j][k] + + # ----- Build Gurobi model ----- + env = gp.Env(empty=True) + env.setParam("OutputFlag", 1) + env.start() + model = gp.Model("S2L_CVRP", env=env) + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + model.setParam("LazyConstraints", 1) + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, args.time_limit * 0.05)) + + # Decision variables + x = {} + for j, k in edges: + x[(j, k)] = model.addVar(vtype=GRB.BINARY, name=f"x_{j}_{k}") + + # Recourse variable theta >= 0 + theta = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, name="theta") + + # Objective: min Σ c_jk * x_jk + theta + model.setObjective( + gp.quicksum(c[(j, k)] * x[(j, k)] for j, k in edges) + theta, + GRB.MINIMIZE + ) + + # Constraint (2): Σ_{j∈C} x_{0,j} = 2K + model.addConstr( + gp.quicksum(x[(0, j)] for j in C) == 2 * K, + name="depot_degree" + ) + + # Constraint (3): degree constraint for each customer j + for j in C: + incident = [] + for h in V: + if h < j: + incident.append(x[(h, j)]) + elif h > j: + incident.append(x[(j, h)]) + model.addConstr(gp.quicksum(incident) == 2, name=f"degree_{j}") + + # Constraint (6): x binary - already set in var definition + + model.update() + + # ----- Callback ----- + def callback(model, where): + if where == GRB.Callback.MIPSOL: + # Get current solution + x_vals = {} + for j, k in edges: + val = model.cbGetSolution(x[(j, k)]) + x_vals[(j, k)] = val + + theta_val = model.cbGetSolution(theta) + + # 1. Find connected components and add SECs / RCIs + components = find_connected_components(x_vals, n) + for comp in components: + if 0 in comp: + continue + # Subtour: component without depot + S = comp + if len(S) < 2: + continue + + # RCI right-hand side (Eq 4) + rhs = rhs_capacity_bound(S, expected, H, W, Q) + + # Σ_{j,k∈S, j 0.5 + ) + if lhs_val > rhs + 0.5: + lhs_expr = gp.quicksum( + x[(min(j, k), max(j, k))] + for j in S for k in S if j < k + ) + model.cbLazy(lhs_expr <= rhs) + + # 2. Extract routes and compute recourse + # (routes already extracted above) + + total_recourse = 0.0 + active_edges = set() + for j, k in edges: + if x_vals[(j, k)] > 0.5: + active_edges.add((j, k)) + + for route in routes: + # Check if always infeasible → add infeasible path inequality (Eq 5) + if is_route_always_infeasible(route, customers_by_id, H, W, Q): + # Add infeasible path inequality: + # Σ_{(j,k)∈R} x_{jk} <= |R| - 1 + # R includes depot-customer edges and inter-customer edges + route_edges = set() + full_path = [0] + route + [0] + for i in range(len(full_path) - 1): + j, k = full_path[i], full_path[i + 1] + route_edges.add((min(j, k), max(j, k))) + model.cbLazy( + gp.quicksum(x[e] for e in route_edges) + <= len(route_edges) - 1 + ) + else: + # Compute recourse for this route + route_recourse = compute_route_recourse( + route, customers_by_id, H, W, Q, cf + ) + total_recourse += route_recourse + + # 3. Optimality cut for recourse (Eq 43) + if total_recourse > theta_val + 1e-6: + # θ >= F(x^v) * (Σ_{active edges} x_{jk} - (n + K - 1)) + # **INFERRED ASSUMPTION**: The cut uses the total number of + # edges in the solution which is n + K (K depot edges + n + # customer-to-customer edges for K routes of total n customers). + # Actually: each route with m_i customers has m_i + 1 edges. + # Total edges = Σ(m_i + 1) = n + K. + n_active = len(active_edges) + model.cbLazy( + theta >= total_recourse * ( + gp.quicksum(x[e] for e in active_edges) - + (n_active - 1) + ) + ) + + model.optimize(callback) + + # ----- Extract solution ----- + result = { + "instance_id": data.get("instance_id", None), + "problem": "S2L-CVRP", + "solver": "Gurobi", + "status": None, + "objective_value": None, + "routing_cost": None, + "recourse_cost": None, + "routes": [], + "time_limit": args.time_limit, + "solve_time": model.Runtime, + } + + if model.SolCount > 0: + # Extract edge values + x_sol = {} + for j, k in edges: + x_sol[(j, k)] = x[(j, k)].X + + routing_cost = sum(c[e] * x_sol[e] for e in edges if x_sol[e] > 0.5) + theta_sol = theta.X + + routes = extract_routes(x_sol, n) + + # Recompute exact recourse for final solution + total_recourse = 0.0 + for route in routes: + route_recourse = compute_route_recourse( + route, customers_by_id, H, W, Q, cf + ) + total_recourse += route_recourse + + result["status"] = "Optimal" if model.Status == GRB.OPTIMAL else "Feasible" + result["objective_value"] = routing_cost + total_recourse + result["routes"] = [list(r) for r in routes] + else: + result["status"] = "NoSolution" + result["objective_value"] = None + + # Save 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"Status: {result['status']}") + print(f"Objective: {result['objective_value']}") + print(f"Routing cost: {result['routing_cost']}") + print(f"Recourse cost: {result['recourse_cost']}") + print(f"Routes: {result['routes']}") + print(f"Solve time: {model.Runtime:.2f}s") + + model.dispose() + env.dispose() + + return result + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="S2L-CVRP solver using Gurobi (Côté, Gendreau, Potvin 2020)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to instance JSON file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to output solution JSON file") + parser.add_argument("--time_limit", type=float, default=3600.0, + 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) + + solve(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/cote2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/cote2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2019/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/cote2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/cote2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2019/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/cote2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/cote2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2019/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/cote2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/cote2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2019/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/cote2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/cote2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2019/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/cote2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/cote2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cote2019/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/cote2019/gurobi_solution/large_solution_1.json b/tasks/cote2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..961fff02835cf65888d14573a804ea28415515f7 --- /dev/null +++ b/tasks/cote2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02e3bc6d9403ef5e109d6369d7fd8cd6bbfff9e330aac2c97f297f0e09bc8c22 +size 397 diff --git a/tasks/cote2019/gurobi_solution/large_solution_2.json b/tasks/cote2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..92c51fd7baf38c96e756890dc95c45ffc82cca26 --- /dev/null +++ b/tasks/cote2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3118ef6657f3ebf8921515cdb473114dd9e7c177d0edd38b3bc873660b8dc79 +size 395 diff --git a/tasks/cote2019/gurobi_solution/large_solution_3.json b/tasks/cote2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..2624baf929341fca9ade6dd6d3f01e16bf27088d --- /dev/null +++ b/tasks/cote2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8477f3296c4dcc2041e1c94a838f294096729f49f3f7bd968e1a80569076982a +size 403 diff --git a/tasks/cote2019/gurobi_solution/large_solution_4.json b/tasks/cote2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4bb5a434c9998eb11fc2f9f53f5be8594cd4fa0d --- /dev/null +++ b/tasks/cote2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4436b2ec3752fa424d55ae2307776b18b78a33e98d67cdfded6c9df9bd62a5d +size 396 diff --git a/tasks/cote2019/gurobi_solution/large_solution_5.json b/tasks/cote2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..de6518f3e3209d7980388615b6d5548c8ebe6819 --- /dev/null +++ b/tasks/cote2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9978aedd75870e7d6a2add821229ab86116f81bdf6f96117a3652c63014fefc +size 361 diff --git a/tasks/cote2019/gurobi_solution/tiny_solution.json b/tasks/cote2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..a2389339c7eeb876693c7cf81d6d6908ef6e5fa1 --- /dev/null +++ b/tasks/cote2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29b91c26b19954e30e51c296e1c2f54586fb135d8f0c15b8bf476445cb5f35be +size 489 diff --git a/tasks/cote2019/gurobi_solution_log/large_log_1.jsonl b/tasks/cote2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d96037c012145af20625b286a6682b928f11760d --- /dev/null +++ b/tasks/cote2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ab523e7ba171a8687af79b540cd762ab9c1d67515408289cec7ff8ca47948ce +size 40 diff --git a/tasks/cote2019/gurobi_solution_log/large_log_2.jsonl b/tasks/cote2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..543a2b87702f6b310c9215cf334bd9408a5c733d --- /dev/null +++ b/tasks/cote2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff3b399a7dff708ed714749e9967bf4dfbfd6b2445dd45aa4ca1239df3edae09 +size 42 diff --git a/tasks/cote2019/gurobi_solution_log/large_log_3.jsonl b/tasks/cote2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..325e5e28922b7c1959517b5429a75b2c403396bf --- /dev/null +++ b/tasks/cote2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22f4fd49bae7a2cf502c75762d2909754ff8bff1085d9febd4e6f5084c15433f +size 40 diff --git a/tasks/cote2019/gurobi_solution_log/large_log_4.jsonl b/tasks/cote2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7ffca96053b42da0d0565df6a4994ba6ef14d31f --- /dev/null +++ b/tasks/cote2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3350390ce5441379d22e82f60c266f64c1d8bf0caaf9bafa3dd4c88db14a48e0 +size 42 diff --git a/tasks/cote2019/gurobi_solution_log/large_log_5.jsonl b/tasks/cote2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..89b6332abd80c3c728900a1b782f77428b1d812c --- /dev/null +++ b/tasks/cote2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a86778de5506e54811a4292753d628162a39cbc8e4abdff7a828b413842753a +size 39 diff --git a/tasks/cote2019/gurobi_solution_log/tiny_log.jsonl b/tasks/cote2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43ed93d05658699590f9e2333e7bb5fcb12550e7 --- /dev/null +++ b/tasks/cote2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ba450b0d97a9173ad7df54b57728322997b8d2c282133e21d01103771f9cb83 +size 39 diff --git a/tasks/cote2019/instance/large_instance_1.json b/tasks/cote2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..af37a9c3eed5b58ea9e01c0968a53e00d2e29626 --- /dev/null +++ b/tasks/cote2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:874dd0526d32b9bd8f3b162a97febc738ca1a228f6460b26658514ce848ae687 +size 17335 diff --git a/tasks/cote2019/instance/large_instance_2.json b/tasks/cote2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..edce59c72d3fae3479a03f6b4ea28b93d3867860 --- /dev/null +++ b/tasks/cote2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c21b8fd0d5d66b768ac9c7f4bf2ceb0d9b65a1aaa481c1a57b70ee97b5547c58 +size 9530 diff --git a/tasks/cote2019/instance/large_instance_3.json b/tasks/cote2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b1f23a7caf40a6561a17e468e929ed326122b86c --- /dev/null +++ b/tasks/cote2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97d3cdad143b23d775135183a52b121210d20d373b00fc9300834833206ce624 +size 12724 diff --git a/tasks/cote2019/instance/large_instance_4.json b/tasks/cote2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..21d6c61ba2b1e2c142b1fb3f378e85fc78027d06 --- /dev/null +++ b/tasks/cote2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6353744a45486ffc494fa9df523c49c1814e84e106714dd3397ac5cecb88f5d +size 17154 diff --git a/tasks/cote2019/instance/large_instance_5.json b/tasks/cote2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d7e857017e1ccf0edf49f06525cb588eb002a14d --- /dev/null +++ b/tasks/cote2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:356e2ec76686de88a6d97b82e76b09d8fbe214302cfbab5a6b364ca4bc996516 +size 8505 diff --git a/tasks/cote2019/instance/tiny_instance.json b/tasks/cote2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b316f24413edf462eff2fe5f79fd6d869fef7aef --- /dev/null +++ b/tasks/cote2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3393aa0fbe1ebb94fb7631fb08821053106c7d25bd7d11c6eb51291362c70cd3 +size 14278 diff --git a/tasks/cote2019/instance_schema.json b/tasks/cote2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..512a3f617ced6633f10e518222bb29bbe449139f --- /dev/null +++ b/tasks/cote2019/instance_schema.json @@ -0,0 +1,46 @@ +{ + "parameters": { + "n_customers": " Number of customers to be served.", + "item_type": " Item category determining the number and dimension ranges of items per customer.", + "domain_size": " Number of possible realizations for each stochastic item.", + "pct_stochastic_customers": " Percentage of customers whose items have uncertain dimensions and weights.", + "num_stochastic_customers": " Number of customers whose items have uncertain dimensions and weights.", + "recourse_cost_cf": " Penalty cost incurred for each customer left unserved due to packing infeasibility." + }, + "vehicle": { + "H": " Height of the rectangular loading area of each vehicle.", + "W": " Width of the rectangular loading area of each vehicle.", + "Q": " Maximum total weight each vehicle can carry.", + "K": " Number of identical vehicles available in the fleet." + }, + "depot": { + "id": " Identifier of the depot node in the distance matrix.", + "x": " Horizontal coordinate of the depot.", + "y": " Vertical coordinate of the depot." + }, + "customers": [ + { + "id": " Unique identifier of the customer, used as a row/column index in the distance matrix.", + "is_stochastic": " Whether this customer's items have uncertain dimensions and weights.", + "num_items": " Number of rectangular items to be delivered to this customer.", + "items": [ + { + "item_id": " Identifier of the item within this customer's order.", + "shape": " Shape category of the item, one of 'vertical', 'horizontal', or 'homogeneous'.", + "is_stochastic": " Whether this item's dimensions and weight are uncertain.", + "num_realizations": " Number of possible size and weight outcomes for this item.", + "realizations": [ + { + "realization_id": " Identifier of this possible outcome for the item.", + "height": " Height of the item in this realization.", + "width": " Width of the item in this realization.", + "weight": " Weight of the item in this realization.", + "probability": " Probability that this realization occurs." + } + ] + } + ] + } + ], + "distance_matrix": " Travel cost between each pair of nodes, where row/column 0 is the depot and rows/columns 1 through n_customers are customers." +} diff --git a/tasks/cote2019/mathematical_formulation.md b/tasks/cote2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..0b04704ef6e9fa5e491a72f24729c95ebc5b3c57 --- /dev/null +++ b/tasks/cote2019/mathematical_formulation.md @@ -0,0 +1,84 @@ +# Original Formulation: Capacitated Vehicle Routing Problem with Stochastic Two-Dimensional Items (S2L-CVRP) + +*Source: The Vehicle Routing Problem with Stochastic Two-Dimensional Items, Jean-François Côté, Michel Gendreau, Jean-Yves Potvin, Transportation Science (2020).* + +## Sets and Parameters + +- $G = (V, E)$: complete undirected graph. + +- $V = \{0, 1, 2, \ldots, n\}$: set of vertices ($n+1$ vertices); vertex $0$ is the depot. + +- $C = V \setminus \{0\}$: set of customers. + +- $E = \{(j,k) : j,k \in V,\; j < k\}$: set of edges. + +- $c_{jk}$: cost associated with edge $(j,k) \in E$. + +- $K$: number of identical vehicles available (all must be used). + +- $H$: height (length) of the loading area of each vehicle. + +- $W$: width of the loading area of each vehicle. + +- $Q$: maximum weight capacity of each vehicle. + +- For each customer $j \in C$: a set $I_j$ of two-dimensional items, of cardinality $m_j$. $\bigcup_{j \in C} I_j = I$ is the set of all items, $\sum_{j \in C} m_j = m$. + +- For each item $i \in I$: there are $d_i$ possible sizes in height, width, and weight with an associated probability distribution ($d_i = 1$ for a deterministic item), $\sum_{r=1}^{d_i} p_i^r = 1$. + +- $p_i^r$: probability that item $i$ has realization $r$. + +- $w_i^r \le W$, $h_i^r \le H$, $q_i^r \le Q$: width, height, and weight of item $i$ under realization $r$. + +- Expected area covered by items of customer $j$: $\displaystyle \tilde{a}_j = \sum_{i \in I_j} \sum_{r=1}^{d_i} p_i^r h_i^r w_i^r$. + +- Expected weight of items of customer $j$: $\displaystyle \tilde{q}_j = \sum_{i \in I_j} \sum_{r=1}^{d_i} p_i^r q_i^r$. + +- $c_f$: cost (penalty) associated with each unserved customer (recourse cost). + +- $\Omega_R$: set of all possible realizations/scenarios for route $R$. + +- $p_{\omega_R}$: probability of scenario $\omega_R \in \Omega_R$. + +- $F(\omega_R)$: number of unserved customers under scenario $\omega_R$. + +- $\mathcal{R}^{\mathit{inf}}$: set of infeasible routes (routes that do not satisfy the two-dimensional packing and unloading requirements, including deterministic routes and stochastic routes infeasible under all scenarios). + +- $\mathcal{R}_{x^v}$: set of routes in integer solution $x^v$. + +## Decision Variables + +- $x_{jk} \in \{0,1\}$, $0 \le j < k \le n$: equals $1$ if edge $(j,k)$ is used, $0$ otherwise. + +- $F(x)$: expected cost of the recourse of solution $x = (x_{jk})$ (defined below via [eq:F7]–[eq:F8]). + +## Objective + +$$\begin{align} +\min \quad & \sum_{j < k} c_{jk}\, x_{jk} + F(x) \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.} \quad +& \sum_{j \in C} x_{0j} = 2K, \tag{2} \\[4pt] +& \sum_{h < j} x_{hj} + \sum_{k > j} x_{jk} = 2, + && j \in C, \tag{3} \\[4pt] +& \sum_{\substack{j,k \in S \\ j < k}} x_{jk} \leq |S| + - \left\lceil \max\!\left\{ + \frac{\sum_{j \in S} \tilde{a}_j}{HW},\; + \frac{\sum_{j \in S} \tilde{q}_j}{Q} + \right\} \right\rceil, + && S \subseteq C,\; 2 \leq |S| \leq n, \tag{4} \\[4pt] +& \sum_{(j,k) \in R} x_{jk} \leq |R| - 1, + && R \in \mathcal{R}^{\mathit{inf}}, \tag{5} \\[4pt] +& x_{jk} \in \{0,1\}, + && 0 \leq j < k \leq n. \tag{6} +\end{align}$$ + +The recourse cost. For an integer solution $x^v$, the recourse cost $F(x^v)$ is $$\begin{align} +F(x^v) = \sum_{R \in \mathcal{R}_{x^v}} F(R), \tag{7} \label{eq:F7} +\end{align}$$ where $F(R)$ is the recourse cost of route $R$. When route $R$ has only deterministic items, $F(R) = 0$ (feasible) or $F(R) = \infty$ (infeasible). When stochastic items are present, $F(R) = \infty$ if $F(\omega_R) > 0$ for every $\omega_R \in \Omega_R$; otherwise route $R$ is feasible and $$\begin{align} +F(R) = c_f \cdot \sum_{\omega_R \in \Omega_R} p_{\omega_R}\, F(\omega_R). \tag{8} \label{eq:F8} +\end{align}$$ The recourse cost is set to $\infty$ in the case of a fractional solution. diff --git a/tasks/cote2019/problem_description.txt b/tasks/cote2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c36c69e96c963894f3089eb2b1f20a6b40b4bf89 --- /dev/null +++ b/tasks/cote2019/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A delivery company operates a fleet of K identical vehicles from a central depot to serve a set of n customers. The depot and customers form the vertices of a complete undirected graph, where each edge has a known travel cost. Each vehicle has a rectangular loading area of height H and width W, and a maximum weight capacity Q. Every customer must be visited by exactly one vehicle, and every vehicle route must start and end at the depot. All K vehicles must be used. + +Each customer requires delivery of a set of two-dimensional rectangular items. Each item has a height, a width, and a weight. Some items are deterministic, meaning their dimensions and weight are known with certainty when routes are planned. Other items are stochastic: their exact height, width, and weight are not known at planning time but are instead drawn from a discrete probability distribution with a finite number of possible realizations, each having a known probability. The probabilities across all realizations of a given item sum to one. Every realization of every item has height at most H, width at most W, and weight at most Q. The expected area covered by a customer's items is computed as the probability-weighted sum of the product of height and width across all realizations of all items belonging to that customer. The expected weight of a customer's items is computed analogously as the probability-weighted sum of item weights. + +The company must select which edges to traverse, thereby determining the assignment of customers to vehicles and the ordering of visits within each route. Each customer must be connected to exactly two edges in the solution (arriving and departing), ensuring it appears on exactly one route. The total number of edges connecting the depot to customers equals twice the number of vehicles, reflecting that each vehicle departs from and returns to the depot. For any subset of customers, the number of edges used strictly among those customers must not exceed the size of the subset minus the maximum of two quantities: the ceiling of the ratio of their total expected area to the loading area H times W, and the ceiling of the ratio of their total expected weight to Q. This prevents the formation of routes that would, in expectation, exceed either the area or weight capacity of a single vehicle, and simultaneously eliminates subtours. + +Items are packed into the vehicle's rectangular loading area without rotation and without overlap. At each delivery stop along a route, the current customer's items must be unloadable by pulling them out of the vehicle from the rear (top of the packing) without moving items belonging to customers who have not yet been served. A route cannot be completed if no valid packing satisfying these two-dimensional orthogonal packing and unloading conditions exists. For deterministic routes, this is checked directly against the known item dimensions. For routes containing stochastic items, a scenario is a joint realization of all stochastic items on that route, and the route is evaluated across all possible scenarios. Any route that cannot be packed under any possible scenario is prohibited entirely from the solution. + +When item sizes become known just before departure and it turns out that the items assigned to a vehicle cannot all be packed into the loading area, some customers are left unserved. The expected penalty cost of a route is the per-customer penalty amount multiplied by the probability-weighted sum of the number of unserved customers across all scenarios for that route. The total expected penalty cost of a solution is the sum of penalty costs over all routes. The goal is to minimize the sum of total travel cost over all edges used plus the total expected penalty cost across all routes. diff --git a/tasks/cote2019/solution_logger.py b/tasks/cote2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/cote2019/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/cote2019/solution_schema.json b/tasks/cote2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8a03d565611cb430840da524d136d0fa80b5340e --- /dev/null +++ b/tasks/cote2019/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total cost of the solution, equal to the sum of routing cost and expected recourse cost.", + "routes": " Ordered sequence of customer identifiers visited by each vehicle, excluding the depot." +} diff --git a/tasks/cunha2021/feasibility_check.py b/tasks/cunha2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cb3d4b3e159feb634561ad687f73c82648de99 --- /dev/null +++ b/tasks/cunha2021/feasibility_check.py @@ -0,0 +1,610 @@ +""" +Feasibility checker for the 3LSPD-U (Three-Level Lot-Sizing Problem with +Distribution and Uncapacitated production). + +Checks the STD formulation constraints from Cunha & Melo (2021): + Constraint (1): Objective function (not a hard constraint) + Constraint (2): Inventory balance for plant and warehouses (equality) + Constraint (3): Inventory balance for retailers (equality) + Constraint (4): Setup forcing constraints (<=) + Constraint (5): Nonnegativity of x and s (>=) + Constraint (6): Integrality of y (binary) + Constraint (7): Objective consistency (Tier C anti-gaming defense) -- the + reported objective_value is recomputed from the solution's + setup variables y and inventory variables s and must agree + with z_STD within tolerance. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value',) +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_constraints_set = set() + + NR = instance["num_retailers"] + NW = instance["num_warehouses"] + NT = instance["num_periods"] + demands = instance["demands"] # [NR][NT] + assignment = instance["retailer_warehouse_assignment"] # retailer r -> warehouse index + warehouse_retailers = {} + for w_key, r_list in instance["warehouse_retailer_sets"].items(): + warehouse_retailers[int(w_key)] = r_list + + # Compute aggregated demands + # Warehouse demand: sum of assigned retailers' demands + wh_demand = [[0.0] * NT for _ in range(NW)] + for w in range(NW): + for t in range(NT): + wh_demand[w][t] = sum(demands[r][t] for r in warehouse_retailers[w]) + + # Plant demand: total demand + plant_demand = [0.0] * NT + for t in range(NT): + plant_demand[t] = sum(demands[r][t] for r in range(NR)) + + # Cumulative demand from period t to NT-1 (0-indexed) + # d^i_{t|T|} = sum_{l=t}^{NT-1} d^i_l + retailer_cum = [[0.0] * NT for _ in range(NR)] + for r in range(NR): + retailer_cum[r][NT - 1] = demands[r][NT - 1] + for t in range(NT - 2, -1, -1): + retailer_cum[r][t] = retailer_cum[r][t + 1] + demands[r][t] + + wh_cum = [[0.0] * NT for _ in range(NW)] + for w in range(NW): + wh_cum[w][NT - 1] = wh_demand[w][NT - 1] + for t in range(NT - 2, -1, -1): + wh_cum[w][t] = wh_cum[w][t + 1] + wh_demand[w][t] + + plant_cum = [0.0] * NT + plant_cum[NT - 1] = plant_demand[NT - 1] + for t in range(NT - 2, -1, -1): + plant_cum[t] = plant_cum[t + 1] + plant_demand[t] + + # Extract decision variables from solution + # x_plant[t], s_plant[t], y_plant[t] + # x_warehouses[w][t], s_warehouses[w][t], y_warehouses[w][t] + # x_retailers[r][t], s_retailers[r][t], y_retailers[r][t] + x_plant = solution.get("x_plant") + s_plant = solution.get("s_plant") + y_plant = solution.get("y_plant") + x_warehouses = solution.get("x_warehouses") + s_warehouses = solution.get("s_warehouses") + y_warehouses = solution.get("y_warehouses") + x_retailers = solution.get("x_retailers") + s_retailers = solution.get("s_retailers") + y_retailers = solution.get("y_retailers") + + missing_vars = [ + name for name, v in [ + ("x_plant", x_plant), ("s_plant", s_plant), ("y_plant", y_plant), + ("x_warehouses", x_warehouses), ("s_warehouses", s_warehouses), + ("y_warehouses", y_warehouses), + ("x_retailers", x_retailers), ("s_retailers", s_retailers), + ("y_retailers", y_retailers), + ] if v is None + ] + + if missing_vars: + # Reviewer note Fix_7: solutions that only export objective_value used + # to pass vacuously. Required decision variables MUST be present. + return { + "feasible": False, + "violated_constraints": [0], + "violations": [ + "Solution is missing required decision variable(s): " + + ", ".join(missing_vars) + ], + "violation_magnitudes": [] + } + + def record_violation(constraint_idx, message, lhs, rhs, violation_amount): + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_constraints_set.add(constraint_idx) + violations.append(message) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint (2): Inventory balance for plant and warehouses + # s^i_{t-1} + x^i_t = sum_{j in delta(i)} x^j_t + s^i_t + # For plant: s_plant[t-1] + x_plant[t] = sum_w x_warehouses[w][t] + s_plant[t] + # For warehouse w: s_warehouses[w][t-1] + x_warehouses[w][t] = sum_r x_retailers[r][t] + s_warehouses[w][t] + # ========================================================================= + + # Plant balance + for t in range(NT): + s_prev = 0.0 if t == 0 else s_plant[t - 1] + lhs = s_prev + x_plant[t] + rhs = sum(x_warehouses[w][t] for w in range(NW)) + s_plant[t] + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 2, + f"Plant inventory balance violated in period {t+1}: " + f"LHS={lhs:.6f}, RHS={rhs:.6f}", + lhs, rhs, violation_amount + ) + + # Warehouse balance + for w in range(NW): + for t in range(NT): + s_prev = 0.0 if t == 0 else s_warehouses[w][t - 1] + lhs = s_prev + x_warehouses[w][t] + rhs_val = sum(x_retailers[r][t] for r in warehouse_retailers[w]) + s_warehouses[w][t] + violation_amount = abs(lhs - rhs_val) + if violation_amount > tol: + record_violation( + 2, + f"Warehouse {w} inventory balance violated in period {t+1}: " + f"LHS={lhs:.6f}, RHS={rhs_val:.6f}", + lhs, rhs_val, violation_amount + ) + + # ========================================================================= + # Constraint (3): Inventory balance for retailers + # s^r_{t-1} + x^r_t = d^r_t + s^r_t + # ========================================================================= + for r in range(NR): + for t in range(NT): + s_prev = 0.0 if t == 0 else s_retailers[r][t - 1] + lhs = s_prev + x_retailers[r][t] + rhs_val = demands[r][t] + s_retailers[r][t] + violation_amount = abs(lhs - rhs_val) + if violation_amount > tol: + record_violation( + 3, + f"Retailer {r} inventory balance violated in period {t+1}: " + f"LHS={lhs:.6f}, RHS={rhs_val:.6f}", + lhs, rhs_val, violation_amount + ) + + # ========================================================================= + # Constraint (4): Setup forcing constraints + # x^i_t <= d^i_{t|T|} * y^i_t + # ========================================================================= + + # Plant + for t in range(NT): + lhs = x_plant[t] + rhs_val = plant_cum[t] * y_plant[t] + violation_amount = max(lhs - rhs_val, 0.0) + if violation_amount > tol: + record_violation( + 4, + f"Plant setup forcing violated in period {t+1}: " + f"x={lhs:.6f} > cum_demand*y={rhs_val:.6f}", + lhs, rhs_val, violation_amount + ) + + # Warehouses + for w in range(NW): + for t in range(NT): + lhs = x_warehouses[w][t] + rhs_val = wh_cum[w][t] * y_warehouses[w][t] + violation_amount = max(lhs - rhs_val, 0.0) + if violation_amount > tol: + record_violation( + 4, + f"Warehouse {w} setup forcing violated in period {t+1}: " + f"x={lhs:.6f} > cum_demand*y={rhs_val:.6f}", + lhs, rhs_val, violation_amount + ) + + # Retailers + for r in range(NR): + for t in range(NT): + lhs = x_retailers[r][t] + rhs_val = retailer_cum[r][t] * y_retailers[r][t] + violation_amount = max(lhs - rhs_val, 0.0) + if violation_amount > tol: + record_violation( + 4, + f"Retailer {r} setup forcing violated in period {t+1}: " + f"x={lhs:.6f} > cum_demand*y={rhs_val:.6f}", + lhs, rhs_val, violation_amount + ) + + # ========================================================================= + # Constraint (5): Nonnegativity: x^i_t, s^i_t >= 0 + # ========================================================================= + + # Plant + for t in range(NT): + for var_name, val in [("x_plant", x_plant[t]), ("s_plant", s_plant[t])]: + if val < -tol: + violation_amount = abs(val) + record_violation( + 5, + f"{var_name}[{t+1}] = {val:.6f} < 0", + val, 0.0, violation_amount + ) + + # Warehouses + for w in range(NW): + for t in range(NT): + for var_name, val in [("x_warehouses", x_warehouses[w][t]), + ("s_warehouses", s_warehouses[w][t])]: + if val < -tol: + violation_amount = abs(val) + record_violation( + 5, + f"{var_name}[{w}][{t+1}] = {val:.6f} < 0", + val, 0.0, violation_amount + ) + + # Retailers + for r in range(NR): + for t in range(NT): + for var_name, val in [("x_retailers", x_retailers[r][t]), + ("s_retailers", s_retailers[r][t])]: + if val < -tol: + violation_amount = abs(val) + record_violation( + 5, + f"{var_name}[{r}][{t+1}] = {val:.6f} < 0", + val, 0.0, violation_amount + ) + + # ========================================================================= + # Constraint (6): Integrality: y^i_t in {0, 1} + # ========================================================================= + + # Plant + for t in range(NT): + val = y_plant[t] + dist = min(abs(val - 0.0), abs(val - 1.0)) + if dist > tol: + record_violation( + 6, + f"y_plant[{t+1}] = {val:.6f} is not binary", + val, round(val), dist + ) + + # Warehouses + for w in range(NW): + for t in range(NT): + val = y_warehouses[w][t] + dist = min(abs(val - 0.0), abs(val - 1.0)) + if dist > tol: + record_violation( + 6, + f"y_warehouses[{w}][{t+1}] = {val:.6f} is not binary", + val, round(val), dist + ) + + # Retailers + for r in range(NR): + for t in range(NT): + val = y_retailers[r][t] + dist = min(abs(val - 0.0), abs(val - 1.0)) + if dist > tol: + record_violation( + 6, + f"y_retailers[{r}][{t+1}] = {val:.6f} is not binary", + val, round(val), dist + ) + + # ========================================================================= + # Constraint (7): Objective consistency (Tier C anti-gaming defense) + # Full recompute of z_STD (eq. 1) from the solution variables: + # z_STD = sum_t ( sum_i sc^i_t y^i_t + sum_i hc^i_t s^i_t ) + # The STD objective depends ONLY on the setup variables y and the + # inventory variables s, both of which are fully present in the + # solution -- so an exact recompute is possible. Reject when the + # self-reported objective_value disagrees beyond tolerance (this is the + # path LLM-evolved candidates exploit by reporting obj=0 / obj=MAX_FLOAT + # while the routes themselves pass constraints 2-6). + # ========================================================================= + 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): + sc_plant = instance["fixed_costs"]["plant"] # [NT] + sc_warehouses = instance["fixed_costs"]["warehouses"] # [NW][NT] + sc_retailers = instance["fixed_costs"]["retailers"] # [NR][NT] + hc_plant = float(instance["holding_costs"]["plant"]) # scalar + hc_warehouse = float(instance["holding_costs"]["warehouses"]) # scalar + hc_retailers = instance["holding_costs"]["retailers"] # [NR] + + # Setup costs: sum_t sum_i sc^i_t * y^i_t + setup_cost = sum(sc_plant[t] * y_plant[t] for t in range(NT)) + setup_cost += sum(sc_warehouses[w][t] * y_warehouses[w][t] + for w in range(NW) for t in range(NT)) + setup_cost += sum(sc_retailers[r][t] * y_retailers[r][t] + for r in range(NR) for t in range(NT)) + + # Holding costs: sum_t sum_i hc^i_t * s^i_t + holding_cost = hc_plant * sum(s_plant[t] for t in range(NT)) + holding_cost += hc_warehouse * sum(s_warehouses[w][t] + for w in range(NW) + for t in range(NT)) + holding_cost += sum(float(hc_retailers[r]) * s_retailers[r][t] + for r in range(NR) for t in range(NT)) + + true_obj = float(setup_cost + holding_cost) + 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: + record_violation( + 7, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed z_STD=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol_obj:.6g})", + reported, true_obj, abs_diff + ) + elif reported is not None: + # Non-finite reported objective (inf / nan) can never equal a + # finite recomputed z_STD -- treat as an obj-consistency failure. + record_violation( + 7, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} is not a finite number", + reported, 0.0, float("inf") + ) + + # Build result + violated_constraints = sorted(violated_constraints_set) + _domain_check_vars_binary = [("y_plant", y_plant), ("y_warehouses", y_warehouses)] + _domain_check_vars_integer = [] + + # ===================================================================== + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # ===================================================================== + # Constraint 1: Binary domain — variables must be 0 or 1 + for var_name, var_dict in _domain_check_vars_binary: + if isinstance(var_dict, dict): + for key, val in var_dict.items(): + try: + v = float(val) + except (TypeError, ValueError): + continue + if abs(v - round(v)) > tol or round(v) not in (0, 1): + viol = min(abs(v - 0), abs(v - 1)) + if viol > tol: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (binary domain): {var_name}[{key}] = {v} not in {0, 1}") + violation_magnitudes.append({ + "constraint": 1, + "lhs": v, + "rhs": 1.0, + "raw_excess": float(viol), + "normalizer": 1.0, + "ratio": float(viol), + }) + + feasible = len(violated_constraints) == 0 + + # Aggregate violation messages by constraint index + aggregated_violations = [] + for c_idx in violated_constraints: + msgs = [v for v in violations if v.startswith( + {2: ("Plant inventory", "Warehouse"), + 3: ("Retailer",), + 4: ("Plant setup", "Warehouse", "Retailer"), + 5: ("x_", "s_"), + 6: ("y_",)}.get(c_idx, ("",))[0] + ) or True] + # Simpler: count violations per constraint + count = sum(1 for vm in violation_magnitudes if vm["constraint"] == c_idx) + aggregated_violations.append( + f"Constraint ({c_idx}) violated {count} time(s)" + ) + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": aggregated_violations, + "violation_magnitudes": violation_magnitudes + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for 3LSPD-U (Cunha & Melo, 2021)" + ) + parser.add_argument("--instance_path", required=True, + help="Path to the JSON file containing the data instance") + parser.add_argument("--solution_path", required=True, + help="Path to the JSON file containing the candidate solution") + parser.add_argument("--result_path", required=True, + help="Path to write the JSON file containing the feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/cunha2021/gurobi_code.py b/tasks/cunha2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..022e99fa2b7e1cafe8f804db7a9d63e49525d8e2 --- /dev/null +++ b/tasks/cunha2021/gurobi_code.py @@ -0,0 +1,212 @@ +""" +STD formulation of the 3LSPD-U (Three-Level Lot-Sizing Problem with +Distribution and Uncapacitated) using Gurobi. + +Reference: Cunha et al. (2021) +""" + +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(instance_path: str, solution_path: str, time_limit: float): + with open(instance_path) as f: + data = json.load(f) + + num_retailers = data["num_retailers"] + num_warehouses = data["num_warehouses"] + NT = data["num_periods"] + + # Index sets + retailers = list(range(num_retailers)) + warehouses = list(range(num_warehouses)) + periods = list(range(NT)) # 0-indexed: period index t corresponds to period t+1 + + # Retailer-warehouse mapping + retailer_warehouse = data["retailer_warehouse_assignment"] # retailer r -> warehouse index + warehouse_retailers = {} + for w_key, r_list in data["warehouse_retailer_sets"].items(): + warehouse_retailers[int(w_key)] = r_list + + # Demands: demands[r][t] + demands = data["demands"] + + # Aggregated demand for warehouse w in period t = sum of its retailers' demands + # Aggregated demand for plant in period t = total demand + warehouse_demand = [[0.0] * NT for _ in warehouses] + plant_demand = [0.0] * NT + for w in warehouses: + for t in periods: + warehouse_demand[w][t] = sum(demands[r][t] for r in warehouse_retailers[w]) + for t in periods: + plant_demand[t] = sum(demands[r][t] for r in retailers) + + # Cumulative demand from period k to NT-1 (inclusive, 0-indexed) + # For retailers + retailer_cum = [[0.0] * NT for _ in retailers] + for r in retailers: + retailer_cum[r][NT - 1] = demands[r][NT - 1] + for t in range(NT - 2, -1, -1): + retailer_cum[r][t] = retailer_cum[r][t + 1] + demands[r][t] + + # For warehouses + warehouse_cum = [[0.0] * NT for _ in warehouses] + for w in warehouses: + warehouse_cum[w][NT - 1] = warehouse_demand[w][NT - 1] + for t in range(NT - 2, -1, -1): + warehouse_cum[w][t] = warehouse_cum[w][t + 1] + warehouse_demand[w][t] + + # For plant + plant_cum = [0.0] * NT + plant_cum[NT - 1] = plant_demand[NT - 1] + for t in range(NT - 2, -1, -1): + plant_cum[t] = plant_cum[t + 1] + plant_demand[t] + + # Costs + sc_plant = data["fixed_costs"]["plant"] # length NT + sc_warehouses = data["fixed_costs"]["warehouses"] # [w][t] + sc_retailers = data["fixed_costs"]["retailers"] # [r][t] + + hc_plant_val = data["holding_costs"]["plant"] # scalar + hc_warehouse_val = data["holding_costs"]["warehouses"] # scalar + hc_retailers_val = data["holding_costs"]["retailers"] # list per retailer + + # Build model + model = gp.Model("3LSPD_U_STD") + model.setParam("Threads", 1) + model.setParam("MIPGap", 1e-4) + model.setParam("TimeLimit", time_limit) + + # Decision variables + # Plant variables (single plant, index 'p') + x_p = model.addVars(NT, lb=0.0, name="x_p") + s_p = model.addVars(NT, lb=0.0, name="s_p") + y_p = model.addVars(NT, vtype=GRB.BINARY, name="y_p") + + # Warehouse variables + x_w = model.addVars(num_warehouses, NT, lb=0.0, name="x_w") + s_w = model.addVars(num_warehouses, NT, lb=0.0, name="s_w") + y_w = model.addVars(num_warehouses, NT, vtype=GRB.BINARY, name="y_w") + + # Retailer variables + x_r = model.addVars(num_retailers, NT, lb=0.0, name="x_r") + s_r = model.addVars(num_retailers, NT, lb=0.0, name="s_r") + y_r = model.addVars(num_retailers, NT, vtype=GRB.BINARY, name="y_r") + + # Objective + obj = gp.LinExpr() + for t in periods: + # Setup costs + obj += sc_plant[t] * y_p[t] + for w in warehouses: + obj += sc_warehouses[w][t] * y_w[w, t] + for r in retailers: + obj += sc_retailers[r][t] * y_r[r, t] + # Holding costs + obj += hc_plant_val * s_p[t] + for w in warehouses: + obj += hc_warehouse_val * s_w[w, t] + for r in retailers: + obj += hc_retailers_val[r] * s_r[r, t] + model.setObjective(obj, GRB.MINIMIZE) + + # Constraints + + # (2) Flow balance for plant: s_{t-1} + x_t = sum_w x_w[w,t] + s_t + for t in periods: + s_prev = 0.0 if t == 0 else s_p[t - 1] + model.addConstr( + s_prev + x_p[t] == gp.quicksum(x_w[w, t] for w in warehouses) + s_p[t], + name=f"balance_plant_{t}" + ) + + # (2) Flow balance for warehouses: s_{t-1} + x_w[w,t] = sum_r x_r[r,t] + s_w[w,t] + for w in warehouses: + for t in periods: + s_prev = 0.0 if t == 0 else s_w[w, t - 1] + model.addConstr( + s_prev + x_w[w, t] == gp.quicksum(x_r[r, t] for r in warehouse_retailers[w]) + s_w[w, t], + name=f"balance_warehouse_{w}_{t}" + ) + + # (3) Flow balance for retailers: s_{t-1} + x_r[r,t] = d_r_t + s_r[r,t] + for r in retailers: + for t in periods: + s_prev = 0.0 if t == 0 else s_r[r, t - 1] + model.addConstr( + s_prev + x_r[r, t] == demands[r][t] + s_r[r, t], + name=f"balance_retailer_{r}_{t}" + ) + + # (4) Setup forcing constraints + # Plant + for t in periods: + model.addConstr(x_p[t] <= plant_cum[t] * y_p[t], name=f"setup_plant_{t}") + + # Warehouses + for w in warehouses: + for t in periods: + model.addConstr(x_w[w, t] <= warehouse_cum[w][t] * y_w[w, t], + name=f"setup_warehouse_{w}_{t}") + + # Retailers + for r in retailers: + for t in periods: + model.addConstr(x_r[r, t] <= retailer_cum[r][t] * y_r[r, t], + name=f"setup_retailer_{r}_{t}") + + model.optimize() + + # Extract solution + result = {} + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + # Reviewer note Fix_7: the feasibility checker requires every + # decision variable from the STD formulation; export them alongside + # the objective so checks (2)-(6) are no longer vacuous. + result["x_plant"] = [float(x_p[t].X) for t in periods] + result["s_plant"] = [float(s_p[t].X) for t in periods] + result["y_plant"] = [float(y_p[t].X) for t in periods] + result["x_warehouses"] = [[float(x_w[w, t].X) for t in periods] for w in warehouses] + result["s_warehouses"] = [[float(s_w[w, t].X) for t in periods] for w in warehouses] + result["y_warehouses"] = [[float(y_w[w, t].X) for t in periods] for w in warehouses] + result["x_retailers"] = [[float(x_r[r, t].X) for t in periods] for r in retailers] + result["s_retailers"] = [[float(s_r[r, t].X) for t in periods] for r in retailers] + result["y_retailers"] = [[float(y_r[r, t].X) for t in periods] for r in retailers] + else: + result["objective_value"] = None + + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Solve 3LSPD-U using STD formulation with Gurobi") + parser.add_argument("--instance_path", type=str, required=True, help="Path to instance JSON file") + parser.add_argument("--solution_path", type=str, default="gurobi_solution_1.json", help="Path to output solution JSON") + parser.add_argument("--time_limit", type=float, required=True, help="Time limit in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/cunha2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/cunha2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cunha2021/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/cunha2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/cunha2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cunha2021/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/cunha2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/cunha2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cunha2021/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/cunha2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/cunha2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cunha2021/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/cunha2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/cunha2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cunha2021/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/cunha2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/cunha2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/cunha2021/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/cunha2021/gurobi_solution/large_solution_1.json b/tasks/cunha2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..06478dea3d0c7c1deb3e23c98e0d8ec82d20bfb8 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c46b207731e24ad6d6fce3fadf3dc83540e5f29a4fc4e7f62d78517c9ffc888 +size 238044 diff --git a/tasks/cunha2021/gurobi_solution/large_solution_2.json b/tasks/cunha2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..2cc6b27dae44b65060354ee99a38ae58cff01208 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdad5d2e00baad2069b06e08b46a14f6e38829bc1b12255619615ecde827956d +size 240235 diff --git a/tasks/cunha2021/gurobi_solution/large_solution_3.json b/tasks/cunha2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..82efc57ff23905a77ffaf8d1cdd09b3b2e556b59 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eec68f25b1dfb6214eee4ebb1e980fe46a96e7cc1daac91cf31506bfcf8be4df +size 239395 diff --git a/tasks/cunha2021/gurobi_solution/large_solution_4.json b/tasks/cunha2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8eb95edf454950acbabe7e15f58a61f47b171623 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e068513a29fed3995287d66c1c1f210497c917d34d8d02bd82ca065f0a852f34 +size 239490 diff --git a/tasks/cunha2021/gurobi_solution/large_solution_5.json b/tasks/cunha2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..4cbdedef7eca9fcf51fd276ad53545ba5a73d944 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a6439851f8902e089e968ff087fa16e75dae6d8f3eb41555eea58b8b55c3f93 +size 240177 diff --git a/tasks/cunha2021/gurobi_solution/tiny_solution.json b/tasks/cunha2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2d5b96cc77e89099b3e8e8f0e05b0e96328f367d --- /dev/null +++ b/tasks/cunha2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e78079626a4f739747f07455402f3eb1a3e57b789e8b29f79ea795a2a28aa26 +size 31594 diff --git a/tasks/cunha2021/gurobi_solution_log/large_log_1.jsonl b/tasks/cunha2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e9803291d7133b5cf6d379d2259e914a3e1d329 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bba904a4b24ab5f38794e720caf9fa748f6684e802a24a6782c2871773e133f +size 5194 diff --git a/tasks/cunha2021/gurobi_solution_log/large_log_2.jsonl b/tasks/cunha2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..baa16d5c65a7099e2407171deaa8fb472ff0cf4b --- /dev/null +++ b/tasks/cunha2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92db10fdef9f43f580184a89f0eb0a145573b3828d8df4ecb5d13bd5c7190ba7 +size 13257 diff --git a/tasks/cunha2021/gurobi_solution_log/large_log_3.jsonl b/tasks/cunha2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0498a9a6e7b934dc71658025287711d509f7df5f --- /dev/null +++ b/tasks/cunha2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44246ae8081eb7fe5dc2c20b7dd696d5334cd2599e247d1dbb9a06c744192de5 +size 9874 diff --git a/tasks/cunha2021/gurobi_solution_log/large_log_4.jsonl b/tasks/cunha2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..486b15a6a64d4f98614749b60709d8709eb3feb1 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4803e0ac2d7bc91ff92dc2f6431c4cee165e58517e154ccbd8ae17ea119cc8e8 +size 6159 diff --git a/tasks/cunha2021/gurobi_solution_log/large_log_5.jsonl b/tasks/cunha2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cfac9d551812b85eaeb5046368eb937c22262ee8 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82537121ae2c9651c1de6e2e618e5b6ac51b735ccbba22d43136cf936aed0896 +size 10893 diff --git a/tasks/cunha2021/gurobi_solution_log/tiny_log.jsonl b/tasks/cunha2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..60bd6fd79fb9e3a9a8aaa1154e1db94e319860f9 --- /dev/null +++ b/tasks/cunha2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:243cd94c9a74e8f5c8545dd4933750e58133b6891010e656f13dfadeb0bce645 +size 594 diff --git a/tasks/cunha2021/instance/large_instance_1.json b/tasks/cunha2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..43aef2f9c8733bab97128140e2bcfc878a3639a1 --- /dev/null +++ b/tasks/cunha2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc0e60ba3942347609c735a78fd30609dbba79baced25c4ea68c497a5cb6bcb9 +size 153307 diff --git a/tasks/cunha2021/instance/large_instance_2.json b/tasks/cunha2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f6651253ea967113ba9bb1491d410c6d21e1403a --- /dev/null +++ b/tasks/cunha2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d466118d0bd20e87ca8b076605079b98db03ee6263eb1b40899d1a2979dbbd32 +size 153384 diff --git a/tasks/cunha2021/instance/large_instance_3.json b/tasks/cunha2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..17461db7945868b0f21078f704345c10dc309d7f --- /dev/null +++ b/tasks/cunha2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:627dedc2ca88d14a84b1452655438b7de61fb47ea3df3b5dab817fea3bd51bcb +size 153341 diff --git a/tasks/cunha2021/instance/large_instance_4.json b/tasks/cunha2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..47e086c64dc9bed3907326bf496c2b620011bc68 --- /dev/null +++ b/tasks/cunha2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25a46147583d151cec88d3565b6f22ddd7869520d24e741d1028d2694853aaf9 +size 153406 diff --git a/tasks/cunha2021/instance/large_instance_5.json b/tasks/cunha2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..708a29466c9b3134077d8f139f73df3e96f9390a --- /dev/null +++ b/tasks/cunha2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c932c86c9726e0e187171b5fc4321313457a73b422c9f11e1b88fce7e41c0f34 +size 153480 diff --git a/tasks/cunha2021/instance/tiny_instance.json b/tasks/cunha2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..d823517b7b052c286cd16b8572eae2282d9c96e3 --- /dev/null +++ b/tasks/cunha2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74a14fb893676b45d49cdde292a21a488e03a9142bc143d72ac6d4b57e4c6164 +size 21245 diff --git a/tasks/cunha2021/instance_schema.json b/tasks/cunha2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..62c954b58629da7df180517e74e4668fe198f192 --- /dev/null +++ b/tasks/cunha2021/instance_schema.json @@ -0,0 +1,20 @@ +{ + "num_retailers": " Total number of retailers in the supply chain network.", + "num_warehouses": " Total number of warehouses in the supply chain network.", + "num_periods": " Number of discrete time periods in the planning horizon.", + "retailer_warehouse_assignment": " Index of the warehouse that each retailer is assigned to.", + "warehouse_retailer_sets": { + "{warehouse_index}": " Indices of retailers served by this warehouse." + }, + "demands": " Quantity of the item demanded by each retailer in each period.", + "fixed_costs": { + "plant": " Fixed setup cost incurred at the plant when it produces in each period.", + "warehouses": " Fixed setup cost incurred at each warehouse when it receives goods in each period.", + "retailers": " Fixed setup cost incurred at each retailer when it receives goods in each period." + }, + "holding_costs": { + "plant": " Per-unit cost of holding inventory at the plant at the end of each period.", + "warehouses": " Per-unit cost of holding inventory at any warehouse at the end of each period.", + "retailers": " Per-unit cost of holding inventory at each retailer at the end of each period." + } +} diff --git a/tasks/cunha2021/mathematical_formulation.md b/tasks/cunha2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..87f08cad7f184035b04dd78c617f3015b5920baf --- /dev/null +++ b/tasks/cunha2021/mathematical_formulation.md @@ -0,0 +1,59 @@ +# Original Formulation: Uncapacitated Three-Level Lot-Sizing and Replenishment Problem with a Distribution Structure (3LSPD-U) + +*Source: Valid inequalities, preprocessing, and an effective heuristic for the uncapacitated three-level lot-sizing and replenishment problem with a distribution structure, Jesus O. Cunha and Rafael A. Melo, 2021.* + +## Sets and Indices + +- $F = P \cup W \cup R$: set of all facilities. + +- $P = \{p\}$: singleton set containing the production plant (level 0). + +- $W$: set of warehouses (level 1). + +- $R$: set of retailers (level 2). + +- $T = \{1, \ldots, NT\}$: time horizon (planning periods). + +- $\delta(i)$: set of successors of facility $i$. For the plant, $\delta(p) = W$; for a warehouse $w \in W$, $\delta(w) \subseteq R$ is the predefined set of retailers it attends. + +- $\delta_w(r) \in W$: the predefined unique warehouse associated with retailer $r \in R$. + +## Parameters + +- $sc^i_t$: fixed setup cost incurred at facility $i \in F$ whenever production/transportation occurs in period $t \in T$. + +- $hc^i_t$: per-unit holding cost charged when items are held in inventory at facility $i \in F$ at the end of period $t \in T$. + +- $d^r_t$: demand of retailer $r \in R$ in period $t \in T$. + +- Derived demands for $i \in P \cup W$: $$d^i_t = + \begin{cases} + \sum_{r \in R} d^r_t, & \text{if } i = p; \\ + \sum_{r \in \delta(i)} d^r_t, & \text{if } i \in W. + \end{cases}$$ + +- $d^i_{kt} = \sum_{l=k}^{t} d^i_l$: cumulative demand from period $k$ up to $t$ for facility $i \in F$, for $1 \le k \le t \le |T|$. + +## Decision Variables + +- $x^i_t \geq 0$: amount produced at the plant (if $i = p$) in period $t$, or amount transported to facility $i \in W \cup R$ from its predecessor in period $t$. + +- $s^i_t \geq 0$: amount of stock at facility $i \in F$ at the end of period $t \in T$. + +- $y^i_t \in \{0,1\}$: setup variable, equal to $1$ whenever $x^i_t > 0$, for $i \in F$, $t \in T$. + +## Objective + +$$\begin{equation} +z_{STD} = \min \sum_{t \in T} \left( \sum_{i \in F} sc^i_t y^i_t + \sum_{i \in F} hc^i_t s^i_t \right) \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +& s^i_{t-1} + x^i_t = \sum_{j \in \delta(i)} x^j_t + s^i_t, && \text{for } i \in P \cup W,\ t \in T, \tag{2} \\ +& s^r_{t-1} + x^r_t = d^r_t + s^r_t, && \text{for } r \in R,\ t \in T, \tag{3} \\ +& x^i_t \leq d^i_{t|T|}\, y^i_t, && \text{for } i \in F,\ t \in T, \tag{4} \\ +& x^i_t,\ s^i_t \geq 0, && \text{for } i \in F,\ t \in T, \tag{5} \\ +& y^i_t \in \{0,1\}, && \text{for } i \in F,\ t \in T. \tag{6} +\end{align}$$ diff --git a/tasks/cunha2021/problem_description.txt b/tasks/cunha2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..563a7a2c2a8956f5b8bcba16349c44a7e2d4277b --- /dev/null +++ b/tasks/cunha2021/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A supply chain consists of three levels of facilities: a single production plant, a set of warehouses, and a set of retailers. The plant produces a single item that flows downward through the network over a finite planning horizon of discrete time periods. Each warehouse serves a predefined subset of retailers, and each retailer is assigned to exactly one warehouse. Goods can only move from the plant to warehouses and from warehouses to their assigned retailers; transfers between warehouses or between retailers are not permitted. There is no limit on the amount that can be produced at the plant or transported to any facility in any period. + +The input data specifies the number of warehouses, the number of retailers, and the number of time periods. A retailer-to-warehouse assignment maps each retailer to its unique warehouse, and equivalently defines for each warehouse the set of retailers it serves. Each retailer has a known demand in each period. The per-period demand at each warehouse is a derived quantity equal to the sum of demands of its assigned retailers in that period, and the per-period demand at the plant is a derived quantity equal to the sum of all retailer demands in that period. Each facility (the plant, each warehouse, and each retailer) has a fixed setup cost for each period, incurred whenever any positive amount is produced at or transported to that facility in that period. Each facility also has a per-unit holding cost for each period, charged on inventory held at that facility at the end of that period. Both fixed setup costs and per-unit holding costs vary by facility and by period. + +The planner must determine, for each period, the amount produced at the plant, the amount shipped from the plant to each warehouse, and the amount shipped from each warehouse to each of its assigned retailers, as well as the inventory held at every facility at the end of each period and whether each facility is active (has a positive inflow) in each period. + +Inventory at each facility starts at zero at the beginning of the planning horizon. For the plant and each warehouse in each period, the inventory carried from the previous period plus the amount received equals the total amount shipped out to all successor facilities plus the inventory carried into the next period. For each retailer in each period, the inventory carried from the previous period plus the amount received from its warehouse equals the retailer's demand in that period plus the inventory carried into the next period. A facility may receive a positive quantity in a given period only if that facility is set up in that period. The amount received by any facility in a period cannot exceed the total remaining demand that the facility must eventually fulfill from that period through the end of the horizon; specifically, for the plant this is the sum of all retailer demands from the current period onward, for a warehouse it is the sum of demands of all its assigned retailers from the current period onward, and for a retailer it is the sum of its own demands from the current period onward. + +The goal is to minimize the total cost over the entire planning horizon, defined as the sum of all fixed setup costs incurred at all facilities in all periods where those facilities are active, plus the sum of all per-unit holding costs for inventory held at all facilities at the end of every period. diff --git a/tasks/cunha2021/solution_logger.py b/tasks/cunha2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/cunha2021/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/cunha2021/solution_schema.json b/tasks/cunha2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a25e918ab1ffca876f984e7280dd209357dfcb4f --- /dev/null +++ b/tasks/cunha2021/solution_schema.json @@ -0,0 +1,12 @@ +{ + "objective_value": " Total cost over the planning horizon, summing all fixed setup costs incurred and all per-unit holding costs charged at every facility in every period.", + "x_plant": " Quantity produced at the plant in each period.", + "s_plant": " Inventory held at the plant at the end of each period.", + "y_plant": " Whether the plant is set up to produce in each period (1 = yes, 0 = no).", + "x_warehouses": " Quantity shipped from the plant to each warehouse in each period.", + "s_warehouses": " Inventory held at each warehouse at the end of each period.", + "y_warehouses": " Whether each warehouse is set up to receive a shipment in each period (1 = yes, 0 = no).", + "x_retailers": " Quantity shipped from the assigned warehouse to each retailer in each period.", + "s_retailers": " Inventory held at each retailer at the end of each period.", + "y_retailers": " Whether each retailer is set up to receive a shipment in each period (1 = yes, 0 = no)." +} diff --git a/tasks/damcikurt2016/feasibility_check.py b/tasks/damcikurt2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..76f1190974cb7e3678d9e362060ca7d366eddda1 --- /dev/null +++ b/tasks/damcikurt2016/feasibility_check.py @@ -0,0 +1,538 @@ +""" +Feasibility checker for Multistage Stochastic Self-Scheduling Unit Commitment (MSS). +Pan & Guan (2016), Operations Research 64(6):1482-1498. + +Checks all hard constraints from the mathematical formulation. +Constraint numbering (top to bottom in formulation section): + 1: (1b) Minimum-up time + 2: (1c) Minimum-down time + 3: (1d) Startup link + 4: (1e) Shutdown variable definition (v_i = y_{i^-} - y_i + u_i) + 5: (1f) Generation bounds + 6: (1g) Ramp-up limit + 7: (1h) Ramp-down limit + 8: (1i) Binary/integrality of y, u (and implied v) + 9: (2) Startup valid inequality (u_i <= min{y_i, 1 - y_{i^-}}) + 10: Objective consistency -- reported objective_value must match the + expected total profit recomputed from (x, y, u). Tier C anti-gaming + defense against candidates that report a fabricated objective_value + while keeping the decision variables technically feasible. + +This is the side-by-side `_new` variant: it is byte-identical to +feasibility_check.py for constraints 1-9 and only ADDS constraint 10. +""" + +import argparse +import json +import math +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'u', 'x', 'y') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +# Gurobi numerical noise on this model is ~1e-4 on large instances +# (e.g. large_41 OPT solution had drift ~1.21e-4 on ramp-up bounds and +# zero-bound generation constraints). 1e-5 was rejecting valid OPT +# solutions; 1e-3 leaves ample margin while still flagging genuine +# infeasibilities. +TOL = 1e-3 +EPS = 1e-3 + + +def build_tree_data(nodes_list): + nodes = {} + for n in nodes_list: + nid = n["id"] + nodes[nid] = { + "time": n["time"], + "parent": n["parent_id"], + "children": n["children_ids"], + "prob": n["probability"], + "price": n["electricity_price_dollars_per_MWh"], + } + return nodes + + +def get_descendants(node_id, nodes): + result = [] + stack = [node_id] + while stack: + cur = stack.pop() + result.append(cur) + stack.extend(nodes[cur]["children"]) + return result + + +def get_H_r(node_i, r, nodes): + """H_r(i) = {k in descendants(i) : 0 <= t(k) - t(i) <= r - 1}""" + t_i = nodes[node_i]["time"] + desc = get_descendants(node_i, nodes) + return [k for k in desc if 0 <= nodes[k]["time"] - t_i <= r - 1] + + +def record_violation(violations_list, magnitudes_list, constraint_idx, msg, lhs, rhs): + violation_amount = abs(lhs - rhs) + if constraint_idx == 8: + # For integrality, measure distance from nearest integer + # lhs is the value, rhs is the nearest integer + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations_list.append(msg) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MSS Unit Commitment (Pan & Guan 2016)" + ) + parser.add_argument("--instance_path", required=True) + parser.add_argument("--solution_path", required=True) + parser.add_argument("--result_path", required=True) + args = parser.parse_args() + + with open(args.instance_path) as f: + inst = json.load(f) + with open(args.solution_path) as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + # Instance parameters + gen = inst["generator"] + C_lo = gen["C_lower_MW"] + C_up = gen["C_upper_MW"] + V_plus = gen["V_plus_MW_per_h"] + V_minus = gen["V_minus_MW_per_h"] + + tree_cfg = inst["scenario_tree"] + L = tree_cfg["L_min_up_time"] + ell = tree_cfg["ell_min_down_time"] + y0_init = tree_cfg.get("initial_generator_status_y0", 0) + x0_init = tree_cfg.get("initial_generation_x0_MW", 0.0) + + nodes = build_tree_data(tree_cfg["nodes"]) + all_nodes = list(nodes.keys()) + non_root = [i for i in all_nodes if nodes[i]["parent"] is not None] + root_id = [i for i in all_nodes if nodes[i]["parent"] is None][0] + + # Solution variables + # The released certificate format is sparse. Omitted entries take the + # corresponding optional sparse_defaults value (zero when absent). This + # permits both all-off and stationary all-on policies to remain compact on + # million-node trees without weakening any constraint check. + sparse_defaults = sol.get("sparse_defaults", {}) + x_default = float(sparse_defaults.get("x", 0.0)) + y_default = float(sparse_defaults.get("y", 0.0)) + u_default = float(sparse_defaults.get("u", 0.0)) + if not all(math.isfinite(value) for value in (x_default, y_default, u_default)): + raise ValueError("sparse defaults must be finite") + x = defaultdict( + lambda: x_default, {int(k): v for k, v in sol["x"].items()} + ) + y = defaultdict( + lambda: y_default, {int(k): v for k, v in sol["y"].items()} + ) + u = defaultdict( + lambda: u_default, {int(k): v for k, v in sol["u"].items()} + ) + + violated_constraints = set() + violations = [] + magnitudes = [] + + # ── Constraint 1: (1b) Minimum-up time ── + # y_i - y_{i^-} <= y_k, for all i in V\{0}, for all k in H_L(i) + for i in non_root: + par = nodes[i]["parent"] + H = get_H_r(i, L, nodes) + for k in H: + lhs_val = y[i] - y[par] + rhs_val = y[k] + excess = lhs_val - rhs_val + if excess > TOL: + violated_constraints.add(1) + record_violation(violations, magnitudes, 1, + f"Min-up time violated: node i={i}, k={k}: " + f"y[{i}]-y[{par}]={lhs_val} > y[{k}]={rhs_val}", + lhs_val, rhs_val) + + # ── Constraint 2: (1c) Minimum-down time ── + # y_{i^-} - y_i <= 1 - y_k, for all i in V\{0}, for all k in H_ell(i) + for i in non_root: + par = nodes[i]["parent"] + H = get_H_r(i, ell, nodes) + for k in H: + lhs_val = y[par] - y[i] + rhs_val = 1 - y[k] + excess = lhs_val - rhs_val + if excess > TOL: + violated_constraints.add(2) + record_violation(violations, magnitudes, 2, + f"Min-down time violated: node i={i}, k={k}: " + f"y[{par}]-y[{i}]={lhs_val} > 1-y[{k}]={rhs_val}", + lhs_val, rhs_val) + + # ── Constraint 3: (1d) Startup link ── + # y_i - y_{i^-} <= u_i, for all i in V\{0} + for i in non_root: + par = nodes[i]["parent"] + lhs_val = y[i] - y[par] + rhs_val = u[i] + excess = lhs_val - rhs_val + if excess > TOL: + violated_constraints.add(3) + record_violation(violations, magnitudes, 3, + f"Startup link violated: node i={i}: " + f"y[{i}]-y[{par}]={lhs_val} > u[{i}]={rhs_val}", + lhs_val, rhs_val) + + # ── Constraint 4: (1e) Shutdown variable definition ── + # v_i = y_{i^-} - y_i + u_i, and v_i should be in {0,1} + # Since v is eliminated, we check that the implied v_i is non-negative and binary + for i in non_root: + par = nodes[i]["parent"] + v_i = y[par] - y[i] + u[i] + # Check v_i >= 0 (equality constraint: v_i = y_{i^-} - y_i + u_i, must be valid) + if v_i < -TOL: + violated_constraints.add(4) + record_violation(violations, magnitudes, 4, + f"Shutdown var v[{i}] = y[{par}]-y[{i}]+u[{i}] = {v_i} < 0", + v_i, 0.0) + # Check v_i <= 1 + if v_i > 1 + TOL: + violated_constraints.add(4) + record_violation(violations, magnitudes, 4, + f"Shutdown var v[{i}] = y[{par}]-y[{i}]+u[{i}] = {v_i} > 1", + v_i, 1.0) + # Check v_i is integer (close to 0 or 1) + if abs(v_i - round(v_i)) > TOL: + violated_constraints.add(4) + record_violation(violations, magnitudes, 4, + f"Shutdown var v[{i}] = {v_i} not binary", + v_i, round(v_i)) + + # ── Constraint 5: (1f) Generation bounds ── + # C_lo * y_i <= x_i <= C_up * y_i, for all i in V + for i in all_nodes: + # Lower bound: x_i >= C_lo * y_i => C_lo * y_i - x_i <= 0 + lb = C_lo * y[i] + if lb - x[i] > TOL: + violated_constraints.add(5) + record_violation(violations, magnitudes, 5, + f"Generation lower bound violated: node {i}: " + f"x[{i}]={x[i]} < C_lo*y[{i}]={lb}", + lb, x[i]) + # Upper bound: x_i <= C_up * y_i => x_i - C_up * y_i <= 0 + ub = C_up * y[i] + if x[i] - ub > TOL: + violated_constraints.add(5) + record_violation(violations, magnitudes, 5, + f"Generation upper bound violated: node {i}: " + f"x[{i}]={x[i]} > C_up*y[{i}]={ub}", + x[i], ub) + + # ── Constraint 6: (1g) Ramp-up limit ── + # x_i - x_{i^-} <= V^+ * y_{i^-} + C_up * (1 - y_{i^-}), for all i in V\{0} + for i in non_root: + par = nodes[i]["parent"] + lhs_val = x[i] - x[par] + rhs_val = V_plus * y[par] + C_up * (1 - y[par]) + excess = lhs_val - rhs_val + if excess > TOL: + violated_constraints.add(6) + record_violation(violations, magnitudes, 6, + f"Ramp-up violated: node {i}: " + f"x[{i}]-x[{par}]={lhs_val} > V+*y[{par}]+C_up*(1-y[{par}])={rhs_val}", + lhs_val, rhs_val) + + # ── Constraint 7: (1h) Ramp-down limit ── + # x_{i^-} - x_i <= V^- * y_i + C_up * (1 - y_i), for all i in V\{0} + for i in non_root: + par = nodes[i]["parent"] + lhs_val = x[par] - x[i] + rhs_val = V_minus * y[i] + C_up * (1 - y[i]) + excess = lhs_val - rhs_val + if excess > TOL: + violated_constraints.add(7) + record_violation(violations, magnitudes, 7, + f"Ramp-down violated: node {i}: " + f"x[{par}]-x[{i}]={lhs_val} > V-*y[{i}]+C_up*(1-y[{i}])={rhs_val}", + lhs_val, rhs_val) + + # ── Constraint 8: (1i) Binary/integrality ── + # y_i in {0,1} for all i; u_i in {0,1} for all i in V\{0} + for i in all_nodes: + if abs(y[i] - round(y[i])) > TOL or round(y[i]) not in (0, 1): + violated_constraints.add(8) + record_violation(violations, magnitudes, 8, + f"y[{i}]={y[i]} not binary", + y[i], round(y[i])) + for i in non_root: + if abs(u[i] - round(u[i])) > TOL or round(u[i]) not in (0, 1): + violated_constraints.add(8) + record_violation(violations, magnitudes, 8, + f"u[{i}]={u[i]} not binary", + u[i], round(u[i])) + # x_i >= 0 + for i in all_nodes: + if x[i] < -TOL: + violated_constraints.add(8) + record_violation(violations, magnitudes, 8, + f"x[{i}]={x[i]} < 0 (non-negativity violated)", + x[i], 0.0) + + # ── Constraint 9: (2) Startup valid inequality ── + # u_i <= y_i and u_i <= 1 - y_{i^-}, for all i in V\{0} + for i in non_root: + par = nodes[i]["parent"] + # u_i <= y_i + excess1 = u[i] - y[i] + if excess1 > TOL: + violated_constraints.add(9) + record_violation(violations, magnitudes, 9, + f"Startup inequality violated: node {i}: " + f"u[{i}]={u[i]} > y[{i}]={y[i]}", + u[i], y[i]) + # u_i <= 1 - y_{i^-} + rhs_val = 1 - y[par] + excess2 = u[i] - rhs_val + if excess2 > TOL: + violated_constraints.add(9) + record_violation(violations, magnitudes, 9, + f"Startup inequality violated: node {i}: " + f"u[{i}]={u[i]} > 1-y[{par}]={rhs_val}", + u[i], rhs_val) + + # ── Constraint 10: Objective consistency (Tier C anti-gaming) ── + # The full expected-profit objective (1a) is recomputed from the + # solution variables (x, y, u). Every variable the objective depends + # on is present in the solution schema, so a FULL recompute applies. + # + # obj = sum_{i in V} p_i * ( q_i*x_i - f(x_i) ) + # - sum_{i in V\{0}} p_i * ( U_bar*u_i + U_under*(y_{i^-} - y_i + u_i) ) + # + # with the linear fuel-cost approximation f(x_i) = fuel_a*y_i + fuel_b*x_i + # (the paper leaves the piecewise-linear form unspecified; the Gurobi + # reference solver uses exactly this linear form). + # + # The root node has no startup variable u_0 and no shutdown term, so its + # contribution is only p_0*(q_0*x_0 - f(x_0)). + # + # A candidate that reports a fabricated objective_value while keeping + # (x, y, u) feasible passes constraints 1-9 but is rejected here. + U_bar = gen["U_bar_startup_cost_dollars"] + # Shutdown cost: the paper does not specify it separately; the instance + # carries it under U_lower_shutdown_cost_dollars. Fall back to U_bar + # (the symmetric default the Gurobi reference solver also applies). + U_under = gen.get("U_lower_shutdown_cost_dollars", U_bar) + fuel_a = gen["fuel_a_dollars_per_h"] + fuel_b = gen["fuel_b_dollars_per_MWh"] + + reported_obj = sol.get("objective_value") + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = 0.0 + for i in all_nodes: + p_i = nodes[i]["prob"] + q_i = nodes[i]["price"] + par = nodes[i]["parent"] + true_obj += p_i * q_i * x[i] - p_i * fuel_b * x[i] - p_i * fuel_a * y[i] + if par is not None: + true_obj -= p_i * U_bar * u[i] + true_obj -= p_i * U_under * (y[par] - y[i] + u[i]) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor, mirroring TOL. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(10) + record_violation(violations, magnitudes, 10, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed expected profit=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol:.6g})", + reported, true_obj) + + # Build result + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if feasible: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {sorted(violated_constraints)}") + for v in violations[:10]: + print(f" - {v}") + if len(violations) > 10: + print(f" ... and {len(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/damcikurt2016/gurobi_code.py b/tasks/damcikurt2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ad566e13eccd07f25b1797f3e53171313a92ba --- /dev/null +++ b/tasks/damcikurt2016/gurobi_code.py @@ -0,0 +1,279 @@ +""" +Gurobi implementation of the Multistage Stochastic Self-Scheduling Unit Commitment (MSS) +Pan & Guan (2016), "Strong Formulations for the Multistage Stochastic +Self-Scheduling Unit Commitment," Operations Research 64(6):1482-1498. + +Implements the deterministic equivalent MILP (formulation MSS, equations 1a-1i + 2). +""" + +import argparse +import json +import sys +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def build_tree_data(nodes_list): + """Parse node list into convenient dicts.""" + nodes = {} + for n in nodes_list: + nid = n["id"] + nodes[nid] = { + "time": n["time"], + "parent": n["parent_id"], + "children": n["children_ids"], + "prob": n["probability"], + "price": n["electricity_price_dollars_per_MWh"], + } + return nodes + + +def get_path_to_root(node_id, nodes): + """Return list of node ids from root to node_id (inclusive).""" + path = [] + cur = node_id + while cur is not None: + path.append(cur) + cur = nodes[cur]["parent"] + path.reverse() + return path + + +def get_descendants(node_id, nodes): + """Return all descendants of node_id including itself.""" + result = [] + stack = [node_id] + while stack: + cur = stack.pop() + result.append(cur) + stack.extend(nodes[cur]["children"]) + return result + + +def get_H_r(node_i, r, nodes): + """ + H_r(i) = { k in descendants(i) : 0 <= t(k) - t(i) <= r - 1 } + Used for min-up/down time constraints. + """ + t_i = nodes[node_i]["time"] + desc = get_descendants(node_i, nodes) + return [k for k in desc if 0 <= nodes[k]["time"] - t_i <= r - 1] + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for MSS Unit Commitment (Pan & Guan 2016)" + ) + parser.add_argument("--instance_path", required=True, help="Path to instance JSON") + parser.add_argument("--solution_path", required=True, help="Path for solution JSON output") + parser.add_argument("--time_limit", type=int, required=True, help="Solver time limit (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) + + with open(args.instance_path) as f: + inst = json.load(f) + + gen = inst["generator"] + C_lo = gen["C_lower_MW"] + C_up = gen["C_upper_MW"] + V_plus = gen["V_plus_MW_per_h"] + V_minus = gen["V_minus_MW_per_h"] + U_bar = gen["U_bar_startup_cost_dollars"] + # NOTE: U_underline (shutdown cost) not specified separately in paper Table 1. + # INFERRED ASSUMPTION: set equal to U_bar (startup cost) as a symmetric default. + U_under = gen.get("U_lower_shutdown_cost_dollars", U_bar) + fuel_a = gen["fuel_a_dollars_per_h"] + fuel_b = gen["fuel_b_dollars_per_MWh"] + + tree_cfg = inst["scenario_tree"] + L = tree_cfg["L_min_up_time"] + ell = tree_cfg["ell_min_down_time"] + + # Initial conditions + # INFERRED ASSUMPTION: root node treated as a free decision variable; + # initial_generator_status_y0 and initial_generation_x0_MW from instance + # are used to fix the root's initial state before period 1. + # The root node IS period 1, so there is no "period 0" node in the tree. + # We interpret y0_init and x0_init as the state BEFORE the root node + # (i.e., the state at period 0, used to compute ramp/startup at root). + y0_init = tree_cfg.get("initial_generator_status_y0", 0) + x0_init = tree_cfg.get("initial_generation_x0_MW", 0.0) + + nodes = build_tree_data(tree_cfg["nodes"]) + all_nodes = list(nodes.keys()) + # Non-root nodes (those with a parent) + non_root = [i for i in all_nodes if nodes[i]["parent"] is not None] + + # f(x_i) = fuel_a * y_i + fuel_b * x_i (linear approximation) + # fuel_a is fixed cost per period online, fuel_b is variable cost per MWh + # INFERRED ASSUMPTION: piecewise linear fuel cost not specified in paper; + # use linear approximation f(x) = fuel_a + fuel_b * x when online (fuel_a * y_i + fuel_b * x_i). + + model = gp.Model("MSS_UC") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + model.setParam("MIPGap", 1e-4) # 0.01% optimality gap as in paper + # Solver hints: l11 + l41 were 1h TLE no-incumbent in prior runs (1M-node + # scenario tree → ~1M binary y vars, weak LP relaxation). MIPFocus=1 + # prioritizes finding any feasible incumbent over closing the gap, and + # NoRelHeurTime gives gurobi a root-node heuristic budget. Other 3 + # instances (l21/l31/l51) already produce results; expected minor + # slowdown is acceptable. + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, args.time_limit * 0.05)) + + # Decision variables + x = model.addVars(all_nodes, lb=0.0, name="x") + y = model.addVars(all_nodes, vtype=GRB.BINARY, name="y") + u = model.addVars(non_root, vtype=GRB.BINARY, name="u") + + # Objective: max sum_i p_i * (q_i*x_i - U_bar*u_i - U_under*(y_{i^-} - y_i + u_i) - f(x_i)) + # f(x_i) = fuel_a * y_i + fuel_b * x_i + # For root node (no u_0): no startup/shutdown cost at root (v_0 undefined) + # INFERRED ASSUMPTION: root node has no startup/shutdown cost since u_0 doesn't exist. + obj = gp.LinExpr() + for i in all_nodes: + p_i = nodes[i]["prob"] + q_i = nodes[i]["price"] + par = nodes[i]["parent"] + revenue = p_i * q_i + fuel = p_i * fuel_b + fixed = p_i * fuel_a + obj += revenue * x[i] - fuel * x[i] - fixed * y[i] + if par is not None: + obj -= p_i * U_bar * u[i] + obj -= p_i * U_under * (y[par] - y[i] + u[i]) + model.setObjective(obj, GRB.MAXIMIZE) + + # Constraint (1f): C_lo * y_i <= x_i <= C_up * y_i + for i in all_nodes: + model.addConstr(x[i] >= C_lo * y[i], name=f"gen_lb_{i}") + model.addConstr(x[i] <= C_up * y[i], name=f"gen_ub_{i}") + + # Constraint (1d): y_i - y_{i^-} <= u_i + for i in non_root: + par = nodes[i]["parent"] + model.addConstr(y[i] - y[par] <= u[i], name=f"startup_def_{i}") + + # Constraint (2): u_i <= y_i and u_i <= 1 - y_{i^-} + for i in non_root: + par = nodes[i]["parent"] + model.addConstr(u[i] <= y[i], name=f"u_le_y_{i}") + model.addConstr(u[i] <= 1 - y[par], name=f"u_le_1my_par_{i}") + + # Constraint (1b): min-up time + # y_i - y_{i^-} <= y_k for all k in H_L(i) + for i in non_root: + par = nodes[i]["parent"] + H = get_H_r(i, L, nodes) + for k in H: + model.addConstr(y[i] - y[par] <= y[k], name=f"minup_{i}_{k}") + + # Constraint (1c): min-down time + # y_{i^-} - y_i <= 1 - y_k for all k in H_ell(i) + for i in non_root: + par = nodes[i]["parent"] + H = get_H_r(i, ell, nodes) + for k in H: + model.addConstr(y[par] - y[i] <= 1 - y[k], name=f"mindown_{i}_{k}") + + # Constraint (1g): ramp-up + # x_i - x_{i^-} <= V^+ * y_{i^-} + C_up * (1 - y_{i^-}) + # Constraint (1h): ramp-down + # x_{i^-} - x_i <= V^- * y_i + C_up * (1 - y_i) + for i in non_root: + par = nodes[i]["parent"] + if par == 0 and nodes[0]["parent"] is None: + # par is root node — use root's y variable + # Ramp-up from root + model.addConstr( + x[i] - x[par] <= V_plus * y[par] + C_up * (1 - y[par]), + name=f"rampup_{i}" + ) + model.addConstr( + x[par] - x[i] <= V_minus * y[i] + C_up * (1 - y[i]), + name=f"rampdown_{i}" + ) + else: + model.addConstr( + x[i] - x[par] <= V_plus * y[par] + C_up * (1 - y[par]), + name=f"rampup_{i}" + ) + model.addConstr( + x[par] - x[i] <= V_minus * y[i] + C_up * (1 - y[i]), + name=f"rampdown_{i}" + ) + + # Handle initial conditions: ramp constraints between initial state and root node + # The root node is node 0 (period 1). We treat the initial state (period 0) + # as a fixed parameter (y0_init, x0_init) not a variable. + # INFERRED ASSUMPTION: Add ramp constraints from initial state to root. + root_id = [i for i in all_nodes if nodes[i]["parent"] is None][0] + # Ramp-up from initial state to root + model.addConstr( + x[root_id] - x0_init <= V_plus * y0_init + C_up * (1 - y0_init), + name="rampup_init" + ) + # Ramp-down from initial state to root + model.addConstr( + x0_init - x[root_id] <= V_minus * y[root_id] + C_up * (1 - y[root_id]), + name="rampdown_init" + ) + # Min-up/down from initial state: if generator was on before root, + # enforce it stays on for first L-1 periods from root (approximation). + # INFERRED ASSUMPTION: initial state constraints not fully specified; only basic ramp applied. + + model.optimize() + + # Collect solution + solution = {} + status = model.Status + + if model.SolCount > 0: + obj_val = model.ObjVal + # Sparse certificate encoding: omitted entries are exactly zero (as + # documented in solution_schema.json and interpreted by the checker). + # Dense maps on the released million-node trees exceed 50 MB each. + x_sol = {str(i): x[i].X for i in all_nodes if abs(x[i].X) > 1e-9} + y_sol = {str(i): 1 for i in all_nodes if y[i].X > 0.5} + u_sol = {str(i): 1 for i in non_root if u[i].X > 0.5} + solution = { + "objective_value": obj_val, + "status": status, + "mip_gap": model.MIPGap if status not in [GRB.OPTIMAL] else 0.0, + "x": x_sol, + "y": y_sol, + "u": u_sol, + } + else: + solution = { + "objective_value": None, + "status": status, + "message": "No feasible solution found within 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"Objective value: {solution['objective_value']}") + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/damcikurt2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/damcikurt2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/damcikurt2016/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/damcikurt2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/damcikurt2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/damcikurt2016/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/damcikurt2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/damcikurt2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/damcikurt2016/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/damcikurt2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/damcikurt2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/damcikurt2016/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/damcikurt2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/damcikurt2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/damcikurt2016/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/damcikurt2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/damcikurt2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/damcikurt2016/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/damcikurt2016/gurobi_solution/large_solution_1.json b/tasks/damcikurt2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3143b9789bb3b7e22350a88a9210994c7976b1ab --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e10f47b7087a0a468ee1131993d8edd4b254141851f9a802da414e08293d0c8d +size 544 diff --git a/tasks/damcikurt2016/gurobi_solution/large_solution_2.json b/tasks/damcikurt2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ec1b0687dfb4e5e336bfa09f8a1e9eb09a934297 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25978f4847a7bce18cad0a4d1d908ca383d9e8723b92ac1d71568292761c9c21 +size 57141090 diff --git a/tasks/damcikurt2016/gurobi_solution/large_solution_3.json b/tasks/damcikurt2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e7c74e0d4c6c89a694851448037479a9860aa1a7 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a37f5fc6ba279f6518784784e6a0a56be4eff21d8422495b0f6c6553b8dd622 +size 55417052 diff --git a/tasks/damcikurt2016/gurobi_solution/large_solution_4.json b/tasks/damcikurt2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e801cb03057c9b9f2db0dfedca5c289dd2820b03 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd99f16bf852c0da08c44237eeef351d539bc77268bed99fdeb49aa0e91fc27e +size 559 diff --git a/tasks/damcikurt2016/gurobi_solution/large_solution_5.json b/tasks/damcikurt2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..961ac73b45a41b30728b7626a1262af30b16f521 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dec3afb47638131dc75c3820fd1d2860e74fe971617ba83acc03adb3ec52d66b +size 55601277 diff --git a/tasks/damcikurt2016/gurobi_solution/tiny_solution.json b/tasks/damcikurt2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..0e0d3d25ccc1718f9394b249f31fe3f4dee09896 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d120f7a09bf35f1699d5b669e87ecc05523220b2a50d115a71d2a691d18b18c +size 22540 diff --git a/tasks/damcikurt2016/gurobi_solution_log/large_log_1.jsonl b/tasks/damcikurt2016/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4b0551f6157d5a1e1601ed984cbdb8d3305d37f1 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f35da8f850ec62095b06fb8d7dbd76b9f65b50c6b80b96211caccfcbdb29f2bb +size 43 diff --git a/tasks/damcikurt2016/gurobi_solution_log/large_log_2.jsonl b/tasks/damcikurt2016/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c0c23c0441101e87ea7ab4b30b75682eb68c683 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5915aef26af184a11ac3b2abde7b8ff8382cdd442d92d65ce8e348ede70dd5d +size 43 diff --git a/tasks/damcikurt2016/gurobi_solution_log/large_log_3.jsonl b/tasks/damcikurt2016/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4044409e3423376bab5fc7a774ad8d5b66ec4577 --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6288f9fb936a978a1ea41456fa2a7f1ce6a2110b3601a80807508fd40ecbe8f +size 41 diff --git a/tasks/damcikurt2016/gurobi_solution_log/large_log_4.jsonl b/tasks/damcikurt2016/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..12f9c7fdf0ce3a7470b832a7ca3da9cec065df7b --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c374c90f48f4b41d8bfd7d57e908c36c0829b11a020bb48e76139ddeeb8df0af +size 43 diff --git a/tasks/damcikurt2016/gurobi_solution_log/large_log_5.jsonl b/tasks/damcikurt2016/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f6f850d2d5b0b84cf6b55bca5508be11458d407e --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36685009cd0d36dea9b56e803f0ee0e17c1fb33785351ece41cfd012e7f2b8de +size 43 diff --git a/tasks/damcikurt2016/gurobi_solution_log/tiny_log.jsonl b/tasks/damcikurt2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..589352a50ca04fe15e01ecfe9f78e9d70c923bae --- /dev/null +++ b/tasks/damcikurt2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6672148f1237563a137ce620185ce0d7cd3fe9f576594bb60d403338d1e1af83 +size 41 diff --git a/tasks/damcikurt2016/instance/large_instance_1.json b/tasks/damcikurt2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0c8491256fb8eec82b161b949ebae8969d471a2b --- /dev/null +++ b/tasks/damcikurt2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:788141698f23bcf08f1d81571fa2f23ccaa777eaf95eadff83088a87d1cf8c9b +size 244735696 diff --git a/tasks/damcikurt2016/instance/large_instance_2.json b/tasks/damcikurt2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b13d2eb0150dc6955e76d544248c0f00aa797bd0 --- /dev/null +++ b/tasks/damcikurt2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf61acac9f60f87857b7678090964193b7aa0206645088c23946b01fd25bac4c +size 245050937 diff --git a/tasks/damcikurt2016/instance/large_instance_3.json b/tasks/damcikurt2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..23f8e12ad179f4f5ecd49ed00e28468f5416df74 --- /dev/null +++ b/tasks/damcikurt2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d27ed03157db9017a7f445fd2881087cabcbffe74f091541f3ec0b0bb52dff8 +size 244876702 diff --git a/tasks/damcikurt2016/instance/large_instance_4.json b/tasks/damcikurt2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..79f9a8e1350bf3a931f658bd3632b8d8de74f06a --- /dev/null +++ b/tasks/damcikurt2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a083706b2eafa8fc323d5b5d040334428caf166d69e0ce2703744d8048e0fd5d +size 244526007 diff --git a/tasks/damcikurt2016/instance/large_instance_5.json b/tasks/damcikurt2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..42331982ae1034b6ea001e829fdacd57f0fa8b15 --- /dev/null +++ b/tasks/damcikurt2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7866773372f9426c9c5acdbfacc5669a9bebbd48bd933628e0717e8f46b42b45 +size 244622708 diff --git a/tasks/damcikurt2016/instance/tiny_instance.json b/tasks/damcikurt2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..e0714f1694e1cfa75ea4f7545b16ea56c055a3c3 --- /dev/null +++ b/tasks/damcikurt2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e103ab5945f8c21e7df161634b5a3834e2e7d1927f00b5e5ae176344d734e8a2 +size 110430 diff --git a/tasks/damcikurt2016/instance_schema.json b/tasks/damcikurt2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0b11a0aa6facf7b14aca29cbba8c54d6e7d59d7d --- /dev/null +++ b/tasks/damcikurt2016/instance_schema.json @@ -0,0 +1,38 @@ +{ + "generator": { + "G": " Number of generators owned by the power producer.", + "C_lower_MW": " Minimum generation output in megawatts when the generator is running.", + "C_upper_MW": " Maximum generation output in megawatts when the generator is running.", + "V_plus_MW_per_h": " Maximum increase in generation level allowed between consecutive time periods, in megawatts per period.", + "V_minus_MW_per_h": " Maximum decrease in generation level allowed between consecutive time periods, in megawatts per period.", + "U_bar_startup_cost_dollars": " Fixed cost in dollars incurred each time the generator is turned on.", + "U_lower_shutdown_cost_dollars": " Fixed cost in dollars incurred each time the generator is turned off.", + "fuel_cost_type": " Type of fuel cost function used to model operating costs.", + "fuel_cost_formula": " Mathematical formula expressing the fuel cost as a function of generation level.", + "fuel_a_dollars_per_h": " Fixed hourly operating cost in dollars incurred whenever the generator is running.", + "fuel_b_dollars_per_MWh": " Variable operating cost in dollars per megawatt-hour of electricity produced.", + "fuel_cost_note": " Explanatory note about the fuel cost approximation used." + }, + "scenario_tree": { + "T_num_periods": " Total number of time periods in the planning horizon.", + "K_branches_per_node": " Number of child nodes branching from each non-leaf node in the scenario tree.", + "L_min_up_time": " Minimum number of consecutive periods the generator must remain on after being started.", + "ell_min_down_time": " Minimum number of consecutive periods the generator must remain off after being shut down.", + "total_nodes": " Total number of nodes in the scenario tree.", + "num_leaf_nodes": " Number of leaf nodes representing final-period outcomes in the scenario tree.", + "num_scenarios": " Total number of distinct root-to-leaf paths in the scenario tree.", + "initial_generator_status_y0": " On/off status of the generator immediately before the first period (1 = on, 0 = off).", + "initial_generation_x0_MW": " Generation level in megawatts immediately before the first period.", + "electricity_price_range_dollars_per_MWh": " Lower and upper bounds of the electricity price distribution in dollars per megawatt-hour.", + "electricity_price_distribution": " Probability distribution from which electricity prices at each node are drawn.", + "nodes": " List of all nodes in the scenario tree, each containing the fields below.", + "nodes[*]": { + "id": " Unique identifier for this node in the scenario tree.", + "time": " Time period associated with this node, starting from 1.", + "parent_id": " Identifier of this node's parent node, or null for the root node.", + "children_ids": " Identifiers of all child nodes branching from this node.", + "probability": " Probability of reaching this node from the root of the scenario tree.", + "electricity_price_dollars_per_MWh": " Electricity market price at this node in dollars per megawatt-hour." + } + } +} diff --git a/tasks/damcikurt2016/mathematical_formulation.md b/tasks/damcikurt2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..42612d7ffcbe245e82a452776c743e8ea16085ad --- /dev/null +++ b/tasks/damcikurt2016/mathematical_formulation.md @@ -0,0 +1,77 @@ +# Original Formulation: Multistage Stochastic Self-Scheduling Unit Commitment (MSS) + +*Source: Strong Formulations for the Multistage Stochastic Self-Scheduling Unit Commitment, Kai Pan and Yongpei Guan, 2016.* + +## Sets and Parameters + +- $\mathcal{T} = (\mathcal{V}, \mathcal{E})$: scenario tree with $T$ time periods. + +- $i \in \mathcal{V}$: nodes of the scenario tree (root node is node $0$). + +- $t(i)$: time period of node $i$. + +- $i^{-}$: unique parent of node $i$ (defined for $i \ne 0$). + +- $\mathcal{V}(i)$: set of all descendants of $i$, including $i$ itself. + +- $\mathcal{H}_r(i) = \{k \in \mathcal{V}(i) : 0 \le t(k) - t(i) \le r-1\}$: nodes used to express minimum up/down time constraints. + +- $p_i$: probability of the state represented by node $i$. + +- $q_i$: electricity price (\$/MWh) at node $i$. + +- $L, \ell$: minimum-up, minimum-down time (periods). + +- $\overline{C}, \underline{C}$: upper/lower generation limit (MW) when online. + +- $V^{+}, V^{-}$: ramp-up/ramp-down rate limit (MW/period). + +- $\bar{U}, \underline{U}$: start-up and shut-down cost (\$). + +- $f(\cdot)$: nondecreasing convex fuel cost function (approximated by a piecewise linear function). + +## Decision Variables + +- $y_i \in \{0,1\}$, $\forall i \in \mathcal{V}$: 1 if generator is online at node $i$. + +- $u_i \in \{0,1\}$, $\forall i \in \mathcal{V}\setminus\{0\}$: 1 if generator starts up at node $i$. + +- $x_i \ge 0$, $\forall i \in \mathcal{V}$: electricity generation amount (MW) at node $i$. + +Note: the original formulation also introduces $v_i$ (shut-down indicator), but $v_i$ is eliminated in the MSS formulation below via the relation $v_i = y_{i^{-}} - y_i + u_i$. + +For the JSON solution certificate, the maps for $x$, $y$, and $u$ use sparse +encoding. A node ID omitted from a map takes the value in the optional +`sparse_defaults` map for that variable (zero when the default is absent), and +an explicitly listed node overrides that default. This is only a serialization +convention and does not alter the full-vector formulation below. + +## Objective (MSS, with $v_i$ eliminated) + +$$\begin{align} +\max \quad & \sum_{i \in \mathcal{V}} p_i \Bigl( q_i x_i - \bigl(\bar{U}\, u_i + \underline{U}(y_{i^{-}} - y_i + u_i) + f(x_i)\bigr) \Bigr) \tag{1a} +\end{align}$$ + +## Constraints + +$$\begin{align} +y_i - y_{i^{-}} &\le y_k, + & \forall i \in \mathcal{V}\setminus\{0\},\; \forall k \in \mathcal{H}_L(i), \tag{1b}\\ +y_{i^{-}} - y_i &\le 1 - y_k, + & \forall i \in \mathcal{V}\setminus\{0\},\; \forall k \in \mathcal{H}_\ell(i), \tag{1c}\\ +y_i - y_{i^{-}} &\le u_i, + & \forall i \in \mathcal{V}\setminus\{0\}, \tag{1d}\\ +\underline{C}\, y_i \le x_i &\le \overline{C}\, y_i, + & \forall i \in \mathcal{V}, \tag{1f}\\ +x_i - x_{i^{-}} &\le V^{+}\, y_{i^{-}} + \overline{C}(1 - y_{i^{-}}), + & \forall i \in \mathcal{V}\setminus\{0\}, \tag{1g}\\ +x_{i^{-}} - x_i &\le V^{-}\, y_i + \overline{C}(1 - y_i), + & \forall i \in \mathcal{V}\setminus\{0\}, \tag{1h}\\ +u_i &\le \min\{y_i,\; 1 - y_{i^{-}}\}, + & \forall i \in \mathcal{V}\setminus\{0\}, \tag{2}\\ +y_i &\in \{0,1\},\; \forall i \in \mathcal{V};\quad u_i \in \{0,1\},\; \forall i \in \mathcal{V}\setminus\{0\}; \quad x_i \ge 0,\; \forall i \in \mathcal{V}. \notag +\end{align}$$ + +Constraints (1b)–(1c) enforce minimum-up/minimum-down time. Constraint (1d) links the turn-on variable $u_i$ to the transition of $y$. Constraints (1f) bound the generation level when online and fix $x_i = 0$ when offline. Constraints (1g)–(1h) impose ramp-up and ramp-down limits. Constraint (2) ensures $u_i = 1$ only when $y_{i^{-}} = 0$ and $y_i = 1$ (a genuine start-up), removing the spurious configurations left by (1b)–(1d) once $v$ has been substituted out. The feasible region is $$P = \bigl\{(x,y,u) \in \mathbb{R}^{|\mathcal{V}|} \times \mathbb{B}^{|\mathcal{V}|} + \times \mathbb{B}^{|\mathcal{V}|-1} + :\; (1b)\text{--}(1d),\; (1f)\text{--}(1h),\; (2)\bigr\}.$$ diff --git a/tasks/damcikurt2016/problem_description.txt b/tasks/damcikurt2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..6ff6e4454604ea7d77e3ec7522ba1f40eb6ac696 --- /dev/null +++ b/tasks/damcikurt2016/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +An independent power producer owns a single thermal generator and must decide, over a multi-period planning horizon, when to turn the generator on or off and how much electricity to produce at each point in time, in order to sell power into a real-time electricity market where prices are uncertain. The uncertain future prices are represented by a scenario tree: a rooted tree in which the root corresponds to the first time period, each non-root node has a unique parent, and each node may branch into multiple children representing different possible price realizations in the next period. Every node in the tree is associated with a time period, an electricity price in dollars per megawatt-hour, and a probability weight reflecting the likelihood of reaching that node from the root. The total number of time periods, the branching structure of the tree, and all node-level prices and probabilities are given as input. + +The generator is characterized by several physical parameters, all provided as input data: an upper generation limit and a lower generation limit, both in megawatts, that bound the output whenever the generator is running; a ramp-up rate and a ramp-down rate, both in megawatts per period, that limit how much generation can increase or decrease between a node and its parent; a minimum-up time stating the number of consecutive periods the generator must remain on after being started; a minimum-down time stating the number of consecutive periods the generator must remain off after being shut down; a fixed startup cost and a fixed shutdown cost, both in dollars, incurred each time the generator transitions from off to on or from on to off, respectively; and a fuel cost function that gives the fuel cost in dollars as a nondecreasing convex piecewise-linear function of the generation level in megawatts. + +At every node the producer must choose whether the generator is on or off and, if on, the generation level. At every non-root node the producer must also determine whether a startup occurs, meaning the generator was off at the parent node and is now on. A shutdown occurs at a non-root node whenever the generator was on at the parent node and is now off; the shutdown event is fully determined by the on/off statuses at the node and its parent together with the startup decision, specifically it equals the parent on/off status minus the current on/off status plus the startup indicator. + +The following operational rules govern these choices. If the generator starts up at a node, it must remain on at every descendant node reachable within a number of periods equal to the minimum-up time minus one, counting from the startup node. If the generator shuts down at a node, it must remain off at every descendant node reachable within a number of periods equal to the minimum-down time minus one, counting from the shutdown node. A startup can occur at a node only if the generator is on at that node and was off at its parent. The generation level at any node where the generator is off must be zero, and at any node where the generator is on it must lie between the lower and upper generation limits. Between any node and its parent, the increase in generation cannot exceed the ramp-up rate when the parent is on, but generation may jump freely from zero to any feasible level when the generator was previously off; symmetrically, the decrease in generation cannot exceed the ramp-down rate when the current node is on, but generation may drop freely to zero when the generator shuts down. Decisions at each node depend only on information revealed along the path from the root to that node, which is enforced by the tree structure itself. + +The goal is to maximize total expected profit across the scenario tree. Expected profit is the probability-weighted sum, over all nodes, of the revenue from selling electricity at that node's price minus the costs incurred at that node. The costs at each node comprise the startup cost if a startup occurs, the shutdown cost if a shutdown occurs, and the fuel cost of producing at the chosen generation level. diff --git a/tasks/damcikurt2016/solution_logger.py b/tasks/damcikurt2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/damcikurt2016/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/damcikurt2016/solution_schema.json b/tasks/damcikurt2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7e890a1ebe889e4db79414f9b37943f4962b3433 --- /dev/null +++ b/tasks/damcikurt2016/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Expected total profit (revenue from electricity sales minus fuel, startup, and shutdown costs) across the scenario tree.", + "x": " Sparse generation overrides by node.", + "y": " Sparse commitment overrides by node.", + "u": " Sparse startup overrides by non-root node.", + "sparse_defaults": " Values for omitted node IDs; each defaults to 0 when this field or key is absent." +} diff --git a/tasks/dayarian2019/feasibility_check.py b/tasks/dayarian2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e9724459acba601d510cacb6ff3e8d18e86bb5ef --- /dev/null +++ b/tasks/dayarian2019/feasibility_check.py @@ -0,0 +1,1044 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Caterer Production-Routing Problem (CPRP). + +Checks each hard constraint from the mathematical formulation in: + Dayarian & Desaulniers (2019), Transportation Science. + +Constraints (numbered as in the paper): + (2) Each customer visited exactly once + (3) Production capacity per subperiod + (4) Production due time linking + (5) Driver availability + (6) Employee availability + (7) Vehicle availability tracking + (8) Workstation availability tracking + (9) Route variable domain (binary) + (10) Shift variable domain (integer >= 0) + (11) Production quantity domain (>= 0) + (12) Vehicle count domain + (13) Workstation count domain + +Released certificate extension: + - ``customers`` is the actual visit order of every trip; + - ``production_staffing`` contains the integer production, setup, + workstation, and shift-start variables omitted by the earlier export; + - (16) recomputes the complete objective from those decisions. + +This makes the checker a verifier of a complete feasible witness instead of a +necessary-condition filter with a loose objective interval. +""" + +import argparse +import json +import math +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ( + 'objective_value', + 'production_schedule', + 'production_staffing', + 'routes', +) +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('production_staffing',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + violations = [] + violation_magnitudes = [] + + # Handle null / empty solutions + if solution.get("objective_value") is None: + violations.append("Solution has no objective value (no feasible solution found)") + violation_magnitudes.append({ + "constraint": 2, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + return { + "feasible": False, + "violated_constraints": [2], + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + params = instance["global_parameters"] + orders = instance["orders"] + products = instance["products"] + periods = instance["periods"] + subperiods = instance["subperiods"] + prod_windows = instance["production_windows"] + travel_time = instance["travel_time_matrix"] + + num_orders = instance["num_orders"] + num_products = instance["num_products"] + num_periods = params["num_periods"] + num_subperiods = params["num_subperiods"] + n_V = instance["num_vehicles"] + n_D = instance["num_drivers"] + n_W = instance["num_workstations"] + n_E = instance["num_production_employees"] + Q = instance["vehicle_capacity"] + sp_per_period = params["subperiods_per_period"] + tau_P = params["preparation_time_minutes"] + tau_S = params["service_time_minutes"] + m_T = params["max_trips_per_route"] + l_bar = params["max_shift_route_length_periods"] + l_D = params["min_paid_time_minutes"] + period_len = params["period_length_minutes"] + horizon_start = params["horizon_start_minutes"] + + routes = solution.get("routes", []) + prod_schedule = solution.get("production_schedule", []) + + violated_set = set() + + def record_violation(constraint_idx, msg, lhs, rhs, op="<="): + """Record a constraint violation.""" + if op == "<=": + raw = lhs - rhs + elif op == ">=": + raw = rhs - lhs + elif op == "=": + raw = abs(lhs - rhs) + else: + raw = abs(lhs - rhs) + normalizer = max(abs(rhs), EPS) + ratio = raw / normalizer + violated_set.add(constraint_idx) + violations.append(msg) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(raw), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ========================================================================= + # Build helper data structures from the solution + # ========================================================================= + + # Count visits per customer from routes + visit_count = defaultdict(int) + # Map: customer -> list of (route_idx, trip_idx, start_period) + customer_delivery = defaultdict(list) + + for route in routes: + for trip in route["trips"]: + for cust in trip["customers"]: + visit_count[cust] += 1 + customer_delivery[cust].append({ + "vehicle": route["vehicle"], + "trip_idx": trip["trip"], + "start_period": trip["start_period"], + }) + + # Build production quantities: q[i][p][u] = quantity + q = defaultdict(lambda: defaultdict(lambda: defaultdict(float))) + for entry in prod_schedule: + i = entry["order"] + p = entry["product"] + u = entry["subperiod"] + q[i][p][u] += entry["quantity"] + + # Valid subperiods per order per product + U_ip = {} + for i in range(num_orders): + U_ip[i] = {} + for p_str, p_data in prod_windows[str(i)].items(): + U_ip[i][int(p_str)] = set(p_data["valid_subperiod_ids"]) + + # U^p: union of U_i^p + U_p = {} + for p in range(num_products): + sp_set = set() + for i in range(num_orders): + if p in U_ip[i]: + sp_set.update(U_ip[i][p]) + U_p[p] = sorted(sp_set) + + # Orders active in each subperiod for each product + O_up = {} + for p in range(num_products): + for u in U_p[p]: + O_up[p, u] = [i for i in range(num_orders) + if p in U_ip[i] and u in U_ip[i][p]] + + # Parse the explicit production/shift certificate. The old release only + # stored q, which was insufficient to verify constraints (3), (6), (8), + # (10), and (13), or to bind the production part of the objective. + staffing = solution.get("production_staffing", {}) + if not isinstance(staffing, dict): + record_violation( + 10, + "production_staffing must be a JSON object", + 0.0, 1.0, "=" + ) + staffing = {} + + def _integer_value(value, label, upper_bound): + if isinstance(value, bool) or not isinstance(value, (int, float)): + record_violation(10, f"{label} must be an integer", 1.0, 0.0, "=") + return 0 + numeric = float(value) + if not math.isfinite(numeric) or abs(numeric - round(numeric)) > TOL: + record_violation( + 10, f"{label}={value!r} is not integral", numeric, round(numeric), "=" + ) + return 0 + integer = int(round(numeric)) + if integer < 0 or integer > upper_bound: + record_violation( + 10, + f"{label}={integer} is outside [0, {upper_bound}]", + integer, upper_bound if integer > upper_bound else 0, "<=" if integer > upper_bound else ">=" + ) + return integer + + def _indexed_staffing(field, value_key, expected_keys, upper_bound): + entries = staffing.get(field, []) + if not isinstance(entries, list): + record_violation(10, f"production_staffing.{field} must be a list", 0.0, 1.0, "=") + entries = [] + values = {} + for position, entry in enumerate(entries): + if not isinstance(entry, dict): + record_violation(10, f"{field}[{position}] must be an object", 0.0, 1.0, "=") + continue + p = entry.get("product") + u = entry.get("subperiod") + key = (p, u) + if ( + isinstance(p, bool) + or isinstance(u, bool) + or not isinstance(p, int) + or not isinstance(u, int) + or key not in expected_keys + ): + record_violation( + 10, + f"{field}[{position}] has invalid product/subperiod key {key!r}", + 1.0, 0.0, "=" + ) + continue + if key in values: + record_violation(10, f"{field} contains duplicate key {key}", 2.0, 1.0, "<=") + continue + values[key] = _integer_value( + entry.get(value_key), f"{field}{key}.{value_key}", upper_bound + ) + missing = expected_keys - set(values) + extra_count = len(set(values) - expected_keys) + if missing or extra_count: + record_violation( + 10, + f"{field} must contain each valid product/subperiod exactly once; " + f"missing={sorted(missing)[:12]}", + len(values), len(expected_keys), "=" + ) + return {key: values.get(key, 0) for key in expected_keys} + + expected_pu = {(p, u) for p in range(num_products) for u in U_p[p]} + f_staff = _indexed_staffing( + "employees_by_product_subperiod", "employees", expected_pu, n_E + ) + beta_staff = _indexed_staffing( + "setups_by_product_subperiod", "setups", expected_pu, n_E + ) + + def _period_vector(field, upper_bound): + raw = staffing.get(field, []) + if not isinstance(raw, list) or len(raw) != num_periods: + record_violation( + 10, + f"production_staffing.{field} must have exactly {num_periods} values", + len(raw) if isinstance(raw, list) else 0, num_periods, "=" + ) + raw = raw if isinstance(raw, list) else [] + return [ + _integer_value( + raw[t] if t < len(raw) else 0, + f"production_staffing.{field}[{t}]", + upper_bound, + ) + for t in range(num_periods) + ] + + w_staff = _period_vector("workstations_by_period", n_W) + alpha_staff = _period_vector("shift_starts_by_period", n_E) + + # Feasible trip start periods for each order + T_i = {} + for o in orders: + i = o["order_id"] + tw_end = o["time_window_end"] + T_i[i] = [] + for per in periods: + t = per["period_id"] + if per["start_time"] + tau_P + travel_time[0][i + 1] <= tw_end: + T_i[i].append(t) + + # Products with positive demand for each order + P_i = {} + for o in orders: + i = o["order_id"] + P_i[i] = [int(pk) for pk in o["demands"].keys() if o["demands"][pk] > 0] + + # ========================================================================= + # Constraint (2): Each customer visited exactly once + # sum_{r in R} a_{ir} theta_r = 1, for all i in O + # ========================================================================= + for i in range(num_orders): + lhs = visit_count[i] + rhs = 1 + if abs(lhs - rhs) > TOL: + record_violation( + 2, + f"Order {i} visited {lhs} time(s) instead of exactly 1", + lhs, rhs, "=" + ) + + # ========================================================================= + # Constraint (3): Production capacity per subperiod + # sum_{i in O_u^p} q_i^{pu} <= eta^p * sum_{s in S} f_s^{pu} psi_s + # + # The released certificate stores f^{pu}, so the checker verifies the + # actual assigned capacity rather than the former n_E upper bound. + # ========================================================================= + for p in range(num_products): + eta = products[p]["production_rate_per_subperiod"] + for u in U_p[p]: + orders_in_u = O_up[p, u] + total_prod = sum(q[i][p].get(u, 0.0) for i in orders_in_u) + capacity = eta * f_staff[p, u] + if total_prod - capacity > TOL: + record_violation( + 3, + f"Production capacity exceeded for product {p}, subperiod {u}: " + f"produced {total_prod:.4f} > capacity {capacity:.4f} " + f"(eta={eta} * f={f_staff[p, u]})", + total_prod, capacity, "<=" + ) + + # ========================================================================= + # Constraint (4): Production due time linking + # sum_{u in U_i^p, e^u <= b^t} q_i^{pu} >= d_i^p * g_{ir}^t * theta_r + # + # For the customer's actual delivery trip start period t*, all production + # for that order's product must be completed (subperiod end <= period start) + # before the trip departs. + # ========================================================================= + for i in range(num_orders): + if not customer_delivery[i]: + continue + for p in P_i[i]: + p_str = str(p) + demand = orders[i]["demands"][p_str] + valid_sps = prod_windows[str(i)][p_str]["valid_subperiod_ids"] + + # For each delivery of this order, check the due time linking + for deliv in customer_delivery[i]: + t = deliv["start_period"] + if t not in T_i[i]: + continue + period_start = periods[t]["start_time"] + # Sum production in subperiods where end_time <= period_start + prod_before = sum( + q[i][p].get(u, 0.0) + for u in valid_sps + if subperiods[u]["end_time"] <= period_start + ) + rhs_val = demand # g_{ir}^t * theta_r = 1 for the actual delivery + if rhs_val - prod_before > TOL: + record_violation( + 4, + f"Production due time violated for order {i}, product {p}, " + f"trip start period {t}: produced before departure = " + f"{prod_before:.4f} < demand {rhs_val}", + prod_before, rhs_val, ">=" + ) + + # ========================================================================= + # Constraint (5): Driver availability + # sum_{r in R} theta_r <= n_D + # ========================================================================= + num_routes_used = len(routes) + if num_routes_used - n_D > TOL: + record_violation( + 5, + f"Driver availability exceeded: {num_routes_used} routes used > " + f"{n_D} drivers available", + num_routes_used, n_D, "<=" + ) + + # ========================================================================= + # Constraint (6): Employee availability + # sum_{s in S} psi_s <= n_E + # + # Count the certified production and setup employees active in each + # subperiod, exactly as in the compact released model. + # ========================================================================= + for u in range(num_subperiods): + employees_needed = 0 + for p in range(num_products): + employees_needed += f_staff.get((p, u), 0) + for u_prime in range(max(0, u - params["setup_length_subperiods"] + 1), u + 1): + employees_needed += beta_staff.get((p, u_prime), 0) + if employees_needed - n_E > TOL: + record_violation( + 6, + f"Employee availability exceeded in subperiod {u}: " + f"need {employees_needed:.0f} employees > {n_E} available", + employees_needed, n_E, "<=" + ) + + # ========================================================================= + # Constraint (7): Vehicle availability tracking + # v^t in [0, n_V], tracking vehicles in use per period + # + # In each period, the number of vehicles simultaneously in use (on active + # trips) must not exceed n_V. + # ========================================================================= + for t_idx in range(num_periods): + per = periods[t_idx] + t_start = per["start_time"] + t_end = per["end_time"] + vehicles_in_use = 0 + for route in routes: + for trip in route["trips"]: + trip_depart = periods[trip["start_period"]]["start_time"] + # Estimate trip return: trip departs, goes to customers, returns + # A vehicle is "in use" from its route start to route end + # Conservatively, a vehicle is used during any period that overlaps + # with any of its trips + if trip_depart < t_end: + # Trip starts before this period ends + # Check if trip could still be active during this period + # The trip started at trip_depart, it needs at least prep time + # For a simpler check: count distinct vehicles active + vehicles_in_use += 1 + break # Count each vehicle only once per period + if vehicles_in_use - n_V > TOL: + record_violation( + 7, + f"Vehicle availability exceeded in period {t_idx}: " + f"{vehicles_in_use} vehicles in use > {n_V} available", + vehicles_in_use, n_V, "<=" + ) + + # ========================================================================= + # Constraint (8): Workstation availability tracking + # w^t in [0, n_W], tracking workstations in use per period + # + # In every subperiod, w^t must cover all certified production and setup + # employees, matching constraint (47) in the compact model. + # ========================================================================= + for t_idx in range(num_periods): + sp_start_id = t_idx * sp_per_period + sp_end_id = sp_start_id + sp_per_period + for u in range(sp_start_id, sp_end_id): + employees_active = 0 + for p in range(num_products): + employees_active += f_staff.get((p, u), 0) + for u_prime in range( + max(0, u - params["setup_length_subperiods"] + 1), u + 1 + ): + employees_active += beta_staff.get((p, u_prime), 0) + if employees_active - w_staff[t_idx] > TOL: + record_violation( + 8, + f"Certified workstations insufficient in period {t_idx}, " + f"subperiod {u}: need {employees_active}, " + f"reported w={w_staff[t_idx]}", + employees_active, w_staff[t_idx], "<=" + ) + + # ========================================================================= + # Constraint (9): Route variable domain - theta_r in {0,1} + # In compact solution, routes are either selected or not. + # Check route feasibility conditions from the paper: + # - Vehicle capacity per trip + # - Time windows + # - Max trips per route + # - Route duration <= l_bar periods + # + # ``customers`` is the certified visit order. Earlier artifacts exported + # only an unordered assignment set, which made exact route-cost checking + # impossible. + # ========================================================================= + + def simulate_trip(customer_sequence, trip_start_time): + """Simulate a trip with a given customer visit sequence. + Return feasibility, actual return time, the compact model's route-end + lower bound, travel time, and violations. + + The compact model defines route_end as at least each customer's + arrival + service + direct return-to-depot time, so that exact bound is + tracked separately from the physical return after the final customer. + Each violation is (message, lhs, rhs, op). + """ + trip_violations = [] + current_time = trip_start_time + tau_P + prev_loc = 0 # depot + travel_total = 0.0 + route_end_bounds = [] + + for c in customer_sequence: + c_loc = c + 1 + travel = travel_time[prev_loc][c_loc] + travel_total += travel + arrival = current_time + travel + tw_start = orders[c]["time_window_start"] + tw_end = orders[c]["time_window_end"] + service_start = max(arrival, tw_start) + + if service_start - tw_end > TOL: + trip_violations.append(( + f"Time window violated for order {c}: " + f"arrival {service_start:.2f} > window end {tw_end}", + service_start, tw_end, "<=" + )) + + current_time = service_start + tau_S + route_end_bounds.append( + service_start + tau_S + travel_time[c_loc][0] + ) + prev_loc = c_loc + + return_travel = travel_time[prev_loc][0] + travel_total += return_travel + trip_return_time = current_time + return_travel + model_end_bound = max(route_end_bounds, default=trip_start_time) + return ( + len(trip_violations) == 0, + trip_return_time, + model_end_bound, + travel_total, + trip_violations, + ) + + total_route_travel_time = 0.0 + total_driver_paid_time = 0.0 + + for route in routes: + v = route["vehicle"] + trip_list = route["trips"] + + # Check max trips per route + if len(trip_list) > m_T: + record_violation( + 9, + f"Route for vehicle {v} has {len(trip_list)} trips > " + f"max {m_T} trips per route", + len(trip_list), m_T, "<=" + ) + + trip_ids = [trip.get("trip") for trip in trip_list] + if trip_ids != list(range(len(trip_list))): + record_violation( + 9, + f"Route for vehicle {v} must list the active trip prefix in " + f"order; got trip ids {trip_ids}", + 1.0, 0.0, "=" + ) + + prev_trip_period = None + route_first_start = None + route_last_end = None + route_travel_time = 0.0 + + for trip in trip_list: + customers = trip["customers"] + start_period = trip["start_period"] + + if start_period < 0 or start_period >= num_periods: + record_violation( + 9, + f"Route vehicle {v}, trip {trip['trip']}: " + f"start_period {start_period} out of range [0, {num_periods-1}]", + start_period, num_periods - 1, "<=" + ) + continue + + trip_start_time = periods[start_period]["start_time"] + + route_first_start = ( + trip_start_time + if route_first_start is None + else min(route_first_start, trip_start_time) + ) + + # Vehicle capacity per trip + total_space = sum(orders[c]["space_requirement"] for c in customers) + if total_space - Q > TOL: + record_violation( + 9, + f"Vehicle capacity exceeded on route vehicle {v}, " + f"trip {trip['trip']}: space {total_space} > capacity {Q}", + total_space, Q, "<=" + ) + + # Verify the reported customer order and retain exact objective + # components from it. + _, _, model_end_bound, trip_travel_time, trip_viols = simulate_trip( + customers, trip_start_time + ) + + for msg, lhs, rhs, op in trip_viols: + record_violation( + 9, + f"Route vehicle {v}, trip {trip['trip']}: {msg}", + lhs, rhs, op + ) + + route_last_end = ( + model_end_bound + if route_last_end is None + else max(route_last_end, model_end_bound) + ) + route_travel_time += trip_travel_time + + # Multi-trip: In the period-discretized model, trip k+1 must start + # at a strictly later period than trip k. + if prev_trip_period is not None: + if start_period <= prev_trip_period: + record_violation( + 9, + f"Multi-trip period ordering violated on route vehicle {v}: " + f"trip {trip['trip']} starts at period {start_period} but " + f"previous trip starts at period {prev_trip_period} " + f"(must be strictly later)", + float(prev_trip_period), float(start_period), "<=" + ) + + prev_trip_period = start_period + + # Route duration + if route_first_start is not None and route_last_end is not None: + route_duration = route_last_end - route_first_start + max_duration = l_bar * period_len + if route_duration - max_duration > TOL: + record_violation( + 9, + f"Route duration exceeded for vehicle {v}: " + f"{route_duration:.2f} min > max {max_duration} min", + route_duration, max_duration, "<=" + ) + total_driver_paid_time += max(route_duration, l_D) + total_route_travel_time += route_travel_time + + # ========================================================================= + # Constraint (10): Shift variable domain - psi_s >= 0, integer + # Validate the compact f/beta/w/alpha certificate, including setup + # continuity, shift starts, minimum paid time, and employee availability. + # ========================================================================= + sigma = params["setup_length_subperiods"] + for p in range(num_products): + sps = U_p[p] + for idx, u in enumerate(sps): + prev_f = ( + f_staff[p, sps[idx - 1]] + if idx > 0 and sps[idx - 1] == u - 1 + else 0 + ) + prev_beta = beta_staff.get((p, u - sigma), 0) + setup_rhs = prev_beta if idx == 0 else prev_f + prev_beta + if f_staff[p, u] - setup_rhs > TOL: + record_violation( + 10, + f"Setup continuity violated for product {p}, subperiod {u}: " + f"f={f_staff[p, u]} > previous f + setup={setup_rhs}", + f_staff[p, u], setup_rhs, "<=" + ) + + for t in range(num_periods): + shift_start_rhs = w_staff[t] if t == 0 else w_staff[t] - w_staff[t - 1] + if shift_start_rhs - alpha_staff[t] > TOL: + record_violation( + 10, + f"Shift-start count insufficient in period {t}: " + f"alpha={alpha_staff[t]} < required {shift_start_rhs}", + alpha_staff[t], shift_start_rhs, ">=" + ) + + min_paid_periods = params["min_paid_time_subperiods"] // sp_per_period + for t in range(num_periods): + paid_floor = sum( + alpha_staff[t - j] + for j in range(1, min(t + 1, min_paid_periods) + 1) + if t - j >= 0 + ) + if paid_floor - w_staff[t] > TOL: + record_violation( + 10, + f"Minimum paid-time coverage violated in period {t}: " + f"w={w_staff[t]} < {paid_floor}", + w_staff[t], paid_floor, ">=" + ) + + total_shift_starts = sum(alpha_staff) + if total_shift_starts - n_E > TOL: + record_violation( + 6, + f"Employee availability exceeded: total shift starts " + f"{total_shift_starts} > {n_E}", + total_shift_starts, n_E, "<=" + ) + + # ========================================================================= + # Constraint (11): Production quantity domain - q_i^{pu} >= 0 + # Also check that production only occurs in valid subperiods. + # Variable domain: order, product, subperiod indices MUST be in range. + # ========================================================================= + for entry in prod_schedule: + i = entry["order"] + p = entry["product"] + u = entry["subperiod"] + qty = entry["quantity"] + + if qty < -TOL: + record_violation( + 11, + f"Negative production quantity for order {i}, product {p}, " + f"subperiod {u}: {qty:.4f}", + qty, 0.0, ">=" + ) + + # Domain checks: indices must be in range + if not (isinstance(i, int) and 0 <= i < num_orders): + record_violation( + 11, + f"Production schedule entry has out-of-range order id {i!r} " + f"(valid: 0..{num_orders - 1})", + float(i) if isinstance(i, (int, float)) else -1.0, + float(num_orders - 1), "<=" + ) + continue + if not (isinstance(p, int) and 0 <= p < num_products): + record_violation( + 11, + f"Production schedule entry has out-of-range product id {p!r} " + f"(valid: 0..{num_products - 1})", + float(p) if isinstance(p, (int, float)) else -1.0, + float(num_products - 1), "<=" + ) + continue + if not (isinstance(u, int) and 0 <= u < num_subperiods): + record_violation( + 11, + f"Production schedule entry has out-of-range subperiod id {u!r} " + f"(valid: 0..{num_subperiods - 1})", + float(u) if isinstance(u, (int, float)) else -1.0, + float(num_subperiods - 1), "<=" + ) + continue + + # Check valid subperiod + if p in U_ip.get(i, {}): + if u not in U_ip[i][p]: + record_violation( + 11, + f"Production for order {i}, product {p} in invalid " + f"subperiod {u} (not in valid set)", + 1.0, 0.0, "<=" + ) + else: + # i is in range and p is in range, but order i doesn't demand product p + record_violation( + 11, + f"Production for order {i}, product {p} but order " + f"has no demand for this product", + 1.0, 0.0, "<=" + ) + + # ========================================================================= + # Constraint (12): Vehicle count domain - 0 <= v^t <= n_V, integer + # Count maximum simultaneous vehicles in use across all periods. + # A vehicle is in use from its first trip start to its last trip return. + # ========================================================================= + vehicles_used_set = set() + for route in routes: + vehicles_used_set.add(route["vehicle"]) + + total_vehicles = len(vehicles_used_set) + if total_vehicles - n_V > TOL: + record_violation( + 12, + f"Total vehicles used ({total_vehicles}) exceeds available ({n_V})", + total_vehicles, n_V, "<=" + ) + + # Check vehicle IDs are valid + for vid in vehicles_used_set: + if vid < 0 or vid >= n_V: + record_violation( + 12, + f"Vehicle ID {vid} out of valid range [0, {n_V - 1}]", + vid, n_V - 1, "<=" + ) + + # ========================================================================= + # Constraint (13): Workstation count domain - 0 <= w^t <= n_W, integer + # Bounds and integrality are enforced while parsing the certificate; the + # coverage inequalities were checked under constraint (8). + # ========================================================================= + # (Already covered in constraint 8 checking) + + # ========================================================================= + # Additional check: Total production meets demand (Constraint 15, redundant + # but we check it as it is a necessary condition for feasibility) + # ========================================================================= + for i in range(num_orders): + for p in P_i[i]: + p_str = str(p) + demand = orders[i]["demands"][p_str] + valid_sps = prod_windows[str(i)][p_str]["valid_subperiod_ids"] + total_produced = sum(q[i][p].get(u, 0.0) for u in valid_sps) + if demand - total_produced > TOL: + # This is implied by constraint (4) but we report as constraint 4 + # since insufficient total production means due-time linking fails + record_violation( + 4, + f"Total production insufficient for order {i}, product {p}: " + f"produced {total_produced:.4f} < demand {demand}", + total_produced, demand, ">=" + ) + + # ========================================================================= + # Constraint (16): exact objective-value consistency + # + # Objective (1): driver salary + vehicle operating cost + employee salary + # + setup cost. Every component is now derived from the explicit route + # order and production staffing certificate. + # ========================================================================= + gamma_D = float(params["driver_salary_per_minute"]) + gamma_E = float(params["employee_salary_per_subperiod"]) + gamma_S = float(params["setup_cost"]) + gamma_V = float(params["vehicle_operating_cost_per_minute"]) + driver_cost = gamma_D * total_driver_paid_time + vehicle_cost = gamma_V * total_route_travel_time + employee_cost = gamma_E * sp_per_period * sum(w_staff) + setup_cost = gamma_S * sum(beta_staff.values()) + recomputed_obj = driver_cost + vehicle_cost + employee_cost + setup_cost + reported = float(solution["objective_value"]) + objective_tolerance = max(1e-4, 1e-6 * max(1.0, abs(recomputed_obj))) + if abs(reported - recomputed_obj) > objective_tolerance: + record_violation( + 16, + f"Objective consistency violated: reported={reported:.10g}, " + f"recomputed={recomputed_obj:.10g} " + f"(driver={driver_cost:.10g}, vehicle={vehicle_cost:.10g}, " + f"employee={employee_cost:.10g}, setup={setup_cost:.10g}, " + f"tol={objective_tolerance:.3g})", + reported, recomputed_obj, "=" + ) + + # ========================================================================= + # Compile results + # ========================================================================= + violated_constraints = sorted(violated_set) + feasible = len(violated_constraints) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the CPRP model") + 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) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + print(f"Result: {status}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + print(f"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/dayarian2019/gurobi_code.py b/tasks/dayarian2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..376dfc3eddb459d4120fe9cb4978cd8c4880802e --- /dev/null +++ b/tasks/dayarian2019/gurobi_code.py @@ -0,0 +1,818 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Caterer Production-Routing Problem (CPRP). + +Paper: "A Branch-Price-and-Cut Algorithm for a Production-Routing Problem + with Short-Life-Span Products" +Authors: Iman Dayarian, Guy Desaulniers (2019), Transportation Science. + +This implements the mathematical model (1)-(15) from the paper using a compact +MIP formulation. Since the original model uses exponentially large sets R (routes) +and S (shifts) that are typically handled via column generation, this compact +formulation directly models routing and production scheduling decisions with +Gurobi as the solver. + +INFERRED ASSUMPTION: Since enumerating all feasible routes R and shifts S is +intractable, we use a compact vehicle routing + production scheduling formulation +that captures the same constraints. The routing uses arc-based decision variables +and the production scheduling uses direct assignment variables. This is equivalent +to the set-partitioning formulation (1)-(15) but amenable to direct MIP solving. +""" + +import argparse +import json +import math +import sys +import itertools +from gurobipy import Model, GRB, quicksum +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_cprp(instance, time_limit): + # ========================================================================= + # Extract instance data + # ========================================================================= + params = instance["global_parameters"] + orders = instance["orders"] + products = instance["products"] + periods = instance["periods"] + subperiods = instance["subperiods"] + prod_windows = instance["production_windows"] + travel_time = instance["travel_time_matrix"] + depot = instance["depot"] + + num_orders = instance["num_orders"] + num_products = instance["num_products"] + num_periods = params["num_periods"] + num_subperiods = params["num_subperiods"] + n_V = instance["num_vehicles"] + n_D = instance["num_drivers"] + n_W = instance["num_workstations"] + n_E = instance["num_production_employees"] + Q = instance["vehicle_capacity"] + period_len = params["period_length_minutes"] + subperiod_len = params["subperiod_length_minutes"] + sp_per_period = params["subperiods_per_period"] + tau_P = params["preparation_time_minutes"] + tau_S = params["service_time_minutes"] + m_T = params["max_trips_per_route"] + l_bar = params["max_shift_route_length_periods"] + l_underline_sp = params["min_paid_time_subperiods"] + l_D = params["min_paid_time_minutes"] + gamma_D = params["driver_salary_per_minute"] + gamma_E = params["employee_salary_per_subperiod"] + gamma_S = params["setup_cost"] + gamma_V = params["vehicle_operating_cost_per_minute"] + sigma = params["setup_length_subperiods"] + horizon_start = params["horizon_start_minutes"] + horizon_end = params["horizon_end_minutes"] + + # Travel time matrix: index 0 = depot, index 1..num_orders = orders + # (already provided in instance as a (num_orders+1) x (num_orders+1) matrix + # where row/col 0 = depot) + # Actually the travel_time_matrix is (num_orders+1) x (num_orders+1) but let's verify + # The matrix is indexed: 0=depot, then orders 0..14 -> matrix indices 0..15 + # But from the JSON it seems index 0 in the matrix IS the depot + # Let's verify: the matrix has 16 rows for 15 orders + depot + n_locs = len(travel_time) # Should be num_orders + 1 + + # Feasible trip start periods for each order + # T_i: periods at the beginning of which a trip can start to deliver order i + # within its time window + T_i = {} + for o in orders: + i = o["order_id"] + tw_start = o["time_window_start"] + tw_end = o["time_window_end"] + feasible_periods = [] + for p_obj in periods: + t = p_obj["period_id"] + trip_start_time = p_obj["start_time"] + # The trip starts at beginning of period t, then has preparation time + # tau_P, then travels to customer. Earliest arrival at customer i: + # trip_start_time + tau_P + h_{depot, i+1} (matrix index i+1 for order i) + earliest_arrival = trip_start_time + tau_P + travel_time[0][i + 1] + # Must arrive within time window + if earliest_arrival <= tw_end: + # Also, the trip must be completable: customer service + return + # must not exceed the horizon + feasible_periods.append(t) + T_i[i] = feasible_periods + + # ========================================================================= + # Build compact MIP model + # ========================================================================= + model = Model("CPRP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ----- ROUTING VARIABLES ----- + # We model routing using multi-trip vehicle routes. + # For tractability with Gurobi, we use a trip-based formulation: + # Each trip k (k=1..m_T) of each vehicle v starts at a period, visits a + # sequence of customers, and returns to depot. + # + # INFERRED ASSUMPTION: We model each vehicle-trip as an independent unit + # with arc-flow variables. A route is a sequence of up to m_T trips by + # the same driver/vehicle. + + # Decision: which vehicle serves which trip starting when, visiting which customers + # For simplicity with 15 orders: use assignment + sequencing variables + + # x[v][k][t][i][j] = 1 if vehicle v, trip k, starting period t, travels + # from location i to location j. This is too many variables. + # + # INFERRED ASSUMPTION: Since this is a small instance (15 orders), we use + # a simplified trip-assignment model where we decide: + # - y[i,v,k]: order i is served by vehicle v in trip k + # - trip_start[v,k,t]: vehicle v trip k starts at period t + # - For sequencing within a trip: we use Miller-Tucker-Zemlin (MTZ) subtour + # elimination + + vehicles = range(n_V) + trips = range(m_T) + + # y[i,v,k] = 1 if order i is assigned to vehicle v, trip k + y = {} + for i in range(num_orders): + for v in vehicles: + for k in trips: + y[i, v, k] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}_{v}_{k}") + + # trip_start[v,k,t] = 1 if vehicle v trip k starts at period t + trip_start = {} + for v in vehicles: + for k in trips: + for t in range(num_periods): + trip_start[v, k, t] = model.addVar(vtype=GRB.BINARY, + name=f"ts_{v}_{k}_{t}") + + # trip_active[v,k] = 1 if vehicle v trip k is used + trip_active = {} + for v in vehicles: + for k in trips: + trip_active[v, k] = model.addVar(vtype=GRB.BINARY, + name=f"ta_{v}_{k}") + + # driver_used[v] = 1 if vehicle/driver v is used + driver_used = {} + for v in vehicles: + driver_used[v] = model.addVar(vtype=GRB.BINARY, name=f"du_{v}") + + # Arc variables for sequencing: x_arc[v,k,i,j] = 1 if in trip (v,k), + # travel from i to j. Locations: 0=depot, 1..num_orders = customers + x_arc = {} + locs = range(n_locs) # 0=depot, 1..num_orders + for v in vehicles: + for k in trips: + for i_loc in locs: + for j_loc in locs: + if i_loc != j_loc: + x_arc[v, k, i_loc, j_loc] = model.addVar( + vtype=GRB.BINARY, + name=f"x_{v}_{k}_{i_loc}_{j_loc}") + + # MTZ position variable u_pos[v,k,i] for subtour elimination + u_pos = {} + for v in vehicles: + for k in trips: + for i in range(1, n_locs): # customers only + u_pos[v, k, i] = model.addVar(vtype=GRB.CONTINUOUS, lb=1, + ub=num_orders, + name=f"u_{v}_{k}_{i}") + + # Trip travel time and duration variables + trip_travel_time = {} + trip_end_period = {} # the period at which trip ends (vehicle returns to depot) + for v in vehicles: + for k in trips: + trip_travel_time[v, k] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"ttt_{v}_{k}") + + # Route duration for driver salary computation + route_start_time = {} + route_end_time = {} + route_duration = {} + for v in vehicles: + route_start_time[v] = model.addVar(vtype=GRB.CONTINUOUS, lb=horizon_start, + ub=horizon_end, name=f"rst_{v}") + route_end_time[v] = model.addVar(vtype=GRB.CONTINUOUS, lb=horizon_start, + ub=horizon_end, name=f"ret_{v}") + route_duration[v] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"rd_{v}") + + # Driver paid time (max of route_duration and l_D) + driver_paid = {} + for v in vehicles: + driver_paid[v] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"dp_{v}") + + # ----- PRODUCTION VARIABLES ----- + # q[i,p,u]: units of product p produced in subperiod u for order i + q = {} + for i in range(num_orders): + for p_str, p_data in prod_windows[str(i)].items(): + p = int(p_str) + for u in p_data["valid_subperiod_ids"]: + q[i, p, u] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"q_{i}_{p}_{u}") + + # f[p,u]: number of employees assigned to product p in subperiod u + f_var = {} + all_subperiod_ids_per_product = {} + for p in range(num_products): + sp_set = set() + for i in range(num_orders): + if str(p) in prod_windows[str(i)]: + sp_set.update(prod_windows[str(i)][str(p)]["valid_subperiod_ids"]) + all_subperiod_ids_per_product[p] = sorted(sp_set) + for u in all_subperiod_ids_per_product[p]: + f_var[p, u] = model.addVar(vtype=GRB.INTEGER, lb=0, ub=n_E, + name=f"f_{p}_{u}") + + # w[t]: number of workstations used in period t + w = {} + for t in range(num_periods): + w[t] = model.addVar(vtype=GRB.INTEGER, lb=0, ub=n_W, name=f"w_{t}") + + # Number of employees starting shift at period t + alpha = {} + for t in range(num_periods): + alpha[t] = model.addVar(vtype=GRB.INTEGER, lb=0, ub=n_E, + name=f"alpha_{t}") + + # beta[p,u]: employees starting setup for product p in subperiod u + beta = {} + for p in range(num_products): + for u in all_subperiod_ids_per_product[p]: + beta[p, u] = model.addVar(vtype=GRB.INTEGER, lb=0, ub=n_E, + name=f"beta_{p}_{u}") + + # Total vehicle travel time for cost + total_vehicle_travel = {} + for v in vehicles: + total_vehicle_travel[v] = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name=f"tvt_{v}") + + # Number of setups for production cost + total_setups = model.addVar(vtype=GRB.CONTINUOUS, lb=0, name="total_setups") + + # Employee paid subperiods + total_employee_cost = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + name="total_emp_cost") + + model.update() + + # ========================================================================= + # CONSTRAINTS + # ========================================================================= + + # --- (2) Each customer visited exactly once --- + for i in range(num_orders): + model.addConstr( + quicksum(y[i, v, k] for v in vehicles for k in trips) == 1, + name=f"visit_{i}") + + # --- Link y to arc variables --- + for v in vehicles: + for k in trips: + # Customer i (matrix index i+1) is visited iff y[i,v,k]=1 + for i in range(num_orders): + i_loc = i + 1 + # If y[i,v,k]=1, then exactly one arc enters and one leaves i_loc + model.addConstr( + quicksum(x_arc[v, k, j_loc, i_loc] + for j_loc in locs if j_loc != i_loc) == y[i, v, k], + name=f"in_{v}_{k}_{i}") + model.addConstr( + quicksum(x_arc[v, k, i_loc, j_loc] + for j_loc in locs if j_loc != i_loc) == y[i, v, k], + name=f"out_{v}_{k}_{i}") + + # Depot: trip starts and ends at depot (loc 0) + model.addConstr( + quicksum(x_arc[v, k, 0, j_loc] for j_loc in range(1, n_locs)) == trip_active[v, k], + name=f"depot_out_{v}_{k}") + model.addConstr( + quicksum(x_arc[v, k, j_loc, 0] for j_loc in range(1, n_locs)) == trip_active[v, k], + name=f"depot_in_{v}_{k}") + + # --- Link trip_active to y --- + for v in vehicles: + for k in trips: + model.addConstr( + trip_active[v, k] <= + quicksum(y[i, v, k] for i in range(num_orders)), + name=f"ta_lb_{v}_{k}") + for i in range(num_orders): + model.addConstr(y[i, v, k] <= trip_active[v, k], + name=f"ta_ub_{v}_{k}_{i}") + + # --- MTZ subtour elimination --- + for v in vehicles: + for k in trips: + for i_loc in range(1, n_locs): + for j_loc in range(1, n_locs): + if i_loc != j_loc: + model.addConstr( + u_pos[v, k, i_loc] - u_pos[v, k, j_loc] + + num_orders * x_arc[v, k, i_loc, j_loc] <= num_orders - 1, + name=f"mtz_{v}_{k}_{i_loc}_{j_loc}") + + # --- Vehicle capacity per trip --- + for v in vehicles: + for k in trips: + model.addConstr( + quicksum(orders[i]["space_requirement"] * y[i, v, k] + for i in range(num_orders)) <= Q, + name=f"cap_{v}_{k}") + + # --- Trip start period assignment --- + for v in vehicles: + for k in trips: + model.addConstr( + quicksum(trip_start[v, k, t] for t in range(num_periods)) == trip_active[v, k], + name=f"ts_assign_{v}_{k}") + + # --- Time window constraints --- + # For each order i assigned to trip (v,k) starting at period t, + # the arrival time must be within [omega_i, bar_omega_i] + # We use a big-M approach + M_time = horizon_end + 500 # Large constant + + # Arrival time at each customer in each trip + arr_time = {} + for v in vehicles: + for k in trips: + for i in range(num_orders): + arr_time[v, k, i] = model.addVar(vtype=GRB.CONTINUOUS, + lb=0, ub=M_time, + name=f"arr_{v}_{k}_{i}") + + model.update() + + # If order i is served by trip (v,k), arrival time is bounded by time windows + for v in vehicles: + for k in trips: + for i in range(num_orders): + tw_s = orders[i]["time_window_start"] + tw_e = orders[i]["time_window_end"] + # arr_time >= tw_s if y=1 + model.addConstr( + arr_time[v, k, i] >= tw_s - M_time * (1 - y[i, v, k]), + name=f"tw_lo_{v}_{k}_{i}") + # arr_time <= tw_e if y=1 + model.addConstr( + arr_time[v, k, i] <= tw_e + M_time * (1 - y[i, v, k]), + name=f"tw_hi_{v}_{k}_{i}") + + # Arrival time consistency with arc-based travel + # If arc (depot -> i) used: arr >= trip_start_time + tau_P + h[0][i+1] + for v in vehicles: + for k in trips: + # Trip start time + # Inactive trip slots have all trip_start binaries equal to zero, + # so their linked time must be allowed to equal zero. Active + # slots still take an actual period start (>= horizon_start). + trip_st_time = model.addVar(vtype=GRB.CONTINUOUS, lb=0, + ub=horizon_end, name=f"tst_{v}_{k}") + model.addConstr( + trip_st_time == quicksum( + periods[t]["start_time"] * trip_start[v, k, t] + for t in range(num_periods)), + name=f"tst_link_{v}_{k}") + + for i in range(num_orders): + i_loc = i + 1 + # From depot to customer i + model.addConstr( + arr_time[v, k, i] >= trip_st_time + tau_P + travel_time[0][i_loc] + - M_time * (1 - x_arc[v, k, 0, i_loc]), + name=f"arr_dep_{v}_{k}_{i}") + + # From customer j to customer i + for j in range(num_orders): + if j != i: + j_loc = j + 1 + model.addConstr( + arr_time[v, k, i] >= + arr_time[v, k, j] + tau_S + travel_time[j_loc][i_loc] + - M_time * (1 - x_arc[v, k, j_loc, i_loc]), + name=f"arr_seq_{v}_{k}_{j}_{i}") + + # --- Trip travel time --- + for v in vehicles: + for k in trips: + model.addConstr( + trip_travel_time[v, k] == + quicksum(travel_time[i_loc][j_loc] * x_arc[v, k, i_loc, j_loc] + for i_loc in locs for j_loc in locs + if i_loc != j_loc), + name=f"ttt_def_{v}_{k}") + + # --- Total vehicle travel time --- + for v in vehicles: + model.addConstr( + total_vehicle_travel[v] == + quicksum(trip_travel_time[v, k] for k in trips), + name=f"tvt_def_{v}") + + # --- Multi-trip sequencing: trip k+1 starts after trip k ends --- + # INFERRED ASSUMPTION: Trip ordering is enforced within the same vehicle. + # Trip k must end before trip k+1 starts. + for v in vehicles: + for k in range(m_T - 1): + # If both trips active, trip k+1 start period > trip k start period + # (simplified: enforce ordering by period) + for t1 in range(num_periods): + for t2 in range(num_periods): + if t2 <= t1: + model.addConstr( + trip_start[v, k, t1] + trip_start[v, k + 1, t2] <= 1, + name=f"seq_{v}_{k}_{t1}_{t2}") + + # --- Trip k+1 can only be active if trip k is active --- + for v in vehicles: + for k in range(m_T - 1): + model.addConstr(trip_active[v, k + 1] <= trip_active[v, k], + name=f"trip_order_{v}_{k}") + + # --- Driver usage --- + for v in vehicles: + model.addConstr( + driver_used[v] >= trip_active[v, 0], + name=f"du_link_{v}") + model.addConstr( + driver_used[v] <= quicksum(trip_active[v, k] for k in trips), + name=f"du_ub_{v}") + + # --- (5) Driver availability --- + model.addConstr( + quicksum(driver_used[v] for v in vehicles) <= n_D, + name="driver_avail") + + # --- Route duration for driver salary --- + # Route start = start of first trip, route end = return time of last trip + for v in vehicles: + for k in trips: + for t in range(num_periods): + model.addConstr( + route_start_time[v] <= periods[t]["start_time"] + + M_time * (1 - trip_start[v, k, t]), + name=f"rst_ub_{v}_{k}_{t}") + + # Route end: after last customer served + service + return to depot + # We approximate: route_end >= arr[last customer] + service + return + for k in trips: + for i in range(num_orders): + i_loc = i + 1 + model.addConstr( + route_end_time[v] >= arr_time[v, k, i] + tau_S + + travel_time[i_loc][0] - M_time * (1 - y[i, v, k]), + name=f"ret_lb_{v}_{k}_{i}") + + model.addConstr( + route_duration[v] >= route_end_time[v] - route_start_time[v], + name=f"rd_def_{v}") + + # Paid time is max of duration and l_D + model.addConstr(driver_paid[v] >= route_duration[v], + name=f"dp_dur_{v}") + model.addConstr(driver_paid[v] >= l_D * driver_used[v], + name=f"dp_min_{v}") + + # --- Route duration <= l_bar periods --- + for v in vehicles: + model.addConstr( + route_duration[v] <= l_bar * period_len, + name=f"max_route_dur_{v}") + + # ========================================================================= + # PRODUCTION CONSTRAINTS + # ========================================================================= + + # --- (3) Production capacity per subperiod --- + for p in range(num_products): + eta = products[p]["production_rate_per_subperiod"] + for u in all_subperiod_ids_per_product[p]: + orders_in_u = [i for i in range(num_orders) + if (i, p, u) in q] + if orders_in_u: + model.addConstr( + quicksum(q[i, p, u] for i in orders_in_u) <= + eta * f_var[p, u], + name=f"prod_cap_{p}_{u}") + + # --- (4) Production due time linking --- + # For each order i, product p, and feasible trip start period t: + # production of d_i^p must be complete by time b^t if the order is + # delivered on a trip starting at period t + for i in range(num_orders): + for p_str, p_data in prod_windows[str(i)].items(): + p = int(p_str) + demand = orders[i]["demands"][p_str] + valid_sps = p_data["valid_subperiod_ids"] + + for t in T_i[i]: + period_start = periods[t]["start_time"] + # Subperiods u with e^u <= b^t (production must be done before + # trip starts) + eligible_sps = [u for u in valid_sps + if subperiods[u]["end_time"] <= period_start] + # Constraint (4): even when eligible_sps is empty, the + # constraint must be added. An empty LHS (= 0) forces the + # RHS to 0, preventing delivery at period t when no + # production can be completed before that period. + lhs = (quicksum(q[i, p, u] for u in eligible_sps) + if eligible_sps else 0) + model.addConstr( + lhs >= + demand * quicksum( + y[i, v, k] * trip_start[v, k, t] + for v in vehicles for k in trips), + name=f"due_{i}_{p}_{t}") + + # --- (15) Total production requirement --- + for i in range(num_orders): + for p_str, p_data in prod_windows[str(i)].items(): + p = int(p_str) + demand = orders[i]["demands"][p_str] + valid_sps = p_data["valid_subperiod_ids"] + model.addConstr( + quicksum(q[i, p, u] for u in valid_sps) >= demand, + name=f"total_prod_{i}_{p}") + + # --- Production setup constraints --- + # (46) f^{pu} <= beta^{p,u-sigma} + f^{p,u-1} + for p in range(num_products): + sps = all_subperiod_ids_per_product[p] + for idx, u in enumerate(sps): + prev_f = f_var[p, sps[idx - 1]] if idx > 0 and sps[idx - 1] == u - 1 else 0 + prev_beta_u = u - sigma + prev_beta = beta[p, prev_beta_u] if (p, prev_beta_u) in beta else 0 + if idx == 0: + # First subperiod: need setup + model.addConstr(f_var[p, u] <= (beta[p, u - sigma] + if (p, u - sigma) in beta else 0), + name=f"setup_first_{p}_{u}") + else: + model.addConstr(f_var[p, u] <= prev_f + prev_beta, + name=f"setup_{p}_{u}") + + # --- (47) Workstation counting: employees in each subperiod --- + # w^{t(u)} >= sum_p (f^{pu} + sum_{u' in [u-sigma+1,u]} beta^{pu'}) + for t in range(num_periods): + sp_start = t * sp_per_period + sp_end = sp_start + sp_per_period + for u in range(sp_start, sp_end): + emp_count = [] + for p in range(num_products): + if (p, u) in f_var: + emp_count.append(f_var[p, u]) + for u_prime in range(max(0, u - sigma + 1), u + 1): + if (p, u_prime) in beta: + emp_count.append(beta[p, u_prime]) + if emp_count: + model.addConstr(w[t] >= quicksum(emp_count), + name=f"ws_count_{t}_{u}") + + # --- (48) Shift start counting --- + for t in range(num_periods): + if t == 0: + model.addConstr(alpha[t] >= w[t], name=f"shift_start_{t}") + else: + model.addConstr(alpha[t] >= w[t] - w[t - 1], + name=f"shift_start_{t}") + + # --- (49) Minimum paid time --- + min_paid_periods = l_underline_sp // sp_per_period # = 6 periods + for t in range(num_periods): + model.addConstr( + w[t] >= quicksum(alpha[t - j] + for j in range(1, min(t + 1, min_paid_periods) + 1) + if t - j >= 0), + name=f"min_paid_{t}") + + # --- (50) Employee availability --- + model.addConstr( + quicksum(alpha[t] for t in range(num_periods)) <= n_E, + name="emp_avail") + + # --- Per-subperiod employee capacity --- + # In each subperiod u, the total employees producing (f_var[p,u]) plus + # employees performing setups (beta[p,u']) must not exceed n_E. + for u in range(num_subperiods): + emp_terms = [] + for p in range(num_products): + if (p, u) in f_var: + emp_terms.append(f_var[p, u]) + for u_prime in range(max(0, u - sigma + 1), u + 1): + if (p, u_prime) in beta: + emp_terms.append(beta[p, u_prime]) + if emp_terms: + model.addConstr(quicksum(emp_terms) <= n_E, + name=f"emp_cap_sp_{u}") + + # --- Total setups --- + model.addConstr( + total_setups == quicksum(beta[p, u] + for p in range(num_products) + for u in all_subperiod_ids_per_product[p] + if (p, u) in beta), + name="total_setups_def") + + # --- Employee cost: sum of gamma_E * n_SP * w^t --- + # INFERRED ASSUMPTION: We approximate shift costs using the compact + # formulation: total employee salary = gamma_E * sum_t (n_SP * w^t) + # This counts the total employee-subperiods of paid time. + model.addConstr( + total_employee_cost == gamma_E * quicksum( + sp_per_period * w[t] for t in range(num_periods)), + name="emp_cost_def") + + # ========================================================================= + # OBJECTIVE FUNCTION (1) + # ========================================================================= + # Route costs: driver salary + vehicle operational cost + # Shift costs: employee salary + setup costs + obj = ( + # Driver salary: gamma_D * max(route_duration, l_D) for each used driver + quicksum(gamma_D * driver_paid[v] for v in vehicles) + + # Vehicle operating cost: gamma_V * total travel time + quicksum(gamma_V * total_vehicle_travel[v] for v in vehicles) + + # Employee salary + total_employee_cost + + # Setup costs + gamma_S * total_setups + ) + + model.setObjective(obj, GRB.MINIMIZE) + + # ========================================================================= + # SOLVE + # ========================================================================= + model.optimize() + + # ========================================================================= + # EXTRACT SOLUTION + # ========================================================================= + solution = { + "instance_id": instance.get("instance_id", 0), + "instance_label": instance.get("instance_label", ""), + "solver": "Gurobi", + "status": model.Status, + "objective_value": None, + "routes": [], + "production_schedule": [], + "production_staffing": { + "employees_by_product_subperiod": [], + "setups_by_product_subperiod": [], + "workstations_by_period": [], + "shift_starts_by_period": [], + }, + } + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["best_bound"] = model.ObjBound if hasattr(model, 'ObjBound') else None + solution["gap"] = model.MIPGap if hasattr(model, 'MIPGap') else None + + # Extract routes + for v in vehicles: + if driver_used[v].X > 0.5: + route_info = {"vehicle": v, "trips": []} + for k in trips: + if trip_active[v, k].X > 0.5: + trip_info = {"trip": k, "customers": [], "start_period": None} + for t in range(num_periods): + if trip_start[v, k, t].X > 0.5: + trip_info["start_period"] = t + # Serialize the actual arc order, not the former + # unordered assignment set. The checker needs this + # order to recompute travel and paid-time costs. + successor = {} + for i_loc in locs: + for j_loc in locs: + if ( + i_loc != j_loc + and x_arc[v, k, i_loc, j_loc].X > 0.5 + ): + successor[i_loc] = j_loc + current = 0 + seen = set() + while current in successor: + nxt = successor[current] + if nxt == 0: + break + if nxt in seen: + break + seen.add(nxt) + trip_info["customers"].append(nxt - 1) + current = nxt + assigned = { + i for i in range(num_orders) if y[i, v, k].X > 0.5 + } + if set(trip_info["customers"]) != assigned: + raise RuntimeError( + f"could not reconstruct route order for vehicle {v}, trip {k}" + ) + route_info["trips"].append(trip_info) + solution["routes"].append(route_info) + + # Extract production schedule + for i in range(num_orders): + for p_str, p_data in prod_windows[str(i)].items(): + p = int(p_str) + for u in p_data["valid_subperiod_ids"]: + # Do not drop small positive split-production terms. A + # single order/product demand can be distributed over + # many subperiods, so filtering at 1e-2 can remove enough + # mass to make an otherwise feasible solver incumbent fail + # the released checker. + if (i, p, u) in q and q[i, p, u].X > 1e-9: + solution["production_schedule"].append({ + "order": i, + "product": p, + "subperiod": u, + # The checker binds production to exact integer + # demand and derives employee lower bounds from + # these quantities. Four-decimal serialization can + # turn a solver-feasible 4.0 into 3.9946 after many + # split terms, so retain full double precision. + "quantity": float(q[i, p, u].X) + }) + + # Export the integer shift/staffing decisions required to verify the + # full production contract and exact objective value. + staffing = solution["production_staffing"] + for p in range(num_products): + for u in all_subperiod_ids_per_product[p]: + staffing["employees_by_product_subperiod"].append({ + "product": p, + "subperiod": u, + "employees": int(round(f_var[p, u].X)), + }) + staffing["setups_by_product_subperiod"].append({ + "product": p, + "subperiod": u, + "setups": int(round(beta[p, u].X)), + }) + staffing["workstations_by_period"] = [ + int(round(w[t].X)) for t in range(num_periods) + ] + staffing["shift_starts_by_period"] = [ + int(round(alpha[t].X)) for t in range(num_periods) + ] + else: + solution["objective_value"] = None + print("WARNING: No feasible solution found within time limit.") + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for the Caterer Production-Routing Problem (CPRP)") + 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, default=3600, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + solution = solve_cprp(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"\nSolution written to: {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']:.2f}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/dayarian2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/dayarian2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dayarian2019/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/dayarian2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/dayarian2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dayarian2019/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/dayarian2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/dayarian2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dayarian2019/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/dayarian2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/dayarian2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dayarian2019/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/dayarian2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/dayarian2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dayarian2019/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/dayarian2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/dayarian2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dayarian2019/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/dayarian2019/gurobi_solution/large_solution_1.json b/tasks/dayarian2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..1cd0647629fa7c5e6bff7e689e77cf0c1560eba4 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e8611f0ccc5ed6a6854694b8c18ce408c4ce7b7a474cfedd2470457ba494d3c +size 54596 diff --git a/tasks/dayarian2019/gurobi_solution/large_solution_2.json b/tasks/dayarian2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..466d4f2aefb9706752874ef0af0e76dbce23a2f1 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f4fe4006ae03da6ed66add69610bb8e68e4a47e5a68f55c39f0069bffeafcf9 +size 51680 diff --git a/tasks/dayarian2019/gurobi_solution/large_solution_3.json b/tasks/dayarian2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1bbae45b6bce3381f29ba649fdca37f737b71938 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:003ba49e365bd86d7582ad4278ded5ecc375105c6af0321b2d4f34f07b6c2c50 +size 49618 diff --git a/tasks/dayarian2019/gurobi_solution/large_solution_4.json b/tasks/dayarian2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2e956537a6859eba561ddbb32bbf5c512029806a --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8beb3a1eb571f56527e256df6cb97d80ddbd2cc00c94cba0cd11328368a6ec8f +size 51613 diff --git a/tasks/dayarian2019/gurobi_solution/large_solution_5.json b/tasks/dayarian2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..484aa8d112eef421a27560f13bfd11faf26e58ba --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bae1d8dd910a73505476a8e0b96806c564cdd20b8b911cce3fac17a04c2403d +size 47219 diff --git a/tasks/dayarian2019/gurobi_solution/tiny_solution.json b/tasks/dayarian2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..d0ea3cc4e1bf3883cf41055185cab08ef27cfb9c --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34f8c9e34052be149dba1aeac6447f6ed7dbd613630600f95e0d1a8972ac6137 +size 14319 diff --git a/tasks/dayarian2019/gurobi_solution_log/large_log_1.jsonl b/tasks/dayarian2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ecde616fe591c976ae090c3d94b97cdf86b165e2 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ed6c43883c9e9f2a1411f766215e0f01ba302eef82aaf6f5ee8b688a5326af4 +size 1502 diff --git a/tasks/dayarian2019/gurobi_solution_log/large_log_2.jsonl b/tasks/dayarian2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b9e1b6324437e6ec4c94cec05145307ba5982046 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ea4b6d31c57adeabb4104452a785d8eee0585654c5b275802439f98a506843d +size 1803 diff --git a/tasks/dayarian2019/gurobi_solution_log/large_log_3.jsonl b/tasks/dayarian2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..751a126f1505dfa0c914e0b9fc16e9c740fc6279 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdbcc48ec9c30774c822766c59ba02311dae7d57b27bde9c0fb84c1f94a90dc3 +size 1563 diff --git a/tasks/dayarian2019/gurobi_solution_log/large_log_4.jsonl b/tasks/dayarian2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7b97dbd989d534888b11e572b625205427b71269 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:193e1553e7371263099e8506911cd4201443fb48278218538cc470ca9561fdf9 +size 432 diff --git a/tasks/dayarian2019/gurobi_solution_log/large_log_5.jsonl b/tasks/dayarian2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..27beb5183876eb55f4b1929a9442cc2c08b65eeb --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:415d4b266a9136f80bfed6179de6cbaf18cdf83e43a0ccbb54f30bfd8cd53b6e +size 1912 diff --git a/tasks/dayarian2019/gurobi_solution_log/tiny_log.jsonl b/tasks/dayarian2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80266ed1d2f6cc74c60bb585146790e67f44deb3 --- /dev/null +++ b/tasks/dayarian2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a35cd1f84b9f8884b907faaaafde3e8a55722000705c6c7aa8984d8dfc7650a3 +size 133 diff --git a/tasks/dayarian2019/instance/large_instance_1.json b/tasks/dayarian2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0fa6c271dd8acdaff808f2aaa453dfe2bcc8cf9c --- /dev/null +++ b/tasks/dayarian2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a6cacbead48c531b9dd121ca4e7a4a3ddbb437992defcd4f9af7a29646df67f +size 37287 diff --git a/tasks/dayarian2019/instance/large_instance_2.json b/tasks/dayarian2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..cc20121d387fce53c16019f69894758ccaf9afc4 --- /dev/null +++ b/tasks/dayarian2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e938b0c03e660ba9731d0a6aaaebbfec88f66a86551d18d1f8c0a8ef0a4758c6 +size 48924 diff --git a/tasks/dayarian2019/instance/large_instance_3.json b/tasks/dayarian2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7e35e8ce68ffe0f487147b805a7d5bfe7e23c264 --- /dev/null +++ b/tasks/dayarian2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03e8b01a926553ca25a67adb756d751e2706552e02682bc14c932d613608062b +size 48800 diff --git a/tasks/dayarian2019/instance/large_instance_4.json b/tasks/dayarian2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c00c8cfb7ef027e28ad9e5c9a5c173518b94b6fe --- /dev/null +++ b/tasks/dayarian2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d25c9433603348fac8fffe5eeedfda3d4c33733cd2b96eb324190b1ddc477b10 +size 47872 diff --git a/tasks/dayarian2019/instance/large_instance_5.json b/tasks/dayarian2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ea12ffec8e375c83543e61d03235ae58f936d1b5 --- /dev/null +++ b/tasks/dayarian2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77c6db5c558eec7e70ce476c2a320aa9979f0830597d122bbbfb9607048c64c6 +size 33899 diff --git a/tasks/dayarian2019/instance/tiny_instance.json b/tasks/dayarian2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..d14e286b9df4a9689df17df12c65b10191d82618 --- /dev/null +++ b/tasks/dayarian2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3738a8e77ab2e7c64ae55239161a33373b36cb9af973db5ef4e6dc7ee6f1b3d +size 14460 diff --git a/tasks/dayarian2019/instance_schema.json b/tasks/dayarian2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..4ce7d0f47e2197c6aaa06ab086e5da064928e139 --- /dev/null +++ b/tasks/dayarian2019/instance_schema.json @@ -0,0 +1,78 @@ +{ + "num_orders": " Total number of customer orders to be fulfilled during the planning horizon.", + "num_products": " Total number of distinct product types that can be produced and delivered.", + "depot": { + "x": " X-coordinate of the central depot location in the service area.", + "y": " Y-coordinate of the central depot location in the service area." + }, + "global_parameters": { + "period_length_minutes": " Duration of each period in minutes.", + "subperiod_length_minutes": " Duration of each subperiod in minutes.", + "subperiods_per_period": " Number of subperiods contained within each period.", + "setup_length_minutes": " Time required to set up a workstation before switching to a different product.", + "setup_length_subperiods": " Number of subperiods consumed by a single workstation setup operation.", + "max_shift_route_length_periods": " Maximum number of periods that a driver shift or vehicle route can span.", + "max_shift_route_length_minutes": " Maximum duration in minutes that a driver shift or vehicle route can span.", + "min_paid_time_subperiods": " Minimum number of subperiods a driver or employee must be paid for once their shift begins.", + "min_paid_time_minutes": " Minimum paid duration in minutes once a driver or employee shift begins.", + "driver_salary_per_minute": " Wage rate paid to each driver per minute of their shift.", + "employee_salary_per_subperiod": " Wage rate paid to each production employee per subperiod worked.", + "setup_cost": " Fixed cost incurred each time a workstation is set up for a different product.", + "vehicle_operating_cost_per_minute": " Cost per minute of operating a delivery vehicle while en route.", + "preparation_time_minutes": " Time in minutes needed at the depot to load a vehicle before it departs on a trip.", + "service_time_minutes": " Time in minutes spent at each customer location during delivery.", + "max_trips_per_route": " Maximum number of trips a single vehicle can make within one route (returning to depot between trips).", + "horizon_start_minutes": " Start time of the planning horizon expressed as minutes from midnight.", + "horizon_end_minutes": " End time of the planning horizon expressed as minutes from midnight.", + "num_periods": " Total number of periods spanning the planning horizon.", + "num_subperiods": " Total number of subperiods spanning the planning horizon." + }, + "num_workstations": " Number of workstations available for production at the depot.", + "num_production_employees": " Number of production employees available to operate workstations.", + "num_vehicles": " Number of delivery vehicles available in the fleet.", + "num_drivers": " Number of drivers available to operate delivery vehicles.", + "vehicle_capacity": " Maximum total space units a single vehicle can carry per trip.", + "products": [ + { + "product_id": " Unique identifier for this product type.", + "production_rate_per_subperiod": " Maximum units of this product that one employee can produce in a single subperiod.", + "life_span_minutes": " Maximum time in minutes allowed between production completion and delivery to the customer." + } + ], + "orders": [ + { + "order_id": " Unique identifier for this customer order.", + "x": " X-coordinate of the customer location for this order.", + "y": " Y-coordinate of the customer location for this order.", + "time_window_start": " Earliest acceptable delivery time in minutes from midnight.", + "time_window_end": " Latest acceptable delivery time in minutes from midnight.", + "service_time": " Time in minutes required to serve this customer upon arrival.", + "demands": " Number of units of each product requested by this order.", + "space_requirement": " Total space units this order occupies in the delivery vehicle." + } + ], + "travel_time_matrix": " Travel time in minutes between each pair of locations, where index 0 is the depot and indices 1 through num_orders correspond to customer order locations.", + "production_windows": { + "{order_id}": { + "{product_id}": { + "release_time": " Earliest time in minutes from midnight at which production of this product for this order may begin.", + "due_time": " Latest time in minutes from midnight by which production of this product for this order must be completed.", + "valid_subperiod_ids": " Subperiod indices during which this product may be produced for this order." + } + } + }, + "periods": [ + { + "period_id": " Unique identifier for this period.", + "start_time": " Start time of this period in minutes from midnight.", + "end_time": " End time of this period in minutes from midnight." + } + ], + "subperiods": [ + { + "subperiod_id": " Unique identifier for this subperiod.", + "start_time": " Start time of this subperiod in minutes from midnight.", + "end_time": " End time of this subperiod in minutes from midnight." + } + ] +} diff --git a/tasks/dayarian2019/mathematical_formulation.md b/tasks/dayarian2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d54767b7b19d7f08f35d775bbf7d7b92be33a07b --- /dev/null +++ b/tasks/dayarian2019/mathematical_formulation.md @@ -0,0 +1,128 @@ +# Original Formulation: Caterer Production-Routing Problem (CPRP) + +*Source: A Branch-Price-and-Cut Algorithm for a Production-Routing Problem with Short-Life-Span Products, I. Dayarian and G. Desaulniers, Transportation Science (Articles in Advance, pp. 1–21), 2019.* + +## Sets and Indices + +- $\mathcal{T}$ : set of time periods, numbered chronologically $1,\dots,|\mathcal{T}|$; period $t$ has start time $b^t$ and end time $e^t$, with $e^t=b^{t+1}$ for $t\in\mathcal{T}\setminus\{|\mathcal{T}|\}$. + +- $\mathcal{U}$ : set of subperiods, numbered $1,\dots,|\mathcal{U}|$; subperiod $u$ has start time $b^u$ and end time $e^u$. + +- $\mathcal{P}$ : set of products. + +- $\mathcal{O}$ : set of orders (customers), indexed by $i$. + +- $\mathcal{P}_i\subseteq\mathcal{P}$ : products with positive demand for order $i\in\mathcal{O}$. + +- $\mathcal{U}_i^p$ : subperiods during which demand of product $p$ for order $i$ may be produced (set by release time and minimum travel time to $i$). + +- $\mathcal{U}^p=\bigcup_{i\in\mathcal{O}}\mathcal{U}_i^p$ : subperiods in which product $p$ may be produced for some order. + +- $\mathcal{O}_u^p$ : orders $i$ such that $u\in\mathcal{U}_i^p$. + +- $\mathcal{T}_i\subseteq\mathcal{T}$ : periods at the beginning of which a trip may start to deliver order $i$ within its time window. + +- $\mathcal{R}$ : set of all feasible delivery routes, indexed by $r$. + +- $\mathcal{S}$ : set of all feasible production employee shifts, indexed by $s$ (a shift also describes the employee assignment in each of its subperiods). + +## Parameters + +- $\eta^p$ : production rate of product $p$ (units per subperiod). + +- $d_i^p$ : demand of order $i$ for product $p$. + +- $n^E,\ n^W$ : maximum number of production employees, maximum number of workstations. + +- $n^V,\ n^D$ : number of available vehicles, number of available drivers. + +- For route $r\in\mathcal{R}$: cost $c_r$ (driver salary $+$ vehicle operational cost); $a_{ir}\in\{0,1\}$, $1$ if $r$ visits customer $i$; $g_{ir}^t\in\{0,1\}$, $1$ if $i$ is visited in $r$ on a trip starting at $b^t$ (for $i\in\mathcal{O}$, $t\in\mathcal{T}_i$); $b_r^t\in\{0,1\}$, $1$ if $r$ starts at $b^t$; $e_r^t\in\{0,1\}$, $1$ if $r$ ends at $e^t$. + +- For shift $s\in\mathcal{S}$: cost $c_s$ (employee salary $+$ setup costs); $f_s^{pu}\in\{0,1\}$, $1$ if $s$ is assigned to product $p$ in subperiod $u$ (for $p\in\mathcal{P}$, $u\in\mathcal{U}^p$); $b_s^t\in\{0,1\}$, $1$ if $s$ starts at $b^t$; $e_s^t\in\{0,1\}$, $1$ if $s$ ends at $e^t$. + +## Decision Variables + +$$\begin{align*} + \theta_r &\in\{0,1\}, && r\in\mathcal{R}: \ 1 \text{ if route } r \text{ is selected.}\\ + \psi_s &\in\mathbb{Z}_{\ge 0}, && s\in\mathcal{S}: \text{ number of production employees working on shift } s.\\ + q_i^{pu} &\in\mathbb{R}_{\ge 0}, && i\in\mathcal{O},\,p\in\mathcal{P}_i,\,u\in\mathcal{U}_i^p: \text{ units of product } p \text{ produced in subperiod } u \text{ for order } i.\\ + v^t &\in\mathbb{Z}, && t\in\mathcal{T}: \text{ number of vehicles used in period } t.\\ + w^t &\in\mathbb{Z}, && t\in\mathcal{T}: \text{ number of workstations used in period } t. +\end{align*}$$ + +## Objective + +$$\begin{equation} + \min \quad \sum_{r\in\mathcal{R}} c_r\,\theta_r \;+\; \sum_{s\in\mathcal{S}} c_s\,\psi_s \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} + \sum_{r\in\mathcal{R}} a_{ir}\,\theta_r &= 1, & \forall i\in\mathcal{O}, \tag{2}\\[4pt] + \sum_{i\in\mathcal{O}_u^p} q_i^{pu} &\le \eta^p \sum_{s\in\mathcal{S}} f_s^{pu}\,\psi_s, & \forall p\in\mathcal{P},\ u\in\mathcal{U}^p, \tag{3}\\[4pt] + \sum_{\substack{u\in\mathcal{U}_i^p\\ e^u\le b^t}} q_i^{pu} &\ge \sum_{r\in\mathcal{R}} d_i^p\, g_{ir}^t\,\theta_r, & \forall i\in\mathcal{O},\ p\in\mathcal{P}_i,\ t\in\mathcal{T}_i, \tag{4}\\[4pt] + \sum_{r\in\mathcal{R}} \theta_r &\le n^D, \tag{5}\\[4pt] + \sum_{s\in\mathcal{S}} \psi_s &\le n^E, \tag{6}\\[4pt] + v^{t-1} + \sum_{r\in\mathcal{R}} \bigl(b_r^t - e_r^{t-1}\bigr)\theta_r &= v^t, & \forall t\in\mathcal{T}, \tag{7}\\[4pt] + w^{t-1} + \sum_{s\in\mathcal{S}} \bigl(b_s^t - e_s^{t-1}\bigr)\psi_s &= w^t, & \forall t\in\mathcal{T}, \tag{8}\\[4pt] + \theta_r &\in \{0,1\}, & \forall r\in\mathcal{R}, \tag{9}\\[4pt] + \psi_s &\ge 0,\ \text{integer}, & \forall s\in\mathcal{S}, \tag{10}\\[4pt] + q_i^{pu} &\ge 0, & \forall i\in\mathcal{O},\ p\in\mathcal{P}_i,\ u\in\mathcal{U}_i^p, \tag{11}\\[4pt] + 0 \le v^t &\le n^V,\ \text{integer}, & \forall t\in\mathcal{T}, \tag{12}\\[4pt] + 0 \le w^t &\le n^W,\ \text{integer}, & \forall t\in\mathcal{T}. \tag{13} +\end{align}$$ + +In constraints (7) and (8), for $t=1$ we set $v^0=w^0=e_r^0=e_s^0=0$ for all $r\in\mathcal{R}$ and $s\in\mathcal{S}$. + +## Released Compact Benchmark Contract + +The executable benchmark uses a finite, aggregate formulation in place of +enumerating $\mathcal R$ and $\mathcal S$. This section is normative for the +released instances, solver, solution schema, and checker. + +For each vehicle $v$ and trip slot $k$, the model selects an active prefix of +trip slots, a start period, an ordered depot-to-depot customer path, and its +customer assignments. Consecutive active slots must have strictly increasing +start-period indices. The compact contract deliberately does **not** add a +continuous-time constraint requiring trip $k$ to return before trip $k+1$ +departs. An inactive slot has start time zero. Arrival times follow the +reported path, preparation, travel, waiting, and service times. The route-end +variable is bounded below by every served customer's arrival plus service and +direct return-to-depot time. Driver paid time is the maximum of this modeled +route duration and the guaranteed minimum; vehicle cost is based on the exact +arcs in the reported order. + +The production completion is represented by nonnegative integers +$f^{pu}$ (producing employees), $\beta^{pu}$ (setup starts), $w^t$ (paid +workstations), and $\alpha^t$ (employee-shift starts). Besides (3), the +released model enforces + +$$ +f^{pu} \le f^{p,u-1}+\beta^{p,u-\sigma}, +$$ + +with absent predecessor terms equal to zero. In each subperiod $u$ of period +$t$, $w^t$ covers all producing employees plus setup employees whose +$\sigma$-subperiod setup interval contains $u$; the same count cannot exceed +$n^E$. Shift starts satisfy + +$$ +\alpha^0\ge w^0,\qquad +\alpha^t\ge w^t-w^{t-1},\qquad +\sum_t\alpha^t\le n^E, +$$ + +and $w^t$ covers the preceding shift starts over the configured minimum paid +periods. All four arrays are integral and use the instance employee and +workstation bounds. + +The JSON certificate stores the selected customer order and every +$f,\beta,w,\alpha$ value. Its objective is checked by exact recomputation: + +$$ +\gamma_D\sum_v \operatorname{paid}_v ++\gamma_V\sum_v \operatorname{travel}_v ++\gamma_E n^{SP}\sum_t w^t ++\gamma_S\sum_{p,u}\beta^{pu}. +$$ diff --git a/tasks/dayarian2019/problem_description.txt b/tasks/dayarian2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..3838ea65d06aba4bb7821adc175aa1a4dee10132 --- /dev/null +++ b/tasks/dayarian2019/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A catering services company operates a central production facility (depot) and must fulfill a set of customer orders within a single day. The planning horizon is divided into equal-length time periods, and each period is further subdivided into equal-length subperiods. The company produces multiple product types and must simultaneously plan production employee shifts and delivery vehicle routes so that every order is produced and delivered on time, at minimum total cost. + +Each order is placed by a customer at a known geographic location and specifies a demand quantity for one or more products, a space requirement representing the physical size of the order for vehicle loading, a service time that a driver must spend at the customer site during delivery, and a time window defined by an earliest and latest allowable delivery time. Products are perishable: each product type has a maximum allowed time between production and delivery, called its life span. Each product type has a known production rate giving the number of units one employee can produce per subperiod. Travel times between every pair of locations (including the depot) are given. Storage at the production facility is not a limiting resource. For each order and each product it demands, a production window is defined by a release time (derived from the order's delivery time window and the product's life span) and a due time (the latest subperiod by which production must be complete so the order can still depart on a trip that meets its time window). + +On the production side, this released benchmark uses an aggregate compact staffing model. For every product and subperiod it records an integer number of producing employees and an integer number of setup starts; for every period it records the number of paid workstations and employee-shift starts. Production may be split and preempted. Product output is bounded by its rate times its assigned employees. A rise in a product's employee count requires the corresponding setup starts, setup employees remain occupied for the configured setup duration, and producing plus setting-up employees cannot exceed the employee or paid-workstation limits. Period-level shift-start and minimum-paid-time inequalities determine the paid workforce. These aggregate variables are the released staffing contract; the benchmark does not claim to reconstruct named individual employee trajectories. + +On the delivery side, a limited number of indexed vehicle/driver pairs are available. Each used pair operates one route with an active prefix of at most the specified number of trip slots. A trip starts at the depot at the beginning of a period, includes a fixed preparation time, visits the reported ordered customer sequence, and returns to the depot. Capacity and customer time windows are enforced. For multiple trips, the released compact formulation requires only that the later trip start in a strictly later period; it does not impose a continuous-time return-before-next-departure constraint, so trip time intervals may overlap. Route paid time runs from its earliest trip start to the largest modeled customer return bound, and is capped by the maximum route duration. Each vehicle index appears in at most one route. + +Every order must be delivered exactly once. Production and delivery are linked by the order's due time: the cumulative quantity of each product produced for an order by the time the order's trip departs the depot must meet the order's demand for that product, and total production of each product for each order across its valid subperiods must at least meet its demand. + +The cost of a route is the driver salary (rate per minute times the maximum of modeled route duration and guaranteed minimum paid time) plus vehicle operating cost (rate per minute times exact travel time in the reported customer order). Production cost is the employee salary rate per subperiod times the period-level paid-workstation count, plus setup cost for every certified setup start. The objective is the exact sum of those four components. A submitted solution therefore includes both the ordered routes and the complete aggregate production-staffing certificate needed to recompute this value. diff --git a/tasks/dayarian2019/solution_logger.py b/tasks/dayarian2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/dayarian2019/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/dayarian2019/solution_schema.json b/tasks/dayarian2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..96f4678226a165e2b598d9fa695319e55f6ca03f --- /dev/null +++ b/tasks/dayarian2019/solution_schema.json @@ -0,0 +1,41 @@ +{ + "objective_value": " Total operating cost including driver salaries, vehicle operating costs, employee salaries, and setup costs.", + "routes": [ + { + "vehicle": " Identifier of the vehicle assigned to this route.", + "trips": [ + { + "trip": " Sequential index of this trip within the vehicle's route.", + "customers": " Ordered sequence of customer order IDs visited during this trip.", + "start_period": " Period index at which this trip departs from the depot." + } + ] + } + ], + "production_schedule": [ + { + "order": " Customer order ID for which this production quantity is allocated.", + "product": " Product type ID being produced.", + "subperiod": " Subperiod index during which production occurs.", + "quantity": " Number of units produced for this order, product, and subperiod." + } + ], + "production_staffing": { + "employees_by_product_subperiod": [ + { + "product": " Product type ID.", + "subperiod": " Valid production subperiod ID for the product.", + "employees": " Number of employees assigned to production in this product/subperiod." + } + ], + "setups_by_product_subperiod": [ + { + "product": " Product type ID.", + "subperiod": " Valid production subperiod ID for the product.", + "setups": " Number of employees starting a setup in this product/subperiod." + } + ], + "workstations_by_period": " Certified workstations/employees paid in each period.", + "shift_starts_by_period": " Number of production employee shifts starting in each period." + } +} diff --git a/tasks/degraeve2007/feasibility_check.py b/tasks/degraeve2007/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..dded58fc78eeb4db3bf76a2dc96ac02fc6099ea5 --- /dev/null +++ b/tasks/degraeve2007/feasibility_check.py @@ -0,0 +1,371 @@ +""" +Feasibility checker for the Capacitated Lot Sizing Problem with Setup Times (CLST). +Based on Degraeve and Jans (2007). + +Constraints (numbered top-to-bottom from the formulation): + 1. Flow balance for period 1: si_i + x_{i,1} = d_{i,1} + s_{i,1} + 2. Flow balance for periods 2..m: s_{i,t-1} + x_{it} = d_{it} + s_{it} + 3. Setup forcing / prod upper bound: x_{it} <= min((cap_t - st_{it})/vt_{it}, sd_{itm}) * y_{it} + 4. Capacity per period: sum_i (st_{it}*y_{it} + vt_{it}*x_{it}) <= cap_t + 5. Variable domains: y_{it} in {0,1}, x_{it} >= 0, s_{it} >= 0, si_i >= 0 + 6. Objective consistency: reported objective_value must equal the objective + recomputed from the solution variables: + obj = sum_i fc_i*si_i + sum_i sum_t (sc_it*y_it + vc_it*x_it + hc_it*s_it) + +NOTE: this is the obj-recompute ("Tier C") variant of feasibility_check.py. +Constraints 1..5 are byte-identical in logic to the original checker; only +constraint 6 (objective consistency) is added. See +docs/data_review_fix/checker_add_obj_recompute.md. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'variables') +_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["dimensions"]["num_products"] + m = instance["dimensions"]["num_periods"] + params = instance["parameters"] + + d = params["demand"] + st = params["setup_time"] + vt = params["variable_production_time"] + cap = params["capacity"] + + variables = solution["variables"] + x = variables["production"] + y = variables["setup"] + s = variables["inventory"] + si = variables["initial_inventory"] + + # Precompute cumulative demand sd[i][t] = sum d[i][l] for l=t..m-1 + sd = [[0.0] * m for _ in range(n)] + for i in range(n): + sd[i][m - 1] = d[i][m - 1] + for t in range(m - 2, -1, -1): + sd[i][t] = sd[i][t + 1] + d[i][t] + + violations = [] + violation_magnitudes = [] + violated_set = set() + + def record(constraint_idx, msg, lhs, rhs, violation_amount): + violated_set.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 1: Flow balance for period 1 (equality) --- + # si_i + x_{i,1} = d_{i,1} + s_{i,1} for all i + for i in range(n): + lhs = si[i] + x[i][0] + rhs = d[i][0] + s[i][0] + va = abs(lhs - rhs) + if va > tol: + record(1, f"Flow balance violated for product {i+1} in period 1: " + f"LHS={lhs}, RHS={rhs}, diff={va}", lhs, rhs, va) + + # --- Constraint 2: Flow balance for periods 2..m (equality) --- + # s_{i,t-1} + x_{it} = d_{it} + s_{it} for all i, t>=2 + for i in range(n): + for t in range(1, m): + lhs = s[i][t - 1] + x[i][t] + rhs = d[i][t] + s[i][t] + va = abs(lhs - rhs) + if va > tol: + record(2, f"Flow balance violated for product {i+1} in period {t+1}: " + f"LHS={lhs}, RHS={rhs}, diff={va}", lhs, rhs, va) + + # --- Constraint 3: Setup forcing / production upper bound (<=) --- + # x_{it} <= min((cap_t - st_{it})/vt_{it}, sd_{itm}) * y_{it} + for i in range(n): + for t in range(m): + if vt[i][t] > 0: + ub_cap = (cap[t] - st[i][t]) / vt[i][t] + else: + ub_cap = 1e15 + ub = min(ub_cap, sd[i][t]) * y[i][t] + ub = max(ub, 0.0) * y[i][t] if y[i][t] > 0.5 else 0.0 + # Recompute cleanly + raw_ub = max(min(ub_cap, sd[i][t]), 0.0) + rhs_val = raw_ub * y[i][t] + lhs_val = x[i][t] + va = lhs_val - rhs_val + if va > tol: + record(3, f"Setup forcing violated for product {i+1} in period {t+1}: " + f"x={lhs_val}, UB*y={rhs_val}, excess={va}", + lhs_val, rhs_val, va) + + # --- Constraint 4: Capacity constraint (<=) --- + # sum_i (st_{it}*y_{it} + vt_{it}*x_{it}) <= cap_t + for t in range(m): + lhs_val = sum(st[i][t] * y[i][t] + vt[i][t] * x[i][t] for i in range(n)) + rhs_val = cap[t] + va = lhs_val - rhs_val + if va > tol: + record(4, f"Capacity exceeded in period {t+1}: " + f"usage={lhs_val}, capacity={rhs_val}, excess={va}", + lhs_val, rhs_val, va) + + # --- Constraint 5: Variable domains --- + # y_{it} in {0,1}, x_{it} >= 0, s_{it} >= 0, si_i >= 0 + for i in range(n): + # si_i >= 0 + if si[i] < -tol: + va = -si[i] + record(5, f"Initial inventory for product {i+1} is negative: si={si[i]}", + si[i], 0.0, va) + for t in range(m): + # y binary + y_val = y[i][t] + if abs(y_val - round(y_val)) > tol or round(y_val) not in (0, 1): + va = abs(y_val - round(y_val)) + record(5, f"Setup variable for product {i+1}, period {t+1} is not binary: y={y_val}", + y_val, round(y_val), va) + # x >= 0 + if x[i][t] < -tol: + va = -x[i][t] + record(5, f"Production for product {i+1}, period {t+1} is negative: x={x[i][t]}", + x[i][t], 0.0, va) + # s >= 0 + if s[i][t] < -tol: + va = -s[i][t] + record(5, f"Inventory for product {i+1}, period {t+1} is negative: s={s[i][t]}", + s[i][t], 0.0, va) + + # --- Constraint 6: Objective consistency (full recompute) --- + # The CLST objective is fully determined by the solution variables + # (production x, setup y, inventory s, initial_inventory si), so the + # reported objective_value can be recomputed exactly and compared: + # obj = sum_i fc_i*si_i + # + sum_i sum_t (sc_it*y_it + vc_it*x_it + hc_it*s_it) + # This rejects fabricated objective values (obj-score-gaming exploits). + hc = params["holding_cost"] + sc = params["setup_cost"] + vc = params["variable_production_cost"] + fc = params["initial_inventory_cost"] + 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 i in range(n): + true_obj += fc[i] * si[i] + for t in range(m): + true_obj += (sc[i][t] * y[i][t] + + vc[i][t] * x[i][t] + + hc[i][t] * s[i][t]) + abs_diff = abs(reported - true_obj) + # 1e-6 relative tolerance with 1e-3 absolute floor: tight enough + # to flag fabricated values while absorbing float accumulation + # over the n*m product/period terms. + tol_obj = max(1e-3, 1e-6 * abs(true_obj)) + if abs_diff > tol_obj: + record(6, f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"objective sum_i fc_i*si_i + sum_it(" + f"sc_it*y_it + vc_it*x_it + hc_it*s_it)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol_obj:.6g})", + reported, true_obj, abs_diff) + + violated_constraints = sorted(violated_set) + feasible = len(violated_constraints) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes if not feasible else [], + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for CLST (Degraeve & Jans, 2007)" + ) + 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() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE: All constraints satisfied.") + else: + print(f"INFEASIBLE: Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/degraeve2007/gurobi_code.py b/tasks/degraeve2007/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..0715ce466ac85b969b5d14f03296431dbcf03ebd --- /dev/null +++ b/tasks/degraeve2007/gurobi_code.py @@ -0,0 +1,201 @@ +""" +CLST (Capacitated Lot Sizing with Setup Times) model using Gurobi. + +Based on the formulation from Degraeve et al. (2007). +""" + +import argparse +import json +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def solve_clst(instance_path: str, solution_path: str, time_limit: float) -> None: + # Load instance data + with open(instance_path, "r") as f: + data = json.load(f) + + n = data["dimensions"]["num_products"] + m = data["dimensions"]["num_periods"] + params = data["parameters"] + + d = params["demand"] # n x m + hc = params["holding_cost"] # n x m + sc = params["setup_cost"] # n x m + vc = params["variable_production_cost"] # n x m + fc = params["initial_inventory_cost"] # n + st = params["setup_time"] # n x m + vt = params["variable_production_time"] # n x m + cap = params["capacity"] # m + + # Precompute cumulative demand sd[i][t] = sum of d[i][l] for l=t..m-1 + # (using 0-indexed arrays) + sd = [[0] * m for _ in range(n)] + for i in range(n): + sd[i][m - 1] = d[i][m - 1] + for t in range(m - 2, -1, -1): + sd[i][t] = sd[i][t + 1] + d[i][t] + + # Build model + model = gp.Model("CLST") + model.setParam("Threads", 1) + model.Params.TimeLimit = time_limit + + # Decision variables + x = {} # production quantity + y = {} # setup indicator (binary) + s = {} # ending inventory + si = {} # initial inventory + + for i in range(n): + si[i] = model.addVar(lb=0.0, name=f"si_{i}") + for t in range(m): + x[i, t] = model.addVar(lb=0.0, name=f"x_{i}_{t}") + y[i, t] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}_{t}") + s[i, t] = model.addVar(lb=0.0, name=f"s_{i}_{t}") + + model.update() + + # Objective + obj = gp.LinExpr() + for i in range(n): + obj += fc[i] * si[i] + for t in range(m): + obj += sc[i][t] * y[i, t] + vc[i][t] * x[i, t] + hc[i][t] * s[i, t] + model.setObjective(obj, GRB.MINIMIZE) + + # Constraint (2.1): inventory balance for t=0 + for i in range(n): + model.addConstr( + si[i] + x[i, 0] == d[i][0] + s[i, 0], + name=f"balance_{i}_0" + ) + + # Constraint (2.2): inventory balance for t >= 1 + for i in range(n): + for t in range(1, m): + model.addConstr( + s[i, t - 1] + x[i, t] == d[i][t] + s[i, t], + name=f"balance_{i}_{t}" + ) + + # Constraint (3): production upper bound linked to setup + for i in range(n): + for t in range(m): + ub = min( + (cap[t] - st[i][t]) / vt[i][t], + sd[i][t] + ) + # Ensure non-negative upper bound + ub = max(ub, 0.0) + model.addConstr( + x[i, t] <= ub * y[i, t], + name=f"setup_link_{i}_{t}" + ) + + # Constraint (4): capacity constraint per period + for t in range(m): + model.addConstr( + gp.quicksum(st[i][t] * y[i, t] + vt[i][t] * x[i, t] for i in range(n)) <= cap[t], + name=f"capacity_{t}" + ) + + # Optimize + model.optimize() + + # Build solution output + solution = { + "instance_path": instance_path, + "solver": "gurobi", + "status": model.Status, + "status_name": _status_name(model.Status), + } + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["best_bound"] = model.ObjBound + solution["mip_gap"] = model.MIPGap + solution["solve_time"] = model.Runtime + solution["node_count"] = int(model.NodeCount) + + # Extract variable values + x_val = [[x[i, t].X for t in range(m)] for i in range(n)] + y_val = [[round(y[i, t].X) for t in range(m)] for i in range(n)] + s_val = [[s[i, t].X for t in range(m)] for i in range(n)] + si_val = [si[i].X for i in range(n)] + + solution["variables"] = { + "production": x_val, + "setup": y_val, + "inventory": s_val, + "initial_inventory": si_val, + } + else: + solution["objective_value"] = None + solution["solve_time"] = model.Runtime + + # Write solution + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Status: {solution['status_name']}") + if solution["objective_value"] is not None: + print(f"Objective: {solution['objective_value']:.4f}") + print(f"Solution written to {solution_path}") + + +def _status_name(status: int) -> str: + names = { + 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 names.get(status, f"UNKNOWN_{status}") + + +def main(): + parser = argparse.ArgumentParser( + description="Solve CLST (Capacitated Lot Sizing with Setup Times) using Gurobi" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the instance JSON file" + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to write the solution JSON file" + ) + parser.add_argument( + "--time_limit", type=float, default=3600.0, + 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) + + solve_clst(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/degraeve2007/gurobi_feasi_result/large_feasi_result_1.json b/tasks/degraeve2007/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/degraeve2007/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/degraeve2007/gurobi_feasi_result/large_feasi_result_2.json b/tasks/degraeve2007/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/degraeve2007/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/degraeve2007/gurobi_feasi_result/large_feasi_result_3.json b/tasks/degraeve2007/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/degraeve2007/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/degraeve2007/gurobi_feasi_result/large_feasi_result_4.json b/tasks/degraeve2007/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/degraeve2007/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/degraeve2007/gurobi_feasi_result/large_feasi_result_5.json b/tasks/degraeve2007/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/degraeve2007/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/degraeve2007/gurobi_feasi_result/tiny_feasi_result.json b/tasks/degraeve2007/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/degraeve2007/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/degraeve2007/gurobi_solution/large_solution_1.json b/tasks/degraeve2007/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..49d7160bde9515eaa86681e2a9a4853490c060b5 --- /dev/null +++ b/tasks/degraeve2007/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce3207165a69fe4ff222329478b49d00b87638577284ff08e8127adabeafdb99 +size 26170 diff --git a/tasks/degraeve2007/gurobi_solution/large_solution_2.json b/tasks/degraeve2007/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d6aab43385e0f8e5d99faafc6f0156bf5121f1d1 --- /dev/null +++ b/tasks/degraeve2007/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c817e4b41895e3bdb845495d6998a6f2f225dd06dd7d4bb71989f7b24663572 +size 25991 diff --git a/tasks/degraeve2007/gurobi_solution/large_solution_3.json b/tasks/degraeve2007/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..2adfcb93f49163a1664b528b5955c7bbd9aec4b3 --- /dev/null +++ b/tasks/degraeve2007/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cc422bd0f9ed0fde2eea90bb30ecd9c138d71fe9789c9e8f9956cc55f20620b +size 25555 diff --git a/tasks/degraeve2007/gurobi_solution/large_solution_4.json b/tasks/degraeve2007/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..fab17545624a9205c7935c478c55952b86b2cad1 --- /dev/null +++ b/tasks/degraeve2007/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0f2a89bb947e02424f69af7b7fc26b9a7195a189472bc39952c088689adb4c2 +size 25637 diff --git a/tasks/degraeve2007/gurobi_solution/large_solution_5.json b/tasks/degraeve2007/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..75a49c3a1e9498c0c59a7ad806ecd3b73af6de81 --- /dev/null +++ b/tasks/degraeve2007/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7438fcb7f1c8c25bba59befc07d994adbeffbfb6b75c07e62aaf0bb19083a17 +size 25690 diff --git a/tasks/degraeve2007/gurobi_solution/tiny_solution.json b/tasks/degraeve2007/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..61e2bc6dbf3a450e6e3031fcc76860fb4b63bcd3 --- /dev/null +++ b/tasks/degraeve2007/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a301108d40aa41d1a7d7cdc0a376296e325ccaace35c2aa8243acae7ecee479e +size 4314 diff --git a/tasks/degraeve2007/gurobi_solution_log/tiny_log.jsonl b/tasks/degraeve2007/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2fd91b34b743b814ebe4369bec2746440aaacf11 --- /dev/null +++ b/tasks/degraeve2007/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc1a33d36655ae9c5e13bb73ceaf2ac9b41261b874c6c49bda49cfdbe179b00b +size 55 diff --git a/tasks/degraeve2007/instance/large_instance_1.json b/tasks/degraeve2007/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..77bfedc0d97e3033fb94a4a6f6ed302bcd64c867 --- /dev/null +++ b/tasks/degraeve2007/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9e55b68aa81d31b848ef0f2b15adc5835a06ce8a09c029a5c578c8eca052271 +size 54291 diff --git a/tasks/degraeve2007/instance/large_instance_2.json b/tasks/degraeve2007/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..653aba8bc08a0deecad3ebc05ad13f2ed39b38b8 --- /dev/null +++ b/tasks/degraeve2007/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9515af2413b6d86928bff0e84681fbe2f698f90df0461254a133df7c869a4adf +size 53828 diff --git a/tasks/degraeve2007/instance/large_instance_3.json b/tasks/degraeve2007/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e544ed5fe8606da4499867f32ce68d6a66307ef8 --- /dev/null +++ b/tasks/degraeve2007/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c39edef94a83c4393e335a114b29da25a16980eababf0e79c5a595954c0eb37 +size 54229 diff --git a/tasks/degraeve2007/instance/large_instance_4.json b/tasks/degraeve2007/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..5f0711729ee645eaa3a26cbf1d0aebe4ff28412b --- /dev/null +++ b/tasks/degraeve2007/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b585ac7a139e06bfb6e22ba22c590989d544368f71e559896818e86df8ce033 +size 53770 diff --git a/tasks/degraeve2007/instance/large_instance_5.json b/tasks/degraeve2007/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9f87c40140d3b9fd279c8609743e95926a017237 --- /dev/null +++ b/tasks/degraeve2007/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22f4be35bcaea9ed36550e5d09a6363d76da49211b80045e162f8dbb9a7b26d9 +size 54243 diff --git a/tasks/degraeve2007/instance/tiny_instance.json b/tasks/degraeve2007/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..be536f41d67dc4539f5c10c0c76b1149fa41e671 --- /dev/null +++ b/tasks/degraeve2007/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2314084eb773dd7ed69c9fc7ea11b11ccbde97dd1c2536d05d12c4bee9ad4359 +size 8917 diff --git a/tasks/degraeve2007/instance_schema.json b/tasks/degraeve2007/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c5098050e5ce28856e712394f03f6dee7a1696b0 --- /dev/null +++ b/tasks/degraeve2007/instance_schema.json @@ -0,0 +1,22 @@ +{ + "dimensions": { + "num_products": " Number of distinct products manufactured at the facility.", + "num_periods": " Number of discrete time periods in the planning horizon." + }, + "factor_settings": { + "capacity_utilization": " Level of production resource capacity tightness (low, medium, or high).", + "time_between_orders": " Average number of periods between consecutive production setups for each product (low, medium, or high).", + "demand_variability": " Degree of period-to-period fluctuation in product demand (medium or high).", + "setup_time_level": " Magnitude of time consumed when initiating production of a product (low or high)." + }, + "parameters": { + "demand": " Quantity of each product that must be delivered in each period.", + "holding_cost": " Per-unit cost of carrying one unit of each product in inventory at the end of each period.", + "setup_cost": " Fixed cost incurred whenever production of each product is initiated in each period.", + "variable_production_cost": " Per-unit cost of producing each product in each period.", + "variable_production_time": " Time consumed on the shared resource to produce one unit of each product in each period.", + "setup_time": " Time consumed on the shared resource when initiating production of each product in each period.", + "capacity": " Total available time on the shared production resource in each period.", + "initial_inventory_cost": " Per-unit penalty cost for each product's initial inventory available at the start of the first period." + } +} diff --git a/tasks/degraeve2007/mathematical_formulation.md b/tasks/degraeve2007/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..ef613c4cac197861dbb97dce534b4ce9893374d2 --- /dev/null +++ b/tasks/degraeve2007/mathematical_formulation.md @@ -0,0 +1,49 @@ +# Original Formulation: Capacitated Lot Sizing Problem with Set Up Times (CLST) + +*Source: A New Dantzig-Wolfe Reformulation and Branch-and-Price Algorithm for the Capacitated Lot Sizing Problem with Set Up Times, Zeger Degraeve and Raf Jans, 2003/2007.* + +## Sets and Indices + +$$\begin{align*} +P &: \text{set of products},\ = \{1,\dots,n\}, \text{ indexed by } i. \\ +T &: \text{set of time periods},\ = \{1,\dots,m\}, \text{ indexed by } t. +\end{align*}$$ + +## Parameters + +$$\begin{align*} +d_{it} &: \text{demand of product } i \text{ in period } t, &&\forall i \in P,\ \forall t \in T \\ +sd_{itk} &: \text{sum of demand of product } i, \text{ from period } t \text{ until period } k, &&\forall i \in P,\ \forall t,k \in T : k \geq t \\ +hc_{it} &: \text{holding cost for product } i \text{ in period } t, &&\forall i \in P,\ \forall t \in T \\ +sc_{it} &: \text{set up cost for product } i \text{ in period } t, &&\forall i \in P,\ \forall t \in T \\ +vc_{it} &: \text{variable production cost for product } i \text{ in period } t, &&\forall i \in P,\ \forall t \in T \\ +fc_{i} &: \text{unit cost for initial inventory for product } i, &&\forall i \in P \\ +st_{it} &: \text{set up time for product } i \text{ in period } t, &&\forall i \in P,\ \forall t \in T \\ +vt_{it} &: \text{variable production time for product } i \text{ in period } t, &&\forall i \in P,\ \forall t \in T \\ +cap_{t} &: \text{capacity in period } t, &&\forall t \in T +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x_{it} &: \text{production of product } i \text{ in period } t, &&\forall i \in P,\ \forall t \in T \\ +y_{it} &: = 1 \text{ if set up for product } i \text{ in period } t,\ = 0 \text{ otherwise}, &&\forall i \in P,\ \forall t \in T \\ +si_{i} &: \text{amount of initial inventory for item } i, &&\forall i \in P \\ +s_{it} &: \text{inventory of product } i \text{ at the end of period } t, &&\forall i \in P,\ \forall t \in T +\end{align*}$$ + +## Objective + +$$\begin{equation} +\min\ \sum_{i \in P} fc_i\, si_i + \sum_{i \in P} \sum_{t \in T} \left( sc_{it}\, y_{it} + vc_{it}\, x_{it} + hc_{it}\, s_{it} \right) \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +si_i + x_{i,1} &= d_{i,1} + s_{i,1} && \forall i \in P \tag{2.1} \\ +s_{i,t-1} + x_{it} &= d_{it} + s_{it} && \forall i \in P,\ \forall t \in T \setminus \{1\} \tag{2.2} \\ +x_{it} &\leq \min\!\left\{ (cap_t - st_{it})/vt_{it},\ sd_{itm} \right\} y_{it} && \forall i \in P,\ \forall t \in T \tag{3} \\ +\sum_{i \in P} \left( st_{it}\, y_{it} + vt_{it}\, x_{it} \right) &\leq cap_t && \forall t \in T \tag{4} \\ +y_{it} \in \{0,1\},\quad x_{it} \geq 0,\quad s_{it} &\geq 0 && \forall i \in P,\ \forall t \in T \tag{5} +\end{align}$$ diff --git a/tasks/degraeve2007/problem_description.txt b/tasks/degraeve2007/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..e10bbae54daa4105e52db13470e03c7ac1c9111b --- /dev/null +++ b/tasks/degraeve2007/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A manufacturing facility produces multiple products over a finite planning horizon divided into discrete time periods. All products share a single production resource that has a limited available capacity in each period, measured in units of time. The input data specifies, for each product and each period, the demand that must be satisfied, a per-unit holding cost for carrying inventory from one period to the next, a fixed setup cost incurred whenever production of that product takes place in that period, a per-unit variable production cost, a setup time consumed by initiating production of that product in that period, and a per-unit variable production time. Each period also has a known total capacity. In addition, each product has an associated per-unit initial inventory cost, which is a large penalty cost used to ensure that a valid plan can always be constructed. + +The planner must determine, for each product in each period, whether to set up for production of that product, how much of that product to produce, and how much inventory of that product to carry forward to the next period. The planner must also determine, for each product, an amount of initial inventory that is available at the start of the first period without requiring a setup. + +Demand must be met in every period for every product. For the first period, the initial inventory of a product plus the production of that product in the first period must equal the demand for that product in the first period plus the ending inventory of that product at the end of the first period. For every subsequent period, the inventory of a product carried from the previous period plus the production of that product in the current period must equal the demand for that product in the current period plus the ending inventory of that product at the end of the current period. + +Production of a product in a given period can only occur if a setup for that product has been performed in that period. Furthermore, the quantity produced of a product in any period is bounded above by the smaller of two quantities: the remaining capacity in that period after accounting for the setup time divided by the per-unit production time, and the cumulative remaining demand for that product from that period through the end of the planning horizon. + +In each period, the total time consumed across all products by setups and production must not exceed the period's capacity. Specifically, for each product that is set up in a period, the setup time is consumed, and for each unit produced of any product, the corresponding variable production time is consumed, and the sum of all these times across all products must remain within the period's capacity. + +The goal is to minimize total cost, which is the sum of four components: the total initial inventory cost across all products, the total setup costs incurred across all products and periods, the total variable production costs across all products and periods, and the total inventory holding costs across all products and periods. diff --git a/tasks/degraeve2007/solution_logger.py b/tasks/degraeve2007/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/degraeve2007/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/degraeve2007/solution_schema.json b/tasks/degraeve2007/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..887118260ca7494f05f3ecd7177c7f86af23d547 --- /dev/null +++ b/tasks/degraeve2007/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total cost comprising initial inventory penalties, setup costs, variable production costs, and inventory holding costs across all products and periods.", + "variables": { + "production": " Quantity of each product produced in each period.", + "setup": " Whether production of each product is initiated in each period (1 = yes, 0 = no).", + "inventory": " Quantity of each product held in inventory at the end of each period.", + "initial_inventory": " Quantity of each product available in inventory at the start of the first period." + } +} diff --git a/tasks/delage2022/feasibility_check.py b/tasks/delage2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..9e4154578b6b825ac0bf330c9d1a64ae0c28d920 --- /dev/null +++ b/tasks/delage2022/feasibility_check.py @@ -0,0 +1,470 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Open-Ended Continuous Stock Cutting Problem (CSCP). + +Checks all hard constraints from the mathematical formulation (equations 16-23) +in Pérez Martínez, Adulyasak, and Jans (2022). + +Constraints are numbered 1-8 counting top to bottom from the formulation: + Constraint 1 (eq 16): sum_{i in T} l_i * a_{ij} <= L * s_j, forall j in P + Constraint 2 (eq 17): z_j <= M * s_j, forall j in P + Constraint 3 (eq 18): q_{ij} = a_{ij} * z_j, forall i in T, j in P + Constraint 4 (eq 19): sum_j q_{ij} + x_i >= d_i, forall i in T + Constraint 5 (eq 20): sum_j z_j >= sum_i x_i + Constraint 6 (eq 21): z_{j-1} >= z_j, forall j in P, j > 1 + Constraint 7 (eq 22): s_j in {0,1}, a_{ij} in Z_+, forall i,j + Constraint 8 (eq 23): x_i >= 0, z_j in Z_+, q_{ij} >= 0, forall i,j + Constraint 9 (eq 15): objective consistency -- the reported objective_value + must equal the recomputed total time + C_s * sum_j s_j + C_r * sum_j z_j. + +Constraint 9 is a Tier-C anti-gaming check: the eval pipeline otherwise trusts +the program's self-reported objective_value. Every variable the objective +(eq 15) depends on -- the pattern setup flags s_j and the repetition counts +z_j -- is present in the solution, so a full recompute is possible and exact. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('extra_pieces', 'objective_value', 'patterns', 'production_quantities') +_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 Open-Ended CSCP" + ) + 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() + + 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}") + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + # --- Parse instance data --- + products = instance["products"] + num_products = instance["num_products"] + num_patterns = instance["num_patterns"] + L = instance["machine_length"] + M_val = instance["M"] + + T = list(range(num_products)) # 0-indexed + P = list(range(num_patterns)) # 0-indexed + + d = {i: products[i]["demand"] for i in T} + l = {i: products[i]["length"] for i in T} + product_ids = {i: products[i]["id"] for i in T} + # Reverse map: product_id (int) -> 0-indexed + id_to_idx = {products[i]["id"]: i for i in T} + + # --- Parse solution --- + patterns = solution["patterns"] + extra_pieces = solution["extra_pieces"] + + # s_j: whether pattern j is used + s = {} + # z_j: repetitions of pattern j + z = {} + # a[i][j]: pieces of product i in pattern j + a = {} + for j in P: + pdata = patterns[str(j)] + s[j] = 1 if pdata["used"] else 0 + z[j] = pdata["repetitions"] + for i in T: + pid_str = str(product_ids[i]) + a[(i, j)] = pdata["pieces"].get(pid_str, 0) + + # x_i: extra pieces + x = {} + for i in T: + pid_str = str(product_ids[i]) + x[i] = extra_pieces.get(pid_str, 0.0) + + # q_{ij} = a_{ij} * z_j (computed from solution, this IS the production quantity) + q = {} + for i in T: + for j in P: + q[(i, j)] = a[(i, j)] * z[j] + + # If the solution provides explicit production_quantities, use those for + # checking constraint 3 (eq 18) mismatch + q_reported = None + if "production_quantities" in solution: + q_reported = {} + for i in T: + for j in P: + key = f"product_{product_ids[i]}_pattern_{j}" + q_reported[(i, j)] = solution["production_quantities"].get(key, 0.0) + + # --- Check constraints --- + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs, rhs, violation_amount): + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ---- Constraint 1 (eq 16): sum_{i in T} l_i * a_{ij} <= L * s_j ---- + for j in P: + lhs = sum(l[i] * a[(i, j)] for i in T) + rhs = L * s[j] + violation_amount = lhs - rhs + if violation_amount > tol: + record_violation( + 1, + f"Constraint 1 (eq 16) violated for pattern {j}: " + f"sum of piece lengths = {lhs}, but L*s_j = {rhs}", + lhs, rhs, violation_amount + ) + + # ---- Constraint 2 (eq 17): z_j <= M * s_j ---- + for j in P: + lhs = z[j] + rhs = M_val * s[j] + violation_amount = lhs - rhs + if violation_amount > tol: + record_violation( + 2, + f"Constraint 2 (eq 17) violated for pattern {j}: " + f"z_j = {lhs}, but M*s_j = {rhs}", + lhs, rhs, violation_amount + ) + + # ---- Constraint 3 (eq 18): q_{ij} = a_{ij} * z_j ---- + # If solution reports explicit q values, check they match a_{ij}*z_j + if q_reported is not None: + for i in T: + for j in P: + lhs = q_reported[(i, j)] + rhs = a[(i, j)] * z[j] + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 3, + f"Constraint 3 (eq 18) violated for product {product_ids[i]}, " + f"pattern {j}: q_reported = {lhs}, a*z = {rhs}", + lhs, rhs, violation_amount + ) + + # ---- Constraint 4 (eq 19): sum_j q_{ij} + x_i >= d_i ---- + for i in T: + total_q = sum(q[(i, j)] for j in P) + lhs = total_q + x[i] + rhs = d[i] + violation_amount = rhs - lhs # >= constraint: RHS exceeds LHS + if violation_amount > tol: + record_violation( + 4, + f"Constraint 4 (eq 19) violated for product {product_ids[i]}: " + f"total production + extra = {lhs}, demand = {rhs}", + lhs, rhs, violation_amount + ) + + # ---- Constraint 5 (eq 20): sum_j z_j >= sum_i x_i ---- + lhs_5 = sum(z[j] for j in P) + rhs_5 = sum(x[i] for i in T) + violation_amount_5 = rhs_5 - lhs_5 # >= constraint + if violation_amount_5 > tol: + record_violation( + 5, + f"Constraint 5 (eq 20) violated: " + f"sum(z_j) = {lhs_5}, sum(x_i) = {rhs_5}", + lhs_5, rhs_5, violation_amount_5 + ) + + # ---- Constraint 6 (eq 21): z_{j-1} >= z_j, for j > 0 ---- + for j in P: + if j > 0: + lhs = z[j - 1] + rhs = z[j] + violation_amount = rhs - lhs # >= constraint: z_{j-1} >= z_j + if violation_amount > tol: + record_violation( + 6, + f"Constraint 6 (eq 21) violated: " + f"z_{j-1} = {lhs} < z_{j} = {rhs}", + lhs, rhs, violation_amount + ) + + # ---- Constraint 7 (eq 22): s_j in {0,1}, a_{ij} in Z_+ ---- + for j in P: + val = s[j] + if val not in (0, 1): + record_violation( + 7, + f"Constraint 7 (eq 22) violated: s_{j} = {val} not in {{0,1}}", + val, 0, 1.0 + ) + for i in T: + val_a = a[(i, j)] + if not isinstance(val_a, int) or val_a < 0: + if isinstance(val_a, float) and abs(val_a - round(val_a)) < tol and val_a >= -tol: + pass # close enough to non-negative integer + else: + violation_amount = abs(val_a - round(val_a)) if val_a >= 0 else abs(val_a) + record_violation( + 7, + f"Constraint 7 (eq 22) violated: a_{product_ids[i]},{j} = {val_a} " + f"not a non-negative integer", + val_a, round(max(val_a, 0)), violation_amount + ) + + # ---- Constraint 8 (eq 23): x_i >= 0, z_j in Z_+, q_{ij} >= 0 ---- + for i in T: + if x[i] < -tol: + record_violation( + 8, + f"Constraint 8 (eq 23) violated: x_{product_ids[i]} = {x[i]} < 0", + x[i], 0.0, abs(x[i]) + ) + + for j in P: + val_z = z[j] + if isinstance(val_z, float): + if abs(val_z - round(val_z)) > tol or val_z < -tol: + violation_amount = abs(val_z - round(val_z)) if val_z >= 0 else abs(val_z) + record_violation( + 8, + f"Constraint 8 (eq 23) violated: z_{j} = {val_z} " + f"not a non-negative integer", + val_z, round(max(val_z, 0)), violation_amount + ) + elif isinstance(val_z, int): + if val_z < 0: + record_violation( + 8, + f"Constraint 8 (eq 23) violated: z_{j} = {val_z} < 0", + val_z, 0, abs(val_z) + ) + + for i in T: + for j in P: + if q[(i, j)] < -tol: + record_violation( + 8, + f"Constraint 8 (eq 23) violated: q_{product_ids[i]},{j} = {q[(i,j)]} < 0", + q[(i, j)], 0.0, abs(q[(i, j)]) + ) + + # ---- Constraint 9 (eq 15): objective consistency ---- + # Tier-C anti-gaming check. The objective (eq 15) is + # C_s * sum_j s_j + C_r * sum_j z_j + # and every term -- the setup flags s_j and repetition counts z_j -- is + # present in the solution, so this is an exact full recompute. Reject the + # solution when the reported objective_value disagrees. + 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: + C_s = instance["cost_setup_pattern"] + C_r = instance["cost_repetition"] + true_obj = float(C_s * sum(s[j] for j in P) + + C_r * sum(z[j] for j in P)) + abs_diff = abs(reported - true_obj) + # The objective is an integer count (C_s, C_r, s_j, z_j all + # integral); a 0.5 absolute floor fires on any integer mismatch, + # with a tiny relative term for large-magnitude safety. + obj_tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > obj_tol: + record_violation( + 9, + f"Constraint 9 (eq 15) violated: reported objective_value " + f"= {reported} differs from recomputed " + f"C_s*sum_j(s_j) + C_r*sum_j(z_j) = {true_obj} " + f"(|diff| = {abs_diff:.6g}, tol = {obj_tol:.6g})", + reported, true_obj, abs_diff + ) + + # --- Build output --- + 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/delage2022/gurobi_code.py b/tasks/delage2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..52a0ac19b9fbb19c0807442ee739e55af9b3a65f --- /dev/null +++ b/tasks/delage2022/gurobi_code.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +""" +Gurobi-based MIP solver for the Open-Ended Continuous Stock Cutting Problem (CSCP). + +Source: Pérez Martínez, Adulyasak, and Jans (2022), +"Logic-Based Benders Decomposition for Integrated Process Configuration +and Production Planning Problems," INFORMS Journal on Computing, 34(4), pp. 2177-2191. + +The OP has a nonlinear constraint q_{ij} = a_{ij} * z_j (eq. 18). +This is linearized via: + 1. Binary substitution (eq. 24): a_{ij} = sum_{k in K_i} b_k * w_{ijk}, + where b_k = 2^{k-1}, K_i = {1, ..., n_i}, n_i = ceil(log2(N_i+1)). + 2. McCormick linearization: u_{ijk} = w_{ijk} * z_j (binary x integer): + u_{ijk} >= 0 + u_{ijk} <= M * w_{ijk} + u_{ijk} <= z_j + u_{ijk} >= z_j - M * (1 - w_{ijk}) + Then q_{ij} = sum_{k in K_i} b_k * u_{ijk} (exact, linear). +""" + +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 main(): + parser = argparse.ArgumentParser( + description="Solve Open-Ended CSCP using Gurobi (linearized MIP)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # ------------------------------------------------------------------ + # Load instance + # ------------------------------------------------------------------ + with open(args.instance_path, "r") as f: + instance = json.load(f) + + products = instance["products"] + num_products = instance["num_products"] + num_patterns = instance["num_patterns"] + L = instance["machine_length"] + C_s = instance["cost_setup_pattern"] + C_r = instance["cost_repetition"] + M = instance["M"] # M = max_{i in T} {d_i} (large number, eq. defined in paper) + + T = list(range(num_products)) # 0-indexed product indices + P = list(range(num_patterns)) # 0-indexed pattern indices + + d = [products[i]["demand"] for i in T] + l = [products[i]["length"] for i in T] + N_i = [products[i]["N_i"] for i in T] # floor(L / l_i) + + # ------------------------------------------------------------------ + # Binary substitution parameters (eq. 24) + # n_i = minimum number of bits to represent N_i + # K_i = {1, ..., n_i} (1-indexed) + # b_k = 2^{k-1} + # ------------------------------------------------------------------ + def get_n_bits(Ni): + if Ni == 0: + return 1 + return max(1, math.ceil(math.log2(Ni + 1))) + + n_bits = [get_n_bits(N_i[i]) for i in T] + K_i = [list(range(1, n_bits[i] + 1)) for i in T] # 1-indexed + + def bk(k): + return 2 ** (k - 1) # b_k = 2^{k-1} + + # ------------------------------------------------------------------ + # Build Gurobi model + # ------------------------------------------------------------------ + model = gp.Model("OpenEndedCSCP_Linearized") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + model.setParam("OutputFlag", 1) + + # --- Variables --- + + # s_j in {0,1}: 1 if pattern j is used (eq. 22) + s = model.addVars(P, vtype=GRB.BINARY, name="s") + + # w_{ijk} in {0,1}: bit k of a_{ij} (binary substitution, eq. 24) + w = {} + for i in T: + for j in P: + for k in K_i[i]: + w[i, j, k] = model.addVar(vtype=GRB.BINARY, name=f"w_{i}_{j}_{k}") + + # z_j in Z_+: number of repetitions of pattern j (eq. 23) + z = model.addVars(P, vtype=GRB.INTEGER, lb=0, ub=M, name="z") + + # x_i >= 0: extra pieces of product i. + # INFERRED ASSUMPTION: declared continuous (x_i >= 0 per eq. 23, in R_+ component + # of y-vector). Physically integer, but relaxed here for faithfulness to OP form. + x = model.addVars(T, lb=0.0, name="x") + + # u_{ijk} = w_{ijk} * z_j (McCormick linearization auxiliary) + u = {} + for i in T: + for j in P: + for k in K_i[i]: + u[i, j, k] = model.addVar(lb=0.0, ub=float(M), name=f"u_{i}_{j}_{k}") + + # q_{ij} >= 0: production quantity (eq. 23), defined by linearization below + q = {} + for i in T: + for j in P: + q[i, j] = model.addVar(lb=0.0, name=f"q_{i}_{j}") + + # --- Objective (eq. 15) --- + model.setObjective( + C_s * gp.quicksum(s[j] for j in P) + C_r * gp.quicksum(z[j] for j in P), + GRB.MINIMIZE + ) + + # --- Constraints --- + + # (16)/(25) Configuration constraints: + # sum_{i in T} l_i * sum_{k in K_i} b_k * w_{ijk} <= L * s_j for all j in P + for j in P: + model.addConstr( + gp.quicksum( + l[i] * gp.quicksum(bk(k) * w[i, j, k] for k in K_i[i]) + for i in T + ) <= L * s[j], + name=f"config_{j}" + ) + + # (17) Linking constraints: z_j <= M * s_j for all j in P + for j in P: + model.addConstr(z[j] <= M * s[j], name=f"link_{j}") + + # McCormick linearization of u_{ijk} = w_{ijk} * z_j + # (w_{ijk} binary, z_j integer with upper bound M) + for i in T: + for j in P: + for k in K_i[i]: + model.addConstr(u[i, j, k] <= M * w[i, j, k], name=f"mck_a_{i}_{j}_{k}") + model.addConstr(u[i, j, k] <= z[j], name=f"mck_b_{i}_{j}_{k}") + model.addConstr(u[i, j, k] >= z[j] - M * (1 - w[i, j, k]), name=f"mck_c_{i}_{j}_{k}") + + # q_{ij} = sum_{k in K_i} b_k * u_{ijk} (exact linearization of a_{ij} * z_j) + for i in T: + for j in P: + model.addConstr( + q[i, j] == gp.quicksum(bk(k) * u[i, j, k] for k in K_i[i]), + name=f"q_def_{i}_{j}" + ) + + # (19) Demand fulfillment: sum_j q_{ij} + x_i >= d_i for all i in T + for i in T: + model.addConstr( + gp.quicksum(q[i, j] for j in P) + x[i] >= d[i], + name=f"demand_{i}" + ) + + # (20) Extra pieces bound: sum_j z_j >= sum_i x_i + model.addConstr( + gp.quicksum(z[j] for j in P) >= gp.quicksum(x[i] for i in T), + name="extra_bound" + ) + + # (21) Symmetry-breaking: z_{j-1} >= z_j for all j in P, j > 1 + for j in P: + if j > 0: + model.addConstr(z[j - 1] >= z[j], name=f"sym_{j}") + + # ------------------------------------------------------------------ + # Solve + # ------------------------------------------------------------------ + model.optimize() + + # ------------------------------------------------------------------ + # Extract solution + # ------------------------------------------------------------------ + if model.SolCount > 0: + obj_val = model.ObjVal + s_sol = {j: int(round(s[j].X)) for j in P} + z_sol = {j: int(round(z[j].X)) for j in P} + x_sol = {i: x[i].X for i in T} + a_sol = { + (i, j): int(sum(bk(k) * round(w[i, j, k].X) for k in K_i[i])) + for i in T for j in P + } + q_sol = {(i, j): q[i, j].X for i in T for j in P} + + solution = { + "objective_value": obj_val, + "status": "optimal" if model.status == GRB.OPTIMAL else "feasible_time_limit", + "patterns": { + str(j): { + "used": bool(s_sol[j]), + "repetitions": z_sol[j], + "pieces": { + str(products[i]["id"]): a_sol[i, j] + for i in T + } + } + for j in P + }, + "extra_pieces": {str(products[i]["id"]): x_sol[i] for i in T}, + "production_quantities": { + f"product_{products[i]['id']}_pattern_{j}": q_sol[i, j] + for i in T for j in P + } + } + else: + solution = { + "objective_value": None, + "status": "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 written to {args.solution_path}") + if solution.get("objective_value") is not None: + print(f"Objective value: {solution['objective_value']}") + print(f"Status: {solution['status']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/delage2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/delage2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delage2022/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/delage2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/delage2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delage2022/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/delage2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/delage2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delage2022/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/delage2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/delage2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delage2022/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/delage2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/delage2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delage2022/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/delage2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/delage2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delage2022/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/delage2022/gurobi_solution/large_solution_1.json b/tasks/delage2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..59f13ca6dbfdb5b52bd1bbce0c8f2f7cac2866be --- /dev/null +++ b/tasks/delage2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2d9b5cfc4fffba2c4b91f7b4f1a5d551ac83bb1e207082648681ed89c68ca80 +size 48391 diff --git a/tasks/delage2022/gurobi_solution/large_solution_2.json b/tasks/delage2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..9ce5b1e078ec706eef61f64edaf49ffc1bba1a56 --- /dev/null +++ b/tasks/delage2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:181b46562b9c22dea386906f25734dd428cb8778eda30f9cb1040405c68ca7e5 +size 48390 diff --git a/tasks/delage2022/gurobi_solution/large_solution_3.json b/tasks/delage2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3ba1bb9f238e2dee290457ec8b49016d58761bbe --- /dev/null +++ b/tasks/delage2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1696a8cc39bccdac21a1af66138cd2142a7e2955b32d859c97e1aa815032c4a +size 48391 diff --git a/tasks/delage2022/gurobi_solution/large_solution_4.json b/tasks/delage2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f75f0359121365ea8a30e493f5fe1f465caa15c8 --- /dev/null +++ b/tasks/delage2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3128bab009b6c5e5bc080a9f3445b48c56b9fe415bf24d1d48b606e9a2b164b +size 48382 diff --git a/tasks/delage2022/gurobi_solution/large_solution_5.json b/tasks/delage2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d3001d7f7e0a3fa5553daa2bc75b3cc87f176f00 --- /dev/null +++ b/tasks/delage2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e476e7080805539069b27d614c5063f8e251b6adbdc4fe88a90d0e5a36ccda6b +size 48387 diff --git a/tasks/delage2022/gurobi_solution/tiny_solution.json b/tasks/delage2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..7f760bdf91a80c0f83135ede92308985c50a54c0 --- /dev/null +++ b/tasks/delage2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04e6cb42b6011a219b6402a823353e6c064d12e952cb69a5d9b952c18ce54e9c +size 1746 diff --git a/tasks/delage2022/gurobi_solution_log/large_log_1.jsonl b/tasks/delage2022/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..974e5aa25d640a10148efa86f31e82e91d4a3f81 --- /dev/null +++ b/tasks/delage2022/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3bf938d5a9118d25a8c18695ff8c68b0d219e42175d236f6734342c1bf20c59 +size 1310 diff --git a/tasks/delage2022/gurobi_solution_log/large_log_2.jsonl b/tasks/delage2022/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c4fa86eaa2be1c5cb8b061373338d874dc1febb8 --- /dev/null +++ b/tasks/delage2022/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a8a5b9ff443db885a63e1d5eeac6e1d337d0556dcaa420dde66a323211a0921 +size 1439 diff --git a/tasks/delage2022/gurobi_solution_log/large_log_3.jsonl b/tasks/delage2022/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fa3a3c09fb715ed3804aeb71456e7c0080e323f --- /dev/null +++ b/tasks/delage2022/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1320d367deea05b7b9e4317aca48cb3fe757ee4714dc7e87e5abf053bcf64b7 +size 1307 diff --git a/tasks/delage2022/gurobi_solution_log/large_log_4.jsonl b/tasks/delage2022/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2d4dcddc7b54ef99c2bee32550fdde6f9a7eeb19 --- /dev/null +++ b/tasks/delage2022/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92436201d6b18231a4c8af9f90df64a6a38f9db3ca520b1424bc0a7d6324875b +size 1342 diff --git a/tasks/delage2022/gurobi_solution_log/large_log_5.jsonl b/tasks/delage2022/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f190805cdecb0ef7c2560216288cb0097ccb2c75 --- /dev/null +++ b/tasks/delage2022/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5a47798808c95a7c6c6f1eac3165dcda0300042925776f2c3a62bcba46508ae +size 860 diff --git a/tasks/delage2022/gurobi_solution_log/tiny_log.jsonl b/tasks/delage2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..03cbf1306b3b799b8b84d782b0446321b80a6baf --- /dev/null +++ b/tasks/delage2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14495cd53d361b0834ad762e6bcbace50a068feb52ba8a467934f18dbb2924c1 +size 83 diff --git a/tasks/delage2022/instance/large_instance_1.json b/tasks/delage2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4e557448ae38e603cce223b12f13c73f939a9660 --- /dev/null +++ b/tasks/delage2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40d89eb515027d18a59a5d8e2f28a1ca801ae0d0ca9707399e289c734f429339 +size 3337 diff --git a/tasks/delage2022/instance/large_instance_2.json b/tasks/delage2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..05b392bbc7dbb46ec3084c10a87a3fafa77d7800 --- /dev/null +++ b/tasks/delage2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50dd6ff4b09b73d1697b4b453a135be455cfb85f675b64901c9729dcfa061db2 +size 3636 diff --git a/tasks/delage2022/instance/large_instance_3.json b/tasks/delage2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..14aa65733e1f700b3dd4f7f5fa96495507ff1535 --- /dev/null +++ b/tasks/delage2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bae5eee14322bda89cc4175cf3eefbbd805ccc458cad735ffc44fc5352fb5d3e +size 3747 diff --git a/tasks/delage2022/instance/large_instance_4.json b/tasks/delage2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..1531ce0fd46ed013ae7a3487792ac3f038ce208a --- /dev/null +++ b/tasks/delage2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abd29c307d439684b5f34a5fce6a623538fbd4fcc471e9485801c11c23535591 +size 3626 diff --git a/tasks/delage2022/instance/large_instance_5.json b/tasks/delage2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e390fac2f45f58f3e32313b7b083ba06b5cdad4b --- /dev/null +++ b/tasks/delage2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe93e34dee1bb7f4ee89ff973d673d1c5ad709f6138ae82e80a5065684edf196 +size 3664 diff --git a/tasks/delage2022/instance/tiny_instance.json b/tasks/delage2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..9d86d3236a794d8d3b07155f90e9856cd46ac7a6 --- /dev/null +++ b/tasks/delage2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c2ca3dc0a557bca82ae9f7fcdf530d2d3004559bb4f8ca74e2b0b17a22d1ade +size 1014 diff --git a/tasks/delage2022/instance_schema.json b/tasks/delage2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a9af622c4ef08143596b61405a2f10542c88423e --- /dev/null +++ b/tasks/delage2022/instance_schema.json @@ -0,0 +1,18 @@ +{ + "machine_length": " Length of the cutting machine in which patterns are configured.", + "num_products": " Number of distinct product types to be cut.", + "num_patterns": " Number of available cutting pattern slots.", + "num_groups": " Number of product groups, where products sharing the same maximum pieces per pattern belong to the same group.", + "cost_setup_pattern": " Time cost incurred once for each cutting pattern that is used.", + "cost_repetition": " Time cost incurred for each repetition of any cutting pattern.", + "M": " Upper bound on the number of repetitions any single pattern may have, equal to the maximum demand among all products.", + "products": [ + { + "id": " Unique identifier of the product type.", + "length": " Length of one piece of this product type.", + "demand": " Number of pieces of this product type that must be produced.", + "N_i": " Maximum number of pieces of this product type that can fit within a single cutting pattern." + } + ], + "groups": " List of product IDs that share the same maximum pieces per pattern value, grouping products with identical fitting capacity." +} diff --git a/tasks/delage2022/mathematical_formulation.md b/tasks/delage2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..a1aa2d400469e97b3d5706f0e9cf40e5ee250e04 --- /dev/null +++ b/tasks/delage2022/mathematical_formulation.md @@ -0,0 +1,63 @@ +# Original Formulation: Open-Ended Continuous Stock Cutting Problem (Open-Ended CSCP) + +*Source: Logic-Based Benders Decomposition for Integrated Process Configuration and Production Planning Problems, Karim Pérez Martı́nez, Yossiri Adulyasak, and Raf Jans, 2022 (original OP formulation of Hajizadeh and Lee, 2007).* + +## Sets and Parameters + +- $T$: set of product types, indexed by $i$. + +- $P$: set of cutting patterns, indexed by $j$. + +- $C_r$: time required for a single pattern use (cutting time per repetition). + +- $C_s$: setup time for a used pattern. + +- $d_i$: demand for product $i$. + +- $l_i$: length of product $i$. + +- $L$: length of the cutting machine. + +- $M$: large number, defined as $M = \max_{i \in T}\{d_i\}$. + +## Decision Variables + +- $s_j \in \{0,1\}$, $\forall j \in P$: 1 if pattern $j$ is used, 0 otherwise (configuration decision, part of $\mathbf{x}$). + +- $a_{ij} \in \mathbb{Z}_+$, $\forall i \in T, j \in P$: number of pieces of product $i$ in pattern $j$ (configuration decision, part of $\mathbf{x}$). + +- $z_j \in \mathbb{R}_+$, $\forall j \in P$: number of repetitions (uses) of pattern $j$ (production planning decision, part of $\mathbf{y}$). + +- $x_i \in \mathbb{R}_+$, $\forall i \in T$: units of product $i$ produced as extra pieces (production planning decision, part of $\mathbf{y}$). + +- $q_{ij} \in \mathbb{R}_+$, $\forall i \in T, j \in P$: units of product $i$ produced by pattern $j$ (production quantities). + +## Objective + +$$\begin{align} +\text{OP:} \quad \min \quad \mathbf{c}^{\mathsf{T}}\mathbf{x} + \mathbf{d}^{\mathsf{T}}\mathbf{y} \;:\; +\min \quad & C_s \sum_{j \in P} s_j + C_r \sum_{j \in P} z_j \tag{15} +\end{align}$$ + +## Constraints + +$$\begin{align} +\mathbf{Ax} \ge \mathbf{a}: \quad & \sum_{i \in T} l_i\, a_{ij} \le L\, s_j, + & \forall j \in P, \tag{16}\\ +\mathbf{Bx} + \mathbf{Cy} \ge \mathbf{b}: \quad & z_j \le M\, s_j, + & \forall j \in P, \tag{17}\\ +\mathbf{q} = f(\mathbf{x},\mathbf{y}): \quad & q_{ij} = a_{ij}\, z_j, + & \forall i \in T,\; j \in P, \tag{18}\\ +\mathbf{Dy} + \mathbf{Eq} \ge \mathbf{e}: \quad & \sum_{j \in P} q_{ij} + x_i \ge d_i, + & \forall i \in T, \tag{19}\\ +& \sum_{j \in P} z_j \ge \sum_{i \in T} x_i, \tag{20}\\ +& z_{j-1} \ge z_j, + & \forall j \in P : j > 1, \tag{21}\\ +\mathbf{x} &\in \mathbb{B}^{|\mathcal{A}|} :\; s_j \in \{0,1\},\; a_{ij} \in \mathbb{Z}_+, + & \forall i \in T,\; j \in P, \tag{22}\\ +\mathbf{y} \in \mathbb{R}_+^{|\mathcal{B}|} \times \mathbb{Z}_+^{|\mathcal{C}|};\; + \mathbf{q} &\in \mathbb{R}_+^{|\mathcal{D}|} :\; x_i \ge 0,\; z_j \in \mathbb{Z}_+;\; q_{ij} \ge 0, + & \forall i \in T,\; j \in P. \tag{23} +\end{align}$$ + +The objective (15) minimizes the total setup and cutting time. Constraints (16) are the configuration (machine length) constraints, which ensure that the total length of the pieces in a used pattern does not exceed the machine length. Constraints (17) link the pattern-use indicator $s_j$ with the number of pattern repetitions $z_j$. **Constraints (18) are the nonlinear (bilinear) production quantity constraints**: the amount of product $i$ produced by pattern $j$ equals the product of the configuration variable $a_{ij}$ (pieces of $i$ per pattern $j$) and the production level $z_j$ (number of repetitions). Constraints (19) ensure demand fulfillment, allowing demand to be met jointly by patterns and extra pieces. Constraints (20) limit the total number of extra pieces by the total number of pattern repetitions. Symmetry-breaking inequalities (21) order the used patterns by the number of repetitions. Constraints (22)–(23) define the variable domains. diff --git a/tasks/delage2022/problem_description.txt b/tasks/delage2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e54a930109fca51c17c3e44e4f248d0dd4f7b03 --- /dev/null +++ b/tasks/delage2022/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A steel tube manufacturer operates an open-ended cutting machine that slices a continuous steel tube into smaller pieces of various product types. The machine has a fixed length, and it is configured using cutting patterns, each of which specifies how many pieces of each product type are cut simultaneously in a single pass. The machine may use multiple distinct patterns, and each pattern may be repeated multiple times. Because the machine is open-ended (the tube extends beyond the machine on one side), each repetition of any pattern can additionally produce one extra piece of any product type beyond what the pattern itself specifies. + +The input data consists of a set of products and a set of available patterns. Each product has a known length and a known demand (the number of pieces required). The cutting machine has a known total length. Two time-cost parameters are given: a setup time incurred once for each pattern that is used, and a cutting time incurred once per repetition of any pattern. A large number, equal to the maximum demand among all products, caps the number of repetitions any single pattern may have. For each product, the maximum number of pieces of that product that can fit within a single pattern is also given (computed as the machine length divided by the product length, rounded down). + +The manufacturer must decide which patterns to use, how many pieces of each product type to include in each pattern, how many times to repeat each pattern, and how many extra pieces of each product type to produce. The total number of units of each product produced by a given pattern equals the number of pieces of that product specified in that pattern multiplied by the number of repetitions of that pattern. If a pattern is not used, no pieces may be assigned to it. If a pattern is used, the sum of the lengths of all pieces assigned to it must not exceed the machine length. A pattern may have repetitions only if it has been set up for use, and its repetition count is limited by the large number described above. For every product, the total production from all patterns plus the extra pieces must meet or exceed the product's demand. The total number of extra pieces produced across all products must not exceed the total number of pattern repetitions across all patterns, reflecting the physical rule that at most one extra piece can be obtained per repetition. To avoid interchangeable orderings among patterns, patterns are ordered so that the number of repetitions of each pattern is at least as large as the number of repetitions of the next pattern. The number of pieces of each product in each pattern must be a whole number of zero or more, and the number of repetitions of each pattern must also be a whole number of zero or more. The number of extra pieces of each product must be zero or more. + +The goal is to minimize the total time, computed as the sum of the setup times for all used patterns plus the sum of the cutting times for all pattern repetitions. diff --git a/tasks/delage2022/solution_logger.py b/tasks/delage2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/delage2022/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/delage2022/solution_schema.json b/tasks/delage2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..23cecf7023d88caeb0434e11306e0b0db23a6acb --- /dev/null +++ b/tasks/delage2022/solution_schema.json @@ -0,0 +1,12 @@ +{ + "objective_value": " Total time required, equal to setup times of all used patterns plus cutting times of all pattern repetitions.", + "patterns": { + "": { + "used": " Whether this pattern is selected for use on the cutting machine.", + "repetitions": " Number of times this pattern is repeated on the cutting machine.", + "pieces": " Number of pieces of each product cut in a single pass of this pattern." + } + }, + "extra_pieces": " Number of extra pieces of each product produced via the open end of the machine across all pattern repetitions.", + "production_quantities": " Total number of pieces of each product produced by each pattern, equal to the pieces per pass multiplied by the number of repetitions." +} diff --git a/tasks/delorme2020/feasibility_check.py b/tasks/delorme2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..182b91b6397dd26fce606abd380915bd828219ce --- /dev/null +++ b/tasks/delorme2020/feasibility_check.py @@ -0,0 +1,415 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Bin Packing / Cutting Stock from Delorme & Iori (2019). + +Verifies the ORIGINAL BPP/CSP constraints against the original solution +structure (per-bin item lists), independent of the reflect-graph reformulation +used by gurobi_code.py. A solution produced by any other method (e.g. a +heuristic that does not use arc flows) can therefore be checked against the +same rules. + +Constraints checked: + Constraint 1: Demand satisfaction + For each item type j, the number of times type j appears + across all bins must be at least d_j. + Constraint 2: Bin capacity + Each bin's total weight must not exceed c. + Constraint 3: Bin count consistency + len(bin_assignments) must equal the reported number of bins + (objective value / num_bins). + Constraint 4: Domain + bin_assignments must be a list of lists of valid item-type + indices in {0, ..., m-1}. + +When bin_assignments is missing the checker reports indeterminate +(feasible=None) and only enforces the necessary lower bounds on z that any +BPP solution must satisfy (total-weight / capacity and large-item count). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('bin_assignments', 'num_bins', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('num_bins',) +_FRONTIEROR_DERIVED_FIELD_RULES = (('num_bins', 'length', 'bin_assignments', None),) +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + c = data["c"] + weights = data["weights"] + demands = data.get("demands", [1] * len(weights)) + return c, weights, demands, data + + +def load_solution(path): + with open(path, "r") as f: + return json.load(f) + + +def compute_violation_amount(lhs, rhs, op, tol): + if op == ">=": + amount = rhs - lhs + elif op == "<=": + amount = lhs - rhs + elif op == "==": + amount = abs(lhs - rhs) + else: + amount = 0.0 + return amount if amount > tol else None + + +def add_violation(violated_set, violations_list, magnitudes_list, + constraint_idx, message, lhs, rhs, op, tol, eps): + violation_amount = compute_violation_amount(lhs, rhs, op, tol) + if violation_amount is None: + return + normalizer = max(abs(rhs), eps) + violated_set.add(constraint_idx) + violations_list.append(message) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + +def check_bpp_packing(c, weights, demands, z_int, bin_assignments, tol, eps): + """Verify a BPP packing against the original problem constraints. + + bin_assignments is a list of bins; each bin is a list of integer item + *widths* (weights). The per-weight demand is computed by grouping the + instance's raw weights/demands by width. + """ + violated_set = set() + violations_list = [] + magnitudes_list = [] + + # Aggregate the instance's per-width demand from raw (weights, demands). + width_demand = {} + for w, d in zip(weights, demands): + width_demand[w] = width_demand.get(w, 0) + d + valid_widths = set(width_demand.keys()) + + if not isinstance(bin_assignments, list): + violated_set.add(4) + violations_list.append( + f"bin_assignments must be a list, got {type(bin_assignments).__name__}" + ) + magnitudes_list.append({ + "constraint": 4, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + return violated_set, violations_list, magnitudes_list + + sanitized_bins = [] + for b_idx, b in enumerate(bin_assignments): + if not isinstance(b, list): + violated_set.add(4) + violations_list.append( + f"bin_assignments[{b_idx}] is not a list (got {type(b).__name__})" + ) + magnitudes_list.append({ + "constraint": 4, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + sanitized_bins.append([]) + continue + clean = [] + for w in b: + if not isinstance(w, int) or w not in valid_widths: + violated_set.add(4) + violations_list.append( + f"bin_assignments[{b_idx}] contains invalid item width {w!r} " + f"(must be an integer width that appears in the instance)" + ) + magnitudes_list.append({ + "constraint": 4, + "lhs": float(w) if isinstance(w, (int, float)) else -1.0, + "rhs": float(c), + "raw_excess": 1.0, + "normalizer": max(float(c), eps), + "ratio": 1.0 / max(float(c), eps), + }) + else: + clean.append(w) + sanitized_bins.append(clean) + + # Constraint 2: bin capacity + for b_idx, b in enumerate(sanitized_bins): + total_w = sum(b) + add_violation( + violated_set, violations_list, magnitudes_list, + 2, + f"Bin {b_idx} total weight {total_w} exceeds capacity {c}", + lhs=total_w, rhs=c, op="<=", tol=tol, eps=eps, + ) + + # Constraint 1: demand satisfaction (per width) + width_count = {} + for b in sanitized_bins: + for w in b: + width_count[w] = width_count.get(w, 0) + 1 + for w, d_required in width_demand.items(): + d_packed = width_count.get(w, 0) + add_violation( + violated_set, violations_list, magnitudes_list, + 1, + f"Width {w} packed {d_packed} time(s) but demand is {d_required}", + lhs=d_packed, rhs=d_required, op=">=", tol=tol, eps=eps, + ) + + # Constraint 3: bin count consistency + add_violation( + violated_set, violations_list, magnitudes_list, + 3, + f"Number of bins in assignment ({len(bin_assignments)}) does not match " + f"reported z ({z_int})", + lhs=len(bin_assignments), rhs=z_int, op="==", tol=tol, eps=eps, + ) + + return violated_set, violations_list, magnitudes_list + + +def check_z_lower_bounds(c, weights, demands, z, tol, eps): + """Necessary lower bounds on z when no packing is provided.""" + violated_set = set() + violations_list = [] + magnitudes_list = [] + + total_weight = sum(w * d for w, d in zip(weights, demands)) + lb_capacity = math.ceil(total_weight / c) + add_violation( + violated_set, violations_list, magnitudes_list, + 3, + f"Reported z ({z}) below capacity lower bound " + f"ceil({total_weight}/{c})={lb_capacity}", + lhs=z, rhs=lb_capacity, op=">=", tol=tol, eps=eps, + ) + + half_c = c / 2.0 + large_item_count = sum(d for w, d in zip(weights, demands) if w > half_c) + add_violation( + violated_set, violations_list, magnitudes_list, + 3, + f"Reported z ({z}) below large-item lower bound ({large_item_count} items " + f"with weight > c/2 each need their own bin)", + lhs=z, rhs=large_item_count, op=">=", tol=tol, eps=eps, + ) + + return violated_set, violations_list, magnitudes_list + + +def main(): + parser = argparse.ArgumentParser( + description="BPP-native feasibility checker (Delorme & Iori 2019)" + ) + parser.add_argument("--instance_path", type=str, required=True) + parser.add_argument("--solution_path", type=str, required=True) + parser.add_argument("--result_path", type=str, required=True) + args = parser.parse_args() + + tol = 1e-5 + eps = 1e-5 + + c, weights, demands, _ = 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 + + z = solution.get("objective_value") + if z is None: + z = solution.get("num_bins") + + if z is None: + status = solution.get("status", "unknown") + result = { + "feasible": None, + "violated_constraints": [], + "violations": [f"No solution to check (status={status})"], + "violation_magnitudes": [], + } + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + return + + z_float = float(z) + z_int = int(round(z_float)) + + bin_assignments = solution.get("bin_assignments") + + if bin_assignments is not None: + violated_set, violations_list, magnitudes_list = check_bpp_packing( + c, weights, demands, z_int, bin_assignments, tol, eps + ) + feasible = len(violated_set) == 0 + else: + violated_set, violations_list, magnitudes_list = check_z_lower_bounds( + c, weights, demands, z_float, tol, eps + ) + if violated_set: + feasible = False + else: + feasible = None + violations_list.append( + "bin_assignments missing — only necessary lower bounds on z were " + "checked; full feasibility cannot be verified." + ) + + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations_list, + "violation_magnitudes": magnitudes_list, + } + + 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/delorme2020/gurobi_code.py b/tasks/delorme2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..cc06e2ae96f5ac886d659bbe225588286f2ac602 --- /dev/null +++ b/tasks/delorme2020/gurobi_code.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Reflect formulation (F_RE) for the Cutting Stock / +Bin Packing Problem. + +Based on: Delorme & Iori (2019) - "Enhanced Pseudo-polynomial Formulations + for Bin Packing and Cutting Stock Problems" + +This implements the F_RE formulation (Equations 16-20) over a reflect multigraph +G = (V, A_s union A_r), where arcs only span [0, c/2]. +""" + +import argparse +import json +from collections import defaultdict + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load a BPP/CSP instance from JSON and return CSP-form data.""" + with open(path, "r") as f: + data = json.load(f) + + c = data["c"] + raw_weights = data["weights"] + raw_demands = data["demands"] + + # Group items by weight to get CSP form (m distinct item types). + weight_to_demand = defaultdict(int) + for w, d in zip(raw_weights, raw_demands): + weight_to_demand[w] += d + + # Sort item types by weight (ascending). + types = sorted(weight_to_demand.items()) + weights = [t[0] for t in types] + demands = [t[1] for t in types] + m = len(weights) + + return c, m, weights, demands, data + + +def compute_normal_patterns(c, m, weights, demands): + """ + Compute the set of normal patterns N via DP (Equation 3). + + N = { w_hat = sum_{j=1}^{m} w_j * x_j : 0 <= w_hat <= c, + x_j in {0, ..., d_j} for j = 1, ..., m } + + Returns a sorted list of reachable values in [0, c]. + """ + reachable = set() + reachable.add(0) + + for j in range(m): + w_j = weights[j] + d_j = demands[j] + new_reachable = set() + for val in reachable: + for k in range(d_j + 1): + new_val = val + k * w_j + if new_val <= c: + new_reachable.add(new_val) + else: + break + reachable = reachable | new_reachable + + return sorted(reachable) + + +def build_reflect_graph(c, m, weights, demands): + """ + Build the reflect multigraph G = (V, A_s union A_r). + + Vertices V: all values in N that are <= c/2, plus R = c/2. + Standard arcs A_s: item arcs within [0, c/2] and loss arcs. + Reflected arcs A_r: item arcs that cross c/2, plus collision arc (R, R, r). + + Each arc is represented as (d, e, arc_type, item_idx) where: + - d, e are vertex values + - arc_type is 's' (standard) or 'r' (reflected) + - item_idx is 0-based item type index, or -1 for loss/collision arcs + + Returns: (vertices_list, arcs, R_val) + """ + N = compute_normal_patterns(c, m, weights, demands) + N_set = set(N) + + # R = c/2 (using integer or half-integer; we use float division) + # For the vertex set we work with half-integers if c is odd. + # Actually, the paper works with integer vertices and adds R = c/2 as a + # special vertex. When c is even, R is an integer that may or may not be + # in N. When c is odd, R = c/2 is not an integer. + # We represent all vertices as floats for generality. + R = c / 2.0 + + # Build vertex set: all values in N that are <= c/2, plus R. + V = set() + for val in N: + if val <= R: + V.add(val) + else: + reflected = c - val + if reflected >= 0: + V.add(reflected) + V.add(R) + V = sorted(V) + V_set = set(V) + + arcs = [] + + # --- Standard item arcs A_s --- + # (d, d + w_j, s) for each item type j and vertex d in V + # where d + w_j <= R and d + w_j is in V_set. + # (We only need d + w_j to be a valid vertex.) + for j in range(m): + w_j = weights[j] + for d in V: + e = d + w_j + if e <= R and e in V_set: + arcs.append((d, e, 's', j)) + + # --- Reflected item arcs A_r --- + # For each item type j and vertex d in V where: + # d < R, d + w_j > R, d + w_j <= c, and c - d - w_j is in V_set. + # Reduction (Proposition 5): only create if d <= c - d - w_j, + # i.e., d <= (c - w_j) / 2. + for j in range(m): + w_j = weights[j] + for d in V: + if d >= R: + continue + fill = d + w_j + if fill <= R: + continue # does not cross c/2, already handled as standard + if fill > c: + continue # exceeds bin capacity + reflected_target = c - fill # = c - d - w_j + if reflected_target < 0: + continue + # Reduction: d <= reflected_target + if d > reflected_target: + continue + if reflected_target in V_set: + arcs.append((d, reflected_target, 'r', j)) + + # --- Collision arc (R, R, r) --- + # Models two paths meeting exactly at c/2. + arcs.append((R, R, 'r', -1)) + + # --- Loss arcs (standard arcs connecting consecutive vertices) --- + # Following Cote-Iori (2018): loss arcs connect consecutive vertices in V. + for i in range(len(V) - 1): + arcs.append((V[i], V[i + 1], 's', -1)) + + return V, arcs, R + + +def solve_with_gurobi(V, arcs, R, c, m, weights, demands, time_limit): + """ + Build and solve the F_RE MIP formulation (Equations 16-20). + + Variables: xi_{d,e,kappa} for each arc (d, e, kappa) in A. + """ + model = gp.Model("ReflectBPP") + + # Solver parameters + model.setParam("TimeLimit", time_limit) + model.setParam("Threads", 1) + model.setParam("Presolve", 1) + model.setParam("Method", 2) + + V_set = set(V) + + # Identify arc subsets + A_r_indices = [] # indices of reflected arcs + A_s_indices = [] # indices of standard arcs + A_j_indices = defaultdict(list) # item type j -> list of arc indices + + for idx, (d, e, arc_type, item_idx) in enumerate(arcs): + if arc_type == 'r': + A_r_indices.append(idx) + else: + A_s_indices.append(idx) + if item_idx >= 0: + A_j_indices[item_idx].append(idx) + + # delta_s^-(e): standard arcs entering vertex e + delta_s_in = defaultdict(list) + # delta_r^-(e): reflected arcs entering vertex e + delta_r_in = defaultdict(list) + # delta^+(e): all arcs emanating from vertex e + delta_out = defaultdict(list) + + for idx, (d, e, arc_type, item_idx) in enumerate(arcs): + if arc_type == 's': + delta_s_in[e].append(idx) + else: + delta_r_in[e].append(idx) + delta_out[d].append(idx) + + # Decision variables: xi for each arc, non-negative integer. + xi = {} + for idx, (d, e, arc_type, item_idx) in enumerate(arcs): + ub = GRB.INFINITY + if item_idx >= 0: + ub = demands[item_idx] + xi[idx] = model.addVar( + vtype=GRB.INTEGER, name=f"xi_{idx}", lb=0, ub=ub + ) + + model.update() + + # Objective (16): min z = sum_{(d,e,r) in A_r} xi_{der} + model.setObjective( + gp.quicksum(xi[idx] for idx in A_r_indices), + GRB.MINIMIZE, + ) + + # Constraints (17): Flow conservation for each e in V \ {0} + # sum_{(d,e,s) in delta_s^-(e)} xi_{des} + # = sum_{(d,e,r) in delta_r^-(e)} xi_{der} + # + sum_{(e,f,kappa) in delta^+(e)} xi_{ef,kappa} + for e in V: + if e == 0: + continue + lhs = gp.quicksum(xi[idx] for idx in delta_s_in.get(e, [])) + rhs_reflect = gp.quicksum(xi[idx] for idx in delta_r_in.get(e, [])) + rhs_out = gp.quicksum(xi[idx] for idx in delta_out.get(e, [])) + model.addConstr(lhs == rhs_reflect + rhs_out, name=f"flow_{e}") + + # Constraint (18): Boundary at vertex 0 + # sum_{(0,e,kappa) in delta^+(0)} xi_{0e,kappa} + # = 2 * sum_{(d,e,r) in A_r} xi_{der} + lhs_zero = gp.quicksum(xi[idx] for idx in delta_out.get(0, [])) + rhs_total = gp.quicksum(xi[idx] for idx in A_r_indices) + model.addConstr(lhs_zero == 2 * rhs_total, name="flow_zero") + + # Constraints (19): Demand satisfaction + # sum_{(d,e,kappa) in A_j} xi_{de,kappa} >= d_j for j = 1,...,m + for j in range(m): + total_flow = gp.quicksum(xi[idx] for idx in A_j_indices.get(j, [])) + model.addConstr(total_flow >= demands[j], name=f"demand_{j}") + + # Solve + model.optimize() + + # Extract solution + obj_val = None + arc_flows = None + if model.SolCount > 0: + obj_val = model.ObjVal + arc_flows = [float(xi[idx].X) for idx in range(len(arcs))] + + return obj_val, arc_flows, model.Status + + +def decode_bins_from_arc_flows(V, arcs, arc_flows, R, weights): + """Convert reflect-graph arc flows into the original BPP solution structure. + + Each bin is a (forward + reflected + backward) closed walk from vertex 0 + back to vertex 0, threading exactly one reflected arc as the midpoint + crossing. We greedily replay the integer arc flows. At each forward step + we prefer (in order) (i) a reflected arc if available — reflect as soon + as possible, ending the forward leg; (ii) a standard item arc; (iii) a + standard loss arc. The backward leg uses the same priority on incoming + standard arcs. A bin is appended only when its closed walk completes. + + Returns: list of bins, each a list of item *widths* (integer weights) + packed in that bin. Loss arcs and the collision arc (R,R,r,-1) contribute + no width. Width-keyed output is used (rather than item indices) so the + representation matches the original BPP/CSP solution structure regardless + of whether the instance lists items individually (BPP raw form) or by + grouped type (CSP form): every demanded item-width must be packed. + """ + if arc_flows is None: + return None + flow = [int(round(f)) for f in arc_flows] + out_idx = {v: [] for v in V} + in_idx = {v: [] for v in V} + for idx, (d, e, kappa, j) in enumerate(arcs): + out_idx[d].append(idx) + in_idx[e].append(idx) + + from collections import deque + + def bfs_std_out(start, end): + """BFS shortest path start → end via standard out-arcs with flow > 0.""" + if start == end: + return [] + parent = {start: None} + q = deque([start]) + while q: + cur = q.popleft() + for idx in out_idx.get(cur, ()): + if flow[idx] <= 0 or arcs[idx][2] != 's': + continue + _, e, _, _ = arcs[idx] + if e in parent: + continue + parent[e] = (cur, idx) + if e == end: + path = [] + node = end + while parent[node] is not None: + prev, arc_idx = parent[node] + path.append(arc_idx) + node = prev + path.reverse() + return path + q.append(e) + return None + + def bfs_std_in(start, end): + """BFS shortest path start → end traversing standard in-arcs (each + arc (d,e,'s',j) is walked in reverse, end → start, so we move from + e to d).""" + if start == end: + return [] + parent = {start: None} + q = deque([start]) + while q: + cur = q.popleft() + for idx in in_idx.get(cur, ()): + if flow[idx] <= 0 or arcs[idx][2] != 's': + continue + d, _, _, _ = arcs[idx] + if d in parent: + continue + parent[d] = (cur, idx) + if d == end: + path = [] + node = end + while parent[node] is not None: + nxt, arc_idx = parent[node] + path.append(arc_idx) + node = nxt + path.reverse() + return path + q.append(d) + return None + + bins = [] + # Each unit of flow on a reflected arc represents one bin's midpoint + # crossing. For each such unit we extract a forward path 0→d via + # standard out-arcs and a backward path e→0 via standard in-arcs; + # the items on those three legs are the bin's contents. + while True: + refl_idx = next( + (i for i, a in enumerate(arcs) if a[2] == 'r' and flow[i] > 0), + None, + ) + if refl_idx is None: + break + d, e, _, j_refl = arcs[refl_idx] + + fwd = bfs_std_out(0.0, d) + bwd = bfs_std_in(e, 0.0) + if fwd is None or bwd is None: + break # flow not decomposable from current state; abort + + for idx in fwd: + flow[idx] -= 1 + flow[refl_idx] -= 1 + for idx in bwd: + flow[idx] -= 1 + + bin_items = [] + for idx in fwd: + j = arcs[idx][3] + if j >= 0: + bin_items.append(weights[j]) + if j_refl >= 0: + bin_items.append(weights[j_refl]) + for idx in bwd: + j = arcs[idx][3] + if j >= 0: + bin_items.append(weights[j]) + bins.append(sorted(bin_items)) + return bins + + +def main(): + parser = argparse.ArgumentParser( + description="Reflect formulation (F_RE) for Bin Packing (Gurobi solver)" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON instance file", + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path for the output solution JSON file", + ) + parser.add_argument( + "--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # Load instance + c, m, weights, demands, instance_data = load_instance(args.instance_path) + + # Build reflect multigraph + V, arcs, R = build_reflect_graph(c, m, weights, demands) + + # Solve MIP + obj_val, arc_flows, status = solve_with_gurobi( + V, arcs, R, c, m, weights, demands, args.time_limit + ) + + # Convert reformulation output back into the original BPP solution + # structure (per-bin item lists), which is what feasibility_check.py + # consumes. arc_flows is kept as a diagnostic field only. If the + # path-decomposition fails to recover exactly the reported number of + # bins (BFS-based flow decomposition can stall on dense instances), + # we emit None so feasibility_check falls back to its weak necessary- + # conditions branch instead of consuming a malformed packing. + bin_assignments = decode_bins_from_arc_flows(V, arcs, arc_flows, R, weights) + if ( + bin_assignments is not None + and obj_val is not None + and len(bin_assignments) != int(round(obj_val)) + ): + bin_assignments = None + + # Reconcile per-width counts with instance demand. The BFS-based arc-flow + # decomposition above can pick the "wrong" item index `j` when multiple + # item arcs out of the same vertex have positive flow — the path is + # vertex-correct but item-identity may swap (it walks j_B's arc when + # j_A's was intended). Net effect: some width is over-packed by 1, another + # is under-packed by 1, with similar widths so capacity is usually fine. + # Repair greedily: for each (over_w B, under_w A) pair find a bin that + # contains B and has enough slack to host A (slack >= A - B; free when + # A <= B). Loop until no more progress. + if bin_assignments is not None: + from collections import Counter + + def _imbalance(bins): + sc = Counter() + for b in bins: + for w in b: + sc[w] += 1 + dmd_dict = {} + for w, dmd in zip(weights, demands): + dmd_dict[w] = dmd_dict.get(w, 0) + dmd + ov = {w: s - dmd_dict.get(w, 0) + for w, s in sc.items() if s > dmd_dict.get(w, 0)} + un = {w: dmd_dict[w] - sc.get(w, 0) + for w in dmd_dict if sc.get(w, 0) < dmd_dict[w]} + return ov, un + + over, under = _imbalance(bin_assignments) + progress = True + while progress and over and under: + progress = False + for over_w in list(over.keys()): + if over_w not in over: + continue + for under_w in list(under.keys()): + if under_w not in under: + continue + delta = under_w - over_w + for b in bin_assignments: + if over_w not in b: + continue + if c - sum(b) < delta: + continue + b.remove(over_w) + b.append(under_w) + b.sort() + over[over_w] -= 1 + under[under_w] -= 1 + if over[over_w] == 0: + del over[over_w] + if under[under_w] == 0: + del under[under_w] + progress = True + break + if progress and over_w not in over: + break + # Residual imbalance (over with no matching under, or under unreachable + # by capacity) is left alone — checker tolerates over-supply, and + # under-supply will surface as a real violation for the user to inspect. + + # Build solution output + solution = { + "objective_value": obj_val, + "status": ( + "optimal" if status == GRB.OPTIMAL else + "time_limit" if status == GRB.TIME_LIMIT else + "feasible" if obj_val is not None else + "infeasible" + ), + "num_bins": int(round(obj_val)) if obj_val is not None else None, + "bin_assignments": bin_assignments, + "arc_flows": arc_flows, + } + + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if obj_val is not None: + print(f"Objective value (bins used): {obj_val}") + + +if __name__ == "__main__": + main() diff --git a/tasks/delorme2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/delorme2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delorme2020/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/delorme2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/delorme2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delorme2020/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/delorme2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/delorme2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delorme2020/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/delorme2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/delorme2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delorme2020/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/delorme2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/delorme2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delorme2020/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/delorme2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/delorme2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/delorme2020/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/delorme2020/gurobi_solution/large_solution_1.json b/tasks/delorme2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..36ec93cfa225a950d4e25d68987711c941609ca2 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbee8a407e3eeb66b4e7a471550ecc2c60d636384cd11fb16aaf44200380c201 +size 16424342 diff --git a/tasks/delorme2020/gurobi_solution/large_solution_2.json b/tasks/delorme2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..022827a3038161f1b144347736bd34e2155ddbe9 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cfa1101b190799158a7ef19b86131de1308e675933e7a82d03a168d00012269 +size 14020881 diff --git a/tasks/delorme2020/gurobi_solution/large_solution_3.json b/tasks/delorme2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d131f0d8d4d3f40e92cae0166ceefe1f11d9c6a4 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0380e9d93d6ebaf9ba226e4cbb816ec561b67a63d7ecc6dbb57c61653e07a7ec +size 16937574 diff --git a/tasks/delorme2020/gurobi_solution/large_solution_4.json b/tasks/delorme2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..98a148e3b083cd517ef88c6f5d04c3115b5e222e --- /dev/null +++ b/tasks/delorme2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f1a58961401964c073adfe81b43006d7fe2276dd1c99b52b0548925e75bb224 +size 15647193 diff --git a/tasks/delorme2020/gurobi_solution/large_solution_5.json b/tasks/delorme2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9960e659c6faccd3c03d5308661d807e28aa8f37 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94cf008f9b1e7552829e2faa8dd1e714a799690c321ddcda648256b70ef6cf5f +size 20385445 diff --git a/tasks/delorme2020/gurobi_solution/tiny_solution.json b/tasks/delorme2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..a2cae4cdcc4375c4f9d3317b56078676bdbbb98b --- /dev/null +++ b/tasks/delorme2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9dabbea3f38d57acab8c38b62bbe7d4ac6551a3042db896a147a6ab6b6a0c474 +size 11311 diff --git a/tasks/delorme2020/gurobi_solution_log/large_log_1.jsonl b/tasks/delorme2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9bf4669bab0c5ce04a4771be10c7983bbf93e488 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7f09fb729c95ff5eb55e6cb06cf1a17fd299b48ba41047ff3e086110db96e68 +size 570 diff --git a/tasks/delorme2020/gurobi_solution_log/large_log_2.jsonl b/tasks/delorme2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5ab89c2c8a2e16ae183f7acc9727b04fd7cb870d --- /dev/null +++ b/tasks/delorme2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29927531cf24c15c3ec94e539ee32f7c0bf428d009247270c08213b0a49e1a39 +size 258 diff --git a/tasks/delorme2020/gurobi_solution_log/large_log_3.jsonl b/tasks/delorme2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d54d9d798a6c8c9f155f81b5b44ef52927e05973 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:985a79789a1e13b4745d910b0a8983f4dd7cfe4d13b40b6be5d17699145f827a +size 305 diff --git a/tasks/delorme2020/gurobi_solution_log/large_log_4.jsonl b/tasks/delorme2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..15f6dce5092f70bd8a7919de96b33291e06d5363 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c89ee2de0084b0bbc9d4450bb88254b9b67d63093ffa296fb25bdad3794b8fda +size 222 diff --git a/tasks/delorme2020/gurobi_solution_log/large_log_5.jsonl b/tasks/delorme2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2a059bb2e0154e7777f42f9123be38a337205df6 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9cfcb9fb94440e561b47ee9086fec86f36fe3e276b4fe836c9689f994ded136 +size 260 diff --git a/tasks/delorme2020/gurobi_solution_log/tiny_log.jsonl b/tasks/delorme2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6333fba89ef95d63152c9c3d1f55e293c8c105b6 --- /dev/null +++ b/tasks/delorme2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2dfb1cd29a6c94b35d14392787e85889bc25e8b632b42f14421ab5754d60ad0f +size 41 diff --git a/tasks/delorme2020/instance/large_instance_1.json b/tasks/delorme2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..720a9016acc7a84b88cc1fcc63195fa9330ba669 --- /dev/null +++ b/tasks/delorme2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c60f8da58536402e5f1ab45076705c71d61a487a7a26e927ac82d6236936e01 +size 8123 diff --git a/tasks/delorme2020/instance/large_instance_2.json b/tasks/delorme2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a96a9ac706abec0e1f3cd1c0c7e1d151b7739840 --- /dev/null +++ b/tasks/delorme2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8aa96cfdf1767d03b28921761d1431f31bce596b176704133506ad8e0aa9470d +size 8260 diff --git a/tasks/delorme2020/instance/large_instance_3.json b/tasks/delorme2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..582445c9ddd2063cfcd14f083684e747408467fe --- /dev/null +++ b/tasks/delorme2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d4450c15fca11fa6b8bf224ab4f962f3b02810485479c7b55c25360519fff4c +size 8266 diff --git a/tasks/delorme2020/instance/large_instance_4.json b/tasks/delorme2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..29d71fd25685fa3efa213d03a71a378c04c554cf --- /dev/null +++ b/tasks/delorme2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95d2f6245c42011e7c5870c391fbb80e197461c1f6740c69830d39af352d41ec +size 8255 diff --git a/tasks/delorme2020/instance/large_instance_5.json b/tasks/delorme2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d2fb0ea69167cf986c98e71a51330143566c3729 --- /dev/null +++ b/tasks/delorme2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f70a4ec43ff4b29591a7a330ae7eab17589f17db77682c56d62bf2c2b062b15 +size 8053 diff --git a/tasks/delorme2020/instance/tiny_instance.json b/tasks/delorme2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a3a88f66f5e5ccb9aeff181dac1a8af434232a60 --- /dev/null +++ b/tasks/delorme2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c72a8cf33c537de1e0b11201789c92c94accd0f4a52469b778ec41355d67e11 +size 973 diff --git a/tasks/delorme2020/instance_schema.json b/tasks/delorme2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e0209664081be99e5ab3101820bdefceb7d5f7d6 --- /dev/null +++ b/tasks/delorme2020/instance_schema.json @@ -0,0 +1,7 @@ +{ + "n": " Total number of items that must be packed into bins.", + "m": " Number of distinct item types.", + "c": " Capacity of each bin.", + "weights": " Width of each item type.", + "demands": " Number of copies required for each item type." +} diff --git a/tasks/delorme2020/mathematical_formulation.md b/tasks/delorme2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..171d427fa1ddae5e38fd154a99751851cf18c071 --- /dev/null +++ b/tasks/delorme2020/mathematical_formulation.md @@ -0,0 +1,63 @@ +# Original Formulation: Cutting Stock Problem – Reflect ($F_{RE}$) + +*Source: Enhanced Pseudo-polynomial Formulations for Bin Packing and Cutting Stock Problems, Maxence Delorme, Manuel Iori, 2019 (INFORMS Journal on Computing).* + +The paper studies the bin packing problem (BPP) and the cutting stock problem (CSP) and proposes a new pseudo-polynomial formulation, *reflect* ($F_{RE}$, Section 4), which models a CSP instance using only half of the bin capacity. $F_{RE}$ is the formulation whose notation is carried into the subsequent algorithmic ($reflect+$) and computational sections, and is reported below as the canonical model. The classical arc-flow formulation $F_{AF}$ (Section 2.3), on which reflect builds, is given under *Variants*. + +## Sets and Parameters + +$$\begin{align*} +c & : \text{bin (stock) capacity, integer.} \\ +m & : \text{number of item types.} \\ +w_j & : \text{width of item type } j,\ j=1,\dots,m,\ \text{integer, } 0 < w_j < c. \\ +d_j & : \text{demand of item type } j,\ j=1,\dots,m,\ \text{integer.} \\ +\mathcal{S} & : \text{set of feasible item-width combinations not exceeding } c, \\ + & \quad \mathcal{S}=\Big\{\hat{w}=\textstyle\sum_{j=1}^{m} w_j x_j : \hat{w}\le c,\ x_j\in\mathbb{N},\ j=1,\dots,m\Big\}. \tag{3}\\ +R & : \text{reflection vertex corresponding to } c/2 \text{ (added explicitly; may be fractional if } c \text{ is odd).} +\end{align*}$$ + +The formulation is built on a multigraph $\mathcal{G}=(\mathcal{V},\mathcal{A})$: $$\begin{align*} +\mathcal{V} & : \text{set of vertices; all partial bin fillings of size smaller than } c/2,\\ + & \quad \text{plus the additional vertex } R \text{ corresponding to } c/2. \\ +\mathcal{A} & : \text{set of arcs, partitioned as } \mathcal{A}=\mathcal{A}_s \cup \mathcal{A}_r. \\ +\mathcal{A}_s & : \text{standard arcs (item and loss arcs proceeding left to right as in } F_{AF}\text{);}\\ + & \quad \text{each is the triplet } (d,e,s). \\ +\mathcal{A}_r & : \text{reflected arcs, i.e. item arcs } (d,e) \text{ of } F_{AF} \text{ with } dc/2 \\ + & \quad \text{reflected into } (d,c-e); \text{ plus the collision arc } (c/2,c/2,r)=(R,R,r);\\ + & \quad \text{each is the triplet } (d,e,r). \\ +(d,e,\kappa) & : \text{generic arc with } \kappa\in\{s,r\}. \\ +\mathcal{A}_j & : \text{item arcs associated with item type } j,\\ + & \quad \mathcal{A}_j=\{(d,d+w_j,s)\in\mathcal{A}_s\}\cup\{(d,c-d-w_j,r)\in\mathcal{A}_r\}. \\ +\delta_s^-(e) & \subseteq \mathcal{A}_s : \text{standard arcs entering vertex } e. \\ +\delta_r^-(e) & \subseteq \mathcal{A}_r : \text{reflected arcs entering vertex } e. \\ +\delta^+(e) & : \text{arcs emanating from vertex } e. +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +z & : \text{number of bins used (integer).} \\ +\xi_{de\kappa} & : \text{number of times arc } (d,e,\kappa)\in\mathcal{A} \text{ is chosen, integer.} +\end{align*}$$ + +## Objective + +$$\begin{align} +(F_{RE}) \quad \min \quad & z = \sum_{(d,e,r) \in \mathcal{A}_r} \xi_{der} + \tag{16} +\end{align}$$ + +## Constraints + +$$\begin{align} +& \sum_{(d,e,s) \in \delta_s^-(e)} \xi_{des} + = \sum_{(d,e,r) \in \delta_r^-(e)} \xi_{der} + + \sum_{(e,f,\kappa) \in \delta^+(e)} \xi_{ef\kappa}, + && e \in \mathcal{V} \setminus \{0\}, \tag{17} \\ +& \sum_{(0,e,\kappa) \in \delta^+(0)} \xi_{0e\kappa} + = 2 \sum_{(d,e,r) \in \mathcal{A}_r} \xi_{der}, \tag{18} \\ +& \sum_{(d,e,\kappa) \in \mathcal{A}_j} \xi_{de\kappa} \geq d_j, + && j = 1, \ldots, m, \tag{19} \\ +& \xi_{de\kappa} \in \mathbb{N}, + && (d,e,\kappa) \in \mathcal{A}. \tag{20} +\end{align}$$ diff --git a/tasks/delorme2020/problem_description.txt b/tasks/delorme2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f771e3c765b0eed0bbd35913bca68aea91d2b00 --- /dev/null +++ b/tasks/delorme2020/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +A facility has an unlimited supply of identical bins (or stock rolls), each with a fixed integer capacity. There are multiple distinct item types, where each item type has an integer width (strictly between zero and the bin capacity) and an integer demand specifying how many copies of that item must be packed. In the bin-packing variant of the problem each item is unique (all demands equal one), but items sharing the same width are grouped into a single type for compactness. The input data specifies the bin capacity, the number of item types, and for each item type its width and demand. + +Every demanded copy of every item type must be placed into exactly one bin. The total width of all items placed in any single bin must not exceed the bin capacity. The goal is to find a packing that satisfies all demand and capacity requirements while using as few bins as possible. diff --git a/tasks/delorme2020/solution_logger.py b/tasks/delorme2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/delorme2020/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/delorme2020/solution_schema.json b/tasks/delorme2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..6b21234ecff934e40ca7651a46c3425da12de585 --- /dev/null +++ b/tasks/delorme2020/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total number of bins used.", + "num_bins": " Total number of bins used, rounded to the nearest integer.", + "bin_assignments": " One inner list per used bin; each inner list holds the integer item widths (weights) packed into that bin. The multiset of widths across all bins must cover every item's demand, and the sum of widths in each bin must not exceed the bin capacity." +} diff --git a/tasks/desaulniers2010/feasibility_check.py b/tasks/desaulniers2010/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..3e8b43ec614a8416044497edf216104bbf441c15 --- /dev/null +++ b/tasks/desaulniers2010/feasibility_check.py @@ -0,0 +1,757 @@ +""" +Feasibility checker for the Split-Delivery Vehicle Routing Problem with +Time Windows (SDVRPTW). + +Based on: Desaulniers (2010), "Branch-and-Price-and-Cut for the Split-Delivery +Vehicle Routing Problem with Time Windows", Operations Research 58(1):179-192. + +Checks constraints (1)-(15) of the arc-flow formulation. + +Tier C addition (obj-recompute defense): constraint (1) -- the objective +function itself -- is recomputed from the solution routes. The objective +minimizes the total travel cost sum_{f} sum_{(i,j)} c_{ij} x^f_{ij}; every +arc-determining variable (the routes) is present in the solution, so the +objective is fully recomputable. The reported objective_value must equal the +recomputed total arc cost (within tolerance), otherwise the solution is +rejected. This defends against candidates that pass the routing constraints +but fabricate a better-looking objective_value. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('deliveries', 'num_vehicles_used', 'objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('num_vehicles_used', 'deliveries') +_FRONTIEROR_DERIVED_FIELD_RULES = (('num_vehicles_used', 'length', 'routes', None),) +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def build_instance_info(data): + """Build graph and precompute data structures from instance JSON.""" + n = data["num_customers"] + Q = data["vehicle_capacity"] + depot = data["depot"] + customers = data["customers"] + dist_matrix = data["distance_matrix"] + + num_nodes = n + 2 # 0..n+1 + + # Service times + service = [0] * num_nodes + service[0] = depot["service_time"] + for c in customers: + service[c["id"]] = c["service_time"] + service[n + 1] = 0 + + # Time windows + e = [0] * num_nodes + l = [0] * num_nodes + e[0] = depot["time_window"][0] + l[0] = depot["time_window"][1] + e[n + 1] = depot["time_window"][0] + l[n + 1] = depot["time_window"][1] + for c in customers: + e[c["id"]] = c["time_window"][0] + l[c["id"]] = c["time_window"][1] + + # Demands + demand = [0] * num_nodes + for c in customers: + demand[c["id"]] = c["demand"] + d_bar = [min(demand[i], Q) for i in range(num_nodes)] + + # Distance / travel-time matrices (0..n+1) + # Node n+1 is the return depot; its distances mirror node 0. + t_mat = [[0.0] * num_nodes for _ in range(num_nodes)] + c_mat = [[0.0] * num_nodes for _ in range(num_nodes)] + + for i in range(n + 1): + for j in range(n + 1): + c_mat[i][j] = dist_matrix[i][j] + t_mat[i][j] = dist_matrix[i][j] + service[i] + + for i in range(n + 1): + c_mat[i][n + 1] = dist_matrix[i][0] + t_mat[i][n + 1] = dist_matrix[i][0] + service[i] + c_mat[n + 1][i] = dist_matrix[0][i] + t_mat[n + 1][i] = dist_matrix[0][i] + service[n + 1] + c_mat[n + 1][n + 1] = 0.0 + t_mat[n + 1][n + 1] = 0.0 + + N = list(range(1, n + 1)) + V = list(range(0, n + 2)) + N_set = set(N) + + # Build arc set A + arcs = set() + for i in V: + for j in V: + if i == j: + continue + if i == n + 1 or j == 0: + continue + if e[i] + t_mat[i][j] <= l[j]: + arcs.add((i, j)) + + V_plus = {i: [] for i in V} + V_minus = {i: [] for i in V} + for (i, j) in arcs: + V_plus[i].append(j) + V_minus[j].append(i) + + kC = {i: math.ceil(demand[i] / Q) for i in N} + kC_N = math.ceil(sum(demand[i] for i in N) / Q) + F_size = sum(kC[i] for i in N) + + A_N = {(i, j) for (i, j) in arcs if i in N_set and j in N_set} + + # A*(N) + A_star_N = set() + A_star_ij = {} + processed = set() + for (i, j) in sorted(A_N): + if (i, j) in processed: + continue + if (j, i) in A_N: + rep = (min(i, j), max(i, j)) + if rep not in A_star_N: + A_star_N.add(rep) + A_star_ij[rep] = [(i, j), (j, i)] + processed.add((i, j)) + processed.add((j, i)) + else: + A_star_N.add((i, j)) + A_star_ij[(i, j)] = [(i, j)] + processed.add((i, j)) + + return { + "n": n, "Q": Q, "num_nodes": num_nodes, + "N": N, "N_set": N_set, "V": V, + "e": e, "l": l, "demand": demand, "d_bar": d_bar, + "t_mat": t_mat, "c_mat": c_mat, "service": service, + "arcs": arcs, "V_plus": V_plus, "V_minus": V_minus, + "kC": kC, "kC_N": kC_N, "F_size": F_size, + "A_N": A_N, "A_star_N": A_star_N, "A_star_ij": A_star_ij, + } + + +def extract_vehicles(solution): + """ + Extract per-vehicle data from solution JSON. + Returns list of dicts with keys: route, deliveries, num_vehicles. + Each entry with num_vehicles > 1 is expanded into separate identical vehicles. + """ + vehicles = [] + for r in solution["routes"]: + route = r["route"] + deliveries = {} + for k, v in r["deliveries"].items(): + deliveries[int(k)] = float(v) + nv = r.get("num_vehicles", 1) + for _ in range(nv): + vehicles.append({"route": list(route), "deliveries": dict(deliveries)}) + return vehicles + + +def record_violation(violations_list, magnitudes_list, violated_set, + constraint_idx, message, lhs, rhs, violation_amount, + tol=1e-5, eps=1e-5): + """Record a violation if violation_amount > tol.""" + if violation_amount > tol: + violated_set.add(constraint_idx) + violations_list.append(message) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + +def check_feasibility(data, solution): + """Check all hard constraints (1)-(15) of the arc-flow formulation.""" + info = build_instance_info(data) + vehicles = extract_vehicles(solution) + + n = info["n"] + Q = info["Q"] + N = info["N"] + N_set = info["N_set"] + e = info["e"] + l = info["l"] + demand = info["demand"] + d_bar = info["d_bar"] + t_mat = info["t_mat"] + c_mat = info["c_mat"] + arcs = info["arcs"] + V_plus = info["V_plus"] + kC = info["kC"] + kC_N = info["kC_N"] + F_size = info["F_size"] + + tol = 1e-5 + eps = 1e-5 + + violations = [] + magnitudes = [] + violated_set = set() + + num_vehicles = len(vehicles) + depot_end = n + 1 # node n+1 + + # ========================================================================= + # Constraint (2): Demand fulfillment + # sum_f delta^f_i >= d_i for all i in N + # ========================================================================= + for i in N: + total_delivered = sum(v["deliveries"].get(i, 0.0) for v in vehicles) + lhs = total_delivered + rhs = demand[i] + va = max(rhs - lhs, 0.0) # >= constraint: rhs - lhs + record_violation(violations, magnitudes, violated_set, + 2, f"Constraint (2): Customer {i} demand not met: " + f"delivered={lhs:.4f}, demand={rhs}", + lhs, rhs, va, tol, eps) + + # ========================================================================= + # Constraint (3): Minimum visit count per customer + # sum_f sum_{j in V+(i)} x^f_{ij} >= k^C_i for all i in N + # ========================================================================= + for i in N: + visit_count = 0 + for v in vehicles: + route = v["route"] + for idx in range(len(route)): + if route[idx] == i: + visit_count += 1 + lhs = visit_count + rhs = kC[i] + va = max(rhs - lhs, 0.0) + record_violation(violations, magnitudes, violated_set, + 3, f"Constraint (3): Customer {i} visited {lhs} times, " + f"minimum required {rhs}", + lhs, rhs, va, tol, eps) + + # ========================================================================= + # Constraint (4): Fleet size computation + # sum_f sum_{j in V+(0)\{n+1}} x^f_{0j} = H + # H is defined as the number of vehicles used (non-empty routes). + # In the solution, H = number of vehicles with routes visiting customers. + # ========================================================================= + # Count vehicles leaving depot to a customer (not directly to n+1) + departures_to_customers = 0 + for v in vehicles: + route = v["route"] + if len(route) >= 2 and route[0] == 0: + next_node = route[1] + if next_node != depot_end: + departures_to_customers += 1 + + H = sum(1 for v in vehicles if any(nd in N_set for nd in v["route"])) + lhs = departures_to_customers + rhs = H + va = abs(lhs - rhs) + record_violation(violations, magnitudes, violated_set, + 4, f"Constraint (4): Departures from depot to customers " + f"({lhs}) != H ({rhs})", + lhs, rhs, va, tol, eps) + + # ========================================================================= + # Constraint (5): Fleet size bounds + # H in [k^C(N), |F|], integer + # ========================================================================= + if H < kC_N: + va = kC_N - H + record_violation(violations, magnitudes, violated_set, + 5, f"Constraint (5): H={H} < k^C(N)={kC_N}", + H, kC_N, va, tol, eps) + if H > F_size: + va = H - F_size + record_violation(violations, magnitudes, violated_set, + 5, f"Constraint (5): H={H} > |F|={F_size}", + H, F_size, va, tol, eps) + if abs(H - round(H)) > tol: + va = abs(H - round(H)) + record_violation(violations, magnitudes, violated_set, + 5, f"Constraint (5): H={H} is not integer", + H, round(H), va, tol, eps) + + # ========================================================================= + # Constraint (6): k-path inequalities (SKIPPED - cutting plane) + # sum_f sum_{(i,j) in A^-(U)} x^f_{ij} >= k_U for all U in P(N) + # Per math_model.txt: "initially relaxed, added as cuts" and + # "Constraints (3)-(7) are redundant for the integer formulation but + # strengthen the linear relaxation." + # These are valid inequalities added as cutting planes during the + # branch-and-price-and-cut process, not hard feasibility constraints + # for the arc-flow formulation solved by Gurobi. + # ========================================================================= + + # Build arc usage from solution (needed for constraint 15) + arc_usage = {} + for v in vehicles: + route = v["route"] + for idx in range(len(route) - 1): + arc = (route[idx], route[idx + 1]) + arc_usage[arc] = arc_usage.get(arc, 0) + 1 + + # ========================================================================= + # Constraint (7): Arc-flow inequalities (SKIPPED - cutting plane) + # sum_f sum_{(i,j) in A*_{i'j'}} x^f_{ij} <= 1 for all (i',j') in A*(N) + # Per math_model.txt: "initially relaxed, added as cuts". + # These are valid inequalities from Corollary 2, not hard feasibility + # constraints for the arc-flow formulation. + # ========================================================================= + + # ========================================================================= + # Constraint (8): Path origin - each vehicle leaves depot exactly once + # sum_{j in V+(0)} x^f_{0,j} = 1 for all f in F + # ========================================================================= + for f_idx, v in enumerate(vehicles): + route = v["route"] + if route[0] != 0: + record_violation(violations, magnitudes, violated_set, + 8, f"Constraint (8): Vehicle {f_idx} route does " + f"not start at depot 0 (starts at {route[0]})", + 0, 1, 1.0, tol, eps) + # Count departures from node 0 + depart_count = sum(1 for idx in range(len(route) - 1) if route[idx] == 0) + lhs_val = depart_count + rhs_val = 1 + va = abs(lhs_val - rhs_val) + record_violation(violations, magnitudes, violated_set, + 8, f"Constraint (8): Vehicle {f_idx} departs from " + f"depot {lhs_val} times (must be 1)", + lhs_val, rhs_val, va, tol, eps) + + # ========================================================================= + # Constraint (9): Flow conservation per vehicle at each customer node + # sum_{j in V+(i)} x^f_{ij} - sum_{j in V-(i)} x^f_{ji} = 0 + # for all f in F, i in N + # ========================================================================= + for f_idx, v in enumerate(vehicles): + route = v["route"] + for i in N: + out_count = 0 + in_count = 0 + for idx in range(len(route) - 1): + if route[idx] == i: + out_count += 1 + if route[idx + 1] == i: + in_count += 1 + lhs_val = out_count - in_count + rhs_val = 0 + va = abs(lhs_val - rhs_val) + record_violation(violations, magnitudes, violated_set, + 9, f"Constraint (9): Vehicle {f_idx}, node {i}: " + f"out={out_count}, in={in_count}, balance={lhs_val}", + lhs_val, rhs_val, va, tol, eps) + + # ========================================================================= + # Constraint (10): Path termination + # sum_{i in V-(n+1)} x^f_{i,n+1} = 1 for all f in F + # ========================================================================= + for f_idx, v in enumerate(vehicles): + route = v["route"] + if route[-1] != depot_end: + record_violation(violations, magnitudes, violated_set, + 10, f"Constraint (10): Vehicle {f_idx} route does " + f"not end at node {depot_end} (ends at {route[-1]})", + 0, 1, 1.0, tol, eps) + arrive_count = sum(1 for idx in range(len(route) - 1) + if route[idx + 1] == depot_end) + lhs_val = arrive_count + rhs_val = 1 + va = abs(lhs_val - rhs_val) + record_violation(violations, magnitudes, violated_set, + 10, f"Constraint (10): Vehicle {f_idx} arrives at " + f"depot {lhs_val} times (must be 1)", + lhs_val, rhs_val, va, tol, eps) + + # ========================================================================= + # Constraint (11): Time consistency (linearized) + # For each vehicle f and each arc (i,j) used: s^f_i + t_{ij} <= s^f_j + # (when x^f_{ij}=1, i.e., on arcs actually traversed) + # + # Constraint (12): Time windows + # e_i <= s^f_i <= l_i for all f, i in V + # + # We compute earliest feasible schedule for each vehicle and check both. + # ========================================================================= + for f_idx, v in enumerate(vehicles): + route = v["route"] + if len(route) < 2: + continue + + # Compute earliest start times along the route + s = [0.0] * len(route) + s[0] = e[route[0]] # depot earliest + + for idx in range(1, len(route)): + i_node = route[idx - 1] + j_node = route[idx] + arrival = s[idx - 1] + t_mat[i_node][j_node] + s[idx] = max(e[j_node], arrival) + + # Check constraint (11): time consistency on used arcs + for idx in range(1, len(route)): + i_node = route[idx - 1] + j_node = route[idx] + lhs_val = s[idx - 1] + t_mat[i_node][j_node] + rhs_val = s[idx] + # Constraint: s_i + t_ij <= s_j (i.e., lhs <= rhs) + va = max(lhs_val - rhs_val, 0.0) + record_violation(violations, magnitudes, violated_set, + 11, f"Constraint (11): Vehicle {f_idx}, arc " + f"({i_node},{j_node}): s_i + t_ij = {lhs_val:.4f} " + f"> s_j = {rhs_val:.4f}", + lhs_val, rhs_val, va, tol, eps) + + # Check constraint (12): time windows + for idx in range(len(route)): + node = route[idx] + s_val = s[idx] + # e_node <= s_val + va_lower = max(e[node] - s_val, 0.0) + record_violation(violations, magnitudes, violated_set, + 12, f"Constraint (12): Vehicle {f_idx}, node {node}: " + f"start time {s_val:.4f} < earliest {e[node]}", + s_val, e[node], va_lower, tol, eps) + # s_val <= l_node + va_upper = max(s_val - l[node], 0.0) + record_violation(violations, magnitudes, violated_set, + 12, f"Constraint (12): Vehicle {f_idx}, node {node}: " + f"start time {s_val:.4f} > latest {l[node]}", + s_val, l[node], va_upper, tol, eps) + + # ========================================================================= + # Constraint (13): Vehicle capacity + # sum_{i in N} delta^f_i <= Q for all f in F + # ========================================================================= + for f_idx, v in enumerate(vehicles): + total_load = sum(v["deliveries"].values()) + lhs_val = total_load + rhs_val = Q + va = max(lhs_val - rhs_val, 0.0) + record_violation(violations, magnitudes, violated_set, + 13, f"Constraint (13): Vehicle {f_idx} load " + f"{lhs_val:.4f} > capacity {rhs_val}", + lhs_val, rhs_val, va, tol, eps) + + # ========================================================================= + # Constraint (14): Delivery quantity bounds and linking + # 0 <= delta^f_i <= d_bar_i * sum_{j in V+(i)} x^f_{ij} + # for all f in F, i in N + # ========================================================================= + for f_idx, v in enumerate(vehicles): + route = v["route"] + visited_in_route = set(route) + for i in N: + delta_fi = v["deliveries"].get(i, 0.0) + # Check non-negativity + if delta_fi < -tol: + va = abs(delta_fi) + record_violation(violations, magnitudes, violated_set, + 14, f"Constraint (14): Vehicle {f_idx}, " + f"customer {i}: delivery {delta_fi:.4f} < 0", + delta_fi, 0.0, va, tol, eps) + # Check upper bound: d_bar_i * (1 if visited, 0 if not) + visits_i = sum(1 for idx in range(len(route) - 1) if route[idx] == i) + upper = d_bar[i] * visits_i + va = max(delta_fi - upper, 0.0) + record_violation(violations, magnitudes, violated_set, + 14, f"Constraint (14): Vehicle {f_idx}, " + f"customer {i}: delivery {delta_fi:.4f} > " + f"d_bar*visits = {upper:.4f} " + f"(d_bar={d_bar[i]}, visits={visits_i})", + delta_fi, upper, va, tol, eps) + + # ========================================================================= + # Constraint (15): Binary requirement + # x^f_{ij} in {0, 1} for all f in F, (i,j) in A + # In route representation, each arc is used 0 or 1 times per vehicle. + # Check no arc is traversed more than once by the same vehicle, and + # that all used arcs are in A. + # ========================================================================= + for f_idx, v in enumerate(vehicles): + route = v["route"] + arc_count = {} + for idx in range(len(route) - 1): + arc = (route[idx], route[idx + 1]) + arc_count[arc] = arc_count.get(arc, 0) + 1 + for arc, cnt in arc_count.items(): + if cnt > 1: + va = cnt - 1 + record_violation(violations, magnitudes, violated_set, + 15, f"Constraint (15): Vehicle {f_idx} " + f"uses arc {arc} {cnt} times (must be 0 or 1)", + cnt, 1, va, tol, eps) + if arc not in arcs: + # Arc not in feasible arc set + record_violation(violations, magnitudes, violated_set, + 15, f"Constraint (15): Vehicle {f_idx} " + f"uses arc {arc} which is not in A", + 1, 0, 1.0, tol, eps) + + # ========================================================================= + # Constraint (1): Objective consistency [Tier C obj-recompute defense] + # minimize sum_{f in F} sum_{(i,j) in A} c_{ij} x^f_{ij} + # = total travel cost over all arcs traversed by all vehicles. + # The routes are the only obj-determining variables and are fully present + # in the solution, so the objective is exactly recomputable. Reject when + # the reported objective_value disagrees with the recomputed total cost. + # Tolerance: 0.1% relative 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: + num_nodes = info["num_nodes"] + true_obj = 0.0 + for v in vehicles: + route = v["route"] + for idx in range(len(route) - 1): + i_node = route[idx] + j_node = route[idx + 1] + if (0 <= i_node < num_nodes) and (0 <= j_node < num_nodes): + true_obj += c_mat[i_node][j_node] + # 0.1% relative tolerance with 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + abs_diff = abs(reported - true_obj) + # A non-finite reported objective (inf / nan) can never match the + # finite recomputed travel cost; force the violation (note nan + # comparisons are False, so abs_diff must be set explicitly). + if not math.isfinite(reported): + abs_diff = float("inf") + record_violation(violations, magnitudes, violated_set, + 1, f"Constraint (1): Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed total arc cost " + f"sum_f sum_(i,j) c_ij*x^f_ij={true_obj:.6f} " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported, true_obj, abs_diff, obj_tol, eps) + + # ========================================================================= + # Build result + # ========================================================================= + violated_constraints = sorted(violated_set) + feasible = len(violated_constraints) == 0 + + # Aggregate violations by constraint index for cleaner messages + constraint_messages = {} + for msg in violations: + # Extract constraint index from message + cidx = None + for vc in violated_constraints: + if msg.startswith(f"Constraint ({vc})"): + cidx = vc + break + if cidx is not None: + if cidx not in constraint_messages: + constraint_messages[cidx] = [] + constraint_messages[cidx].append(msg) + + # Create summary violations list (one per violated constraint) + summary_violations = [] + for cidx in violated_constraints: + msgs = constraint_messages.get(cidx, []) + if len(msgs) <= 3: + summary_violations.extend(msgs) + else: + summary_violations.extend(msgs[:2]) + summary_violations.append( + f"Constraint ({cidx}): ... and {len(msgs) - 2} more violations" + ) + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": summary_violations, + "violation_magnitudes": magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for SDVRPTW (Desaulniers 2010)" + ) + 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() + + data = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(data, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"FEASIBLE - no constraints violated") + else: + print(f"INFEASIBLE - violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/desaulniers2010/gurobi_code.py b/tasks/desaulniers2010/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5e18edf9f008fa00efb1fcbee8c60bb69742db --- /dev/null +++ b/tasks/desaulniers2010/gurobi_code.py @@ -0,0 +1,373 @@ +""" +Gurobi implementation of the arc-flow formulation for the Split-Delivery +Vehicle Routing Problem with Time Windows (SDVRPTW). + +Based on: Desaulniers (2010), "Branch-and-Price-and-Cut for the Split-Delivery +Vehicle Routing Problem with Time Windows", Operations Research 58(1):179-192. + +Implements equations (1)-(15) from the paper. +""" + +import argparse +import json +import math +import time +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(instance_path, solution_path, time_limit): + data = load_instance(instance_path) + + n = data["num_customers"] + Q = data["vehicle_capacity"] + depot = data["depot"] + customers = data["customers"] + dist = data["distance_matrix"] # (n+1) x (n+1), indices 0..n for depot + customers + + # Node set: 0 = depot start, 1..n = customers, n+1 = depot end + # The distance matrix is (n+1) x (n+1) with rows/cols for depot (0) and customers (1..n). + # We need to add node n+1 (depot end) with same location as depot. + + # Build full distance/time matrix for nodes 0..n+1 + num_nodes = n + 2 # 0, 1, ..., n, n+1 + t_mat = [[0.0] * num_nodes for _ in range(num_nodes)] + c_mat = [[0.0] * num_nodes for _ in range(num_nodes)] + + # Travel time includes service time at i (standard Solomon convention) + service = [0] * num_nodes + service[0] = depot["service_time"] + for cust in customers: + service[cust["id"]] = cust["service_time"] + service[n + 1] = 0 + + # Time windows + e = [0] * num_nodes + l = [0] * num_nodes + e[0] = depot["time_window"][0] + l[0] = depot["time_window"][1] + e[n + 1] = depot["time_window"][0] + l[n + 1] = depot["time_window"][1] + for cust in customers: + cid = cust["id"] + e[cid] = cust["time_window"][0] + l[cid] = cust["time_window"][1] + + # Demands + demand = [0] * num_nodes + for cust in customers: + demand[cust["id"]] = cust["demand"] + d_bar = [min(demand[i], Q) for i in range(num_nodes)] + + # Fill distance/cost matrix + # dist matrix from JSON is (n+1) x (n+1) with index 0=depot, 1..n=customers + for i in range(n + 1): + for j in range(n + 1): + c_mat[i][j] = dist[i][j] + # t_{ij} = distance + service time at i (Solomon convention) + t_mat[i][j] = dist[i][j] + service[i] + + # Node n+1 has same distances as depot (node 0) + for i in range(n + 1): + c_mat[i][n + 1] = dist[i][0] + t_mat[i][n + 1] = dist[i][0] + service[i] + c_mat[n + 1][i] = dist[0][i] + t_mat[n + 1][i] = dist[0][i] + service[n + 1] + c_mat[n + 1][n + 1] = 0.0 + t_mat[n + 1][n + 1] = 0.0 + + # Build arc set A + # Arc (i,j) exists if e_i + t_{ij} <= l_j, i != j + # Include (0, n+1) but not (n+1, 0) + N = list(range(1, n + 1)) # customer nodes + V = list(range(0, n + 2)) # all nodes + + arcs = [] + for i in V: + for j in V: + if i == j: + continue + if i == n + 1 and j == 0: + continue # no arc (n+1, 0) + if j == 0: + continue # no arcs into depot start + if i == n + 1: + continue # no arcs from depot end (except handled above) + if e[i] + t_mat[i][j] <= l[j]: + arcs.append((i, j)) + + arc_set = set(arcs) + + # Successor and predecessor sets + V_plus = {i: [] for i in V} + V_minus = {i: [] for i in V} + for (i, j) in arcs: + V_plus[i].append(j) + V_minus[j].append(i) + + # Upper bound on number of vehicles + F_size = sum(math.ceil(demand[i] / Q) for i in N) + F = list(range(F_size)) + + # k^C_i = ceil(d_i / Q) + kC = {i: math.ceil(demand[i] / Q) for i in N} + # k^C(N) = ceil(sum d_i / Q) + kC_N = math.ceil(sum(demand[i] for i in N) / Q) + + print(f"Instance: {n} customers, {Q} capacity, {F_size} vehicles (upper bound)") + print(f"Arcs: {len(arcs)}, kC(N): {kC_N}") + + # Build Gurobi model + model = gp.Model("SDVRPTW") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[f,i,j] binary: vehicle f uses arc (i,j) + x = {} + for f in F: + for (i, j) in arcs: + x[f, i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{f}_{i}_{j}") + + # delta[f,i] >= 0: quantity delivered by vehicle f to customer i + delta = {} + for f in F: + for i in N: + delta[f, i] = model.addVar(lb=0.0, ub=d_bar[i], vtype=GRB.CONTINUOUS, + name=f"delta_{f}_{i}") + + # s[f,i]: visit start time at node i for vehicle f + s = {} + for f in F: + for i in V: + s[f, i] = model.addVar(lb=e[i], ub=l[i], vtype=GRB.CONTINUOUS, + name=f"s_{f}_{i}") + + # H: total number of vehicles used + H = model.addVar(lb=kC_N, ub=F_size, vtype=GRB.INTEGER, name="H") + + model.update() + + # Objective (1): minimize total travel cost + model.setObjective( + gp.quicksum(c_mat[i][j] * x[f, i, j] for f in F for (i, j) in arcs), + GRB.MINIMIZE + ) + + # Constraint (2): Demand fulfillment + for i in N: + model.addConstr( + gp.quicksum(delta[f, i] for f in F) >= demand[i], + name=f"demand_{i}" + ) + + # Constraint (3): Minimum number of visits per customer (only when k^C_i >= 2) + for i in N: + if kC[i] >= 2: + model.addConstr( + gp.quicksum(x[f, i, j] for f in F for j in V_plus[i]) >= kC[i], + name=f"min_visits_{i}" + ) + + # Constraint (4): Fleet size definition + model.addConstr( + gp.quicksum(x[f, 0, j] for f in F for j in V_plus[0] if j != n + 1) == H, + name="fleet_size" + ) + + # Constraint (5): H bounds already set via variable bounds + + # Constraints (8)-(10): Path structure per vehicle + for f in F: + # (8): each vehicle leaves depot exactly once + model.addConstr( + gp.quicksum(x[f, 0, j] for j in V_plus[0]) == 1, + name=f"depart_{f}" + ) + # (9): flow conservation at each customer + for i in N: + model.addConstr( + gp.quicksum(x[f, i, j] for j in V_plus[i] if (i, j) in arc_set) + - gp.quicksum(x[f, j, i] for j in V_minus[i] if (j, i) in arc_set) == 0, + name=f"flow_{f}_{i}" + ) + # (10): each vehicle arrives at depot end exactly once + model.addConstr( + gp.quicksum(x[f, i, n + 1] for i in V_minus[n + 1] if (i, n + 1) in arc_set) == 1, + name=f"arrive_{f}" + ) + + # Constraint (11) linearized: s_i + t_{ij} - s_j <= M*(1 - x_{ij}) + # Big-M: M = l_i + t_{ij} - e_j + for f in F: + for (i, j) in arcs: + M_val = l[i] + t_mat[i][j] - e[j] + model.addConstr( + s[f, i] + t_mat[i][j] - s[f, j] <= M_val * (1 - x[f, i, j]), + name=f"time_{f}_{i}_{j}" + ) + + # Constraint (12): Time windows already handled by variable bounds + + # Constraint (13): Vehicle capacity + for f in F: + model.addConstr( + gp.quicksum(delta[f, i] for i in N) <= Q, + name=f"capacity_{f}" + ) + + # Constraint (14): Delivery linking + for f in F: + for i in N: + model.addConstr( + delta[f, i] <= d_bar[i] * gp.quicksum( + x[f, i, j] for j in V_plus[i] if (i, j) in arc_set + ), + name=f"link_{f}_{i}" + ) + + # Constraint (15): Binary requirements already set via variable types + + # --- Symmetry breaking (inferred assumption): order vehicles --- + # **INFERRED ASSUMPTION**: Add symmetry-breaking constraints to help Gurobi. + # Vehicles are identical, so we can order them by usage. + # Vehicle f is used only if vehicle f-1 is used. + for f in range(1, len(F)): + # If vehicle f leaves the depot to a customer, then vehicle f-1 must also + model.addConstr( + gp.quicksum(x[f, 0, j] for j in V_plus[0] if j != n + 1) + <= gp.quicksum(x[f - 1, 0, j] for j in V_plus[0] if j != n + 1), + name=f"sym_break_{f}" + ) + + print("Model built. Optimizing...") + model.optimize() + + # Extract solution + result = { + "instance": instance_path, + "solver": "Gurobi", + "status": model.Status, + "status_name": "", + "objective_value": None, + "num_vehicles_used": None, + "routes": [], + "deliveries": [], + "time_limit": time_limit, + "solve_time": model.Runtime + } + + if model.Status == GRB.OPTIMAL: + result["status_name"] = "OPTIMAL" + elif model.Status == GRB.TIME_LIMIT: + result["status_name"] = "TIME_LIMIT" + elif model.Status == GRB.INFEASIBLE: + result["status_name"] = "INFEASIBLE" + else: + result["status_name"] = f"OTHER_{model.Status}" + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["num_vehicles_used"] = round(H.X) + + # Extract routes and deliveries + for f in F: + route_arcs = [(i, j) for (i, j) in arcs if x[f, i, j].X > 0.5] + if not route_arcs: + continue + # Check if vehicle is used (goes to a customer) + leaves_to_customer = any(i == 0 and j != n + 1 for (i, j) in route_arcs) + if not leaves_to_customer: + continue + + # Reconstruct route sequence + adj = {} + for (i, j) in route_arcs: + adj[i] = j + route_seq = [0] + current = 0 + visited = set() + while current != n + 1 and current in adj and current not in visited: + visited.add(current) + current = adj[current] + route_seq.append(current) + + # Get deliveries for this vehicle + vehicle_deliveries = {} + for i in N: + qty = delta[f, i].X + if qty > 1e-6: + vehicle_deliveries[i] = round(qty, 2) + + result["routes"].append({ + "vehicle": f, + "route": route_seq, + "deliveries": vehicle_deliveries + }) + + # Also collect per-customer delivery summary + delivery_summary = {} + for i in N: + total = sum(delta[f, i].X for f in F) + delivery_summary[str(i)] = { + "demand": demand[i], + "total_delivered": round(total, 2) + } + result["deliveries"] = delivery_summary + else: + result["objective_value"] = None + print("No feasible solution found.") + + # Write solution + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Vehicles used: {result['num_vehicles_used']}") + print(f"Solve time: {model.Runtime:.2f}s") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for SDVRPTW (arc-flow formulation)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + build_and_solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/desaulniers2010/gurobi_feasi_result/large_feasi_result_1.json b/tasks/desaulniers2010/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2010/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/desaulniers2010/gurobi_feasi_result/large_feasi_result_2.json b/tasks/desaulniers2010/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2010/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/desaulniers2010/gurobi_feasi_result/large_feasi_result_3.json b/tasks/desaulniers2010/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2010/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/desaulniers2010/gurobi_feasi_result/large_feasi_result_4.json b/tasks/desaulniers2010/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2010/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/desaulniers2010/gurobi_feasi_result/large_feasi_result_5.json b/tasks/desaulniers2010/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2010/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/desaulniers2010/gurobi_feasi_result/tiny_feasi_result.json b/tasks/desaulniers2010/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2010/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/desaulniers2010/gurobi_solution/large_solution_1.json b/tasks/desaulniers2010/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..228b578fcb1b9741f919839b337a5fb1dd8dd620 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bad6b5b7b029ed149dcd1a77c2d0df8d7e413a34bfd915dc69c203c80ffd88c +size 10444 diff --git a/tasks/desaulniers2010/gurobi_solution/large_solution_2.json b/tasks/desaulniers2010/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c231de8acdee6f9b87a915925be482ff7ee9fde9 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edfc9f5f9d8e131bc4a9da9c94adab943f1644a278b7598eb2e9ddcbb2f30d9f +size 9876 diff --git a/tasks/desaulniers2010/gurobi_solution/large_solution_3.json b/tasks/desaulniers2010/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b4f1b47741bf86d7b94aa451f942192b352bf9f2 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92c1535d95b6f33badd210e1a0b86ecc673851d9800f64c31a24685ff088292c +size 11218 diff --git a/tasks/desaulniers2010/gurobi_solution/large_solution_4.json b/tasks/desaulniers2010/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..93ee1c2f72ed7ff8e5d8fe91cdc10efb4a9377a0 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:676fbb6c4227484e06ca882cae3c4709439ccea9fd79b63715dc0934ce292d68 +size 12552 diff --git a/tasks/desaulniers2010/gurobi_solution/large_solution_5.json b/tasks/desaulniers2010/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..071a429c483f2fe5fced55aff463106d561bc1b4 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:891c03ee6954967ba29b81379f4d5d6075dc08a2812f9c496562932af112deb3 +size 20898 diff --git a/tasks/desaulniers2010/gurobi_solution/tiny_solution.json b/tasks/desaulniers2010/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..25ee49c3d8daccc0bb6caef0c802a517891b368f --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17eea931c5be3bc73e83349066cd2d293968cbc3a7d31db0ad09c6eb6550d066 +size 3837 diff --git a/tasks/desaulniers2010/gurobi_solution_log/large_log_1.jsonl b/tasks/desaulniers2010/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5365b513cb9c983ef5484878daaec92f6a54eedb --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ed3b7896661d7b3d359c93cfb473a3f5d9a6cbe1a34812e5eb3ab8c3644c8dd +size 2940 diff --git a/tasks/desaulniers2010/gurobi_solution_log/large_log_2.jsonl b/tasks/desaulniers2010/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..50a909088d85979cf4768091d03ce1dc60adb83a --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd70548178d44c23737ddd73f0d062e5ad2fbddef6152d3071bc319eead5e32e +size 1693 diff --git a/tasks/desaulniers2010/gurobi_solution_log/large_log_3.jsonl b/tasks/desaulniers2010/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7d2defaa20932e5e6242a3528f5017221adbedce --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:554dd883fb784e4ddb24bd79041361844a0a5c7a594244a0abd7e5bf76594cbe +size 2554 diff --git a/tasks/desaulniers2010/gurobi_solution_log/large_log_4.jsonl b/tasks/desaulniers2010/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0d355b2c7b00a2caf46aa8d17c80b362fb0edcd2 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd55541498fc86f012986de04bf8ee0cdcdfb15d2605598b78156b8ba2caf6aa +size 916 diff --git a/tasks/desaulniers2010/gurobi_solution_log/large_log_5.jsonl b/tasks/desaulniers2010/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..abcdc5e20d077ff084993b8c1e9cb55e6a60ce00 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:867c113228b5babb5e842925e1a1063da2363bd320bc5d2f1cf77b2f1635e3d7 +size 994 diff --git a/tasks/desaulniers2010/gurobi_solution_log/tiny_log.jsonl b/tasks/desaulniers2010/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd722b0922976fe8d9471c6982bcda363875cc94 --- /dev/null +++ b/tasks/desaulniers2010/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9cc9647f83c9c4537cab4643077cdda5867366f7bf401af49f2d664dca2b053 +size 336 diff --git a/tasks/desaulniers2010/instance/large_instance_1.json b/tasks/desaulniers2010/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..262694fc48fa4d88378dd5308528485f880dc8b2 --- /dev/null +++ b/tasks/desaulniers2010/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47e6776e41de3c84598086b3aa03c96f4d6fc8c0913c9e01ca0cd86c71c73237 +size 40536 diff --git a/tasks/desaulniers2010/instance/large_instance_2.json b/tasks/desaulniers2010/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8a6c10e93df9455db85ebead5fba10ef0de5cab2 --- /dev/null +++ b/tasks/desaulniers2010/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5457adf97cab361dbd6de48b62dd3418437d756d0973114fe74943daf2c3b40a +size 40570 diff --git a/tasks/desaulniers2010/instance/large_instance_3.json b/tasks/desaulniers2010/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1e1e921f45dc0b4097a107017b70908084e8358d --- /dev/null +++ b/tasks/desaulniers2010/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2af5f8c4a3b659c26c6241010ee715f0e148f459b6aa6385fbb8dbeaf87c49f +size 40495 diff --git a/tasks/desaulniers2010/instance/large_instance_4.json b/tasks/desaulniers2010/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f1ccdd8dab922b6b2c5032001a6987c25e8456e9 --- /dev/null +++ b/tasks/desaulniers2010/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8642f95125e504494c10b4f2c6700a6d02e54d62b804f0ad682cba8d22377ef +size 40589 diff --git a/tasks/desaulniers2010/instance/large_instance_5.json b/tasks/desaulniers2010/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e18473877f8dad6620914dbb70bf58ee8a6085a7 --- /dev/null +++ b/tasks/desaulniers2010/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d190e8991e5368ba0b71ceaf286e99d0f5698ac6c29dd5e4976214fb01759eb +size 140230 diff --git a/tasks/desaulniers2010/instance/tiny_instance.json b/tasks/desaulniers2010/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..9c25cb138d2dc6714cff1d96d70fcb2beeaeb228 --- /dev/null +++ b/tasks/desaulniers2010/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:894c56244445382b72a1267437079282ddfebd9b2d08adf3f3f78105cadc3563 +size 14239 diff --git a/tasks/desaulniers2010/instance_schema.json b/tasks/desaulniers2010/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..85f2b91bce0aa410a2d9e6df2aba2305ca9eb559 --- /dev/null +++ b/tasks/desaulniers2010/instance_schema.json @@ -0,0 +1,29 @@ +{ + "num_customers": " Number of customers to be served.", + "vehicle_capacity": " Maximum total quantity a single vehicle can carry across all its deliveries.", + "num_vehicles_upper_bound": " Maximum number of vehicles available in the fleet.", + "scheduling_horizon": " End of the planning period within which all vehicles must depart from and return to the depot.", + "depot": { + "id": " Identifier for the depot node.", + "x": " Horizontal coordinate of the depot location.", + "y": " Vertical coordinate of the depot location.", + "time_window": " Earliest departure and latest return time for all vehicles at the depot.", + "service_time": " Time spent at the depot before departing (always zero).", + "demand": " Demand at the depot (always zero)." + }, + "customers": [ + { + "id": " Unique identifier for the customer, numbered from 1 to num_customers.", + "x": " Horizontal coordinate of the customer location.", + "y": " Vertical coordinate of the customer location.", + "demand": " Quantity of goods the customer requires to be delivered.", + "time_window": " Earliest and latest time at which service may begin at this customer.", + "service_time": " Time a vehicle spends at this customer regardless of the quantity delivered." + } + ], + "distance_matrix": " Travel distance between each pair of locations, where row and column 0 is the depot and 1 through num_customers are customers.", + "travel_time_equals_distance": " Whether the travel time between two locations equals the distance between them.", + "triangle_inequality": " Whether distances and travel times satisfy the triangle inequality.", + "split_deliveries_allowed": " Whether a customer's demand may be fulfilled by deliveries from multiple vehicles.", + "service_time_independent_of_quantity": " Whether the service time at a customer is the same regardless of the quantity delivered." +} diff --git a/tasks/desaulniers2010/mathematical_formulation.md b/tasks/desaulniers2010/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..405c1fb2742f35f538383ba022f4d4df1de150d3 --- /dev/null +++ b/tasks/desaulniers2010/mathematical_formulation.md @@ -0,0 +1,84 @@ +# Original Formulation: Split-Delivery Vehicle Routing Problem with Time Windows (SDVRPTW) — Arc-Flow Formulation + +*Source: Branch-and-Price-and-Cut for the Split-Delivery Vehicle Routing Problem with Time Windows, Guy Desaulniers, 2010.* + +## Sets and Parameters + +- $\mathcal{N} = \{1,\dots,n\}$: set of $n$ customers. + +- $\mathcal{V} = \mathcal{N} \cup \{0, n+1\}$: node set, where $0$ and $n+1$ represent the depot at the start and end of the planning horizon. + +- $\mathcal{A} \subset \mathcal{V}\times\mathcal{V}$: set of arcs; $(i,j) \in \mathcal{A}$ if $e_i + t_{ij} \le l_j$ (with the depot arcs $(0,j)$ and $(j,n+1)$ defined analogously, but not $(n+1,0)$). + +- $\mathcal{F}$: set of available (identical) vehicles, each with capacity $Q$. + +- $\mathcal{V}^{+}(i) = \{j \in \mathcal{V} : (i,j) \in \mathcal{A}\}$: successor set of $i$. + +- $\mathcal{V}^{-}(i) = \{j \in \mathcal{V} : (j,i) \in \mathcal{A}\}$: predecessor set of $i$. + +- $c_{ij} \ge 0$: cost of arc $(i,j)$. + +- $t_{ij} \ge 0$: travel time of arc $(i,j)$ (includes service time at $i$ if any). + +- $d_i$: demand of customer $i$; $\bar{d}_i = \min\{d_i, Q\}$. + +- $[e_i, l_i]$: time window at node $i$. + +- $k^{C}_{i}$: minimum number of vehicles needed to service customer $i$ (with $\mathcal{U} = \{i\}$) respecting only the vehicle-capacity constraints. + +- $k^{C}(\mathcal{N}) = \lceil \sum_{i\in\mathcal{N}} d_i / Q \rceil$: minimum number of vehicles needed to service all customers under vehicle-capacity constraints. + +- $\mathcal{P}(\mathcal{N})$: collection of subsets $\mathcal{U} \subseteq \mathcal{N}$ with $|\mathcal{U}| \ge 2$ and $k_{\mathcal{U}} > 1$ (here $k_{\mathcal{U}} = \max\{k^{C}_{\mathcal{U}}, k^{T}_{\mathcal{U}}\}$). + +- $\mathcal{A}^{-}(\mathcal{U}) = \{(i,j)\in\mathcal{A} : i \in \mathcal{V}\setminus\mathcal{U},\; j \in \mathcal{U}\}$: arcs entering $\mathcal{U}$. + +- $\mathcal{A}^{*}(\mathcal{N}) \subseteq \mathcal{A}$: a chosen subset containing, for each pair of reverse arcs $(i,j),(j,i) \in \mathcal{A}(\mathcal{N})$, exactly one of them. + +## Decision Variables + +- $x^{f}_{ij} \in \{0,1\}$, $\forall f \in \mathcal{F}, (i,j) \in \mathcal{A}$: 1 if vehicle $f$ uses arc $(i,j)$, 0 otherwise. + +- $\delta^{f}_{i} \ge 0$, $\forall f \in \mathcal{F}, i \in \mathcal{N}$: quantity delivered by vehicle $f$ to customer $i$. + +- $s^{f}_{i} \in \mathbb{R}$, $\forall f \in \mathcal{F}, i \in \mathcal{V}$: visit start time of vehicle $f$ at node $i$ (value is irrelevant if $f$ does not visit $i$). + +- $H \ge 0$: total number of vehicles used (integer). + +## Objective + +$$\begin{align} +\min \quad & \sum_{f \in \mathcal{F}} \sum_{(i,j) \in \mathcal{A}} c_{ij}\, x^{f}_{ij} \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{f \in \mathcal{F}} \delta^{f}_{i} &\ge d_i, + & \forall i \in \mathcal{N}, \tag{2}\\ +\sum_{f \in \mathcal{F}} \sum_{j \in \mathcal{V}^{+}(i)} x^{f}_{ij} &\ge k^{C}_{i}, + & \forall i \in \mathcal{N}, \tag{3}\\ +\sum_{f \in \mathcal{F}} \sum_{j \in \mathcal{V}^{+}(0)} x^{f}_{0j} &= H, \tag{4}\\ +H &\in \bigl[k^{C}(\mathcal{N}),\; |\mathcal{F}|\bigr],\; H\ \text{integer}, \tag{5}\\ +\sum_{f \in \mathcal{F}} \sum_{(i,j) \in \mathcal{A}^{-}(\mathcal{U})} x^{f}_{ij} &\ge k_{\mathcal{U}}, + & \forall \mathcal{U} \in \mathcal{P}(\mathcal{N}), \tag{6}\\ +\sum_{f \in \mathcal{F}} \sum_{(i,j) \in \mathcal{A}^{*}_{i'j'}} x^{f}_{ij} &\le 1, + & \forall (i',j') \in \mathcal{A}^{*}(\mathcal{N}), \tag{7}\\ +\sum_{j \in \mathcal{V}^{+}(0)} x^{f}_{0j} &= 1, + & \forall f \in \mathcal{F}, \tag{8}\\ +\sum_{j \in \mathcal{V}^{+}(i)} x^{f}_{ij} - \sum_{j \in \mathcal{V}^{-}(i)} x^{f}_{ji} &= 0, + & \forall f \in \mathcal{F},\; i \in \mathcal{N}, \tag{9}\\ +\sum_{i \in \mathcal{V}^{-}(n+1)} x^{f}_{i,n+1} &= 1, + & \forall f \in \mathcal{F}, \tag{10}\\ +x^{f}_{ij}\bigl(s^{f}_{i} + t_{ij} - s^{f}_{j}\bigr) &\le 0, + & \forall f \in \mathcal{F},\; (i,j) \in \mathcal{A}, \tag{11}\\ +e_i \le s^{f}_{i} &\le l_i, + & \forall f \in \mathcal{F},\; i \in \mathcal{V}, \tag{12}\\ +\sum_{i \in \mathcal{N}} \delta^{f}_{i} &\le Q, + & \forall f \in \mathcal{F}, \tag{13}\\ +0 \le \delta^{f}_{i} &\le \bar{d}_i \sum_{j \in \mathcal{V}^{+}(i)} x^{f}_{ij}, + & \forall f \in \mathcal{F},\; i \in \mathcal{N}, \tag{14}\\ +x^{f}_{ij} &\in \{0,1\}, + & \forall f \in \mathcal{F},\; (i,j) \in \mathcal{A}. \tag{15} +\end{align}$$ + +The objective (1) minimizes the total travel cost. Constraints (2) ensure that the demand of each customer is fulfilled. Constraints (3)–(6) are redundant inequalities used to strengthen the LP relaxation: (3) imposes a minimum number of visits at each customer, (4)–(5) compute and bound the number of vehicles used, and (6) are the $k$-path inequalities. Constraints (7) restrict the feasible space while keeping at least one optimal integer solution. Constraints (8)–(10) define a path for each vehicle from $0$ to $n+1$. Constraints (11) ensure that the customer time windows are respected whenever an arc is used; **they are the bilinear coupling $x^{f}_{ij}(s^{f}_{i} + t_{ij} - s^{f}_{j}) \le 0$ in its original nonlinear form**. Constraints (12) enforce time windows on the $s$ variables, (13) are vehicle-capacity constraints, and (14) limit the quantity delivered to a customer and force it to zero if the route of the vehicle does not visit that customer. Finally, binary requirements on $x^{f}_{ij}$ are given in (15). diff --git a/tasks/desaulniers2010/problem_description.txt b/tasks/desaulniers2010/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e8d98231ff4d30a30138d28850b54abc5eded73 --- /dev/null +++ b/tasks/desaulniers2010/problem_description.txt @@ -0,0 +1,15 @@ +# Problem Description + +A delivery company operates a fleet of identical vehicles from a single depot to serve a set of customers. Each customer has a known positive demand, a location specified by coordinates in a plane, and a time window during which service must begin. The depot also has a time window representing the planning horizon within which all vehicles must depart and return. Each vehicle has a fixed carrying capacity. The number of available vehicles may be set to an upper bound computed as the sum, over all customers, of the ceiling of each customer's demand divided by the vehicle capacity. + +The input data for each instance specifies the number of customers, the vehicle capacity, the depot location and its time window, and for each customer an identifier, coordinates, demand quantity, time window, and service time. A symmetric distance and travel time matrix is provided for all pairs of locations including the depot. Distances are Euclidean, computed with one decimal place and truncated. Travel times equal distances, and the triangle inequality holds for both costs and travel times. The travel time along an arc from one location to another includes the service time at the origin location. Service times are independent of the quantity delivered. + +Each vehicle travels a route that starts at the depot, visits some subset of customers, and returns to the depot. A direct arc between two locations exists only if a vehicle that begins service at the origin at the start of the origin's time window would arrive at the destination no later than the end of the destination's time window. An arc directly from the departure depot to the return depot also exists, representing an idle vehicle. The cost of traversing an arc equals the distance between the two locations. + +Unlike the classical vehicle routing problem, a customer's demand may be fulfilled by deliveries from multiple vehicles. Each vehicle that visits a customer delivers some quantity to that customer, and the total quantity delivered to each customer across all vehicles must be at least the customer's demand. The quantity a single vehicle can deliver to a customer is at most the minimum of the customer's demand and the vehicle capacity, and a vehicle can deliver a positive quantity to a customer only if that vehicle's route actually visits that customer. The total quantity carried by each vehicle across all its deliveries must not exceed the vehicle capacity. + +Each vehicle's route must form a simple path from the departure depot to the return depot, meaning that at every customer node the number of incoming arcs used by that vehicle equals the number of outgoing arcs, exactly one arc leaves the departure depot, and exactly one arc enters the return depot. When a vehicle traverses an arc, its visit start time at the destination must be no earlier than its visit start time at the origin plus the travel time on that arc. At every node, the vehicle's visit start time must fall within that node's time window; a vehicle may arrive before the time window opens and wait, but service cannot begin after the window closes. + +The total number of vehicles used equals the number of vehicles whose routes leave the departure depot to visit at least one customer. This count must be an integer and must fall between the minimum number of vehicles needed to cover the total demand, computed as the ceiling of total demand divided by vehicle capacity, and the total number of available vehicles. + +The goal is to determine routes for the vehicles, the quantity each vehicle delivers to each customer it visits, and the visit schedule at each location so as to minimize the total travel cost, defined as the sum of arc costs over all arcs used by all vehicles. diff --git a/tasks/desaulniers2010/solution_logger.py b/tasks/desaulniers2010/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/desaulniers2010/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/desaulniers2010/solution_schema.json b/tasks/desaulniers2010/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c4d946a46de5a415f2304dd34fbeba766a9e943d --- /dev/null +++ b/tasks/desaulniers2010/solution_schema.json @@ -0,0 +1,17 @@ +{ + "objective_value": " Total travel distance summed over all arcs traversed by all vehicles.", + "num_vehicles_used": " Number of vehicles that leave the depot to visit at least one customer.", + "routes": [ + { + "vehicle": " Identifier of the vehicle assigned to this route.", + "route": " Ordered sequence of node identifiers visited, starting at the departure depot (0) and ending at the return depot (num_customers+1).", + "deliveries": " Quantity of goods this vehicle delivers to each customer it visits on this route." + } + ], + "deliveries": { + "": { + "demand": " Original demand quantity of the customer.", + "total_delivered": " Total quantity delivered to the customer summed across all vehicles that visit it." + } + } +} diff --git a/tasks/desaulniers2014/feasibility_check.py b/tasks/desaulniers2014/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5031609cd2ebcf2bca7d0c4ce3670a63877f01ac --- /dev/null +++ b/tasks/desaulniers2014/feasibility_check.py @@ -0,0 +1,760 @@ +""" +Feasibility checker for the Inventory-Routing Problem (IRP). + +Based on: Desaulniers, Rakke, Coelho (2014) - "A Branch-Price-and-Cut Algorithm +for the Inventory-Routing Problem", Les Cahiers du GERAD G-2014-19 + +Checks hard constraints (2)-(9) from the mathematical formulation. +Valid inequalities (19), (21), (23), (24) are cuts and are NOT checked. + +Constraint (10): objective-value consistency (Tier C anti-gaming check). +The reported objective_value is recomputed from the solution (travel cost +from routes + holding cost from simulated inventories) and rejected when it +disagrees, defeating fabricated objective values that pass (2)-(9). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'solution_details') +_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_instance(data): + """Parse instance data into structured parameters.""" + num_cust = data["num_customers"] + num_per = data["num_periods"] + Q = data["vehicle_capacity"] + depot = data["depot"] + customers = data["customers"] + + N = list(range(1, num_cust + 1)) + P = list(range(1, num_per + 1)) + rho = num_per + + # Customer params + d = {} # demand[i][p] + C = {} # capacity + I0 = {} # initial inventory + h = {} # holding cost + for c in customers: + cid = c["id"] + d[cid] = {p: c["demand_per_period"] for p in P} + C[cid] = c["max_inventory"] + I0[cid] = c["initial_inventory"] + h[cid] = c["holding_cost"] + + d0 = depot["production_per_period"] + C0 = depot["max_inventory"] + I0_0 = depot["initial_inventory"] + h0 = depot["holding_cost"] + dist = data["distance_matrix"] + K = data["num_vehicles"] + + # I^{0,s}_i = max{0, I0_i - sum_{l=1}^{s} d^l_i} + I0s = {} + for i in N: + for s in P: + I0s[i, s] = max(0, I0[i] - sum(d[i][l] for l in range(1, s + 1))) + + # d_bar^s_i (residual demands) + d_bar = {} + for i in N: + for s in P: + if s == 1: + d_bar[i, s] = max(0, d[i][1] - I0[i]) + else: + d_bar[i, s] = max(0, d[i][s] - I0s[i, s - 1]) + + return { + 'N': N, 'P': P, 'rho': rho, 'Q': Q, 'K': K, + 'd': d, 'C': C, 'I0': I0, 'h': h, + 'd0': d0, 'C0': C0, 'I0_0': I0_0, 'h0': h0, + 'dist': dist, 'I0s': I0s, 'd_bar': d_bar, + } + + +def parse_solution(sol_data, params): + """ + Parse solution into a unified representation. + + Returns: + routes_per_period: dict {period: list of routes} + Each route is a dict with: + 'customers': list of customer ids in visit order + 'deliveries': dict {customer_id: total_quantity_delivered} + deliveries_per_period: dict {period: {customer_id: total_quantity_delivered}} + """ + P = params['P'] + routes_per_period = {p: [] for p in P} + deliveries_per_period = {p: {} for p in P} + + sd = sol_data.get("solution_details", {}) + + if "routes" in sd: + # Efficient algorithm format: list of route objects + for r in sd["routes"]: + period = r["period"] + customers = r["route"] # list of customer ids (no depot) + deliveries_raw = r.get("deliveries", {}) + + # Sum sub-deliveries per customer + total_del = {} + for cust_key, val in deliveries_raw.items(): + cust_id = int(cust_key) + if isinstance(val, dict): + total_del[cust_id] = sum(val.values()) + else: + total_del[cust_id] = val + + routes_per_period[period].append({ + 'customers': customers, + 'deliveries': total_del, + 'raw': None, # efficient format does not provide arc sequence + }) + + for cust_id, qty in total_del.items(): + deliveries_per_period[period][cust_id] = ( + deliveries_per_period[period].get(cust_id, 0) + qty + ) + + elif "periods" in sd: + # Gurobi format: dict keyed by period + for p_str, pdata in sd["periods"].items(): + period = int(p_str) + if period not in routes_per_period: + continue + + routes_raw = pdata.get("routes", []) + deliveries_raw = pdata.get("deliveries", {}) + + # Build delivery map for this period + period_deliveries = {} + for cust_key, qty in deliveries_raw.items(): + cust_id = int(cust_key) + period_deliveries[cust_id] = qty + + deliveries_per_period[period] = period_deliveries + + # Parse routes: each route is [0, c1, c2, ..., 0] + for route_nodes in routes_raw: + customers = [n for n in route_nodes if n != 0] + # Assign deliveries to customers on this route + route_del = {} + for c in customers: + if c in period_deliveries: + route_del[c] = period_deliveries[c] + + routes_per_period[period].append({ + 'customers': customers, + 'deliveries': route_del, + 'raw': list(route_nodes), + }) + + return routes_per_period, deliveries_per_period + + +def check_feasibility(instance_data, sol_data): + """ + Check all hard constraints (2)-(9) from the IRP formulation. + + Returns a dict with feasibility results. + """ + tol = 1e-5 + eps = 1e-5 + + params = parse_instance(instance_data) + N = params['N'] + P = params['P'] + rho = params['rho'] + Q = params['Q'] + K = params['K'] + d = params['d'] + C = params['C'] + I0 = params['I0'] + d0 = params['d0'] + C0 = params['C0'] + I0_0 = params['I0_0'] + I0s = params['I0s'] + d_bar = params['d_bar'] + dist = params['dist'] + + routes_per_period, deliveries_per_period = parse_solution(sol_data, params) + + violations = [] + violation_magnitudes = [] + violated_constraint_set = set() + + def record_violation(constraint_idx, message, lhs, rhs, violation_amount): + violated_constraint_set.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, + }) + + # ========================================================================= + # Simulate inventory flows to get depot inventory per period + # ========================================================================= + depot_inv = {} # I^p_0 at end of period p + cust_inv = {} # inventory at customer i at end of period p + + # Initialize + prev_depot_inv = I0_0 + prev_cust_inv = {i: I0[i] for i in N} + + for p in P: + # Supplier produces at start of period + depot_after_prod = prev_depot_inv + d0 + + # Total quantity shipped out in this period + total_shipped = sum(deliveries_per_period[p].get(i, 0) for i in N) + depot_inv[p] = depot_after_prod - total_shipped + + # Customer inventories: receive deliveries then consume demand + for i in N: + delivered = deliveries_per_period[p].get(i, 0) + cust_inv[i, p] = prev_cust_inv[i] + delivered - d[i][p] + + prev_depot_inv = depot_inv[p] + prev_cust_inv = {i: cust_inv[i, p] for i in N} + + # ========================================================================= + # Constraint (2): Supplier inventory balance + # I^{p-1}_0 + d^p_0 - sum_deliveries = I^p_0 + # Equivalently: LHS = I^{p-1}_0 + d^p_0 - sum_deliveries, RHS = I^p_0 + # This is an equality constraint. + # ========================================================================= + for p in P: + prev_inv = I0_0 if p == 1 else depot_inv[p - 1] + total_shipped = sum(deliveries_per_period[p].get(i, 0) for i in N) + lhs = prev_inv + d0 - total_shipped + rhs = depot_inv[p] + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 2, + f"Constraint (2): Supplier inventory balance violated in period {p}: " + f"LHS={lhs:.4f}, RHS(I^{p}_0)={rhs:.4f}, diff={violation_amount:.4f}", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (3): Customer demand satisfaction + # Total delivered to customer i across all periods must satisfy residual + # demand. In compact form: for each customer i and period s, the total + # delivery dedicated to satisfying demand in period s must equal d_bar^s_i. + # + # Since both efficient and gurobi solutions only report total delivery per + # customer per period (not sub-delivery breakdown), we check the aggregate + # form: each customer's inventory must never go negative (stockout), which + # is the practical implication of demand satisfaction. + # + # Specifically: I^0_i + sum_{p'=1}^{s} delivered_{i,p'} - sum_{p'=1}^{s} d^{p'}_i >= 0 + # for all i in N, s in P. + # + # This is equivalent to checking no stockout occurs at any customer in any + # period. The equality form (3) implies that total deliveries across + # the horizon exactly match total residual demand. We check both + # no-stockout and total demand matching. + # ========================================================================= + for i in N: + for s in P: + inv_at_end = cust_inv[i, s] + if inv_at_end < -tol: + # Stockout: demand not satisfied + lhs = inv_at_end + rhs = 0.0 + violation_amount = -inv_at_end # how much below zero + record_violation( + 3, + f"Constraint (3): Customer {i} demand not satisfied in period {s}: " + f"end-of-period inventory={inv_at_end:.4f} < 0 (stockout)", + lhs, rhs, violation_amount + ) + + # Also check total residual demand is met across the horizon + for i in N: + total_residual = sum(d_bar[i, s] for s in P) + total_delivered = sum(deliveries_per_period[p].get(i, 0) for p in P) + # Under FIFO, total delivery must cover total residual demand + # (any excess becomes end-of-horizon inventory) + if total_delivered < total_residual - tol: + lhs = total_delivered + rhs = total_residual + violation_amount = total_residual - total_delivered + record_violation( + 3, + f"Constraint (3): Customer {i} total delivery insufficient: " + f"delivered={total_delivered:.4f}, residual demand={total_residual:.4f}", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (4): Customer holding capacity + # I^{0,s}_i + deliveries_in_inventory_at_s <= C_i - d^s_i + # Equivalently: end-of-period inventory <= C_i - d^s_i (before consumption) + # Or more practically: inventory after receiving delivery but before consumption + # must not exceed C_i. Since consumption happens in the same period: + # cust_inv[i,s] + d[i][s] <= C_i (inventory before consumption <= C_i) + # which is: cust_inv[i,s] <= C_i - d[i][s] + # + # Actually the constraint bounds the inventory AFTER consumption too: + # end-of-period inventory cust_inv[i,s] <= C_i + # And pre-consumption inventory (after delivery) <= C_i + # ========================================================================= + for i in N: + for s in P: + # Check inventory after delivery, before consumption + delivered = deliveries_per_period[s].get(i, 0) + prev_inv = I0[i] if s == 1 else cust_inv[i, s - 1] + inv_after_delivery = prev_inv + delivered + + lhs = inv_after_delivery + rhs = C[i] + violation_amount = lhs - rhs + if violation_amount > tol: + record_violation( + 4, + f"Constraint (4): Customer {i} inventory capacity exceeded in period {s}: " + f"inventory after delivery={lhs:.4f} > capacity={rhs:.4f}", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (5): At most one visit per customer per period + # sum_{r in R} sum_{w in W^p_r} a_{ri} * y^p_{rw} <= 1 + # In the solution: count how many routes visit customer i in period p + # ========================================================================= + for i in N: + for p in P: + visit_count = sum( + 1 for r in routes_per_period[p] + if i in r['customers'] + ) + lhs = visit_count + rhs = 1.0 + violation_amount = lhs - rhs + if violation_amount > tol: + record_violation( + 5, + f"Constraint (5): Customer {i} visited {visit_count} times in period {p} " + f"(at most 1 allowed)", + float(lhs), rhs, violation_amount + ) + + # ========================================================================= + # Linking: deliveries imply visits (implicit in original RDP formulation). + # Sub-deliveries q^s_{wi} only exist for customers i in N_r of route r with + # y^p_{rw} > 0, so a positive aggregate delivery requires a visit. Without + # this check, q_{ip} > 0 while customer i is absent from every route in + # period p would be silently accepted (stockout / capacity checks use the + # aggregate q_{ip} but never tie it to z_{ip}). + # ========================================================================= + for p in P: + for i in N: + qty = deliveries_per_period[p].get(i, 0) + if qty > tol and not any(i in r['customers'] for r in routes_per_period[p]): + record_violation( + 5, + f"Delivery/visit link: customer {i} received delivery {qty:.4f} " + f"in period {p} but is not on any route", + qty, 0.0, qty, + ) + + # ========================================================================= + # Constraint (6): Vehicle availability - at most K vehicles per period + # sum_{r in R} sum_{w in W^p_r} y^p_{rw} <= K + # Count number of routes used in each period + # ========================================================================= + for p in P: + num_routes = len(routes_per_period[p]) + lhs = num_routes + rhs = float(K) + violation_amount = lhs - rhs + if violation_amount > tol: + record_violation( + 6, + f"Constraint (6): {num_routes} routes used in period {p}, " + f"but only {K} vehicles available", + float(lhs), rhs, violation_amount + ) + + # ========================================================================= + # Constraint (7): Supplier inventory bounds: 0 <= I^p_0 <= C_0 + # Two sub-constraints: lower bound (>= 0) and upper bound (<= C_0) + # ========================================================================= + for p in P: + inv = depot_inv[p] + + # Lower bound: I^p_0 >= 0 + if inv < -tol: + lhs = inv + rhs = 0.0 + violation_amount = -inv + record_violation( + 7, + f"Constraint (7): Supplier inventory negative in period {p}: " + f"I^{p}_0={inv:.4f} < 0", + lhs, rhs, violation_amount + ) + + # Upper bound: I^p_0 <= C_0 + violation_amount_ub = inv - C0 + if violation_amount_ub > tol: + lhs = inv + rhs = float(C0) + record_violation( + 7, + f"Constraint (7): Supplier inventory exceeds capacity in period {p}: " + f"I^{p}_0={inv:.4f} > C_0={C0}", + lhs, rhs, violation_amount_ub + ) + + # ========================================================================= + # Constraint (8) family: Non-negativity of delivery quantities (q^s_{wi}). + # The original (8) bound y^p_{rw} >= 0 is structurally satisfied because + # parsed routes carry y^p_{rw} = 1 (used). Per the same non-negativity + # family in the original RDP, sub-deliveries q must also be >= 0; we test + # that here as the actionable form on the original solution structure. + # ========================================================================= + for p in P: + for r_idx, r in enumerate(routes_per_period[p]): + for cust_id, qty in r['deliveries'].items(): + if qty < -tol: + lhs = qty + rhs = 0.0 + violation_amount = -qty + record_violation( + 8, + f"Constraint (8) family: Negative delivery quantity {qty:.4f} to " + f"customer {cust_id} on route {r_idx + 1} in period {p}", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (9): Integrality on routes + # sum_{w in W^p_r} y^p_{rw} in {0, 1} + # With realized explicit routes, integrality of route usage is inherently + # satisfied. We instead verify the reported route is well-formed: + # (a) starts and ends at the depot (0) + # (b) interior nodes are distinct (no subtour cycle through any customer) + # so truncated routes and disconnected subtours are flagged rather than + # silently accepted as members of R. + # ========================================================================= + for p in P: + for r_idx, r in enumerate(routes_per_period[p]): + raw = r.get('raw') + if raw is None: + continue + # (a) depot start/end + if len(raw) < 2 or raw[0] != 0 or raw[-1] != 0: + record_violation( + 9, + f"Constraint (9) structure: Route {r_idx + 1} in period {p} " + f"is malformed (must start and end at depot 0): {raw}", + float(len(raw)), 0.0, 1.0, + ) + continue + # (b) no customer visited twice within one route (would imply a + # subtour cycle through that customer rather than a simple + # depot-to-depot path). + interior = [n for n in raw[1:-1] if n != 0] + seen = set() + dupes = [] + for n in interior: + if n in seen: + dupes.append(n) + seen.add(n) + if dupes: + record_violation( + 9, + f"Constraint (9) structure: Route {r_idx + 1} in period {p} " + f"revisits customer(s) {dupes} (disconnected subtour in {raw})", + float(len(dupes)), 0.0, float(len(dupes)), + ) + + # ========================================================================= + # Vehicle capacity (paper Hard Constraint #8 / R-membership): + # total_load on each used route <= Q. Distinct from constraint (9) above + # (which is route-usage integrality / structural well-formedness). The + # capacity bound was previously folded into the (9) check; per the paper + # it belongs to R-membership and is enforced here as its own block so a + # solution with total_load > Q is correctly flagged. + # ========================================================================= + for p in P: + for r_idx, r in enumerate(routes_per_period[p]): + total_load = sum(r['deliveries'].values()) + lhs = total_load + rhs = float(Q) + violation_amount = total_load - Q + if violation_amount > tol: + record_violation( + "vehicle_capacity", + f"Vehicle capacity (R-membership): Route {r_idx + 1} in period {p} " + f"load={total_load:.4f} exceeds vehicle capacity Q={Q}", + lhs, rhs, violation_amount + ) + + # ========================================================================= + # Constraint (10): Objective-value consistency (Tier C anti-gaming check). + # The objective (1) is min sum_{p,r,w} c_{rw} y^p_{rw} + sum_p h_0 I^p_0, + # i.e. total vehicle travel cost plus inventory holding cost at the supplier + # and at all customers across the horizon. Every variable that determines + # this objective is present in the solution: routes give the travel arcs, + # and deliveries determine the end-of-period inventories (already simulated + # above as depot_inv / cust_inv) on which holding costs are charged. The + # objective is therefore fully recomputable. Reject solutions whose reported + # objective_value disagrees with the recomputed value -- this catches + # fabricated objective values (e.g. obj=0 or obj=sys.float_info.max) that + # otherwise pass constraints (2)-(9). + # ========================================================================= + reported_obj = sol_data.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 = None + try: + cust_h = params['h'] + dep_h0 = params['h0'] + # Travel cost: sum of arc costs over every used route. Gurobi + # routes carry the full depot-to-depot node sequence in 'raw'; + # efficient-format routes carry only the customer visit order, + # so the depot (0) is prepended and appended. + travel_cost = 0.0 + for p in P: + for r in routes_per_period[p]: + raw = r.get('raw') + if raw is not None: + seq = list(raw) + else: + seq = [0] + list(r['customers']) + [0] + for k in range(len(seq) - 1): + travel_cost += dist[seq[k]][seq[k + 1]] + # Holding cost: charged on simulated end-of-period inventory at + # the supplier (depot_inv) and at every customer (cust_inv). + holding_cost = 0.0 + for p in P: + holding_cost += dep_h0 * depot_inv[p] + for i in N: + holding_cost += cust_h[i] * cust_inv[i, p] + true_obj = travel_cost + holding_cost + except (KeyError, IndexError, TypeError): + true_obj = None + if true_obj is not None: + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + record_violation( + 10, + f"Constraint (10): Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed travel+holding cost={true_obj:.4f} " + f"(travel={travel_cost:.4f}, holding={holding_cost:.4f}, " + f"|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported, true_obj, abs_diff + ) + + # ========================================================================= + # Build result + # ========================================================================= + violated_constraints = sorted(violated_constraint_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 the Inventory-Routing Problem (IRP)") + 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_data = load_json(args.instance_path) + sol_data = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol_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, sol_data) + + 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/desaulniers2014/gurobi_code.py b/tasks/desaulniers2014/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a68eaa079f1a24dd0c61363c1f5f04c5db149389 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_code.py @@ -0,0 +1,377 @@ +""" +Gurobi MIP formulation for the Inventory-Routing Problem (IRP). + +Based on: Desaulniers, Rakke, Coelho (2014) - "A Branch-Price-and-Cut Algorithm +for the Inventory-Routing Problem" + +Since the paper's formulation (1)-(9) is a Dantzig-Wolfe decomposition (column generation) +that CANNOT be directly input into a MIP solver, we implement a compact arc-flow +formulation for the IRP that is equivalent and can be solved directly by Gurobi. + +This compact formulation uses: +- Binary variables z_{ip} for whether customer i is visited in period p +- Binary arc variables x_{ijp} for routing in period p +- Continuous variables q_{ip} for quantity delivered to customer i in period p +- Continuous variables I_{ip} for inventory at node i at end of period p + +Replenishment policy: Maximum-Level (ML) - any quantity can be delivered as long as +the maximum inventory capacity is not exceeded. + +Assumptions (inferred): +- Travel costs are symmetric (c_{ij} = c_{ji}), based on Euclidean distances in the instance. +- The distance_matrix provided in the instance is used directly as travel cost. +- Demands are constant per period (demand_per_period). +- Production is constant per period (production_per_period). +""" + +import argparse +import json +import math +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, 'r') as f: + data = json.load(f) + return data + + +def solve_irp(instance_path, solution_path, time_limit): + data = load_instance(instance_path) + + # ------------------------------------------------------------------ + # Extract instance data + # ------------------------------------------------------------------ + num_customers = data["num_customers"] + num_periods = data["num_periods"] + num_vehicles = data["num_vehicles"] + Q = data["vehicle_capacity"] + + depot = data["depot"] + customers = data["customers"] + dist = data["distance_matrix"] + + N = list(range(1, num_customers + 1)) # customer indices + V = [0] + N # all nodes (0 = depot) + P = list(range(1, num_periods + 1)) # periods 1..rho + + # Depot parameters + I0_0 = depot["initial_inventory"] + C_0 = depot["max_inventory"] + h_0 = depot["holding_cost"] + prod = depot["production_per_period"] # d^p_0 + + # Customer parameters (indexed by customer id 1..n) + demand = {} + C = {} + I0 = {} + h = {} + for c in customers: + cid = c["id"] + demand[cid] = c["demand_per_period"] + C[cid] = c["max_inventory"] + I0[cid] = c["initial_inventory"] + h[cid] = c["holding_cost"] + + # Travel cost matrix + cost = {} + for i in V: + for j in V: + cost[i, j] = dist[i][j] + + # ------------------------------------------------------------------ + # Build Gurobi model + # ------------------------------------------------------------------ + model = gp.Model("IRP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # --- Decision variables --- + + # x[i,j,p] = 1 if arc (i,j) is traversed in period p + x = {} + for p in P: + for i in V: + for j in V: + if i != j: + x[i, j, p] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}_{p}") + + # z[i,p] = 1 if customer i is visited in period p + z = {} + for p in P: + for i in N: + z[i, p] = model.addVar(vtype=GRB.BINARY, name=f"z_{i}_{p}") + + # q[i,p] = quantity delivered to customer i in period p + q = {} + for p in P: + for i in N: + q[i, p] = model.addVar(lb=0, vtype=GRB.CONTINUOUS, name=f"q_{i}_{p}") + + # I_cust[i,p] = inventory at customer i at end of period p + I_cust = {} + for i in N: + for p in P: + I_cust[i, p] = model.addVar(lb=0, ub=C[i], vtype=GRB.CONTINUOUS, + name=f"Ic_{i}_{p}") + + # I_dep[p] = inventory at depot at end of period p + I_dep = {} + for p in P: + I_dep[p] = model.addVar(lb=0, ub=C_0, vtype=GRB.CONTINUOUS, + name=f"Id_{p}") + + # u[i,j,p] = flow (number of units of load) on arc (i,j) in period p + # Used for subtour elimination (MTZ-like flow formulation) + f_var = {} + for p in P: + for i in V: + for j in V: + if i != j: + f_var[i, j, p] = model.addVar(lb=0, vtype=GRB.CONTINUOUS, + name=f"f_{i}_{j}_{p}") + + model.update() + + # --- Objective function --- + # Minimize routing costs + inventory holding costs + obj = gp.LinExpr() + + # Routing costs + for p in P: + for i in V: + for j in V: + if i != j: + obj += cost[i, j] * x[i, j, p] + + # Holding costs at customers + for p in P: + for i in N: + obj += h[i] * I_cust[i, p] + + # Holding costs at depot + for p in P: + obj += h_0 * I_dep[p] + + model.setObjective(obj, GRB.MINIMIZE) + + # --- Constraints --- + + # (C1) Depot inventory balance + for p in P: + total_delivered = gp.quicksum(q[i, p] for i in N) + if p == 1: + model.addConstr(I0_0 + prod - total_delivered == I_dep[p], + name=f"depot_inv_{p}") + else: + model.addConstr(I_dep[p - 1] + prod - total_delivered == I_dep[p], + name=f"depot_inv_{p}") + + # (C2) Customer inventory balance (no stockouts) + for i in N: + for p in P: + if p == 1: + model.addConstr(I0[i] + q[i, p] - demand[i] == I_cust[i, p], + name=f"cust_inv_{i}_{p}") + else: + model.addConstr(I_cust[i, p - 1] + q[i, p] - demand[i] == I_cust[i, p], + name=f"cust_inv_{i}_{p}") + + # (C3) Customer inventory capacity: inventory after delivery <= C_i + # Inventory right after delivery (before consumption) = I_{i,p-1} + q_{i,p} + # This must be <= C_i + for i in N: + for p in P: + if p == 1: + model.addConstr(I0[i] + q[i, p] <= C[i], + name=f"cust_cap_{i}_{p}") + else: + model.addConstr(I_cust[i, p - 1] + q[i, p] <= C[i], + name=f"cust_cap_{i}_{p}") + + # (C4) Delivery only if visited + # q[i,p] <= C_i * z[i,p] (if not visited, no delivery) + for i in N: + for p in P: + model.addConstr(q[i, p] <= C[i] * z[i, p], + name=f"link_qz_{i}_{p}") + + # (C5) Each customer visited at most once per period + # (already implied by z being binary, but we link z to routing) + # z[i,p] = 1 iff customer i is visited in period p + for i in N: + for p in P: + model.addConstr( + gp.quicksum(x[j, i, p] for j in V if j != i) == z[i, p], + name=f"visit_{i}_{p}") + + # (C6) Flow conservation for routing: each visited node has in-degree = out-degree + for p in P: + for i in N: + model.addConstr( + gp.quicksum(x[j, i, p] for j in V if j != i) == + gp.quicksum(x[i, j, p] for j in V if j != i), + name=f"flow_{i}_{p}") + + # (C7) At most K vehicles leave the depot in each period + for p in P: + model.addConstr( + gp.quicksum(x[0, j, p] for j in N) <= num_vehicles, + name=f"vehicles_{p}") + + # (C8) Depot out-degree = depot in-degree (balanced routes) + for p in P: + model.addConstr( + gp.quicksum(x[0, j, p] for j in N) == + gp.quicksum(x[j, 0, p] for j in N), + name=f"depot_balance_{p}") + + # (C9) Subtour elimination via commodity flow + # Flow on arcs leaving depot = total delivery on corresponding route + # f[0,j,p] <= Q * x[0,j,p] + for p in P: + for j in N: + model.addConstr(f_var[0, j, p] <= Q * x[0, j, p], + name=f"flow_depot_out_{j}_{p}") + + # Flow conservation at customer nodes + for p in P: + for i in N: + model.addConstr( + gp.quicksum(f_var[j, i, p] for j in V if j != i) - + gp.quicksum(f_var[i, j, p] for j in V if j != i) == q[i, p], + name=f"flow_cons_{i}_{p}") + + # Flow on arcs bounded by capacity times arc usage + for p in P: + for i in V: + for j in V: + if i != j: + model.addConstr(f_var[i, j, p] <= Q * x[i, j, p], + name=f"flow_cap_{i}_{j}_{p}") + + # (C10) Non-negativity of customer inventory (no stockouts) + # Already handled by lb=0 on I_cust variables + + # ------------------------------------------------------------------ + # Solve + # ------------------------------------------------------------------ + model.optimize() + + # ------------------------------------------------------------------ + # Extract solution + # ------------------------------------------------------------------ + result = {} + + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + + # Extract routes and deliveries + solution_details = {"periods": {}} + for p in P: + period_info = {"routes": [], "deliveries": {}} + + # Find routes by tracing arcs from depot + visited_arcs = [] + for i in V: + for j in V: + if i != j and x[i, j, p].X > 0.5: + visited_arcs.append((i, j)) + + # Trace routes from depot + routes = [] + depot_successors = [j for (i, j) in visited_arcs if i == 0] + used_arcs = set() + for start in depot_successors: + route = [0, start] + used_arcs.add((0, start)) + current = start + while current != 0: + next_node = None + for (i, j) in visited_arcs: + if i == current and (i, j) not in used_arcs: + next_node = j + used_arcs.add((i, j)) + break + if next_node is None: + break + route.append(next_node) + current = next_node + routes.append(route) + + period_info["routes"] = routes + + # Deliveries + deliveries = {} + for i in N: + qval = q[i, p].X + if qval > 1e-6: + deliveries[str(i)] = round(qval, 4) + period_info["deliveries"] = deliveries + + # Inventories + inventories = {} + inventories["depot"] = round(I_dep[p].X, 4) + for i in N: + inventories[str(i)] = round(I_cust[i, p].X, 4) + period_info["inventories"] = inventories + + solution_details["periods"][str(p)] = period_info + + result["solution_details"] = solution_details + result["status"] = "Optimal" if model.Status == GRB.OPTIMAL else "Feasible" + result["mip_gap"] = model.MIPGap if hasattr(model, 'MIPGap') else None + + else: + result["objective_value"] = None + result["status"] = "Infeasible or no solution found" + + # Write solution + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status']}") + + return result + + +def main(): + parser = argparse.ArgumentParser(description="Gurobi MIP for Inventory-Routing Problem") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path 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_irp(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/desaulniers2014/gurobi_feasi_result/large_feasi_result_1.json b/tasks/desaulniers2014/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2014/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/desaulniers2014/gurobi_feasi_result/large_feasi_result_2.json b/tasks/desaulniers2014/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2014/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/desaulniers2014/gurobi_feasi_result/large_feasi_result_3.json b/tasks/desaulniers2014/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2014/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/desaulniers2014/gurobi_feasi_result/large_feasi_result_4.json b/tasks/desaulniers2014/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2014/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/desaulniers2014/gurobi_feasi_result/large_feasi_result_5.json b/tasks/desaulniers2014/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2014/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/desaulniers2014/gurobi_feasi_result/tiny_feasi_result.json b/tasks/desaulniers2014/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2014/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/desaulniers2014/gurobi_solution/large_solution_1.json b/tasks/desaulniers2014/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..b46ca92a123ef8f905dfbca5be115c997f5c24c4 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72dcc8e1182cdebe574a3b8987ef5a4224d9cf1445921456640a1a2ce5eb90a8 +size 5959 diff --git a/tasks/desaulniers2014/gurobi_solution/large_solution_2.json b/tasks/desaulniers2014/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a508d5906ef7879298983530ae78f77d8403f28c --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0d1a0b5962709e97a01323d63dead90ca90fde1546ddccedbfd96e153ab2d63 +size 6148 diff --git a/tasks/desaulniers2014/gurobi_solution/large_solution_3.json b/tasks/desaulniers2014/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..256fb68da75b834cbd16f2a7313349f9be8fe0c1 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28cba5814813124db45e2321b04c1fe369c5941c7797e4c20150b202154ac159 +size 5947 diff --git a/tasks/desaulniers2014/gurobi_solution/large_solution_4.json b/tasks/desaulniers2014/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ba274e2f6bfd244b92d3893ca24ade6a0950836c --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edf1ff7f5abb737f5e54d29f2bd7065d7992a9384143fc71c422e506b0f3ef4a +size 6127 diff --git a/tasks/desaulniers2014/gurobi_solution/large_solution_5.json b/tasks/desaulniers2014/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3feededcf0dcb81ad45d4bd02ebab90c1efae808 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ca8fa4a18542d6e9ea821e21e8ca1a91494a7bd4e27758be8905036bebf0100 +size 6045 diff --git a/tasks/desaulniers2014/gurobi_solution/tiny_solution.json b/tasks/desaulniers2014/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..fe77149ba17ac696b3706f2b5346d88cb24b3648 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f221bb6525f3bda85cf96b371e5acb45f2c34a682384e916bcd24f1908da046f +size 1161 diff --git a/tasks/desaulniers2014/gurobi_solution_log/large_log_1.jsonl b/tasks/desaulniers2014/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6f6a53e42306a09b2149809f10db4181c5a83dc0 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41d1dcbacebb00d5aa9b6102800327d77ff98e5925d59626f6c9960c141e2fe0 +size 3283 diff --git a/tasks/desaulniers2014/gurobi_solution_log/large_log_2.jsonl b/tasks/desaulniers2014/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..42ff12059232b2c8f2f93eab274670e3f7c084c1 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0098ca6674f050384ef14a2d4b27b35742cc4aac82faaedfbb1fad51f4dd6a5a +size 2687 diff --git a/tasks/desaulniers2014/gurobi_solution_log/large_log_3.jsonl b/tasks/desaulniers2014/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..be31b78e57dac2bf244f2cdace14c5b82c4dd7b0 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:539a3e04c9b9a5dbcee2aba05f0c9c1d821a8d3d08f3be010650e7664407b890 +size 1070 diff --git a/tasks/desaulniers2014/gurobi_solution_log/large_log_4.jsonl b/tasks/desaulniers2014/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cff19f4d994401e660040e71052dbc65b87091d8 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3524790149d5f68d64f22a0559a1f008209d592307579eb13656c639c66627ee +size 3236 diff --git a/tasks/desaulniers2014/gurobi_solution_log/large_log_5.jsonl b/tasks/desaulniers2014/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..63b678c1c78cfc006d543d7232c70f08d4bc4d01 --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e628bb960b654c2955e843df0064ecd99f2507d8503a33c672f0894b632c2758 +size 1293 diff --git a/tasks/desaulniers2014/gurobi_solution_log/tiny_log.jsonl b/tasks/desaulniers2014/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..036f6ef99888ffeb4e55f9b26c160841e758716c --- /dev/null +++ b/tasks/desaulniers2014/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58dd0fd16bdac7fc432332d269056efa0e33b49847431ae3ae9ce408032595ee +size 99 diff --git a/tasks/desaulniers2014/instance/large_instance_1.json b/tasks/desaulniers2014/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ee4518d6a2a227c740a4ed2f7270446517989606 --- /dev/null +++ b/tasks/desaulniers2014/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c37d27a739651835de403d2f4a428dd0d409b1fe3abf8b989298d31225f0003a +size 39596 diff --git a/tasks/desaulniers2014/instance/large_instance_2.json b/tasks/desaulniers2014/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..31ced064ad09cc4127f92ef8d8a7b6a8850d6b6b --- /dev/null +++ b/tasks/desaulniers2014/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1dc6e3e53760fdc51b8bd667a842f4b66f781dc4dee860961ad5b5ef23e4b8e +size 39633 diff --git a/tasks/desaulniers2014/instance/large_instance_3.json b/tasks/desaulniers2014/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..2de52a26a029743eebbefa65b94f42582319970e --- /dev/null +++ b/tasks/desaulniers2014/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:018ad93e65d4fcf8d91682904ec02830cacf2320b33062220d7dc7ec2ec31e1d +size 39657 diff --git a/tasks/desaulniers2014/instance/large_instance_4.json b/tasks/desaulniers2014/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..35fe80cfc5e8af59df0b6795d705d6ee5a9e092f --- /dev/null +++ b/tasks/desaulniers2014/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae63ad61479083c238c1c29cdb67462d4ae92161f84538a6735d7585d380b300 +size 39637 diff --git a/tasks/desaulniers2014/instance/large_instance_5.json b/tasks/desaulniers2014/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..2c3ca1fcbc0f117dcc0c5ebc89f5dd44e0dcb868 --- /dev/null +++ b/tasks/desaulniers2014/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:991cb2d736a5994433561800a2cd32fa002db031bd90fd5bfda9354bef9259e7 +size 39638 diff --git a/tasks/desaulniers2014/instance/tiny_instance.json b/tasks/desaulniers2014/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..5a75f4b7a4ba954c1b5c65208e6391c0a39ec316 --- /dev/null +++ b/tasks/desaulniers2014/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be3ee267cc83053320b97d0b7f00c99896930c0f0cf1c7ba79a48cc3c4ca56dc +size 2094 diff --git a/tasks/desaulniers2014/instance_schema.json b/tasks/desaulniers2014/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b1f83c0c97e229a7b4d7e0036a21a696e08dd653 --- /dev/null +++ b/tasks/desaulniers2014/instance_schema.json @@ -0,0 +1,28 @@ +{ + "num_customers": " Number of customers to be served by the supplier.", + "num_periods": " Number of discrete time periods in the planning horizon.", + "num_vehicles": " Number of homogeneous vehicles available for deliveries each period.", + "vehicle_capacity": " Maximum total quantity that can be loaded onto a single vehicle for one route.", + "depot": { + "id": " Identifier for the supplier location (always 0).", + "x": " Horizontal coordinate of the supplier.", + "y": " Vertical coordinate of the supplier.", + "initial_inventory": " Quantity of commodity on hand at the supplier at the start of the planning horizon.", + "max_inventory": " Maximum quantity of commodity the supplier can store at any time.", + "production_per_period": " Quantity of commodity produced at the supplier in each period.", + "holding_cost": " Per-unit cost charged on the supplier's end-of-period inventory." + }, + "customers": [ + { + "id": " Unique identifier for the customer (1-indexed).", + "x": " Horizontal coordinate of the customer.", + "y": " Vertical coordinate of the customer.", + "initial_inventory": " Quantity of commodity on hand at the customer at the start of the planning horizon.", + "max_inventory": " Maximum quantity of commodity the customer can store at any time.", + "min_inventory": " Minimum quantity of commodity the customer must hold at the end of any period.", + "demand_per_period": " Quantity of commodity consumed by the customer in each period.", + "holding_cost": " Per-unit cost charged on the customer's end-of-period inventory." + } + ], + "distance_matrix": " Symmetric travel cost between each pair of locations, where row and column 0 is the supplier and rows/columns 1 through num_customers are customers." +} diff --git a/tasks/desaulniers2014/mathematical_formulation.md b/tasks/desaulniers2014/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..eff04019efaa78c172b00c660157728ac3723cb6 --- /dev/null +++ b/tasks/desaulniers2014/mathematical_formulation.md @@ -0,0 +1,90 @@ +# Original Formulation: Inventory-Routing Problem (IRP) + +*Source: A Branch-Price-and-Cut Algorithm for the Inventory-Routing Problem, G. Desaulniers, J.G. Rakke, L.C. Coelho, Les Cahiers du GERAD G-2014-19, 2014.* + +## Sets and Indices + +$$\begin{align*} +& P = \{1, 2, \ldots, \rho\} && \text{set of periods in the planning horizon}\\ +& \rho + 1 && \text{fictitious period to handle end inventories}\\ +& N && \text{set of customers}\\ +& 0 && \text{the supplier (depot)}\\ +& R && \text{set of feasible routes}\\ +& N_r && \text{set of customers visited in route } r \in R\\ +& W^p_r && \text{set of extreme RDPs (route delivery patterns) when route } r\\ +&&& \text{is used in period } p \in P\\ +& P^+_{ip} && \text{periods of the sub-deliveries of a delivery to customer } i\\ +&&& \text{in period } p \ (\text{defined below})\\ +& P^-_{is} = \{ p \in P \mid s \in P^+_{ip} \} && \text{periods at which a sub-delivery can fulfill the demand of}\\ +&&& \text{customer } i \text{ in period } s +\end{align*}$$ The set of sub-delivery periods is $$P^+_{ip} = \Big\{ s \in \{p{+}1, \ldots, \rho{+}1\} \;\Big|\; +\big(s \in P,\ \bar{d}^s_i > 0,\ \textstyle\sum_{\ell=p}^{s} d^\ell_i \le C_i\big) +\ \text{or}\ \big(s = \rho{+}1,\ \textstyle\sum_{\ell=p}^{s} d^\ell_i < C_i\big) \Big\}.$$ + +## Parameters + +$$\begin{align*} +& d^p_0 && \text{quantity produced by the supplier in period } p \in P\\ +& d^p_i && \text{demand (consumption) of customer } i \in N \text{ in period } p \in P\\ +& C_i && \text{inventory (holding) capacity of customer } i \in N\\ +& C_0 && \text{inventory capacity of the supplier}\\ +& I^0_i && \text{initial inventory at customer } i \in N,\ I^0_i \le C_i\\ +& I^0_0 && \text{initial inventory at the supplier,}\ I^0_0 \le C_0\\ +& h_i && \text{unit holding cost at customer } i \in N\\ +& h_0 && \text{unit holding cost at the supplier}\\ +& Q && \text{vehicle capacity (homogeneous fleet)}\\ +& K && \text{number of available vehicles}\\ +& c_{ij} && \text{travel cost between locations } i \text{ and } j,\ i,j \in N \cup \{0\}\\ +& a_{ri} && \text{1 if route } r \in R \text{ visits customer } i \in N,\ 0 \text{ otherwise} +\end{align*}$$ + +Residual inventory from the initial stock at customer $i$ at the end of period $s$: $$I^{0,s}_i = \max\Big\{0,\ I^0_i - \textstyle\sum_{\ell=1}^{s} d^\ell_i\Big\}, \qquad \forall i \in N,\ s \in P.$$ Residual demands: $$\bar{d}^s_i = +\begin{cases} +\max\{0,\ d^1_i - I^0_i\} & \text{if } s = 1\\[2pt] +\max\{0,\ d^s_i - I^{0,s-1}_i\} & \text{otherwise,} +\end{cases} +\qquad \forall i \in N,\ s \in P.$$ Upper bound on the quantity dedicated to each sub-delivery period $s \in P^+_{ip}$: $$u^s_{ip} = +\begin{cases} +\min\{\bar{d}^s_i,\ C_i - I^{0,s-1}_i\} & \text{if } s = p\\[2pt] +C_i - \sum_{\ell=p}^{s-1} d^\ell_i - I^{0,s-1}_i & \text{if } s = \rho+1\\[2pt] +\min\{\bar{d}^s_i,\ C_i - \sum_{\ell=p}^{s-1} d^\ell_i - I^{0,s-1}_i\} & \text{otherwise.} +\end{cases}$$ Route delivery pattern (RDP) parameters. An extreme RDP $w \in W^p_r$ specifies $q^s_{wi} \in [0, u^s_{ip}]$, the quantity delivered to customer $i \in N_r$ dedicated to period $s \in P^+_{ip}$ (an extreme RDP contains at most one partial sub-delivery, i.e. at most one $q^s_{wi} \in (0, u^s_{ip})$): $$\begin{align*} +& q_w = \textstyle\sum_{i \in N_r} \sum_{s \in P^+_{ip}} q^s_{wi} && \text{total quantity delivered (loaded at the supplier) in RDP } w\\ +& b^s_{wi} && \text{quantity delivered to customer } i \in N_r \text{ in inventory at end of } s \in P^+_{ip}\\ +& c_{rw} && \text{sum of travel costs and holding costs for route } r \text{ with RDP } w +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +& y^p_{rw} \in [0,1] && \text{proportion of route } r \in R \text{ operated with extreme RDP } w \in W^p_r\\ +&&& \text{in period } p \in P \ (\text{continuous})\\ +& I^p_0 \ge 0 && \text{inventory at the supplier at the end of period } p \in P +\end{align*}$$ + +## Objective + +$$\begin{equation} +\min \quad \sum_{p \in P} \sum_{r \in R} \sum_{w \in W^p_r} c_{rw}\, y^p_{rw} \;+\; \sum_{p \in P} h_0\, I^p_0 \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +& I^{p-1}_0 + d^p_0 - \sum_{r \in R} \sum_{w \in W^p_r} q_w\, y^p_{rw} = I^p_0, +&& \forall p \in P, \tag{2}\\ +& \sum_{p \in P^-_{is}} \sum_{r \in R} \sum_{w \in W^p_r} q^s_{wi}\, y^p_{rw} = \bar{d}^s_i, +&& \forall i \in N,\ s \in P \text{ such that } \bar{d}^s_i > 0, \tag{3}\\ +& I^{0,s}_i + \sum_{p \in P^-_{is}} \sum_{r \in R} \sum_{w \in W^p_r} b^s_{wi}\, y^p_{rw} \le C_i - d^s_i, +&& \forall i \in N,\ s \in P, \tag{4}\\ +& \sum_{r \in R} \sum_{w \in W^p_r} a_{ri}\, y^p_{rw} \le 1, +&& \forall i \in N,\ p \in P, \tag{5}\\ +& \sum_{r \in R} \sum_{w \in W^p_r} y^p_{rw} \le K, +&& \forall p \in P, \tag{6}\\ +& 0 \le I^p_0 \le C_0, +&& \forall p \in P, \tag{7}\\ +& y^p_{rw} \ge 0, +&& \forall p \in P,\ r \in R,\ w \in W^p_r, \tag{8}\\ +& \sum_{w \in W^p_r} y^p_{rw} \in \{0,1\}, +&& \forall p \in P,\ r \in R. \tag{9} +\end{align}$$ diff --git a/tasks/desaulniers2014/problem_description.txt b/tasks/desaulniers2014/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c752bc7611c6d925c782f8e2b48606324926b460 --- /dev/null +++ b/tasks/desaulniers2014/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A single supplier distributes a single commodity to a set of customers over a finite planning horizon consisting of a given number of discrete periods, using a homogeneous fleet of vehicles each with a known carrying capacity. The supplier produces a known quantity of the commodity in each period, and each customer consumes a known quantity (its demand) in each period. Both the supplier and every customer have a maximum inventory capacity and an initial inventory level that does not exceed that capacity. Each location — the supplier and every customer — has a per-unit holding cost charged on its end-of-period inventory. A symmetric travel cost is specified for every pair of locations, including between the supplier and each customer, and between every pair of customers. + +In each period the supplier first produces its output, then dispatches vehicles to make deliveries. Customers receive deliveries at the beginning of the period and may use the delivered goods to satisfy that period's demand. The supplier must decide, for each period, which customers to visit, what quantity to deliver to each visited customer, and how to combine the visits into vehicle routes that each start and end at the supplier. Any quantity may be delivered to a customer as long as the customer's inventory capacity is never exceeded; there is no requirement to fill the customer's storage completely upon a visit. No customer may experience a stockout in any period: the combination of its on-hand inventory and any delivery received must cover its demand in every period. + +Each route spans a single period, departs from and returns to the supplier, and the total quantity loaded onto a vehicle for the route must not exceed the vehicle capacity. Each customer may be visited by at most one vehicle in any given period. The total number of routes operated in any period must not exceed the number of available vehicles. The supplier's inventory at the end of every period must remain between zero and its maximum capacity, inclusive. + +The supplier's inventory must balance across periods: the inventory at the end of any period equals the inventory at the end of the previous period plus that period's production minus the total quantity loaded onto all vehicles dispatched in that period. Each customer's inventory must likewise balance across periods: the inventory at the end of any period equals the inventory at the end of the previous period plus the quantity delivered to the customer in that period minus the customer's demand in that period. + +The goal is to minimize the total cost, which is the sum of two components: the total travel cost incurred by all vehicle routes across all periods, plus the total inventory holding cost at all locations (supplier and customers) across all periods, where each location's holding cost in a period equals its per-unit holding cost multiplied by its end-of-period inventory level. diff --git a/tasks/desaulniers2014/solution_logger.py b/tasks/desaulniers2014/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/desaulniers2014/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/desaulniers2014/solution_schema.json b/tasks/desaulniers2014/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a636373736d62be8dd4b0238a9d276ced4671dae --- /dev/null +++ b/tasks/desaulniers2014/solution_schema.json @@ -0,0 +1,15 @@ +{ + "objective_value": " Total cost combining all vehicle travel costs and inventory holding costs across all locations and periods.", + "solution_details": { + "periods": { + "{period}": { + "routes": " Sequence of location identifiers visited on each vehicle route in this period, each starting and ending at the supplier (0).", + "deliveries": " Quantity of commodity delivered to each customer who receives a delivery in this period.", + "inventories": { + "depot": " Quantity of commodity stored at the supplier at the end of this period.", + "{customer}": " Quantity of commodity stored at each customer at the end of this period." + } + } + } + } +} diff --git a/tasks/desaulniers2016/feasibility_check.py b/tasks/desaulniers2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c667e342acce1c2b989a4546cafddd2e09c0e420 --- /dev/null +++ b/tasks/desaulniers2016/feasibility_check.py @@ -0,0 +1,752 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Inventory-Routing Problem (IRP). + +Checks a candidate solution against the compact arc-flow formulation (Part B) +from math_model.txt (Desaulniers, Rakke, and Coelho 2016). + +Hard constraints checked (numbered top-to-bottom in Part B): + 1. Supplier inventory balance + 2. Customer inventory balance + 3. No stockouts (inventory non-negativity) + 4. Inventory capacity (customer) + 5. Supplier inventory capacity + 6. Delivery only if visited + 7. Flow conservation for vehicles + 8. Each vehicle leaves depot at most once + 9. Depot flow balance (leaves = returns) + 10. At most one visit per customer per period + 11. Subtour elimination (MTZ) + 12. Vehicle load constraints + 13. Variable domains (binary x, binary z, non-negative q, non-negative I) + 14. Objective consistency (reported objective_value must equal the + objective recomputed from the solution variables: total vehicle + travel cost plus end-of-period holding cost at every location) + +NOTE: This is the obj-recompute-augmented variant of feasibility_check.py. +It is identical to the original for constraints 0..13; it ONLY adds the new +constraint 14 (Tier C defense against fabricated objective_value reports). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('inventories', 'objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('inventories',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_instance(path): + with open(path) as f: + return json.load(f) + + +def load_solution(path): + with open(path) as f: + return json.load(f) + + +def parse_solution(instance, solution): + """ + Parse solution routes into a uniform structure. + Returns a list of (period, vehicle_index, route, deliveries) tuples. + + Handles two solution formats: + - efficient: routes[period] is a list of route objects + - gurobi: routes[period] is a dict of vehicle-indexed route objects + """ + num_periods = instance["num_periods"] + parsed = [] + + raw_routes = solution.get("routes", {}) + + for p in range(1, num_periods + 1): + period_data = raw_routes.get(str(p), {}) + + if isinstance(period_data, list): + # efficient format: list of route dicts + for k_idx, route_obj in enumerate(period_data): + route = route_obj["route"] + deliveries = {} + for cust_str, qty in route_obj.get("deliveries", {}).items(): + deliveries[int(cust_str)] = float(qty) + parsed.append((p, k_idx, route, deliveries)) + elif isinstance(period_data, dict): + # gurobi format: dict keyed by vehicle index (string) + for k_str, route_obj in period_data.items(): + route = route_obj["route"] + deliveries = {} + for cust_str, qty in route_obj.get("deliveries", {}).items(): + deliveries[int(cust_str)] = float(qty) + parsed.append((p, int(k_str), route, deliveries)) + # empty period: nothing to add + + return parsed + + +def check_feasibility(instance, solution): + """Check all hard constraints. Return (feasible, violated_constraints, violations, violation_magnitudes).""" + n = instance["num_customers"] + T = instance["num_periods"] + K = instance["num_vehicles"] + Q = instance["vehicle_capacity"] + customers = list(range(1, n + 1)) + periods = list(range(1, T + 1)) + + dist = instance["distance_matrix"] + h = instance["holding_costs"] + demands = instance["customer_demands"] # demands[i-1][p-1] + production = instance["supplier_production"] # production[p-1] + C = instance["inventory_capacities"] # C[i] for i in 0..n + I0 = instance["initial_inventories"] # I0[i] for i in 0..n + + def d(i, p): + """Demand of customer i (1-indexed) in period p (1-indexed).""" + return demands[i - 1][p - 1] + + def d0(p): + """Production at supplier in period p (1-indexed).""" + return production[p - 1] + + # Parse solution + route_entries = parse_solution(instance, solution) + + # Build per-period structures + # For each period p, collect the list of vehicle routes + period_vehicles = {p: [] for p in periods} + for (p, k_idx, route, deliveries) in route_entries: + period_vehicles[p].append((k_idx, route, deliveries)) + + # Aggregate deliveries: total_delivery[i][p] = total quantity delivered to customer i in period p + total_delivery = {i: {p: 0.0 for p in periods} for i in customers} + for (p, k_idx, route, deliveries) in route_entries: + for ci, qty in deliveries.items(): + if ci in total_delivery: + total_delivery[ci][p] += qty + + # Compute inventories + # Supplier inventory + sup_inv = {0: float(I0[0])} # sup_inv[p] = inventory at end of period p; sup_inv[0] = initial + # Customer inventory + cust_inv = {i: {0: float(I0[i])} for i in customers} + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Domain check: every node id appearing in any route must be a valid + # depot (0) or customer (1..n) id; every delivery key must be a valid + # customer id. + # ========================================================================= + valid_nodes = {0} | set(customers) + for (p, k_idx, route, deliveries) in route_entries: + for node in route: + if node not in valid_nodes: + violated_constraints.add(0) + violations.append( + f"Domain: route in period {p}, vehicle {k_idx} contains " + f"invalid node id {node!r} (not depot 0 or customer 1..{n})" + ) + violation_magnitudes.append({ + "constraint": 0, + "lhs": float(node) if isinstance(node, (int, float)) else 0.0, + "rhs": 0.0, "raw_excess": 1.0, + "normalizer": 1.0, "ratio": 1.0, + }) + for cid in deliveries: + if cid not in customers: + violated_constraints.add(0) + violations.append( + f"Domain: deliveries in period {p}, vehicle {k_idx} " + f"references invalid customer id {cid!r}" + ) + violation_magnitudes.append({ + "constraint": 0, + "lhs": float(cid) if isinstance(cid, (int, float)) else 0.0, + "rhs": 0.0, "raw_excess": 1.0, + "normalizer": 1.0, "ratio": 1.0, + }) + + def record_violation(constraint_idx, message, lhs, rhs, op): + """Record a violation with normalized magnitude.""" + if op == '=': + violation_amount = abs(lhs - rhs) + elif op in ('<=', '<'): + violation_amount = max(0.0, lhs - rhs) + elif op in ('>=', '>'): + violation_amount = max(0.0, rhs - lhs) + else: + violation_amount = 0.0 + + if violation_amount > TOL: + 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 + }) + + # ========================================================================= + # Constraint 1: Supplier inventory balance + # I_{0p} = I_{0,p-1} + d_{0p} - sum_k sum_i q_{ip}^k, for all p + # ========================================================================= + for p in periods: + prev_inv = sup_inv.get(p - 1, float(I0[0])) + total_shipped = sum( + sum(deliveries.values()) + for (pp, k_idx, route, deliveries) in route_entries if pp == p + ) + computed_inv = prev_inv + d0(p) - total_shipped + sup_inv[p] = computed_inv + + # The constraint is an equality: I_{0p} = I_{0,p-1} + d_{0p} - total_shipped + # If inventories are provided in the solution, check them; otherwise this is + # automatically satisfied by our computation. + # However, we still track sup_inv[p] for later constraint checks. + + # ========================================================================= + # Constraint 2: Customer inventory balance + # I_{ip} = I_{i,p-1} + sum_k q_{ip}^k - d_{ip}, for all i in N, p in P + # ========================================================================= + for i in customers: + for p in periods: + prev_inv = cust_inv[i].get(p - 1, float(I0[i])) + delivered = total_delivery[i][p] + demand = d(i, p) + computed_inv = prev_inv + delivered - demand + cust_inv[i][p] = computed_inv + + # Constraints 1 and 2 are balance equations defining inventories. + # Since we compute inventories from the solution, they hold by construction. + # However, if the solution provides explicit inventories, we check consistency. + if "inventories" in solution: + sol_inv = solution["inventories"] + # Check supplier inventory + for p in periods: + sol_val = float(sol_inv.get("0", {}).get(str(p), sup_inv[p])) + lhs = sup_inv[p] + rhs = sol_val + record_violation(1, f"Supplier inventory mismatch at period {p}: " + f"computed={lhs:.4f}, solution={rhs:.4f}", + lhs, rhs, '=') + # Check customer inventories + for i in customers: + for p in periods: + sol_val = float(sol_inv.get(str(i), {}).get(str(p), cust_inv[i][p])) + lhs = cust_inv[i][p] + rhs = sol_val + record_violation(2, f"Customer {i} inventory mismatch at period {p}: " + f"computed={lhs:.4f}, solution={rhs:.4f}", + lhs, rhs, '=') + + # ========================================================================= + # Constraint 3: No stockouts (inventory non-negativity) + # I_{ip} >= 0, for all i in V, p in P + # ========================================================================= + # Supplier + for p in periods: + lhs = 0.0 + rhs = sup_inv[p] + record_violation(3, f"Supplier stockout at period {p}: inventory={rhs:.4f} < 0", + lhs, rhs, '<=') + + # Customers + for i in customers: + for p in periods: + lhs = 0.0 + rhs = cust_inv[i][p] + record_violation(3, f"Customer {i} stockout at period {p}: inventory={rhs:.4f} < 0", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 4: Inventory capacity (customer) + # I_{i,p-1} + sum_k q_{ip}^k <= C_i, for all i in N, p in P + # ========================================================================= + for i in customers: + for p in periods: + prev_inv = cust_inv[i].get(p - 1, float(I0[i])) + delivered = total_delivery[i][p] + lhs = prev_inv + delivered + rhs = float(C[i]) + record_violation(4, f"Customer {i} inventory capacity exceeded at period {p}: " + f"prev_inv({prev_inv:.4f}) + delivery({delivered:.4f}) = {lhs:.4f} > capacity({rhs:.4f})", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 5: Supplier inventory capacity + # 0 <= I_{0p} <= C_0, for all p in P + # ========================================================================= + for p in periods: + inv = sup_inv[p] + # Lower bound (already checked in constraint 3) + # Upper bound + lhs = inv + rhs = float(C[0]) + record_violation(5, f"Supplier inventory capacity exceeded at period {p}: " + f"inventory={inv:.4f} > capacity={rhs:.4f}", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 6: Delivery only if visited + # q_{ip}^k <= C_i * z_{ip}^k, for all i in N, k in K, p in P + # If vehicle k does not visit customer i in period p, delivery must be 0. + # ========================================================================= + for (p, k_idx, route, deliveries) in route_entries: + # Customers visited on this route (excluding depot 0) + visited = set(node for node in route if node != 0) + for ci, qty in deliveries.items(): + if ci not in visited and qty > TOL: + lhs = qty + rhs = 0.0 + record_violation(6, f"Period {p}, vehicle {k_idx}: delivery of {qty:.4f} " + f"to customer {ci} who is not on the route {route}", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 7: Flow conservation for vehicles + # sum_j x_{ijp}^k = sum_j x_{jip}^k = z_{ip}^k, for all i in N, k, p + # Each customer node must have equal in-degree and out-degree, matching visit. + # ========================================================================= + for (p, k_idx, route, deliveries) in route_entries: + if len(route) < 2: + continue + # Count in-degree and out-degree for each customer node + in_deg = {} + out_deg = {} + for idx in range(len(route) - 1): + u, v = route[idx], route[idx + 1] + if v != 0: + in_deg[v] = in_deg.get(v, 0) + 1 + if u != 0: + out_deg[u] = out_deg.get(u, 0) + 1 + + # All customer nodes that appear in the route + cust_nodes = set(node for node in route if node != 0) + for ci in cust_nodes: + ind = in_deg.get(ci, 0) + outd = out_deg.get(ci, 0) + if ind != outd: + lhs = float(ind) + rhs = float(outd) + record_violation(7, f"Period {p}, vehicle {k_idx}: flow conservation violated " + f"at customer {ci}: in-degree={ind}, out-degree={outd}", + lhs, rhs, '=') + # z_{ip}^k = 1 if visited, so in-degree should be 1 + if ind != 1: + lhs = float(ind) + rhs = 1.0 + record_violation(7, f"Period {p}, vehicle {k_idx}: customer {ci} " + f"in-degree={ind} != 1 (should visit exactly once per route)", + lhs, rhs, '=') + + # ========================================================================= + # Constraint 8: Each vehicle leaves depot at most once + # sum_j x_{0jp}^k <= 1, for all k, p + # This means each route starts from depot at most once. + # ========================================================================= + for (p, k_idx, route, deliveries) in route_entries: + # Count arcs leaving depot + depot_out = sum(1 for idx in range(len(route) - 1) if route[idx] == 0) + lhs = float(depot_out) + rhs = 1.0 + record_violation(8, f"Period {p}, vehicle {k_idx}: depot has {depot_out} " + f"outgoing arcs (should be <= 1)", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 9: Depot flow balance (leaves = returns) + # sum_j x_{0jp}^k = sum_j x_{j0p}^k, for all k, p + # ========================================================================= + for (p, k_idx, route, deliveries) in route_entries: + depot_out = sum(1 for idx in range(len(route) - 1) if route[idx] == 0) + depot_in = sum(1 for idx in range(len(route) - 1) if route[idx + 1] == 0) + lhs = float(depot_out) + rhs = float(depot_in) + record_violation(9, f"Period {p}, vehicle {k_idx}: depot out-arcs={depot_out} " + f"!= depot in-arcs={depot_in}", + lhs, rhs, '=') + + # ========================================================================= + # Constraint 10: At most one visit per customer per period + # sum_k z_{ip}^k <= 1, for all i in N, p in P + # ========================================================================= + for p in periods: + visit_count = {i: 0 for i in customers} + for (pp, k_idx, route, deliveries) in route_entries: + if pp != p: + continue + visited = set(node for node in route if node != 0) + for ci in visited: + if ci in visit_count: + visit_count[ci] += 1 + for ci in customers: + lhs = float(visit_count[ci]) + rhs = 1.0 + record_violation(10, f"Customer {ci} visited {visit_count[ci]} times " + f"in period {p} (should be <= 1)", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 11: Subtour elimination (MTZ) + # u_{ip}^k - u_{jp}^k + Q * x_{ijp}^k <= Q - q_{jp}^k + # for all i,j in N, i != j, k, p + # + # We check this structurally: a valid route must be a simple path from depot + # through customers back to depot (no subtours). If the route starts and ends + # at depot and visits each customer at most once, there are no subtours. + # ========================================================================= + for (p, k_idx, route, deliveries) in route_entries: + if len(route) < 2: + continue + # Check route starts and ends at depot + if route[0] != 0: + record_violation(11, f"Period {p}, vehicle {k_idx}: route does not start at depot: {route}", + 1.0, 0.0, '=') + if route[-1] != 0: + record_violation(11, f"Period {p}, vehicle {k_idx}: route does not end at depot: {route}", + 1.0, 0.0, '=') + + # Check no customer is visited more than once within a single route + cust_in_route = [node for node in route if node != 0] + if len(cust_in_route) != len(set(cust_in_route)): + from collections import Counter + counts = Counter(cust_in_route) + dupes = {c: cnt for c, cnt in counts.items() if cnt > 1} + record_violation(11, f"Period {p}, vehicle {k_idx}: subtour/repeated customer " + f"in route {route}: duplicates={dupes}", + float(max(counts.values())), 1.0, '<=') + + # Check no intermediate depot visits (would indicate subtours) + interior = route[1:-1] + depot_in_interior = interior.count(0) + if depot_in_interior > 0: + lhs = float(depot_in_interior + 1) # number of "sub-routes" + rhs = 1.0 + record_violation(11, f"Period {p}, vehicle {k_idx}: depot appears in interior " + f"of route {route} ({depot_in_interior} times), indicating subtour", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 12: Vehicle load constraints + # sum_i q_{ip}^k <= Q, for all k, p + # ========================================================================= + for (p, k_idx, route, deliveries) in route_entries: + total_load = sum(deliveries.values()) + lhs = total_load + rhs = float(Q) + record_violation(12, f"Period {p}, vehicle {k_idx}: load={total_load:.4f} " + f"exceeds capacity={Q}", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 13: Variable domains + # x_{ijp}^k in {0,1}, z_{ip}^k in {0,1}, q_{ip}^k >= 0, I_{ip} >= 0 + # We check non-negativity of delivery quantities. + # Binary constraints on x and z are structural (routes are sequences of nodes). + # I_{ip} >= 0 is already checked in constraint 3. + # ========================================================================= + for (p, k_idx, route, deliveries) in route_entries: + for ci, qty in deliveries.items(): + if qty < -TOL: + lhs = 0.0 + rhs = qty + record_violation(13, f"Period {p}, vehicle {k_idx}: negative delivery " + f"quantity {qty:.4f} to customer {ci}", + lhs, rhs, '<=') + + # Also check number of vehicles used per period does not exceed K + # (This is implicit from constraint 8 applied per vehicle, but since solutions + # may not have explicit vehicle indices, we check the count directly.) + for p in periods: + num_routes = len(period_vehicles[p]) + if num_routes > K: + # This would violate constraint 8 (more routes than vehicles) + lhs = float(num_routes) + rhs = float(K) + record_violation(8, f"Period {p}: {num_routes} routes used but only {K} " + f"vehicles available", + lhs, rhs, '<=') + + # ========================================================================= + # Constraint 14: Objective consistency (Tier C anti-gaming check) + # + # The reported objective_value must equal the objective recomputed from + # the solution variables. For the compact arc-flow IRP (Part B), the + # objective is: + # min sum_p sum_k sum_(i,j) c_ij x_ijp^k + sum_p sum_i h_i I_ip + # \________ travel cost ________/ \__ holding cost __/ + # + # Both components are FULLY determined by what the solution carries: + # - travel cost = sum of distance-matrix entries along every route arc. + # - holding cost = h_i * I_ip summed over every location i in {0}u N and + # every period p, where I_ip is recomputed from the + # inventory-balance equations (constraints 1 and 2) -- + # i.e. the deterministic ground-truth inventory implied + # by the deliveries, NOT the solution's self-reported + # "inventories" field (which an exploit could fabricate + # independently; that field is separately verified by + # constraints 1/2). + # + # This is a FULL recompute: no second-stage / scenario variables exist, + # so the true objective is exactly computable. A candidate that lies + # about objective_value (e.g. reports 0.0 or sys.float_info.max while the + # routes/inventories imply a real cost) is rejected here. + # ========================================================================= + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None and math.isfinite(reported): + # Travel cost: sum distance-matrix entries along every route arc. + # Skip arcs touching invalid node ids (already flagged by the + # domain check) so this never raises IndexError. + travel_cost = 0.0 + for (p, k_idx, route, deliveries) in route_entries: + for idx in range(len(route) - 1): + a, b = route[idx], route[idx + 1] + if a in valid_nodes and b in valid_nodes: + travel_cost += float(dist[a][b]) + + # Holding cost: h_i * I_ip over all locations (depot 0 and + # customers 1..n) and all periods, using the inventories + # recomputed from the balance equations. + holding_cost = 0.0 + for p in periods: + holding_cost += float(h[0]) * sup_inv[p] + for i in customers: + for p in periods: + holding_cost += float(h[i]) * cust_inv[i][p] + + true_obj = travel_cost + holding_cost + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor; this + # absorbs the 2-decimal rounding used when solutions serialize + # deliveries/inventories, while still catching any real lie. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + record_violation( + 14, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed travel_cost+holding_cost=" + f"{true_obj} (travel_cost={travel_cost}, " + f"holding_cost={holding_cost}, |diff|={abs_diff:.6g}, " + f"tol={tol:.6g})", + reported, true_obj, '=', + ) + elif reported is not None: + # Non-finite reported objective (inf / nan) can never equal a + # finite recomputed cost: reject outright. + record_violation( + 14, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} is not a finite number", + 0.0, 1.0, '=', + ) + + # Compile results + sorted_violated = sorted(violated_constraints) + feasible = len(sorted_violated) == 0 + + # Deduplicate violation messages per constraint + unique_violations = [] + seen_msgs = set() + for msg in violations: + if msg not in seen_msgs: + seen_msgs.add(msg) + unique_violations.append(msg) + + return feasible, sorted_violated, unique_violations, violation_magnitudes + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for IRP solutions (Desaulniers et al. 2016)") + 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_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 + + feasible, violated_constraints, violations, violation_magnitudes = check_feasibility( + instance, 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) + + if feasible: + print(f"FEASIBLE: Solution satisfies all hard constraints.") + else: + print(f"INFEASIBLE: {len(violated_constraints)} constraint(s) violated: {violated_constraints}") + for v in violations: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/desaulniers2016/gurobi_code.py b/tasks/desaulniers2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..07f8b2203528075b1cbb79493bde53029b05f83f --- /dev/null +++ b/tasks/desaulniers2016/gurobi_code.py @@ -0,0 +1,457 @@ +#!/usr/bin/env python3 +""" +Compact arc-flow formulation for the Inventory-Routing Problem (IRP) +under Maximum-Level (ML) replenishment policy, solved directly by Gurobi. + +Based on: Desaulniers, Rakke, and Coelho (2016), +"A Branch-Price-and-Cut Algorithm for the Inventory-Routing Problem", +Transportation Science 50(3), pp. 1060-1076. + +NOTE: The paper's own formulation (Eqs. 1-9) is an RDP-based set-partitioning +model designed for column generation. This compact arc-flow formulation is +**NOT EXPLICITLY SPECIFIED IN PAPER** — it is reconstructed from the standard +IRP literature (Archetti et al. 2007, Coelho and Laporte 2014) as referenced +in the paper. The paper uses this type of formulation as a competitor +(branch-and-cut approach). + +Assumptions: +- Travel costs c_{ij} are the Euclidean distances (rounded to integer) as per + the benchmark instances of Archetti et al. (2007). The instance JSON provides + a precomputed distance matrix which we use directly. +- Holding costs are charged on inventory at the END of each period. +- The fleet is homogeneous (all vehicles have the same capacity Q). +- Each customer can be serviced at most once per period. +- Subtour elimination uses Miller-Tucker-Zemlin (MTZ) formulation. + (INFERRED ASSUMPTION: The exact subtour elimination used in the competitor + paper Coelho and Laporte 2014 is not specified; MTZ is a standard choice.) +- Sequence of operations: production occurs before deliveries; customers receive + deliveries at the beginning of the period and can use them to fulfill demand. +""" + +import argparse +import json +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 load_instance(instance_path): + """Load an IRP instance from a JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def solve_irp(data, time_limit): + """ + Solve the IRP using a compact arc-flow formulation with Gurobi. + + Returns a dict with the solution information. + """ + # ================================================================ + # Extract instance data + # ================================================================ + n = data["num_customers"] # number of customers + T = data["num_periods"] # number of periods + K_num = data["num_vehicles"] # number of vehicles + Q = data["vehicle_capacity"] # vehicle capacity + + # Sets + customers = list(range(1, n + 1)) # 1..n + depot = 0 + V = list(range(n + 1)) # 0..n (all locations) + periods = list(range(1, T + 1)) # 1..T + vehicles = list(range(K_num)) # 0..K-1 + + # Distance matrix (precomputed, integer Euclidean distances) + dist = data["distance_matrix"] + + # Holding costs for each location (index 0 = depot, 1..n = customers) + h = data["holding_costs"] + + # Customer demands: customer_demands[i-1][p-1] = demand of customer i in period p + cust_demands = data["customer_demands"] + + # Supplier production: supplier_production[p-1] = production in period p + supplier_prod = data["supplier_production"] + + # Inventory capacities: index 0 = depot, 1..n = customers + inv_cap = data["inventory_capacities"] + + # Initial inventories: index 0 = depot, 1..n = customers + init_inv = data["initial_inventories"] + + # Helper to get demand d_{ip} + def d(i, p): + """Demand of customer i (1-indexed) in period p (1-indexed).""" + if i == 0: + return supplier_prod[p - 1] + else: + return cust_demands[i - 1][p - 1] + + # ================================================================ + # Build Gurobi model + # ================================================================ + model = gp.Model("IRP_ArcFlow") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) # Show solver output + + # ---------------------------------------------------------------- + # Decision Variables + # ---------------------------------------------------------------- + + # x[i,j,p,k]: binary, 1 if vehicle k traverses arc (i,j) in period p + x = {} + for p in periods: + for k in vehicles: + for i in V: + for j in V: + if i != j: + x[i, j, p, k] = model.addVar( + vtype=GRB.BINARY, name=f"x_{i}_{j}_{p}_{k}") + + # z[i,p,k]: binary, 1 if vehicle k visits customer i in period p + z = {} + for i in customers: + for p in periods: + for k in vehicles: + z[i, p, k] = model.addVar( + vtype=GRB.BINARY, name=f"z_{i}_{p}_{k}") + + # q[i,p,k]: continuous, quantity delivered to customer i by vehicle k in period p + q = {} + for i in customers: + for p in periods: + for k in vehicles: + q[i, p, k] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, name=f"q_{i}_{p}_{k}") + + # I[i,p]: inventory at location i at end of period p + I = {} + for i in V: + for p in periods: + I[i, p] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, name=f"I_{i}_{p}") + + # u[i,p,k]: MTZ auxiliary variable for subtour elimination + u = {} + for i in customers: + for p in periods: + for k in vehicles: + u[i, p, k] = model.addVar( + lb=0.0, ub=Q, vtype=GRB.CONTINUOUS, name=f"u_{i}_{p}_{k}") + + model.update() + + # ---------------------------------------------------------------- + # Objective: minimize total travel + holding costs + # ---------------------------------------------------------------- + obj = gp.LinExpr() + + # Travel costs + for p in periods: + for k in vehicles: + for i in V: + for j in V: + if i != j: + obj += dist[i][j] * x[i, j, p, k] + + # Holding costs (at all locations, end of each period) + for p in periods: + for i in V: + obj += h[i] * I[i, p] + + model.setObjective(obj, GRB.MINIMIZE) + + # ---------------------------------------------------------------- + # Constraints + # ---------------------------------------------------------------- + + # 1. Supplier (depot) inventory balance: + # I_{0,p} = I_{0,p-1} + d_{0p} - sum_k sum_i q_{ip}^k + for p in periods: + prev_inv = init_inv[0] if p == 1 else I[0, p - 1] + total_delivered = gp.quicksum( + q[i, p, k] for i in customers for k in vehicles) + model.addConstr( + I[0, p] == prev_inv + d(0, p) - total_delivered, + name=f"supplier_inv_balance_{p}") + + # 2. Customer inventory balance: + # I_{ip} = I_{i,p-1} + sum_k q_{ip}^k - d_{ip} + for i in customers: + for p in periods: + prev_inv = init_inv[i] if p == 1 else I[i, p - 1] + total_received = gp.quicksum(q[i, p, k] for k in vehicles) + model.addConstr( + I[i, p] == prev_inv + total_received - d(i, p), + name=f"cust_inv_balance_{i}_{p}") + + # 3. Inventory non-negativity is already enforced by lb=0.0 on I variables + + # 4. Customer inventory capacity: + # I_{i,p-1} + sum_k q_{ip}^k <= C_i for i in N, p in P + for i in customers: + for p in periods: + prev_inv = init_inv[i] if p == 1 else I[i, p - 1] + total_received = gp.quicksum(q[i, p, k] for k in vehicles) + model.addConstr( + prev_inv + total_received <= inv_cap[i], + name=f"cust_inv_cap_{i}_{p}") + + # 5. Supplier inventory capacity: + # 0 <= I_{0p} <= C_0 + for p in periods: + model.addConstr(I[0, p] <= inv_cap[0], + name=f"supplier_inv_cap_{p}") + + # 6. Delivery only if visited: + # q_{ip}^k <= C_i * z_{ip}^k + for i in customers: + for p in periods: + for k in vehicles: + model.addConstr( + q[i, p, k] <= inv_cap[i] * z[i, p, k], + name=f"delivery_if_visit_{i}_{p}_{k}") + + # 7. Flow conservation for vehicles: + # sum_j x_{ijp}^k = z_{ip}^k (inflow) + # sum_j x_{jip}^k = z_{ip}^k (outflow) + for i in customers: + for p in periods: + for k in vehicles: + model.addConstr( + gp.quicksum(x[j, i, p, k] for j in V if j != i) == z[i, p, k], + name=f"flow_in_{i}_{p}_{k}") + model.addConstr( + gp.quicksum(x[i, j, p, k] for j in V if j != i) == z[i, p, k], + name=f"flow_out_{i}_{p}_{k}") + + # 8. Each vehicle leaves depot at most once per period: + # sum_j x_{0jp}^k <= 1 + for p in periods: + for k in vehicles: + model.addConstr( + gp.quicksum(x[0, j, p, k] for j in customers) <= 1, + name=f"depot_leave_{p}_{k}") + + # 9. Each vehicle returns to depot if it leaves: + # sum_j x_{0jp}^k = sum_j x_{j0p}^k + for p in periods: + for k in vehicles: + model.addConstr( + gp.quicksum(x[0, j, p, k] for j in customers) == + gp.quicksum(x[j, 0, p, k] for j in customers), + name=f"depot_return_{p}_{k}") + + # 10. At most one visit per customer per period: + # sum_k z_{ip}^k <= 1 + for i in customers: + for p in periods: + model.addConstr( + gp.quicksum(z[i, p, k] for k in vehicles) <= 1, + name=f"one_visit_{i}_{p}") + + # 11. MTZ subtour elimination: + # u_{ip}^k - u_{jp}^k + Q * x_{ijp}^k <= Q - q_{jp}^k + # for i,j in N, i != j + for p in periods: + for k in vehicles: + for i in customers: + for j in customers: + if i != j: + model.addConstr( + u[i, p, k] - u[j, p, k] + Q * x[i, j, p, k] + <= Q - q[j, p, k], + name=f"mtz_{i}_{j}_{p}_{k}") + + # 12. Vehicle load capacity: + # sum_i q_{ip}^k <= Q + for p in periods: + for k in vehicles: + model.addConstr( + gp.quicksum(q[i, p, k] for i in customers) <= Q, + name=f"vehicle_cap_{p}_{k}") + + # 13. MTZ variable linking with depot: + # q_{ip}^k <= u_{ip}^k for all i in N, k, p + for i in customers: + for p in periods: + for k in vehicles: + model.addConstr( + q[i, p, k] <= u[i, p, k], + name=f"mtz_link_{i}_{p}_{k}") + + # ---------------------------------------------------------------- + # Symmetry breaking: order vehicles by first customer visited + # (INFERRED ASSUMPTION: helps solver performance; not from paper) + # ---------------------------------------------------------------- + # Vehicles are identical, so we can impose ordering constraints + for p in periods: + for k in range(len(vehicles) - 1): + model.addConstr( + gp.quicksum(x[0, j, p, k] for j in customers) >= + gp.quicksum(x[0, j, p, k + 1] for j in customers), + name=f"sym_break_{p}_{k}") + + # ---------------------------------------------------------------- + # Optimize + # ---------------------------------------------------------------- + model.optimize() + + # ---------------------------------------------------------------- + # Extract solution + # ---------------------------------------------------------------- + solution = {} + + if model.Status == GRB.OPTIMAL or model.Status == GRB.TIME_LIMIT: + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["status"] = "optimal" if model.Status == GRB.OPTIMAL else "time_limit" + solution["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + solution["solve_time"] = model.Runtime + + # Extract routes + routes = {} + for p in periods: + routes[str(p)] = {} + for k in vehicles: + route_arcs = [] + for i in V: + for j in V: + if i != j and x[i, j, p, k].X > 0.5: + route_arcs.append([i, j]) + if route_arcs: + # Build ordered route + route_seq = build_route(route_arcs) + deliveries = {} + for i in customers: + val = q[i, p, k].X + if val > 0.001: + deliveries[str(i)] = round(val, 2) + routes[str(p)][str(k)] = { + "route": route_seq, + "deliveries": deliveries + } + + solution["routes"] = routes + + # Extract inventories + inventories = {} + for i in V: + inventories[str(i)] = {} + for p in periods: + inventories[str(i)][str(p)] = round(I[i, p].X, 2) + + solution["inventories"] = inventories + + # Cost breakdown + travel_cost = sum( + dist[i][j] * x[i, j, p, k].X + for p in periods for k in vehicles + for i in V for j in V if i != j and x[i, j, p, k].X > 0.5 + ) + holding_cost = sum( + h[i] * I[i, p].X for p in periods for i in V + ) + solution["travel_cost"] = round(travel_cost, 2) + solution["holding_cost"] = round(holding_cost, 2) + else: + solution["objective_value"] = None + solution["status"] = "no_feasible_solution" + solution["solve_time"] = model.Runtime + elif model.Status == GRB.INFEASIBLE: + solution["objective_value"] = None + solution["status"] = "infeasible" + solution["solve_time"] = model.Runtime + else: + solution["objective_value"] = None + solution["status"] = f"gurobi_status_{model.Status}" + solution["solve_time"] = model.Runtime + + return solution + + +def build_route(arcs): + """Build an ordered route from a list of arcs starting and ending at depot 0.""" + if not arcs: + return [] + + # Build adjacency from arcs + adj = {} + for (i, j) in arcs: + adj[i] = j + + # Start from depot + route = [0] + current = adj.get(0) + visited = {0} + while current is not None and current not in visited: + route.append(current) + visited.add(current) + current = adj.get(current) + route.append(0) # return to depot + return route + + +def main(): + parser = argparse.ArgumentParser( + description="Solve IRP using compact arc-flow formulation with 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, default=3600, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # Load instance + data = load_instance(args.instance_path) + + print(f"Instance: {data.get('instance_class', 'unknown')}, " + f"Customers: {data['num_customers']}, " + f"Periods: {data['num_periods']}, " + f"Vehicles: {data['num_vehicles']}, " + f"Capacity: {data['vehicle_capacity']}") + + # Solve + solution = solve_irp(data, args.time_limit) + + # Write solution + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"\nSolution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']}") + print(f"Status: {solution['status']}") + else: + print(f"No feasible solution found. Status: {solution['status']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/desaulniers2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/desaulniers2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2016/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/desaulniers2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/desaulniers2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2016/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/desaulniers2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/desaulniers2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2016/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/desaulniers2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/desaulniers2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2016/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/desaulniers2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/desaulniers2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2016/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/desaulniers2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/desaulniers2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/desaulniers2016/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/desaulniers2016/gurobi_solution/large_solution_1.json b/tasks/desaulniers2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5dfd21a9e751476637dfb83820671748feadf141 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5aba660131e9292dea7ab8b354aebc73e7a13c255ec2e43a2a10b3f36c1bb8db +size 5966 diff --git a/tasks/desaulniers2016/gurobi_solution/large_solution_2.json b/tasks/desaulniers2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..df600264c4414aba061731123f89b5b92c0fc728 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89606c42ba4d8cc57ed5df7ab4caf976236d8fa79f26da0608bf939d78a23927 +size 5855 diff --git a/tasks/desaulniers2016/gurobi_solution/large_solution_3.json b/tasks/desaulniers2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..70b042e91e4112bd0179284502c736f49936d41d --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:940eb36cbb7ff4c421040dd8a712abff0d7b6eba4633880b830ba82a88c26dc2 +size 7270 diff --git a/tasks/desaulniers2016/gurobi_solution/large_solution_4.json b/tasks/desaulniers2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..5b9e09636cc121630c5aada27641a21a06bdebf5 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97b266e21f2e3833cbae93c7315439a6dad9538fb50a953d9cca139799ee7c7b +size 6149 diff --git a/tasks/desaulniers2016/gurobi_solution/large_solution_5.json b/tasks/desaulniers2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..270fa07de4fc03d5845f1aeef4f61e3aa1248f10 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3f15a6a918502554fe54779499dff89b771d4c8cbe1aaaa58d9a65891292ffa +size 6139 diff --git a/tasks/desaulniers2016/gurobi_solution/tiny_solution.json b/tasks/desaulniers2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..c23d26552df22885db13c7ac5c53d8f34a7899f1 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:670f5b226ad9e5a5570c67b8c9f94efe38e21ee679726a8eda65e74697c63ae0 +size 1149 diff --git a/tasks/desaulniers2016/gurobi_solution_log/large_log_1.jsonl b/tasks/desaulniers2016/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5245bf24eea1607be5f33c511b8d89eb4afc43a7 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4426e9ef5c90070d3a3c0ef2c775a21ad32b0e2a0a06141deb8d15622091774c +size 2779 diff --git a/tasks/desaulniers2016/gurobi_solution_log/large_log_2.jsonl b/tasks/desaulniers2016/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b2674261d68e3449fea7873939ac33a809653cd --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5461352266ec0106f9d8379787211269f688848c040e71c6c832f1e651f469ce +size 2849 diff --git a/tasks/desaulniers2016/gurobi_solution_log/large_log_3.jsonl b/tasks/desaulniers2016/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eaa3646bb8f9f599dfd09b2a72336daa227ed131 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04ffa5894b9195ff51968f56923911a2af0fa1c1f751bc5bbb920d53316f9975 +size 3389 diff --git a/tasks/desaulniers2016/gurobi_solution_log/large_log_4.jsonl b/tasks/desaulniers2016/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f905cb84833582192690efa09b1c61c3380752b4 --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd586a7cb9024c7e1d213e820e5b5f2185fafaf2e7d50367e6e50b2dd8e1f5a7 +size 2605 diff --git a/tasks/desaulniers2016/gurobi_solution_log/large_log_5.jsonl b/tasks/desaulniers2016/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9a56b60f7bc361e2138434975d357fa67aea68bd --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1695a2a73587d5a6ab8b0b9f2c7e2397aac93a6ff2315daaa508dc7199f86eee +size 2147 diff --git a/tasks/desaulniers2016/gurobi_solution_log/tiny_log.jsonl b/tasks/desaulniers2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..06698ac49b103857f5181007e44b8b3e60ff762d --- /dev/null +++ b/tasks/desaulniers2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53fd21529d85d2687de3fbe298e8e312f611d167d9d73d419b658471a04f76f2 +size 86 diff --git a/tasks/desaulniers2016/instance/large_instance_1.json b/tasks/desaulniers2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..57da9a9e70946a6fb51cc7124341f85835ecde3c --- /dev/null +++ b/tasks/desaulniers2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f36c467ea1190a3ca12bb2127b59fc5fdefdefb52b6f9c6b5e1f26e3cc66ffe +size 31495 diff --git a/tasks/desaulniers2016/instance/large_instance_2.json b/tasks/desaulniers2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..0f2b9587ff12434c8bdc516239390214fccd4f8c --- /dev/null +++ b/tasks/desaulniers2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d84d79c3c317c39f4269521cc4b1485fd6fa2479982069d3e6869d38acd880c +size 28973 diff --git a/tasks/desaulniers2016/instance/large_instance_3.json b/tasks/desaulniers2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..20324a7019f98ac6dfa57f284b88995db8380674 --- /dev/null +++ b/tasks/desaulniers2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8507779f70427eeb5694b9b44a2ada0c2b9fc26789986964f1e4673006a463f7 +size 28953 diff --git a/tasks/desaulniers2016/instance/large_instance_4.json b/tasks/desaulniers2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..0cd305f52c03151a5dc16bdc53fbc90e1cb66ad5 --- /dev/null +++ b/tasks/desaulniers2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90056a2c820a2530b6cc47aaab113cd056ed088e52419c4d33f0e507d7176131 +size 28980 diff --git a/tasks/desaulniers2016/instance/large_instance_5.json b/tasks/desaulniers2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..beb67821b73756f79de157b929bcd4d832a61a8e --- /dev/null +++ b/tasks/desaulniers2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca2f752e5e2181cc6643c0ff42bbb0b0debaef3ec982e6e73c9a886b75f6a49e +size 28962 diff --git a/tasks/desaulniers2016/instance/tiny_instance.json b/tasks/desaulniers2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..4b4f3ca4476a03b9a1e0803e2453218e43ac477c --- /dev/null +++ b/tasks/desaulniers2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f95d3cb96f7a50e331a9e968367f47433d58fc9b26be85f57ca8f6d95d8f068d +size 1674 diff --git a/tasks/desaulniers2016/instance_schema.json b/tasks/desaulniers2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..da2291cd636a4d4ed18b9b30c7163242bfbcb7de --- /dev/null +++ b/tasks/desaulniers2016/instance_schema.json @@ -0,0 +1,14 @@ +{ + "num_customers": " Number of customers to be served by the supplier.", + "num_periods": " Number of discrete time periods in the planning horizon.", + "num_vehicles": " Number of identical vehicles available for deliveries each period.", + "vehicle_capacity": " Maximum total quantity that a single vehicle can carry on one route.", + "num_nodes": " Total number of locations, including the depot (index 0) and all customers.", + "coordinates": " X and Y coordinates of each location on a plane.", + "distance_matrix": " Symmetric travel cost between each pair of locations, computed as rounded Euclidean distance.", + "holding_costs": " Per-unit cost charged on inventory remaining at each location at the end of each period.", + "customer_demands": " Quantity of commodity consumed by each customer in each period.", + "supplier_production": " Quantity of commodity produced at the depot in each period.", + "inventory_capacities": " Maximum inventory that can be stored at each location, with index 0 for the depot and the rest for customers.", + "initial_inventories": " Inventory on hand at each location at the start of the planning horizon, with index 0 for the depot and the rest for customers." +} diff --git a/tasks/desaulniers2016/mathematical_formulation.md b/tasks/desaulniers2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..41ff5b725f8f628f558c509283fbb0167796ffbc --- /dev/null +++ b/tasks/desaulniers2016/mathematical_formulation.md @@ -0,0 +1,91 @@ +# Original Formulation: Inventory-Routing Problem (IRP) + +*Source: A Branch-Price-and-Cut Algorithm for the Inventory-Routing Problem, Guy Desaulniers, Jørgen G. Rakke, Leandro C. Coelho, 2016.* + +This is the innovative mixed-integer program (1)–(9) stated in §2 “Problem Definition and Mathematical Model.” It is a route / route-delivery-pattern (RDP) formulation under the maximum-level (ML) replenishment policy. The route set $R$ and the extreme-RDP sets $W_r^p$ have exponential cardinality (the paper solves it by branch-price-and-cut); per the formulation’s definition these index sets are kept as-is and are *not* replaced by an arc-flow reformulation. + +## Sets and Indices + +$$\begin{align*} +& 0 : \text{the single supplier (depot)} \\ +& N : \text{set of customers; each } i \in N \text{ consumes } d_i^p \text{ in period } p \\ +& P = \{1, 2, \ldots, \rho\} : \text{finite planning horizon; } \rho+1 \text{ is a fictitious period for end inventories} \\ +& R : \text{set of feasible routes (each starts and ends at the depot } 0\text{)} \\ +& N_r : \text{set of customers visited in route } r \in R \\ +& A_r : \text{set of pairs of locations } (i,j) \text{ visited consecutively along route } r \\ +& W_r^p : \text{set of extreme RDPs available when route } r \text{ is used in period } p \in P \\ +& P_{ip}^+ \subseteq \{p, p{+}1, \ldots, \rho{+}1\} : \text{set of periods to which a subdelivery of a delivery} \\ +&\qquad\quad \text{to customer } i \text{ in period } p \text{ can be dedicated (assumed nonempty)} \\ +& P_{is}^- = \{p \in P \mid s \in P_{ip}^+\} : \text{set of periods at which a subdelivery can be made to} \\ +&\qquad\quad \text{fulfill the demand of customer } i \text{ at period } s +\end{align*}$$ + +## Parameters + +$$\begin{align*} +& K : \text{number of vehicles (homogeneous fleet)} \\ +& Q : \text{vehicle capacity} \\ +& d_0^p : \text{quantity produced at the supplier in period } p \in P \\ +& d_i^p : \text{demand (consumption) of customer } i \in N \text{ in period } p \in P \\ +& C_i\ (C_0) : \text{inventory capacity of customer } i \in N \text{ (supplier } 0\text{)} \\ +& I_i^0 \le C_i\ (I_0^0 \le C_0) : \text{initial inventory of customer } i \in N \text{ (supplier } 0\text{)} \\ +& h_i\ (h_0) : \text{unit holding cost at customer } i \in N \text{ (supplier } 0\text{)} \\ +& c_{ij} : \text{traveling cost between locations } i \text{ and } j \\ +& a_{ri} \in \{0,1\} : \text{1 if route } r \text{ visits customer } i \in N, \text{ 0 otherwise} \\ +& I_i^{0,s} = \max\!\Big\{0,\ I_i^0 - \textstyle\sum_{\ell=1}^{s} d_i^\ell\Big\} : \text{initial inventory remaining at customer } i \text{ at end of period } s \\ +& q_{wi}^s \in [0,\ u_{ip}^s] : \text{quantity in extreme RDP } w \in W_r^p \text{ delivered to customer } i \in N_r \text{ and} \\ +&\qquad\quad \text{dedicated to period } s \in P_{ip}^+ \\ +& q_w = \textstyle\sum_{i \in N_r}\sum_{s \in P_{ip}^+} q_{wi}^s : \text{total quantity delivered in RDP } w \text{ (loaded at the supplier)} \\ +& b_{wi}^s : \text{quantity delivered to customer } i \text{ in RDP } w \text{ that remains in inventory at end of period } s \\ +& c_{rw} = \textstyle\sum_{(i,j) \in A_r} c_{ij} + \sum_{i \in N_r}\sum_{s \in P_{ip}^+} h_i\, b_{wi}^s : \text{cost associated with route } r \text{ and RDP } w +\end{align*}$$ + +Residual demands and subdelivery upper bounds: $$\begin{align*} +& \bar{d}_i^s = + \begin{cases} + \max\{0,\ d_i^1 - I_i^0\} & \text{if } s = 1 \\ + \max\{0,\ d_i^s - I_i^{0,s-1}\} & \text{otherwise} + \end{cases} + \qquad \forall\, s \in P, \\[4pt] +& u_{ip}^s = + \begin{cases} + \min\{\bar{d}_i^s,\ C_i - I_i^{0,s-1}\} & \text{if } s = p \\ + C_i - \sum_{\ell=p}^{s-1} d_i^\ell - I_i^{0,s-1} & \text{if } s = \rho+1 \\ + \min\{\bar{d}_i^s,\ C_i - \sum_{\ell=p}^{s-1} d_i^\ell - I_i^{0,s-1}\} & \text{otherwise.} + \end{cases} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +& y_{rw}^p \in [0,1] : \text{proportion of route } r \in R \text{ operated with RDP } w \in W_r^p \text{ in period } p \in P \\ +& I_0^p \ge 0 : \text{inventory at the supplier at the end of period } p \in P +\end{align*}$$ + +## Objective + +$$\begin{equation} +\min\ \left\{ \sum_{p \in P} \sum_{r \in R} \sum_{w \in W_r^p} c_{rw}\, y_{rw}^p + + \sum_{p \in P} h_0\, I_0^p \right\} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +& I_0^{p-1} + d_0^p - \sum_{r \in R} \sum_{w \in W_r^p} q_w\, y_{rw}^p = I_0^p, + && \forall\, p \in P, \tag{2} \\[4pt] +& \sum_{p \in P_{is}^-} \sum_{r \in R} \sum_{w \in W_r^p} q_{wi}^s\, y_{rw}^p = \bar{d}_i^s, + && \forall\, i \in N,\ s \in P \text{ s.t. } \bar{d}_i^s > 0, \tag{3} \\[4pt] +& I_i^{0,s} + \sum_{p \in P_{is}^-} \sum_{r \in R} \sum_{w \in W_r^p} b_{wi}^s\, y_{rw}^p + d_i^s \le C_i, + && \forall\, i \in N,\ s \in P, \tag{4} \\[4pt] +& \sum_{r \in R} \sum_{w \in W_r^p} a_{ri}\, y_{rw}^p \le 1, + && \forall\, i \in N,\ p \in P, \tag{5} \\[4pt] +& \sum_{r \in R} \sum_{w \in W_r^p} y_{rw}^p \le K, + && \forall\, p \in P, \tag{6} \\[4pt] +& 0 \le I_0^p \le C_0, + && \forall\, p \in P, \tag{7} \\[4pt] +& y_{rw}^p \ge 0, + && \forall\, p \in P,\ r \in R,\ w \in W_r^p, \tag{8} \\[4pt] +& \sum_{w \in W_r^p} y_{rw}^p \in \{0,1\}, + && \forall\, p \in P,\ r \in R. \tag{9} +\end{align}$$ diff --git a/tasks/desaulniers2016/problem_description.txt b/tasks/desaulniers2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..6fb70edd6ae28a56aa399234029ce2582436dc80 --- /dev/null +++ b/tasks/desaulniers2016/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A single supplier operates a depot that produces a known quantity of a single commodity in each period of a finite planning horizon. The supplier must distribute this commodity to a set of customers using a homogeneous fleet of vehicles, each with a common capacity. The planning horizon consists of a fixed number of discrete periods, and the set of locations comprises the depot (indexed zero) and all customers. The input data specifies, for every pair of locations, a symmetric travel cost derived from the rounded Euclidean distance between their coordinates. Each customer has a known demand (consumption) in each period, an inventory capacity, an initial inventory level that does not exceed that capacity, and a per-unit holding cost charged on inventory remaining at the end of each period. The depot likewise has an inventory capacity, an initial inventory that does not exceed that capacity, and a per-unit holding cost. + +The supplier must decide, for each period, which subset of customers to visit, how much to deliver to each visited customer, and how to combine those visits into vehicle routes that start and end at the depot. Within each period, the supplier first adds its production to depot inventory, then dispatches vehicles to make deliveries, and customers receive their deliveries at the start of the period so that the delivered goods are available to satisfy that period's demand. No customer may experience a stockout in any period, meaning that the inventory at every customer at the end of every period must remain nonnegative. Similarly, the depot inventory at the end of every period must be nonnegative and must not exceed the depot's inventory capacity. + +The inventory at each customer at the end of a period equals its inventory at the end of the previous period plus the total quantity delivered to it in the current period minus its demand in the current period. The same balance applies at the depot, where inventory equals the previous period's ending inventory plus the current period's production minus the total quantity shipped out across all vehicles in the current period. The quantity delivered to a customer in any period may be any nonnegative amount, subject to the restriction that the customer's inventory immediately after receiving the delivery (that is, the previous ending inventory plus the delivery quantity) must not exceed the customer's inventory capacity. Each customer may be visited by at most one vehicle in any given period. The total quantity loaded onto any single vehicle in a given period, summed across all customers it visits on its route, must not exceed the vehicle capacity. In each period, the number of routes operated must not exceed the number of available vehicles. Every route must form a simple tour beginning and ending at the depot, visiting each customer on the route exactly once, and no subtours among customers are permitted. + +The goal is to minimize the total cost, defined as the sum of two components: the total travel cost, obtained by summing the travel costs of all arcs traversed by all vehicles across all periods, and the total holding cost, obtained by summing the per-unit holding cost times the ending inventory at every location (depot and all customers) in every period. diff --git a/tasks/desaulniers2016/solution_logger.py b/tasks/desaulniers2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/desaulniers2016/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/desaulniers2016/solution_schema.json b/tasks/desaulniers2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..45e2f10ae1663db0b6be0d4166b2d71c2c10b507 --- /dev/null +++ b/tasks/desaulniers2016/solution_schema.json @@ -0,0 +1,14 @@ +{ + "objective_value": " Total cost of the distribution plan, equal to the sum of all vehicle travel costs and end-of-period holding costs at the depot and all customers across the planning horizon.", + "routes": { + "{period}": { + "{vehicle}": { + "route": " Ordered sequence of location indices traversed by this vehicle in this period, starting and ending at the depot (index 0).", + "deliveries": " Quantity of the commodity delivered by this vehicle to each customer it visits in this period." + } + } + }, + "inventories": { + "{location}": " Inventory on hand at this location (depot or customer) at the end of each period." + } +} diff --git a/tasks/dienstknecht2024/feasibility_check.py b/tasks/dienstknecht2024/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..af67b13ae37b0bf431403fd7a52ec7a94e04d577 --- /dev/null +++ b/tasks/dienstknecht2024/feasibility_check.py @@ -0,0 +1,594 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Trade-Container Assignment Problem in Construction +Projects (TCAPCP) — period-based formulation (TCAPCP_Per). + +Source: Dienstknecht & Briskorn (2024), EJOR 315(1), 324-337. + +Checks all hard constraints from the mathematical model that can be evaluated +from the assignment (x) variables provided in the solution. Constraints +involving only internal auxiliary variables (y, z, f) that are not part of the +solution output are checked where they impose requirements on x, specifically +the dispersion limit which constrains the number of connected components +(clusters) of assigned containers. + +Constraint numbering follows the paper's TCAPCP_Per formulation, counted +top-to-bottom: + Constraint 1 = Eq (2): Demand satisfaction + Constraint 2 = Eq (3): Container capacity + Constraint 3 = Eq (4): z <= x (source linking) — auxiliary, skip + Constraint 4 = Eq (5): y <= x first endpoint — auxiliary, skip + Constraint 5 = Eq (6): y <= x second endpoint — auxiliary, skip + Constraint 6 = Eq (7): Flow conservation — auxiliary, skip + Constraint 7 = Eq (8): Flow capacity forward — auxiliary, skip + Constraint 8 = Eq (9): Flow capacity reverse — auxiliary, skip + Constraint 9 = Eq (10): Dispersion limit (max clusters) + Constraint 10 = Eq (11): Re-assignment detection (existing container) + Constraint 11 = Eq (12): Re-assignment detection (new container) + Constraint 12 = Eq (13): Non-negativity of flows — auxiliary, skip + Constraint 13 = Eq (19): Domain of r (0 <= r <= 1) + Constraint 14 = Eq (15): Domain of x (binary, container available) + Constraint 15 = Eq (16): Domain of y — auxiliary, skip + Constraint 16 = Eq (17): Domain of z — auxiliary, skip + Constraint 17 = Eq (18): Symmetry breaking — auxiliary, skip + Constraint 18 = Eq (1): Objective consistency (Tier C anti-gaming check) + +Constraints 10, 11, 13 all constrain the r variable. Since r is derived from x +and constrained to [0,1], and because in any feasible solution the minimization +objective pushes r to its lower bound, we check that the implied r values are +within [0,1] (Constraint 13) and that the linking constraints (10, 11) hold, +i.e., r >= x_c^{j,p} - x_c^{j,p-1} for existing containers and r >= x_c^{j,p} +for newly available containers. Since r is free in [0,1] and these are only +lower bounds (the solution can always set r=1), the binding feasibility check +is whether these constraints are satisfiable, which they always are for binary x +as long as r is allowed in [0,1]. We still verify them for completeness by +computing the implied minimum r and checking it does not exceed 1. + +Constraint 18 (objective consistency) is a Tier C defense added on top of the +original checker. The eval pipeline trusts the solution's self-reported +``objective_value``; LLM-evolved candidates have learned to fabricate it. The +objective Z = sum_{j} sum_{p=s_j+1}^{f_j} r^{j,p} counts trade re-assignments. +The r^{j,p} variables are NOT part of the solution output, but they are purely +auxiliary and fully determined by the x assignments: constraints (11)-(12) +impose lower bounds on each r^{j,p}, the [0,1] domain (19) leaves r free above +those bounds, and the minimization (1) therefore drives every r^{j,p} to +exactly its implied lower bound r_lower(j,p). Hence the objective of any x +assignment is exactly sum_{j,p} r_lower(j,p) — a full, exact recomputation, +not a loose bound. We reject solutions whose reported objective_value disagrees +with that recomputation. This is an append-only addition: it can only ADD +constraint 18 to the set of violations; it never alters constraints 1-17. +""" + +import json +import argparse +from collections import deque + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, 'r') as fh: + return json.load(fh) + + +def build_container_lookup(instance): + """Build lookup structures for containers.""" + containers = {} + for c in instance['containers']: + containers[c['id']] = c + return containers + + +def build_trade_lookup(instance): + """Build lookup structures for trades.""" + trades = {} + for t in instance['trades']: + trades[t['id']] = t + return trades + + +def get_available_containers(containers, p): + """Return set of container IDs available in period p (C^p).""" + return { + cid for cid, c in containers.items() + if c['availability_start'] <= p <= c['availability_end'] + } + + +def get_active_trades(trades, p): + """Return set of trade IDs active in period p (J^p).""" + return { + tid for tid, t in trades.items() + if t['start_period'] <= p <= t['end_period'] + } + + +def count_clusters(assigned_containers, containers): + """ + Count the number of connected components (clusters) among the assigned + containers using the adjacency graph. + + Returns the number of clusters. + """ + if not assigned_containers: + return 0 + + assigned_set = set(assigned_containers) + visited = set() + num_clusters = 0 + + for start in assigned_set: + if start in visited: + continue + num_clusters += 1 + queue = deque([start]) + visited.add(start) + while queue: + node = queue.popleft() + for neighbor in containers[node]['adjacent_containers']: + if neighbor in assigned_set and neighbor not in visited: + visited.add(neighbor) + queue.append(neighbor) + + return num_clusters + + +def make_violation(constraint_idx, lhs, rhs, raw_excess): + """Create a violation magnitude entry.""" + normalizer = max(abs(rhs), EPS) + return { + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(raw_excess), + "normalizer": float(normalizer), + "ratio": float(raw_excess / normalizer), + } + + +def check_feasibility(instance, solution): + """ + Check all hard constraints and return feasibility result. + """ + P = instance['problem_parameters']['num_periods'] + containers = build_container_lookup(instance) + trades = build_trade_lookup(instance) + + assignments = solution['assignments'] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # Helper: get assigned containers for trade j in period p + def get_assigned(j, p): + j_str = str(j) + p_str = str(p) + if j_str not in assignments: + return [] + if p_str not in assignments[j_str]: + return [] + return assignments[j_str][p_str] + + # ========================================================================= + # Constraint 1 — Eq (2): Demand satisfaction (equality) + # sum_{c in C^p} x_c^{j,p} = n_j for all p=1..P, j in J^p + # ========================================================================= + for p in range(1, P + 1): + active_trades = get_active_trades(trades, p) + avail_containers = get_available_containers(containers, p) + for j in active_trades: + assigned = get_assigned(j, p) + n_j = trades[j]['container_demand'] + lhs = len(assigned) + rhs = n_j + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (Demand): Trade {j} in period {p} " + f"has {lhs} containers assigned, needs {rhs}" + ) + violation_magnitudes.append(make_violation(1, lhs, rhs, violation_amount)) + + # ========================================================================= + # Constraint 2 — Eq (3): Container capacity (<=) + # sum_{j in J^p} x_c^{j,p} <= 1 for all p=1..P, c in C^p + # ========================================================================= + for p in range(1, P + 1): + active_trades = get_active_trades(trades, p) + avail_containers = get_available_containers(containers, p) + # Count how many trades each container is assigned to in this period + container_usage = {} + for j in active_trades: + assigned = get_assigned(j, p) + for c in assigned: + container_usage[c] = container_usage.get(c, 0) + 1 + for c in avail_containers: + usage = container_usage.get(c, 0) + lhs = usage + rhs = 1 + violation_amount = max(0, lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(2) + trades_using = [ + j for j in active_trades if c in get_assigned(j, p) + ] + violations.append( + f"Constraint 2 (Capacity): Container {c} in period {p} " + f"assigned to {usage} trades: {trades_using}" + ) + violation_magnitudes.append(make_violation(2, lhs, rhs, violation_amount)) + + # ========================================================================= + # Constraint 9 — Eq (10): Dispersion limit (<=) + # Number of clusters of trade j in period p <= d_j^max + # sum_{c in C^p} z_c^{j,p} <= d_j^max + # The z variables identify cluster sources; the number of sources equals + # the number of connected components in the subgraph of assigned containers. + # ========================================================================= + for p in range(1, P + 1): + active_trades = get_active_trades(trades, p) + for j in active_trades: + assigned = get_assigned(j, p) + if not assigned: + continue + num_clusters = count_clusters(assigned, containers) + d_max = trades[j]['max_dispersion'] + lhs = num_clusters + rhs = d_max + violation_amount = max(0, lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(9) + violations.append( + f"Constraint 9 (Dispersion): Trade {j} in period {p} " + f"has {num_clusters} clusters, max allowed is {d_max}" + ) + violation_magnitudes.append(make_violation(9, lhs, rhs, violation_amount)) + + # ========================================================================= + # Constraint 10 — Eq (11): Re-assignment detection (existing container) (<=) + # x_c^{j,p} - x_c^{j,p-1} <= r^{j,p} + # for p=2..P, j in J^p with s_j < p, c in C^p ∩ C^{p-1} + # + # Constraint 11 — Eq (12): Re-assignment detection (new container) (<=) + # x_c^{j,p} <= r^{j,p} + # for p=2..P, j in J^p with s_j < p, c in C^p \ C^{p-1} + # + # Constraint 13 — Eq (19): Domain of r: 0 <= r^{j,p} <= 1 + # + # These three constraints together require that the implied minimum value + # of r^{j,p} (the maximum of all lower bounds from constraints 10 and 11) + # must not exceed 1. Since x is binary and r can be at most 1, the only + # way this fails is if the constraints are somehow contradictory, which + # cannot happen for binary x with r in [0,1]. We verify anyway. + # + # The implied minimum r^{j,p} is also exactly the contribution of (j,p) to + # the objective Z = sum r^{j,p} (the minimization drives r down to it), so + # we accumulate it into `recomputed_objective` for the Constraint 18 check. + # The (j,p) pairs visited here — p in [2,P], j active with s_j < p — are + # exactly the index set p in [s_j+1, f_j] summed over in objective (1). + # ========================================================================= + recomputed_objective = 0.0 + for p in range(2, P + 1): + active_trades_p = get_active_trades(trades, p) + avail_p = get_available_containers(containers, p) + avail_pm1 = get_available_containers(containers, p - 1) + + for j in active_trades_p: + s_j = trades[j]['start_period'] + if s_j >= p: + continue # trade starts at p, not a re-assignment period + + assigned_p = set(get_assigned(j, p)) + assigned_pm1 = set(get_assigned(j, p - 1)) + + # Compute implied minimum r from constraint 10 + r_lower = 0.0 + for c in avail_p & avail_pm1: + x_cur = 1 if c in assigned_p else 0 + x_prev = 1 if c in assigned_pm1 else 0 + diff = x_cur - x_prev + if diff > r_lower: + r_lower = diff + + # Compute implied minimum r from constraint 11 + for c in avail_p - avail_pm1: + x_cur = 1 if c in assigned_p else 0 + if x_cur > r_lower: + r_lower = x_cur + + # Accumulate the objective contribution of r^{j,p} (its minimum + # value equals r_lower; the minimization objective realizes it). + recomputed_objective += r_lower + + # Check constraint 13: r must be <= 1 + lhs = r_lower + rhs = 1.0 + violation_amount = max(0, lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(13) + violations.append( + f"Constraint 13 (r domain): Trade {j} in period {p} " + f"requires r = {r_lower}, exceeds upper bound 1" + ) + violation_magnitudes.append(make_violation(13, lhs, rhs, violation_amount)) + + # ========================================================================= + # Constraint 14 — Eq (15): Domain of x (binary, container availability) + # x_c^{j,p} in {0,1} for all p=1..P, j in J^p, c in C^p + # This also implicitly requires that assigned containers are in C^p. + # ========================================================================= + for p in range(1, P + 1): + active_trades = get_active_trades(trades, p) + avail_containers = get_available_containers(containers, p) + for j in active_trades: + assigned = get_assigned(j, p) + for c in assigned: + if c not in avail_containers: + violated_constraints.add(14) + violations.append( + f"Constraint 14 (x domain): Trade {j} in period {p} " + f"assigned to container {c} which is not available " + f"(available: periods {containers[c]['availability_start']}" + f"-{containers[c]['availability_end']})" + ) + # LHS = 1 (assigned), RHS = 0 (not in domain) + violation_magnitudes.append(make_violation(14, 1, 0, 1.0)) + + # Also check that trades have assignments for all their active periods + for tid, t in trades.items(): + t_str = str(tid) + for p in range(t['start_period'], t['end_period'] + 1): + p_str = str(p) + if t_str not in assignments or p_str not in assignments[t_str]: + # Missing assignment for an active period — demand violation + n_j = t['container_demand'] + if n_j > 0: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (Demand): Trade {tid} has no assignment " + f"for active period {p}, needs {n_j} containers" + ) + violation_magnitudes.append(make_violation(1, 0, n_j, n_j)) + + # ========================================================================= + # Constraint 18 — Eq (1): Objective consistency (Tier C anti-gaming check) + # Z = sum_{j} sum_{p=s_j+1}^{f_j} r^{j,p} + # + # `recomputed_objective` accumulated above is exactly sum_{j,p} r_lower(j,p), + # the true objective implied by the x assignments (the r variables are + # auxiliary, not in the solution, and the minimization drives each to its + # lower bound). We reject any solution whose self-reported objective_value + # disagrees with this exact recomputation. The objective is an integer + # count of re-assignments, so a 0.5 absolute tolerance fires on any + # mismatch of >= 1 (with a tiny relative floor for very large counts). + # This is append-only: it can add constraint 18 but never touches 1-17. + # ========================================================================= + 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(recomputed_objective) + abs_diff = abs(reported - true_obj) + tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(18) + violations.append( + f"Constraint 18 (Objective consistency): reported " + f"objective_value={reported} differs from recomputed total " + f"re-assignments sum_{{j,p}} r_lower(j,p)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + violation_magnitudes.append( + make_violation(18, reported, true_obj, abs_diff) + ) + + # ========================================================================= + # 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 TCAPCP (Dienstknecht & Briskorn 2024)" + ) + parser.add_argument( + '--instance_path', type=str, required=True, + help='Path to the JSON file containing the data instance' + ) + parser.add_argument( + '--solution_path', type=str, required=True, + help='Path to the JSON file containing the candidate solution' + ) + parser.add_argument( + '--result_path', type=str, required=True, + help='Path to write the JSON file containing the feasibility result' + ) + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as fh: + json.dump(result, fh, indent=2) + + if result['feasible']: + print(f"FEASIBLE — no constraint violations detected.") + else: + print(f"INFEASIBLE — {len(result['violated_constraints'])} constraint(s) violated: " + f"{result['violated_constraints']}") + for v in result['violations']: + print(f" - {v}") + + +if __name__ == '__main__': + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/dienstknecht2024/gurobi_code.py b/tasks/dienstknecht2024/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..9b92b1fa8da16c37f183124872c8935132e3bc90 --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_code.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python3 +""" +TCAPCP_Win MIP formulation solved with Gurobi. + +Implements the time-window-based MIP (MIP TCAPCP_Win) for the Trade-Container +Assignment Problem in Construction Projects (TCAPCP) from: + Dienstknecht & Briskorn (2024), EJOR 315(1), 324-337. + +The TCAPCP_Win formulation exploits Property 1: re-assignments only occur in +critical periods P'. This reduces the number of binary variables compared to +the period-based formulation (TCAPCP_Per). + +The paper shows TCAPCP_Win is superior to TCAPCP_Per and recommends it +(Section 6.2: "We will, therefore, abandon MIP TCAPCP_Per in favor of MIP +TCAPCP_Win subsequently."). +""" + +import json +import argparse +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(path): + """Load a TCAPCP instance from a JSON file.""" + with open(path, 'r') as f: + data = json.load(f) + return data + + +def compute_time_windows(P, containers, trades): + """ + Compute the set P' of critical periods and derive time windows W. + + P' := {p | p = 2, ..., P : exists j in J such that s_j = p + OR exists c in C such that f_c + 1 = p} + + Time windows partition the horizon into non-overlapping intervals. + Each window w_i = [s_{w_i}, f_{w_i}) covers periods s_{w_i} to f_{w_i}-1. + """ + P_prime = set() + for t in trades: + s_j = t['start_period'] + if 2 <= s_j <= P: + P_prime.add(s_j) + for c in containers: + f_c = c['availability_end'] + p = f_c + 1 + if 2 <= p <= P: + P_prime.add(p) + + # Critical start periods always include period 1 + critical_starts = sorted({1} | P_prime) + + # Derive time windows: w_i = [critical_starts[i], critical_starts[i+1]) + # Last window ends at P+1 + windows = [] + for k in range(len(critical_starts)): + s_w = critical_starts[k] + if k + 1 < len(critical_starts): + f_w = critical_starts[k + 1] + else: + f_w = P + 1 + windows.append((s_w, f_w)) + + return windows + + +def precompute_window_data(windows, containers, trades): + """ + Precompute sets C^{w_i}, J^{w_i}, and adjacency pairs for each window. + """ + m = len(windows) + + # Build adjacency and neighbor lookup + neighbors = {} + for c in containers: + neighbors[c['id']] = set(c['adjacent_containers']) + + # Ordered adjacency pairs (c1, c2) with c1 < c2 + adj_pairs = set() + for c in containers: + for c2_id in c['adjacent_containers']: + if c['id'] < c2_id: + adj_pairs.add((c['id'], c2_id)) + + trade_by_id = {t['id']: t for t in trades} + + C_w = [] # C_w[i] = set of container IDs available in window i + J_w = [] # J_w[i] = set of trade IDs active in window i + adj_pairs_w = [] # adj_pairs_w[i] = adjacency pairs within window i + + for i, (s_w, f_w) in enumerate(windows): + # C^{w_i} = {c in C : s_c <= s_w AND f_c >= f_w - 1} + c_set = set() + for c in containers: + if c['availability_start'] <= s_w and c['availability_end'] >= f_w - 1: + c_set.add(c['id']) + C_w.append(c_set) + + # J^{w_i} = {j in J : s_j <= s_w <= f_j} + j_set = set() + for t in trades: + if t['start_period'] <= s_w and s_w <= t['end_period']: + j_set.add(t['id']) + J_w.append(j_set) + + # Adjacency pairs restricted to this window + pairs = set() + for (c1, c2) in adj_pairs: + if c1 in c_set and c2 in c_set: + pairs.add((c1, c2)) + adj_pairs_w.append(pairs) + + return C_w, J_w, adj_pairs_w, neighbors, trade_by_id + + +def solve_tcapcp_win(instance_data, time_limit): + """ + Build and solve the full MIP TCAPCP_Win formulation using Gurobi. + """ + P = instance_data['problem_parameters']['num_periods'] + containers = instance_data['containers'] + trades = instance_data['trades'] + + # Compute time windows + windows = compute_time_windows(P, containers, trades) + m = len(windows) + + # Precompute window data + C_w, J_w, adj_pairs_w, neighbors, trade_by_id = precompute_window_data( + windows, containers, trades + ) + + # Build Gurobi model + model = gp.Model("TCAPCP_Win") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ========================================================================= + # Decision variables + # ========================================================================= + + # x[c, j, i]: binary - 1 if trade j assigned to container c in window i + x = {} + for i in range(m): + for j in J_w[i]: + for c in C_w[i]: + x[c, j, i] = model.addVar(vtype=GRB.BINARY, name=f"x_{c}_{j}_{i}") + + # y[(c1,c2), j, i]: binary - 1 if c1 and c2 in same cluster, c1 < c2 + y = {} + for i in range(m): + for j in J_w[i]: + for (c1, c2) in adj_pairs_w[i]: + y[c1, c2, j, i] = model.addVar( + vtype=GRB.BINARY, name=f"y_{c1}_{c2}_{j}_{i}" + ) + + # z[c, j, i]: binary - 1 if c is source of flow for trade j in window i + z = {} + for i in range(m): + for j in J_w[i]: + for c in C_w[i]: + z[c, j, i] = model.addVar(vtype=GRB.BINARY, name=f"z_{c}_{j}_{i}") + + # f[c1, c2, j, i]: continuous >= 0 - flow on directed arc (c1,c2) + # Created for both directions of each adjacency pair + f = {} + for i in range(m): + for j in J_w[i]: + for (c1, c2) in adj_pairs_w[i]: + f[c1, c2, j, i] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, name=f"f_{c1}_{c2}_{j}_{i}" + ) + f[c2, c1, j, i] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, name=f"f_{c2}_{c1}_{j}_{i}" + ) + + # r[j, i]: continuous [0,1] - 1 if trade j re-assigned in window i + # Relaxed from binary per eq. (34) / paper's eq. (19) + r = {} + for i in range(1, m): + s_w_i = windows[i][0] + for j in J_w[i]: + s_j = trade_by_id[j]['start_period'] + if s_j < s_w_i: + r[j, i] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0, ub=1, name=f"r_{j}_{i}" + ) + + model.update() + + # ========================================================================= + # Objective function (20): minimize total re-assignments + # ========================================================================= + model.setObjective( + gp.quicksum(r[j, i] for (j, i) in r), GRB.MINIMIZE + ) + + # ========================================================================= + # Constraints + # ========================================================================= + + # (21) Demand satisfaction + for i in range(m): + for j in J_w[i]: + n_j = trade_by_id[j]['container_demand'] + model.addConstr( + gp.quicksum(x[c, j, i] for c in C_w[i]) == n_j, + name=f"demand_{j}_{i}" + ) + + # (22) Container capacity - at most one trade per container per window + for i in range(m): + for c in C_w[i]: + active_trades = [j for j in J_w[i]] + if active_trades: + model.addConstr( + gp.quicksum(x[c, j, i] for j in active_trades) <= 1, + name=f"capacity_{c}_{i}" + ) + + # (23) Cluster source linking: z <= x + for i in range(m): + for j in J_w[i]: + for c in C_w[i]: + model.addConstr( + z[c, j, i] <= x[c, j, i], + name=f"source_{c}_{j}_{i}" + ) + + # (24) y <= x (first endpoint) + for i in range(m): + for j in J_w[i]: + for (c1, c2) in adj_pairs_w[i]: + model.addConstr( + y[c1, c2, j, i] <= x[c1, j, i], + name=f"y_x1_{c1}_{c2}_{j}_{i}" + ) + + # (25) y <= x (second endpoint) + for i in range(m): + for j in J_w[i]: + for (c1, c2) in adj_pairs_w[i]: + model.addConstr( + y[c1, c2, j, i] <= x[c2, j, i], + name=f"y_x2_{c1}_{c2}_{j}_{i}" + ) + + # (26) Symmetry breaking: 1 - y >= z_{c'} (for c < c') + # Forces the container with larger index not to be source when adjacent + # to a same-cluster container with smaller index + for i in range(m): + for j in J_w[i]: + for (c1, c2) in adj_pairs_w[i]: + model.addConstr( + 1 - y[c1, c2, j, i] >= z[c2, j, i], + name=f"symbreak_{c1}_{c2}_{j}_{i}" + ) + + # (27) Flow conservation / cluster identification + for i in range(m): + for j in J_w[i]: + n_j = trade_by_id[j]['container_demand'] + for c in C_w[i]: + # Incoming flow to c from adjacent containers in this window + in_flow = gp.quicksum( + f[c2, c, j, i] + for c2 in neighbors[c] + if c2 in C_w[i] + and (min(c, c2), max(c, c2)) in adj_pairs_w[i] + ) + # Outgoing flow from c to adjacent containers in this window + out_flow = gp.quicksum( + f[c, c2, j, i] + for c2 in neighbors[c] + if c2 in C_w[i] + and (min(c, c2), max(c, c2)) in adj_pairs_w[i] + ) + model.addConstr( + z[c, j, i] * n_j + in_flow - out_flow >= x[c, j, i], + name=f"flowcons_{c}_{j}_{i}" + ) + + # (28) Flow capacity (both directions bounded by y * n_j) + for i in range(m): + for j in J_w[i]: + n_j = trade_by_id[j]['container_demand'] + for (c1, c2) in adj_pairs_w[i]: + # Forward direction + model.addConstr( + f[c1, c2, j, i] <= y[c1, c2, j, i] * n_j, + name=f"fcap_fwd_{c1}_{c2}_{j}_{i}" + ) + # Reverse direction + model.addConstr( + f[c2, c1, j, i] <= y[c1, c2, j, i] * n_j, + name=f"fcap_rev_{c2}_{c1}_{j}_{i}" + ) + + # (29) Dispersion limit + for i in range(m): + for j in J_w[i]: + d_max_j = trade_by_id[j]['max_dispersion'] + model.addConstr( + gp.quicksum(z[c, j, i] for c in C_w[i]) <= d_max_j, + name=f"dispersion_{j}_{i}" + ) + + # (31) Re-assignment detection: container available in both windows + for i in range(1, m): + s_w_i = windows[i][0] + for j in J_w[i]: + s_j = trade_by_id[j]['start_period'] + if s_j < s_w_i: + for c in C_w[i]: + if c in C_w[i - 1]: + # j must also be in J_w[i-1] (proven by construction) + model.addConstr( + x[c, j, i] - x[c, j, i - 1] <= r[j, i], + name=f"reassign_same_{c}_{j}_{i}" + ) + + # (32) Re-assignment detection: container newly available in window i + for i in range(1, m): + s_w_i = windows[i][0] + for j in J_w[i]: + s_j = trade_by_id[j]['start_period'] + if s_j < s_w_i: + for c in C_w[i]: + if c not in C_w[i - 1]: + model.addConstr( + x[c, j, i] <= r[j, i], + name=f"reassign_new_{c}_{j}_{i}" + ) + + # ========================================================================= + # Solve + # ========================================================================= + model.optimize() + + # ========================================================================= + # Extract solution + # ========================================================================= + solution = {"objective_value": None} + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + + # Extract assignments: for each trade, for each period, the containers + assignments = {} + for t in trades: + j = t['id'] + trade_assignments = {} + for i in range(m): + if j in J_w[i]: + s_w, f_w = windows[i] + assigned_containers = [] + for c in sorted(C_w[i]): + if (c, j, i) in x and x[c, j, i].X > 0.5: + assigned_containers.append(c) + # Apply assignment to all periods in this window + for p in range(s_w, min(f_w, P + 1)): + trade_assignments[str(p)] = assigned_containers + assignments[str(j)] = trade_assignments + + solution["assignments"] = assignments + solution["status"] = ( + "optimal" if model.Status == GRB.OPTIMAL else "feasible" + ) + try: + solution["mip_gap"] = model.MIPGap + except Exception: + solution["mip_gap"] = None + else: + solution["objective_value"] = None + solution["status"] = "infeasible" + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Solve TCAPCP using MIP TCAPCP_Win formulation with Gurobi" + ) + parser.add_argument( + '--instance_path', type=str, required=True, + help='Path to the JSON file containing the problem instance' + ) + parser.add_argument( + '--solution_path', type=str, 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) + + instance_data = load_instance(args.instance_path) + solution = solve_tcapcp_win(instance_data, args.time_limit) + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']}") + print(f"Status: {solution['status']}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == '__main__': + main() diff --git a/tasks/dienstknecht2024/gurobi_feasi_result/large_feasi_result_1.json b/tasks/dienstknecht2024/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dienstknecht2024/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/dienstknecht2024/gurobi_feasi_result/large_feasi_result_2.json b/tasks/dienstknecht2024/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dienstknecht2024/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/dienstknecht2024/gurobi_feasi_result/large_feasi_result_3.json b/tasks/dienstknecht2024/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dienstknecht2024/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/dienstknecht2024/gurobi_feasi_result/large_feasi_result_4.json b/tasks/dienstknecht2024/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dienstknecht2024/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/dienstknecht2024/gurobi_feasi_result/large_feasi_result_5.json b/tasks/dienstknecht2024/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dienstknecht2024/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/dienstknecht2024/gurobi_feasi_result/tiny_feasi_result.json b/tasks/dienstknecht2024/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/dienstknecht2024/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/dienstknecht2024/gurobi_solution/large_solution_1.json b/tasks/dienstknecht2024/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0a7ccb576df0545b3e86b447f7c34a113ac7b721 --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e91d4a3a9e70c04147d1f6a60be72e0c8b3ecf64912e7e4e5b0b85b52d3981b +size 6739 diff --git a/tasks/dienstknecht2024/gurobi_solution/large_solution_2.json b/tasks/dienstknecht2024/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..208b058f517f47ff68b0defb2bd0054f0e6f7a2c --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8855ebd0012194807976121d633e4aec228324f6f47d6bd92653ed2e1ea5f8b8 +size 5920 diff --git a/tasks/dienstknecht2024/gurobi_solution/large_solution_3.json b/tasks/dienstknecht2024/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..57a593cdf56b33e726dd99993baefb9599421f7f --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e16cfb0666bc8196e54a5907be7f3b455cbfab86271194cf61a1d92702286a37 +size 6156 diff --git a/tasks/dienstknecht2024/gurobi_solution/large_solution_4.json b/tasks/dienstknecht2024/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..6ecdc001554e5fb712b1c8f4d8f10373e767aef8 --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:603531f3ffa8fc6b1d4b58ab465f291fa33b2eb3481a7380af12a42f1827ea22 +size 6400 diff --git a/tasks/dienstknecht2024/gurobi_solution/large_solution_5.json b/tasks/dienstknecht2024/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e4539b5cd2a16a1706fce5b9148317c1b7c5bdca --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7dca430435d197e0ac6c1954a2abd03644c7ff247762faa6fc4ace1766d481b +size 6703 diff --git a/tasks/dienstknecht2024/gurobi_solution/tiny_solution.json b/tasks/dienstknecht2024/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..40e82570c0f2e6a8c469084943ac5e0dcb46fd7f --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5adc38f829bad632fb886acd3fb550901fe30cc9fdb8eac679e6d826d086ca2 +size 1776 diff --git a/tasks/dienstknecht2024/gurobi_solution_log/large_log_1.jsonl b/tasks/dienstknecht2024/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0c97bb32e4f1c8028856e087097ee066852ac4af --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e216db8162cad733dcffc9bff1b3917b975c1911c1c4a2cdfcbdb69d4c1622a1 +size 40 diff --git a/tasks/dienstknecht2024/gurobi_solution_log/large_log_2.jsonl b/tasks/dienstknecht2024/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c36e0f1f3f3ab6c250ab98a08a643b10eb0cb496 --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:991bf222c23a46de7e223c4028e31f867d3c525b7a8ebbbec07bfb5333392c91 +size 809 diff --git a/tasks/dienstknecht2024/gurobi_solution_log/large_log_3.jsonl b/tasks/dienstknecht2024/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/dienstknecht2024/gurobi_solution_log/large_log_4.jsonl b/tasks/dienstknecht2024/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84ba3fcd859325cdcc72cc120b1dc610f79ece6d --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f3e547fcec4e6d509300c771f4212173c8e74fa1fdcebce7200874df78a07ef +size 43 diff --git a/tasks/dienstknecht2024/gurobi_solution_log/large_log_5.jsonl b/tasks/dienstknecht2024/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7a72edb8f356be673114dc1d4f6956a21012ac5f --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0365b507b7e663e9cb76a18f65c1a5f5b20a1a4f029d9f2801054fa2515b4c65 +size 81 diff --git a/tasks/dienstknecht2024/gurobi_solution_log/tiny_log.jsonl b/tasks/dienstknecht2024/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9f5de054d5d77ba3f8460e9a8b656421e1f3ab3 --- /dev/null +++ b/tasks/dienstknecht2024/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26f5c0177798d89b128eb8b6f2eaa30af88724c768a750ba52cac7a7a085ca75 +size 80 diff --git a/tasks/dienstknecht2024/instance/large_instance_1.json b/tasks/dienstknecht2024/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..84fd4ff30d958051f75d21ac94bea7320f20322f --- /dev/null +++ b/tasks/dienstknecht2024/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b70c01af784a1e3fc91f3d00e9e2446c55e14bebfc4564a80e6370f3213fd30 +size 13893 diff --git a/tasks/dienstknecht2024/instance/large_instance_2.json b/tasks/dienstknecht2024/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..cd97ae00dba265bb4a266b3feb14789568790175 --- /dev/null +++ b/tasks/dienstknecht2024/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1ce56196aa0a985ae05cdb2c43ae21c4e66bf0123f6807f791a1eab0edbb677 +size 13889 diff --git a/tasks/dienstknecht2024/instance/large_instance_3.json b/tasks/dienstknecht2024/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..a9d103a371aeee8bd9df9af7b01832dfcf697df0 --- /dev/null +++ b/tasks/dienstknecht2024/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cba6ac7da9a6fe0933791ba86b138f1e23a179d2b0e9c293f51839a98cbca84c +size 13880 diff --git a/tasks/dienstknecht2024/instance/large_instance_4.json b/tasks/dienstknecht2024/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..932c28df57c88916619bdb9e555beef954e1cb8a --- /dev/null +++ b/tasks/dienstknecht2024/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dd82338453929b0ce6753989727be8ed59fbb098c4f53a89539f7e423146240 +size 13895 diff --git a/tasks/dienstknecht2024/instance/large_instance_5.json b/tasks/dienstknecht2024/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fd7a064cb956597d01614c2d3f76e117c23172ff --- /dev/null +++ b/tasks/dienstknecht2024/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a944bddfb2043651bf1081c839bac7244ada22308d850e4c59c0c41fc181f77 +size 13903 diff --git a/tasks/dienstknecht2024/instance/tiny_instance.json b/tasks/dienstknecht2024/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..dcaf083c0d6b67564676ce7c3db6620707281c5b --- /dev/null +++ b/tasks/dienstknecht2024/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af583de6a6fc35375c26b499838cd900657c0ca1069f34a38cb561b2ea55ceb8 +size 7742 diff --git a/tasks/dienstknecht2024/instance_schema.json b/tasks/dienstknecht2024/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..155cf3ef932a061ef7550ebf5bee52e857720b31 --- /dev/null +++ b/tasks/dienstknecht2024/instance_schema.json @@ -0,0 +1,33 @@ +{ + "problem_parameters": { + "num_periods": " Total number of periods in the construction project planning horizon.", + "num_containers": " Total number of containers in the container unit on the construction site.", + "num_trades": " Total number of trades requiring container accommodation during the project.", + "cu_width": " Width of the container unit in number of containers per layer.", + "cu_depth": " Depth of the container unit in number of containers per layer.", + "cu_height": " Number of stacked layers in the container unit.", + "d_max": " Maximum number of separate container clusters any trade will tolerate." + }, + "containers": [ + { + "id": " Unique identifier for this container.", + "position": { + "x": " Position of this container along the width axis of the container unit.", + "y": " Position of this container along the depth axis of the container unit.", + "z": " Layer index of this container in the container unit." + }, + "availability_start": " First period in which this container is available on-site for assignment.", + "availability_end": " Last period in which this container is available on-site for assignment.", + "adjacent_containers": " Identifiers of all containers physically adjacent to this one within the container unit." + } + ], + "trades": [ + { + "id": " Unique identifier for this trade.", + "start_period": " First period in which this trade is active and requires containers.", + "end_period": " Last period in which this trade is active and requires containers.", + "container_demand": " Number of containers this trade needs in each period it is active.", + "max_dispersion": " Maximum number of separate container clusters allowed for this trade in any period." + } + ] +} diff --git a/tasks/dienstknecht2024/mathematical_formulation.md b/tasks/dienstknecht2024/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f2808b50fd51755e2e2618c23b548dcb10cbf4a4 --- /dev/null +++ b/tasks/dienstknecht2024/mathematical_formulation.md @@ -0,0 +1,81 @@ +# Original Formulation: Trade–Container Assignment Problem in Construction Projects (TCAPCP) + +*Source: A graph-based model and a heuristic for the trade–container assignment problem in construction projects (MIP TCAPCP$_{Per}$), M. Dienstknecht and D. Briskorn, European Journal of Operational Research 315(1), 324–337, 2024.* + +## Sets and Indices + +$$\begin{align*} +&C && \text{set of containers (single containers are the nodes of graph } G=(C,\mathcal{A})\text{).}\\ +&\mathcal{J} && \text{set of trades.}\\ +&\mathcal{A} && \text{set of arcs reflecting container adjacency:}\\ +&&& \mathcal{A}=\{(c,c')\mid c\neq c'\in C,\ c'\in\mathcal{A}_c\},\ \text{with } c'\in\mathcal{A}_c\iff c\in\mathcal{A}_{c'}.\\ +&C^p && \text{set of containers available in period } p:\ C^p=\{c\in C:\ s_c\le p\le f_c\}.\\ +&\mathcal{J}^p && \text{set of trades active in period } p:\ \mathcal{J}^p=\{j\mid j\in\mathcal{J}:\ s_j\le p\le f_j\}. +\end{align*}$$ + +## Parameters + +Each container $c\in C$ is a triple $(s_c,f_c,\mathcal{A}_c)$; each trade $j\in\mathcal{J}$ is a quadruple $(s_j,f_j,n_j,d_j^{max})$ of positive integers. $$\begin{align*} +&P && \text{number of periods the construction project spans.}\\ +&s_c,f_c\in\{1,\dots,P\} && \text{start / end of on-site availability of container } c,\ s_c\le f_c.\\ +&\mathcal{A}_c\subseteq C && \text{set of containers adjacent to } c.\\ +&s_j,f_j\in\{1,\dots,P\} && \text{start / finish period of trade } j,\ s_j\le f_j.\\ +&n_j && \text{number of containers trade } j \text{ requires in each period } [s_j,f_j].\\ +&d_j^{max}\in\mathbb{N} && \text{maximum willingness of dispersion of trade } j \text{ (max.\ number of clusters).} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +&x_c^{j,p}\in\{0,1\} && 1 \text{ if trade } j \text{ is assigned to container } c \text{ in period } p.\\ +&y_{(c,c')}^{j,p}\in\{0,1\} && 1 \text{ if containers } c \text{ and } c' \text{ belong to the same cluster of trade } j \text{ in period } p.\\ +&z_c^{j,p}\in\{0,1\} && 1 \text{ if container } c \text{ is the source of a flow associated with trade } j \text{ in period } p.\\ +&r^{j,p}\in\{0,1\} && 1 \text{ if trade } j \text{ is re-assigned in period } p.\\ +&f_{(c,c')}^{j,p}\ge 0 && \text{flow associated with trade } j \text{ in period } p \text{ on arc } (c,c')\ \text{(continuous).} +\end{align*}$$ + +## Objective + +$$\begin{align} +\min\ Z = \sum_{j\in\mathcal{J}}\ \sum_{p=s_j+1}^{f_j} r^{j,p} \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +&\sum_{c\in C^p} x_c^{j,p} = n_j + && \forall\, p=1,\dots,P;\ j\in\mathcal{J}^p \tag{2}\\[2pt] +&\sum_{j\in\mathcal{J}^p} x_c^{j,p} \le 1 + && \forall\, p=1,\dots,P;\ c\in C^p \tag{3}\\[2pt] +&z_c^{j,p} \le x_c^{j,p} + && \forall\, p=1,\dots,P;\ j\in\mathcal{J}^p;\ c\in C^p \tag{4}\\[2pt] +&y_{(c,c')}^{j,p} \le x_c^{j,p} + && \forall\, p=1,\dots,P;\ j\in\mathcal{J}^p;\ c= 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/dienstknecht2024/solution_schema.json b/tasks/dienstknecht2024/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a77a67c9cb43f05cdfb012db507efc257ed35c3d --- /dev/null +++ b/tasks/dienstknecht2024/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total number of re-assignments across all trades and periods of the project.", + "assignments": " Containers assigned to each trade in each period of that trade's active interval." +} diff --git a/tasks/earl2005/feasibility_check.py b/tasks/earl2005/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0cabe36937e11cee685109be547a89bb17fe3a --- /dev/null +++ b/tasks/earl2005/feasibility_check.py @@ -0,0 +1,742 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Defensive Drill 1 solutions (with objective recompute). + +Paper: "Multi-vehicle Cooperative Control Using Mixed Integer Linear Programming" + Earl & D'Andrea (2005) + +Checks the released polygonal MILP semantics exactly. Radii are polygon +apothem values and obstacle checks occur at the N_u control-step boundaries, +matching gurobi_code.py and mathematical_formulation.md. + +Constraints: + 1. Defender Dynamics + IC (Eq. 6) - linear discrete-time state transition + 2. Control-Input Polygon Feasibility - exact M_u half-spaces + 3. Auxiliary |u| constraints (Eq. 10) - checked only if zx/zy present + 4. Attacker Dynamics (Eq. 17) - linear motion while active + 5. Attacker Initial Conditions (Eq. 19) - start in attack mode at given pos + 6. Attacker State Machine - mode[k+1]=1 iff mode[k]=1 AND not in-zone AND not intercepted + 7. Defense Zone containment - exact M_dz half-spaces + 8. Interception - exact M_I half-spaces at interpolated defender positions + 9. Defender Zone Avoidance - exact released four-side obstacle polygon + 10. Objective Consistency (Tier C) - reported objective_value must equal + the recomputed objective J = sum_{j,k>=1} gamma_j[k] + + epsilon * sum_{i,k}(|u_xi[k]| + |u_yi[k]|) + (when zx/zy are absent, the optimal z = |u| is used as the canonical + interpretation; when present, the stored z is used directly). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('attackers', 'defenders', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('attackers', 'defenders') +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(inst, sol): + """Run all feasibility checks; return the result dict (no I/O).""" + tol = 1e-5 + eps = 1e-5 + + # Check if solution has variable data + if 'defenders' not in sol or 'attackers' not in sol: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Solution contains no variable data (solver may have failed)."], + "violation_magnitudes": [] + } + + # Instance parameters + N_D = inst['N_D'] + N_A = inst['N_A'] + M_u = inst['M_u'] + M_I = inst['M_I'] + M_dz = inst['M_dz'] + N_u = inst['N_u'] + N_a = inst['N_a'] + R_dz = inst['R_dz'] + R_I = inst['R_I'] + T_a_val = inst['T_a'] + T_u_val = inst['T_u'] + defenders_inst = inst['defenders'] + attackers_inst = inst['attackers'] + + # Inferred parameters (matching solver code, NOT SPECIFIED IN PAPER) + H = 100.0 + eps_c = 1e-4 + M_o = 4 + N_o = N_u + + defenders_sol = sol['defenders'] + attackers_sol = sol['attackers'] + + # Structural validation: the constraint checks below index defenders_sol[i] + # for i in range(N_D), attackers_sol[j] for j in range(N_A), and trajectory + # arrays at [k]/[k+1] up to N_u/N_a. A solution that omits agents or supplies + # short arrays would otherwise raise IndexError/KeyError and crash the + # checker (reported upstream as checker_error). Validate up front and return + # a clean infeasible verdict instead. + struct_errors = [] + if not isinstance(defenders_sol, list) or len(defenders_sol) != N_D: + struct_errors.append( + f"defenders: expected {N_D} entries, got " + f"{len(defenders_sol) if isinstance(defenders_sol, list) else type(defenders_sol).__name__}") + if not isinstance(attackers_sol, list) or len(attackers_sol) != N_A: + struct_errors.append( + f"attackers: expected {N_A} entries, got " + f"{len(attackers_sol) if isinstance(attackers_sol, list) else type(attackers_sol).__name__}") + + if not struct_errors: + # Per-agent key/length checks (only over the indices actually accessed). + def_arr_full = ['x', 'y', 'xdot', 'ydot'] # indexed up to k+1 => need N_u+1 + def_arr_ctrl = ['ux', 'uy'] # indexed up to k => need N_u + for i in range(N_D): + ds = defenders_sol[i] + if not isinstance(ds, dict): + struct_errors.append(f"Defender {i}: expected object, got {type(ds).__name__}") + continue + for key in def_arr_full: + v = ds.get(key) + if not isinstance(v, list) or len(v) != N_u + 1: + struct_errors.append( + f"Defender {i} field '{key}': need >= {N_u + 1} values, " + f"got {len(v) if isinstance(v, list) else 'missing'}") + for key in def_arr_ctrl: + v = ds.get(key) + if not isinstance(v, list) or len(v) != N_u: + struct_errors.append( + f"Defender {i} field '{key}': need >= {N_u} values, " + f"got {len(v) if isinstance(v, list) else 'missing'}") + for j in range(N_A): + asol = attackers_sol[j] + if not isinstance(asol, dict): + struct_errors.append(f"Attacker {j}: expected object, got {type(asol).__name__}") + continue + for key in ('p', 'q', 'a', 'gamma'): + v = asol.get(key) + if not isinstance(v, list) or len(v) != N_a + 1: + struct_errors.append( + f"Attacker {j} field '{key}': need >= {N_a + 1} values, " + f"got {len(v) if isinstance(v, list) else 'missing'}") + delta = asol.get('delta') + if ( + not isinstance(delta, list) + or len(delta) != N_D + or any(not isinstance(row, list) or len(row) != N_a + 1 + for row in delta) + ): + struct_errors.append( + f"Attacker {j} field 'delta': need shape " + f"[{N_D}][{N_a + 1}]") + + if struct_errors: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["Malformed solution structure: " + "; ".join(struct_errors[:10])], + "violation_magnitudes": [] + } + + e_Tu = math.exp(-T_u_val) + + violation_magnitudes = [] + constraint_violations = {} + + def record(cidx, msg, lhs_val, rhs_val, raw_excess): + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violation_magnitudes.append({ + "constraint": cidx, + "lhs": float(lhs_val), + "rhs": float(rhs_val), + "raw_excess": float(raw_excess), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + constraint_violations.setdefault(cidx, []).append(msg) + + def check_eq(cidx, msg, actual, expected): + diff = abs(actual - expected) + if diff > tol: + record(cidx, msg, actual, expected, diff) + + def check_leq(cidx, msg, lhs_val, rhs_val): + excess = lhs_val - rhs_val + if excess > tol: + record(cidx, msg, lhs_val, rhs_val, excess) + + def check_geq(cidx, msg, lhs_val, rhs_val): + excess = rhs_val - lhs_val + if excess > tol: + record(cidx, msg, lhs_val, rhs_val, excess) + + def rb(v): + return round(float(v)) + + # Serialized state indicators are part of the feasibility witness; do not + # silently coerce fractional values through round(). + for j in range(N_A): + asol = attackers_sol[j] + for name in ('a', 'gamma'): + for k, value in enumerate(asol[name]): + numeric = float(value) + nearest = min((0.0, 1.0), key=lambda target: abs(numeric - target)) + check_eq( + 6, + f"Attacker {j} {name}[{k}]={numeric} is not binary", + numeric, + nearest, + ) + for i, row in enumerate(asol['delta']): + for k, value in enumerate(row): + numeric = float(value) + nearest = min((0.0, 1.0), key=lambda target: abs(numeric - target)) + check_eq( + 6, + f"Attacker {j} delta[{i}][{k}]={numeric} is not binary", + numeric, + nearest, + ) + + def def_pos(d_sol, t): + k_u = int(t / T_u_val) + if k_u >= N_u: + k_u = N_u - 1 + tau = t - k_u * T_u_val + e_tau = math.exp(-tau) + xa = (d_sol['x'][k_u] + + (1.0 - e_tau) * d_sol['xdot'][k_u] + + (tau - 1.0 + e_tau) * d_sol['ux'][k_u]) + ya = (d_sol['y'][k_u] + + (1.0 - e_tau) * d_sol['ydot'][k_u] + + (tau - 1.0 + e_tau) * d_sol['uy'][k_u]) + return xa, ya + + # ================================================================ + # Constraint 1: Defender Dynamics (Eq. 6) + Initial Conditions + # ================================================================ + for i in range(N_D): + di = defenders_inst[i] + ds = defenders_sol[i] + check_eq(1, f"Defender {i} IC x: {ds['x'][0]} != {di['x_s']}", + ds['x'][0], di['x_s']) + check_eq(1, f"Defender {i} IC y: {ds['y'][0]} != {di['y_s']}", + ds['y'][0], di['y_s']) + check_eq(1, f"Defender {i} IC xdot: {ds['xdot'][0]} != {di['xdot_s']}", + ds['xdot'][0], di['xdot_s']) + check_eq(1, f"Defender {i} IC ydot: {ds['ydot'][0]} != {di['ydot_s']}", + ds['ydot'][0], di['ydot_s']) + for k in range(N_u): + exp_x = (ds['x'][k] + (1.0 - e_Tu) * ds['xdot'][k] + + (T_u_val - 1.0 + e_Tu) * ds['ux'][k]) + check_eq(1, f"Defender {i} dynamics x k={k}: {ds['x'][k+1]:.8f} != {exp_x:.8f}", + ds['x'][k+1], exp_x) + exp_y = (ds['y'][k] + (1.0 - e_Tu) * ds['ydot'][k] + + (T_u_val - 1.0 + e_Tu) * ds['uy'][k]) + check_eq(1, f"Defender {i} dynamics y k={k}: {ds['y'][k+1]:.8f} != {exp_y:.8f}", + ds['y'][k+1], exp_y) + exp_xd = e_Tu * ds['xdot'][k] + (1.0 - e_Tu) * ds['ux'][k] + check_eq(1, f"Defender {i} dynamics xdot k={k}: {ds['xdot'][k+1]:.8f} != {exp_xd:.8f}", + ds['xdot'][k+1], exp_xd) + exp_yd = e_Tu * ds['ydot'][k] + (1.0 - e_Tu) * ds['uy'][k] + check_eq(1, f"Defender {i} dynamics ydot k={k}: {ds['ydot'][k+1]:.8f} != {exp_yd:.8f}", + ds['ydot'][k+1], exp_yd) + + # ================================================================ + # Constraint 2: Exact released control-input polygon (Eq. 8) + # ================================================================ + for i in range(N_D): + ds = defenders_sol[i] + for k in range(N_u): + ux, uy = ds['ux'][k], ds['uy'][k] + rhs = math.cos(math.pi / M_u) + for m in range(1, M_u + 1): + projection = ( + math.sin(2.0 * math.pi * m / M_u) * ux + + math.cos(2.0 * math.pi * m / M_u) * uy + ) + check_leq( + 2, + f"Defender {i} control polygon k={k}, side={m}: " + f"projection={projection:.6f} > {rhs:.6f}", + projection, + rhs, + ) + + # ================================================================ + # Constraint 3: Auxiliary |u| constraints (Eq. 10) + # ================================================================ + has_z = len(defenders_sol) > 0 and 'zx' in defenders_sol[0] + if has_z: + for i in range(N_D): + ds = defenders_sol[i] + for k in range(N_u): + zx, zy = ds['zx'][k], ds['zy'][k] + ux, uy = ds['ux'][k], ds['uy'][k] + check_leq(3, f"Defender {i} ux<=zx k={k}", ux, zx) + check_leq(3, f"Defender {i} -ux<=zx k={k}", -ux, zx) + check_leq(3, f"Defender {i} uy<=zy k={k}", uy, zy) + check_leq(3, f"Defender {i} -uy<=zy k={k}", -uy, zy) + if zx < -tol: + record(3, f"Defender {i} zx<0 k={k}", zx, 0.0, -zx) + if zy < -tol: + record(3, f"Defender {i} zy<0 k={k}", zy, 0.0, -zy) + + # ================================================================ + # Constraint 4: Attacker Dynamics (Eq. 17) + # ================================================================ + for j in range(N_A): + ai = attackers_inst[j] + asol = attackers_sol[j] + vp, vq = ai['v_p'], ai['v_q'] + for k in range(N_a): + ak = rb(asol['a'][k]) + exp_p = asol['p'][k] + vp * T_a_val * ak + check_eq(4, f"Attacker {j} dynamics p k={k}: {asol['p'][k+1]:.8f} != {exp_p:.8f}", + asol['p'][k + 1], exp_p) + exp_q = asol['q'][k] + vq * T_a_val * ak + check_eq(4, f"Attacker {j} dynamics q k={k}: {asol['q'][k+1]:.8f} != {exp_q:.8f}", + asol['q'][k + 1], exp_q) + + # ================================================================ + # Constraint 5: Attacker Initial Conditions (Eq. 19) + # ================================================================ + for j in range(N_A): + ai = attackers_inst[j] + asol = attackers_sol[j] + check_eq(5, f"Attacker {j} IC p: {asol['p'][0]} != {ai['p_s']}", + asol['p'][0], ai['p_s']) + check_eq(5, f"Attacker {j} IC q: {asol['q'][0]} != {ai['q_s']}", + asol['q'][0], ai['q_s']) + check_eq(5, f"Attacker {j} IC a: {rb(asol['a'][0])} != 1", + float(rb(asol['a'][0])), 1.0) + + # ================================================================ + # Constraint 6: Attacker State Machine (self-consistency) + # ================================================================ + for j in range(N_A): + asol = attackers_sol[j] + gamma_arr = asol.get('gamma') + delta_mat = asol.get('delta') + for k in range(1, N_a): + ak = rb(asol['a'][k]) + ak1 = rb(asol['a'][k + 1]) + gm_stored = rb(gamma_arr[k]) + dc_stored = 1 if any( + rb(delta_mat[i][k]) == 1 for i in range(N_D) + ) else 0 + expected_ak1 = 1 if (ak == 1 and gm_stored == 0 and dc_stored == 0) else 0 + if ak1 != expected_ak1: + record(6, + f"Attacker {j} state-machine k={k}: a[k]={ak}, " + f"gamma={gm_stored}, delta_comb={dc_stored} -> expected a[k+1]={expected_ak1}, got {ak1}", + float(ak1), float(expected_ak1), abs(ak1 - expected_ak1)) + + # ================================================================ + # Constraint 7: Zone consistency under exact polygon inequalities + # ================================================================ + for j in range(N_A): + asol = attackers_sol[j] + gamma_arr = asol.get('gamma') + if gamma_arr is None: + continue + for k in range(1, N_a + 1): + pk, qk = asol['p'][k], asol['q'][k] + gm = rb(gamma_arr[k]) + projections = [ + math.sin(2.0 * math.pi * m / M_dz) * pk + + math.cos(2.0 * math.pi * m / M_dz) * qk + for m in range(1, M_dz + 1) + ] + if gm == 1: + for m, projection in enumerate(projections, 1): + check_leq( + 7, + f"Attacker {j} zone k={k}, side={m}: gamma=1 but " + f"projection={projection:.6f} > R_dz={R_dz}", + projection, + R_dz, + ) + elif max(projections) < R_dz + eps_c - tol: + record( + 7, + f"Attacker {j} zone k={k}: gamma=0 but no polygon side " + f"reaches R_dz+eps_c={R_dz + eps_c}", + max(projections), + R_dz + eps_c, + R_dz + eps_c - max(projections), + ) + + # ================================================================ + # Constraint 8: Interception consistency under exact polygon inequalities + # ================================================================ + for j in range(N_A): + asol = attackers_sol[j] + delta_mat = asol.get('delta') + if delta_mat is None: + continue + for k in range(1, N_a + 1): + pk, qk = asol['p'][k], asol['q'][k] + for i in range(N_D): + ds = defenders_sol[i] + t_ak = k * T_a_val + xa_i, ya_i = def_pos(ds, t_ak) + d = rb(delta_mat[i][k]) + projections = [ + math.sin(2.0 * math.pi * m / M_I) * (pk - xa_i) + + math.cos(2.0 * math.pi * m / M_I) * (qk - ya_i) + for m in range(1, M_I + 1) + ] + if d == 1: + for m, projection in enumerate(projections, 1): + check_leq( + 8, + f"Intercept i={i} j={j} k={k}, side={m}: " + f"delta=1 but projection={projection:.6f} > R_I={R_I}", + projection, + R_I, + ) + elif max(projections) < R_I + eps_c - tol: + record( + 8, + f"Intercept i={i} j={j} k={k}: delta=0 but no " + f"polygon side reaches R_I+eps_c={R_I + eps_c}", + max(projections), + R_I + eps_c, + R_I + eps_c - max(projections), + ) + + # ================================================================ + # Constraint 9: Defender avoidance of the released four-side polygon + # ================================================================ + for i in range(N_D): + ds = defenders_sol[i] + for k in range(1, N_o + 1): + xk, yk = ds['x'][k], ds['y'][k] + max_projection = max( + math.sin(2.0 * math.pi * m / M_o) * xk + + math.cos(2.0 * math.pi * m / M_o) * yk + for m in range(1, M_o + 1) + ) + if max_projection < R_dz + eps_c - tol: + record(9, + f"Defender {i} enters avoidance polygon at k={k}: " + f"max projection={max_projection:.6f} < " + f"R_dz+eps_c={R_dz + eps_c}", + max_projection, R_dz + eps_c, + R_dz + eps_c - max_projection) + + # ================================================================ + # Constraint 10: Objective Consistency (Tier C anti-exploit defense) + # Recompute J = sum_{j,k>=1} gamma_j[k] + # + epsilon * sum_{i,k}(z_xi[k] + z_yi[k]) + # When zx/zy are absent from the solution, use z = |u| (the minimum + # value of z given fixed u, which is what the solver picks at optimum + # since z appears only in the obj with positive coefficient and the + # only constraint is z >= |u|). This makes the recomputation a unique + # deterministic function of the displayed variables, suitable for + # strict equality checking against the reported objective_value. + # ================================================================ + reported_raw = sol.get('objective_value') + if reported_raw is not None: + try: + reported = float(reported_raw) + except (TypeError, ValueError): + reported = None + if reported is not None and math.isfinite(reported): + epsilon = float(inst.get('epsilon', 0.0)) + sum_gamma = 0 + gamma_available = True + for j in range(N_A): + asol = attackers_sol[j] + g = asol.get('gamma') + if g is None: + gamma_available = False + break + for k in range(1, N_a + 1): + if k < len(g): + sum_gamma += rb(g[k]) + if gamma_available: + sum_z = 0.0 + z_available = True + for i in range(N_D): + ds = defenders_sol[i] + ux_list = ds.get('ux') + uy_list = ds.get('uy') + if ux_list is None or uy_list is None: + z_available = False + break + zx_list = ds.get('zx') + zy_list = ds.get('zy') + for k in range(N_u): + if zx_list is not None and k < len(zx_list): + sum_z += float(zx_list[k]) + elif k < len(ux_list): + sum_z += abs(float(ux_list[k])) + if zy_list is not None and k < len(zy_list): + sum_z += float(zy_list[k]) + elif k < len(uy_list): + sum_z += abs(float(uy_list[k])) + if z_available: + true_obj = float(sum_gamma) + epsilon * sum_z + diff = abs(reported - true_obj) + tol_obj = max(1e-6, 5e-6 * abs(true_obj)) + if diff > tol_obj: + record(10, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed " + f"sum_gamma + epsilon*sum(z|=|u|)={true_obj} " + f"(sum_gamma={sum_gamma}, epsilon={epsilon}, sum_z={sum_z}, " + f"|diff|={diff:.3g}, tol={tol_obj:.3g})", + reported, true_obj, diff) + elif reported is not None and not math.isfinite(reported): + # reported is +/-inf or NaN: cannot match any finite recomputed obj. + # Compute a finite recomputed obj for the message; if all parts + # are accessible, this still flags constraint 10. + epsilon = float(inst.get('epsilon', 0.0)) + sum_gamma = 0 + for j in range(N_A): + asol = attackers_sol[j] + g = asol.get('gamma') + if g is None: + sum_gamma = None + break + for k in range(1, N_a + 1): + if k < len(g): + sum_gamma += rb(g[k]) + sum_z = 0.0 + if sum_gamma is not None: + for i in range(N_D): + ds = defenders_sol[i] + ux_list = ds.get('ux') + uy_list = ds.get('uy') + if ux_list is None or uy_list is None: + sum_gamma = None + break + zx_list = ds.get('zx') + zy_list = ds.get('zy') + for k in range(N_u): + if zx_list is not None and k < len(zx_list): + sum_z += float(zx_list[k]) + elif k < len(ux_list): + sum_z += abs(float(ux_list[k])) + if zy_list is not None and k < len(zy_list): + sum_z += float(zy_list[k]) + elif k < len(uy_list): + sum_z += abs(float(uy_list[k])) + if sum_gamma is not None: + true_obj = float(sum_gamma) + epsilon * sum_z + record(10, + f"Objective consistency violated: reported objective_value=" + f"{reported} is not finite; recomputed obj={true_obj}", + reported, true_obj, float('inf')) + + # ================================================================ + # Aggregate and output + # ================================================================ + violated_constraints = sorted(constraint_violations.keys()) + + agg_violations = [] + for cidx in violated_constraints: + msgs = constraint_violations[cidx] + count = len(msgs) + if count == 1: + agg_violations.append(f"Constraint {cidx}: {msgs[0]}") + else: + agg_violations.append( + f"Constraint {cidx}: {count} violations, e.g., {msgs[0]}") + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": agg_violations, + "violation_magnitudes": violation_magnitudes if not feasible else [] + } + + +def main(): + parser = argparse.ArgumentParser( + description="Check feasibility of a candidate solution for Defensive Drill 1.") + 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: + inst = json.load(f) + with open(args.solution_path) as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(inst, sol) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + feasible = result["feasible"] + print(f"Feasibility: {feasible}") + if not feasible: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" {v}") + + +if __name__ == '__main__': + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/earl2005/gurobi_code.py b/tasks/earl2005/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..8eeea76aa8a6a5e425572dd3551561e602623f61 --- /dev/null +++ b/tasks/earl2005/gurobi_code.py @@ -0,0 +1,521 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of Defensive Drill 1 MILP. + +Paper: "Multi-vehicle Cooperative Control Using Mixed Integer Linear Programming" +Authors: Matthew G. Earl and Raffaello D'Andrea (2005) + +Implements the full MILP formulation (Eq. 44) with both epsilon > 0 and epsilon = 0 +objective options, as described in Sections II–V of the paper. +""" + +import argparse +import json +import math +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def compute_AB(T_u): + """Compute state-transition matrices A[k] and B[k] for a given step time T_u. + Eq. (6) from the paper. + """ + e = math.exp(-T_u) + A = [ + [1, 0, 1 - e, 0], + [0, 1, 0, 1 - e], + [0, 0, e, 0], + [0, 0, 0, e], + ] + B = [ + [T_u - 1 + e, 0], + [0, T_u - 1 + e], + [1 - e, 0], + [0, 1 - e], + ] + return A, B + + +def defender_pos_at_time(t, T_u, N_u, x_var, y_var, xdot_var, ydot_var, ux_var, uy_var, i): + """Return linear (Gurobi) expressions for the defender i's (x, y) position + at continuous time t, computed via Eq. (7). + + Eq. (7): + x(t) = x_u[k] + (1 - exp(t_u[k] - t)) * xdot_u[k] + + (t - t_u[k] - 1 + exp(t_u[k] - t)) * u_x[k] + where k satisfies t_u[k] <= t <= t_u[k+1], t_u[k] = k * T_u. + + Since A[k] and B[k] are pre-computed constants, the resulting expressions + are linear in the decision variables. + """ + k_u = int(t / T_u) + if k_u >= N_u: + k_u = N_u - 1 # clamp to last control interval + tau = t - k_u * T_u # time elapsed since start of interval k_u + e_tau = math.exp(-tau) + + # x_{a,i}(t) = x_i[k_u] + (1 - e^{-tau}) * xdot_i[k_u] + # + (tau - 1 + e^{-tau}) * ux_i[k_u] + xa = (x_var[i, k_u] + + (1.0 - e_tau) * xdot_var[i, k_u] + + (tau - 1.0 + e_tau) * ux_var[i, k_u]) + ya = (y_var[i, k_u] + + (1.0 - e_tau) * ydot_var[i, k_u] + + (tau - 1.0 + e_tau) * uy_var[i, k_u]) + return xa, ya + + +# --------------------------------------------------------------------------- +# Main solver +# --------------------------------------------------------------------------- + +def solve(instance_path, solution_path, time_limit): + # ------------------------------------------------------------------ + # Load instance + # ------------------------------------------------------------------ + with open(instance_path) as f: + inst = json.load(f) + + N_D = inst['N_D'] + N_A = inst['N_A'] + eps = inst['epsilon'] # epsilon in objective (0 or 0.1) + M_u = inst['M_u'] + M_I = inst['M_I'] + M_dz = inst['M_dz'] + N_u = inst['N_u'] + N_a = inst['N_a'] + R_dz = inst['R_dz'] + R_I = inst['R_I'] + T_a = inst['T_a'] + T_u = inst['T_u'] + defenders = inst['defenders'] + attackers = inst['attackers'] + + # ------------------------------------------------------------------ + # Inferred / assumed parameters (NOT SPECIFIED IN PAPER) + # ------------------------------------------------------------------ + # H: big-M constant. Paper says H must be "larger than the maximum + # dimension of the vehicle's operating environment plus the radius + # of the obstacle." Playing field radius R_f = 15, R_dz = 2, so + # H = 100 is a safe conservative choice. + H = 100.0 + + # eps_c: small tolerance for strict-inequality big-M constraints (Eq. 14, 23, 29). + # Paper describes it as "a small positive number"; we use 1e-4. + eps_c = 1e-4 + + # M_o: sides of polygon approximating the obstacle (Defense Zone) for + # defender avoidance. NOT SPECIFIED IN PAPER for the computational study. + # We use M_o = 4 (consistent with the other polygon parameters). + M_o = 4 + + # N_o: number of obstacle-avoidance check steps. NOT SPECIFIED IN PAPER. + # We set N_o = N_u and place checks at t_o[k] = k * T_u (the defender + # control-step boundaries), so x_{o,i}[k] = x_i[k] exactly. + N_o = N_u + + # ------------------------------------------------------------------ + # Pre-compute dynamics matrices (uniform T_u) + # ------------------------------------------------------------------ + A, B = compute_AB(T_u) + + # ------------------------------------------------------------------ + # Build Gurobi model + # ------------------------------------------------------------------ + model = gp.Model("DefensiveDrill1") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("MIPFocus", 1) + model.setParam("NoRelHeurTime", min(60.0, time_limit * 0.05)) + + # ---- Decision variables ------------------------------------------ + + # Defender state x_{u,i}[k] = (x, y, xdot, ydot), k in {0,...,N_u} + x_v = {} + y_v = {} + xdot_v = {} + ydot_v = {} + for i in range(N_D): + for k in range(N_u + 1): + x_v[i, k] = model.addVar(lb=-GRB.INFINITY, name=f"x_{i}_{k}") + y_v[i, k] = model.addVar(lb=-GRB.INFINITY, name=f"y_{i}_{k}") + xdot_v[i, k] = model.addVar(lb=-GRB.INFINITY, name=f"xdot_{i}_{k}") + ydot_v[i, k] = model.addVar(lb=-GRB.INFINITY, name=f"ydot_{i}_{k}") + + # Defender control u_i[k] and auxiliary |u| variables, k in {0,...,N_u-1} + ux_v = {} + uy_v = {} + zx_v = {} + zy_v = {} + for i in range(N_D): + for k in range(N_u): + ux_v[i, k] = model.addVar(lb=-GRB.INFINITY, name=f"ux_{i}_{k}") + uy_v[i, k] = model.addVar(lb=-GRB.INFINITY, name=f"uy_{i}_{k}") + zx_v[i, k] = model.addVar(lb=0.0, name=f"zx_{i}_{k}") + zy_v[i, k] = model.addVar(lb=0.0, name=f"zy_{i}_{k}") + + # Attacker position p_j[k], q_j[k], k in {0,...,N_a} + p_v = {} + q_v = {} + for j in range(N_A): + for k in range(N_a + 1): + p_v[j, k] = model.addVar(lb=-GRB.INFINITY, name=f"p_{j}_{k}") + q_v[j, k] = model.addVar(lb=-GRB.INFINITY, name=f"q_{j}_{k}") + + # Attacker mode a_j[k] in {0,1}, k in {0,...,N_a} + a_v = {} + for j in range(N_A): + for k in range(N_a + 1): + a_v[j, k] = model.addVar(vtype=GRB.BINARY, name=f"a_{j}_{k}") + + # gamma_j[k]: 1 iff attacker j is inside Defense Zone at step k + gamma_v = {} + for j in range(N_A): + for k in range(1, N_a + 1): + gamma_v[j, k] = model.addVar(vtype=GRB.BINARY, name=f"gamma_{j}_{k}") + + # g_{mj}[k]: auxiliary binary for gamma, m in {1,...,M_dz} + g_v = {} + for j in range(N_A): + for k in range(1, N_a + 1): + for m in range(1, M_dz + 1): + g_v[m, j, k] = model.addVar(vtype=GRB.BINARY, name=f"g_{m}_{j}_{k}") + + # delta_{ij}[k]: 1 iff attacker j is in intercept region of defender i + delta_v = {} + for i in range(N_D): + for j in range(N_A): + for k in range(1, N_a + 1): + delta_v[i, j, k] = model.addVar(vtype=GRB.BINARY, + name=f"delta_{i}_{j}_{k}") + + # d_{mij}[k]: auxiliary binary for delta, m in {1,...,M_I} + d_v = {} + for i in range(N_D): + for j in range(N_A): + for k in range(1, N_a + 1): + for m in range(1, M_I + 1): + d_v[m, i, j, k] = model.addVar(vtype=GRB.BINARY, + name=f"d_{m}_{i}_{j}_{k}") + + # delta_comb_j[k]: combined interception indicator for attacker j at step k. + # NOT SPECIFIED IN PAPER for N_D > 1. + # Inferred assumption: attacker j is "intercepted" if delta_{ij}[k] = 1 + # for at least one defender i. This variable encodes the OR over i. + delta_comb_v = {} + for j in range(N_A): + for k in range(1, N_a + 1): + delta_comb_v[j, k] = model.addVar(vtype=GRB.BINARY, + name=f"delta_comb_{j}_{k}") + + # b_{mi}[k]: auxiliary binary for defender i obstacle avoidance. + # The paper mentions b_{mij}[k] with a j-index for the multi-defender case + # but states it "follows a similar trend" without specifying the role of j. + # Inferred assumption: obstacle avoidance depends only on defender i, not + # on attacker j, so b is indexed only by (m, i, k). + b_v = {} + for i in range(N_D): + for k in range(1, N_o + 1): + for m in range(1, M_o + 1): + b_v[m, i, k] = model.addVar(vtype=GRB.BINARY, name=f"b_{m}_{i}_{k}") + + model.update() + + # ---- Objective (Eq. 44) ------------------------------------------ + obj = gp.quicksum(gamma_v[j, k] for j in range(N_A) for k in range(1, N_a + 1)) + if eps > 0.0: + obj = obj + eps * gp.quicksum( + zx_v[i, k] + zy_v[i, k] + for i in range(N_D) for k in range(N_u) + ) + model.setObjective(obj, GRB.MINIMIZE) + + # ---- Constraint 1: Defender initial conditions ------------------- + for i in range(N_D): + d = defenders[i] + model.addConstr(x_v[i, 0] == d['x_s'], name=f"ic_x_{i}") + model.addConstr(y_v[i, 0] == d['y_s'], name=f"ic_y_{i}") + model.addConstr(xdot_v[i, 0] == d['xdot_s'], name=f"ic_xd_{i}") + model.addConstr(ydot_v[i, 0] == d['ydot_s'], name=f"ic_yd_{i}") + + # ---- Constraint 2: Defender dynamics (Eq. 6) --------------------- + # x_u[k+1] = A[k] * x_u[k] + B[k] * u[k] + # With uniform T_u, A and B are the same for all k. + e_Tu = math.exp(-T_u) + for i in range(N_D): + for k in range(N_u): + model.addConstr( + x_v[i, k+1] == x_v[i, k] + (1.0 - e_Tu) * xdot_v[i, k] + + (T_u - 1.0 + e_Tu) * ux_v[i, k], + name=f"dyn_x_{i}_{k}") + model.addConstr( + y_v[i, k+1] == y_v[i, k] + (1.0 - e_Tu) * ydot_v[i, k] + + (T_u - 1.0 + e_Tu) * uy_v[i, k], + name=f"dyn_y_{i}_{k}") + model.addConstr( + xdot_v[i, k+1] == e_Tu * xdot_v[i, k] + (1.0 - e_Tu) * ux_v[i, k], + name=f"dyn_xd_{i}_{k}") + model.addConstr( + ydot_v[i, k+1] == e_Tu * ydot_v[i, k] + (1.0 - e_Tu) * uy_v[i, k], + name=f"dyn_yd_{i}_{k}") + + # ---- Constraint 3: Control-input polygon (Eq. 8) ----------------- + cos_pi_Mu = math.cos(math.pi / M_u) + for i in range(N_D): + for k in range(N_u): + for m in range(1, M_u + 1): + sm = math.sin(2.0 * math.pi * m / M_u) + cm = math.cos(2.0 * math.pi * m / M_u) + model.addConstr( + sm * ux_v[i, k] + cm * uy_v[i, k] <= cos_pi_Mu, + name=f"ctrl_{i}_{k}_{m}") + + # ---- Constraint 4: Auxiliary |u| constraints (Eq. 10) ----------- + for i in range(N_D): + for k in range(N_u): + model.addConstr( ux_v[i, k] <= zx_v[i, k], name=f"zx_p_{i}_{k}") + model.addConstr(-ux_v[i, k] <= zx_v[i, k], name=f"zx_n_{i}_{k}") + model.addConstr( uy_v[i, k] <= zy_v[i, k], name=f"zy_p_{i}_{k}") + model.addConstr(-uy_v[i, k] <= zy_v[i, k], name=f"zy_n_{i}_{k}") + + # ---- Constraint 5: Attacker initial conditions (Eq. 19) ---------- + for j in range(N_A): + att = attackers[j] + model.addConstr(p_v[j, 0] == att['p_s'], name=f"ic_p_{j}") + model.addConstr(q_v[j, 0] == att['q_s'], name=f"ic_q_{j}") + model.addConstr(a_v[j, 0] == 1, name=f"ic_a_{j}") + + # ---- Constraint 6: Attacker dynamics (Eq. 17) -------------------- + # p[k+1] = p[k] + v_p * T_a * a[k] (linear: v_p, T_a are constants) + for j in range(N_A): + att = attackers[j] + v_p = att['v_p'] + v_q = att['v_q'] + for k in range(N_a): + model.addConstr( + p_v[j, k+1] == p_v[j, k] + v_p * T_a * a_v[j, k], + name=f"att_p_{j}_{k}") + model.addConstr( + q_v[j, k+1] == q_v[j, k] + v_q * T_a * a_v[j, k], + name=f"att_q_{j}_{k}") + + # ---- Constraint 7: Defense Zone indicator (Eq. 23 & 25) ---------- + for j in range(N_A): + for k in range(1, N_a + 1): + for m in range(1, M_dz + 1): + sm = math.sin(2.0 * math.pi * m / M_dz) + cm = math.cos(2.0 * math.pi * m / M_dz) + lhs = sm * p_v[j, k] + cm * q_v[j, k] + # Eq. 23a + model.addConstr( + lhs <= R_dz + H * (1.0 - g_v[m, j, k]), + name=f"dz23a_{m}_{j}_{k}") + # Eq. 23b + model.addConstr( + lhs >= R_dz + eps_c - (H + eps_c) * g_v[m, j, k], + name=f"dz23b_{m}_{j}_{k}") + # Eq. 25a: g_{mj}[k] >= gamma_j[k] for all m + for m in range(1, M_dz + 1): + model.addConstr( + g_v[m, j, k] >= gamma_v[j, k], + name=f"dz25a_{m}_{j}_{k}") + # Eq. 25b: sum_{l}(1 - g_{lj}[k]) + gamma_j[k] >= 1 + model.addConstr( + gp.quicksum(1.0 - g_v[l, j, k] for l in range(1, M_dz + 1)) + + gamma_v[j, k] >= 1.0, + name=f"dz25b_{j}_{k}") + + # ---- Constraint 8: Defender position at attacker time steps (Eq. 7) - + # Pre-compute linear expressions for x_{a,i}[k], y_{a,i}[k]. + xa_expr = {} + ya_expr = {} + for k in range(1, N_a + 1): + t_ak = k * T_a + for i in range(N_D): + xa_expr[i, k], ya_expr[i, k] = defender_pos_at_time( + t_ak, T_u, N_u, + x_v, y_v, xdot_v, ydot_v, ux_v, uy_v, i) + + # ---- Constraint 9: Intercept region indicator (Eq. 29 & 31) ------ + for i in range(N_D): + for j in range(N_A): + for k in range(1, N_a + 1): + for m in range(1, M_I + 1): + sm = math.sin(2.0 * math.pi * m / M_I) + cm = math.cos(2.0 * math.pi * m / M_I) + lhs = (sm * (p_v[j, k] - xa_expr[i, k]) + + cm * (q_v[j, k] - ya_expr[i, k])) + # Eq. 29a + model.addConstr( + lhs <= R_I + H * (1.0 - d_v[m, i, j, k]), + name=f"int29a_{m}_{i}_{j}_{k}") + # Eq. 29b + model.addConstr( + lhs >= R_I + eps_c - (H + eps_c) * d_v[m, i, j, k], + name=f"int29b_{m}_{i}_{j}_{k}") + # Eq. 31a: d_{mij}[k] >= delta_{ij}[k] for all m + for m in range(1, M_I + 1): + model.addConstr( + d_v[m, i, j, k] >= delta_v[i, j, k], + name=f"int31a_{m}_{i}_{j}_{k}") + # Eq. 31b: sum_{l}(1 - d_{lij}[k]) + delta_{ij}[k] >= 1 + model.addConstr( + gp.quicksum(1.0 - d_v[l, i, j, k] for l in range(1, M_I + 1)) + + delta_v[i, j, k] >= 1.0, + name=f"int31b_{i}_{j}_{k}") + + # ---- Constraint 10: Combined interception indicator -------------- + # NOT SPECIFIED IN PAPER for N_D > 1. + # Inferred assumption: delta_comb_j[k] = 1 iff any defender i intercepts + # attacker j at step k (OR over i). + # Implementation via standard OR-linearisation: + # delta_comb_j[k] >= delta_{ij}[k] for all i (if any is 1, combined >= 1) + # delta_comb_j[k] <= sum_i delta_{ij}[k] (if none is 1, combined = 0) + for j in range(N_A): + for k in range(1, N_a + 1): + for i in range(N_D): + model.addConstr( + delta_comb_v[j, k] >= delta_v[i, j, k], + name=f"comb_lb_{i}_{j}_{k}") + model.addConstr( + delta_comb_v[j, k] <= gp.quicksum(delta_v[i, j, k] for i in range(N_D)), + name=f"comb_ub_{j}_{k}") + + # ---- Constraint 11: Attacker state machine (Eq. 34) -------------- + # One-on-one form from the paper, generalized using delta_comb_v for N_D > 1. + # The exact multi-defender generalisation is NOT SPECIFIED IN PAPER; + # we replace delta[k] with delta_comb_v[j,k]. + for j in range(N_A): + for k in range(1, N_a): # k+1 ranges up to N_a + dc = delta_comb_v[j, k] + gm = gamma_v[j, k] + # Eq. 34a: a[k+1] + delta[k] <= 1 + model.addConstr(a_v[j, k+1] + dc <= 1.0, name=f"sm34a_{j}_{k}") + # Eq. 34b: a[k+1] - a[k] <= 0 + model.addConstr(a_v[j, k+1] - a_v[j, k] <= 0.0, name=f"sm34b_{j}_{k}") + # Eq. 34c: a[k+1] + gamma[k] <= 1 + model.addConstr(a_v[j, k+1] + gm <= 1.0, name=f"sm34c_{j}_{k}") + # Eq. 34d: a[k] - delta[k] - gamma[k] - a[k+1] <= 0 + model.addConstr(a_v[j, k] - dc - gm - a_v[j, k+1] <= 0.0, + name=f"sm34d_{j}_{k}") + + # ---- Constraint 12: Defender avoidance of Defense Zone (Eq. 14 & 15) - + # t_o[k] = k * T_u; at these times x_{o,i}[k] = x_i[k] (defender state). + # Obstacle centered at origin, R_obst = R_dz. + for i in range(N_D): + for k in range(1, N_o + 1): + for m in range(1, M_o + 1): + sm = math.sin(2.0 * math.pi * m / M_o) + cm = math.cos(2.0 * math.pi * m / M_o) + # Eq. 14 (strict > replaced by >= + eps_c): + # (x_o - 0)*s + (y_o - 0)*c >= R_obst + eps_c - H * b_{mi}[k] + model.addConstr( + sm * x_v[i, k] + cm * y_v[i, k] + >= R_dz + eps_c - H * b_v[m, i, k], + name=f"avoid14_{m}_{i}_{k}") + # Eq. 15: sum_m b_{mi}[k] <= M_o - 1 + model.addConstr( + gp.quicksum(b_v[m, i, k] for m in range(1, M_o + 1)) <= M_o - 1, + name=f"avoid15_{i}_{k}") + + # ---- Solve ------------------------------------------------------- + model.optimize() + + # ---- Extract solution -------------------------------------------- + solution = {} + if model.SolCount > 0: + solution['objective_value'] = model.objVal + solution['status'] = model.status + solution['mip_gap'] = model.MIPGap + + sol_defenders = [] + for i in range(N_D): + sol_defenders.append({ + 'x': [x_v[i, k].X for k in range(N_u + 1)], + 'y': [y_v[i, k].X for k in range(N_u + 1)], + 'xdot': [xdot_v[i, k].X for k in range(N_u + 1)], + 'ydot': [ydot_v[i, k].X for k in range(N_u + 1)], + 'ux': [ux_v[i, k].X for k in range(N_u)], + 'uy': [uy_v[i, k].X for k in range(N_u)], + }) + solution['defenders'] = sol_defenders + + # Original Earl & D'Andrea formulation has per-(defender, attacker, step) + # intercept indicator delta_{ij}[k]. The scalar delta_comb is a + # benchmark-added auxiliary (OR_i delta_{ij}) only needed for the + # N_D-on-N_A state machine linearization; it is NOT part of the paper's + # original variables and is therefore NOT exported. + sol_attackers = [] + for j in range(N_A): + sol_attackers.append({ + 'p': [p_v[j, k].X for k in range(N_a + 1)], + 'q': [q_v[j, k].X for k in range(N_a + 1)], + 'a': [a_v[j, k].X for k in range(N_a + 1)], + 'gamma': [0.0] + [gamma_v[j, k].X for k in range(1, N_a + 1)], + # delta[i][k]: whether defender i intercepts attacker j at step k. + # Padded at k=0 with 0.0 to match other per-step arrays. + 'delta': [ + [0.0] + [delta_v[i, j, k].X for k in range(1, N_a + 1)] + for i in range(N_D) + ], + }) + solution['attackers'] = sol_attackers + else: + solution['objective_value'] = None + solution['status'] = model.status + solution['mip_gap'] = None + print("WARNING: No feasible solution found within the time limit.", + file=sys.stderr) + + with open(solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to: {solution_path}") + print(f"Objective value: {solution['objective_value']}") + return solution + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Solve Defensive Drill 1 (Earl & D'Andrea 2005) with Gurobi.") + parser.add_argument('--instance_path', type=str, required=True, + help='Path to the JSON problem instance file.') + parser.add_argument('--solution_path', type=str, required=True, + help='Path to write the solution JSON file ' + '(e.g. gurobi_solution_1.json).') + parser.add_argument('--time_limit', type=int, default=300, + 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/earl2005/gurobi_feasi_result/large_feasi_result_1.json b/tasks/earl2005/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/earl2005/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/earl2005/gurobi_feasi_result/large_feasi_result_2.json b/tasks/earl2005/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/earl2005/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/earl2005/gurobi_feasi_result/large_feasi_result_3.json b/tasks/earl2005/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/earl2005/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/earl2005/gurobi_feasi_result/large_feasi_result_4.json b/tasks/earl2005/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/earl2005/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/earl2005/gurobi_feasi_result/large_feasi_result_5.json b/tasks/earl2005/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/earl2005/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/earl2005/gurobi_feasi_result/tiny_feasi_result.json b/tasks/earl2005/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/earl2005/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/earl2005/gurobi_solution/large_solution_1.json b/tasks/earl2005/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ba9699c079a460113bec716ab6b084da4d63408f --- /dev/null +++ b/tasks/earl2005/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68b151e35eb29ec20caee461e085726c437643845eb966d9c9b5d71a521162cd +size 142434 diff --git a/tasks/earl2005/gurobi_solution/large_solution_2.json b/tasks/earl2005/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..dc0646b8b8cb4a99f64853b1aa88f44dec459037 --- /dev/null +++ b/tasks/earl2005/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d915b25b84084188e4e695e230c94642afc293783bcfa1cb6cff812668dab96 +size 141779 diff --git a/tasks/earl2005/gurobi_solution/large_solution_3.json b/tasks/earl2005/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7a87177b624b0d57f9ce8b9ff5f98a48cfe74d5a --- /dev/null +++ b/tasks/earl2005/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2114173087acbc64f66ec4a36c76ff24917e9e2138845a8235227e113150d149 +size 142336 diff --git a/tasks/earl2005/gurobi_solution/large_solution_4.json b/tasks/earl2005/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..1a514de101942711651615135b91a6d69011fa69 --- /dev/null +++ b/tasks/earl2005/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc8ea09f36941131fce9574bd7e4fd49363f900c9829b87d15963ad78dd926f1 +size 140495 diff --git a/tasks/earl2005/gurobi_solution/large_solution_5.json b/tasks/earl2005/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7989abcbc5f5c754dc97d6493d7ccca4063fa923 --- /dev/null +++ b/tasks/earl2005/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eaf91d90331b9d9a6497a17ee9bc6bae547e5ae0b71eeebe0a01ba2d8951cc0a +size 142117 diff --git a/tasks/earl2005/gurobi_solution/tiny_solution.json b/tasks/earl2005/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..fe41b1b4322089254804725a32774e26cd99605d --- /dev/null +++ b/tasks/earl2005/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cb16902c634ab809aac24e0691a50673ad1cd12d73e5f4652bed22b41ae3ca8 +size 10765 diff --git a/tasks/earl2005/gurobi_solution_log/large_log_1.jsonl b/tasks/earl2005/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84cf8fe1d79ea0f646f80c6e488cefc8d1bf8e02 --- /dev/null +++ b/tasks/earl2005/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31337c69ca51dab9b487ac9594587607121313eeb197ae95c5d5b206275da068 +size 257 diff --git a/tasks/earl2005/gurobi_solution_log/large_log_2.jsonl b/tasks/earl2005/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c32a864b9833153067d8ee75cc2744e5763229e --- /dev/null +++ b/tasks/earl2005/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aac40e843b1419210ce59da2cbcd2a44cc4ceda22af8818fc1509b5b83cfdf5c +size 42 diff --git a/tasks/earl2005/gurobi_solution_log/large_log_3.jsonl b/tasks/earl2005/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6a0ae1409bf238fdf3a377361c07d0675375454d --- /dev/null +++ b/tasks/earl2005/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92a36f855ef33bbe3b80fe7f9dc5d3a02770da02e576866de1b8709daa00ada0 +size 256 diff --git a/tasks/earl2005/gurobi_solution_log/large_log_4.jsonl b/tasks/earl2005/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e517e6b7e8a04e3402b77709913ec1090f60cfa4 --- /dev/null +++ b/tasks/earl2005/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a93a908ed2b1ceebaa83acfb4961818f707df92a13ed6e79db5976fbfc3f9f7f +size 41 diff --git a/tasks/earl2005/gurobi_solution_log/large_log_5.jsonl b/tasks/earl2005/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a3003bb5a06d5b8982404c06bef748f668bd5ac0 --- /dev/null +++ b/tasks/earl2005/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80725ecb0c21fb87eb318c717368f1c66efe73bc2fe8e74c107f1feb8e54593a +size 255 diff --git a/tasks/earl2005/gurobi_solution_log/tiny_log.jsonl b/tasks/earl2005/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9fc400a0aa17cc11093595fbc9fcc02dc87d60b8 --- /dev/null +++ b/tasks/earl2005/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31fad69c6d5701887c9b0961c1bf19bfb07dfe7398451740a1e4fee805050626 +size 40 diff --git a/tasks/earl2005/instance/large_instance_1.json b/tasks/earl2005/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3a9b63e39e48b3da48b39b2f2267bfdc75f229f2 --- /dev/null +++ b/tasks/earl2005/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77c3924e35f7ee64ab0266e9c9748051cd6d37d5f25e25c3b4f942b7f9c81ac2 +size 5804 diff --git a/tasks/earl2005/instance/large_instance_2.json b/tasks/earl2005/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..cbae967dcad24d1c0ed61f65be52700137fdcd12 --- /dev/null +++ b/tasks/earl2005/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:921655b28f2a4ce1f0d453e4deb0d708f54dd6e5f4798ba7a22cc2e9097fc632 +size 5806 diff --git a/tasks/earl2005/instance/large_instance_3.json b/tasks/earl2005/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..fa35e09c56bf2fc73852548f31aa951065a60a1b --- /dev/null +++ b/tasks/earl2005/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f0cd359bdaf2b9f1a67cb4a6691400f640a2821c06e6bab9d07df39ced16f31 +size 5824 diff --git a/tasks/earl2005/instance/large_instance_4.json b/tasks/earl2005/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..90c5df65eea34650a4d2c9477db73a6ae34b8547 --- /dev/null +++ b/tasks/earl2005/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:971aea5460adcefd34bf457b7165244a57cfd27f8728daf0a2e385e393a6f0d2 +size 5812 diff --git a/tasks/earl2005/instance/large_instance_5.json b/tasks/earl2005/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..25721c83c4341a7469e32cb365ccd83aff92a9aa --- /dev/null +++ b/tasks/earl2005/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5f5cdfe37d98dfc85449dee070527f3c4cd3b3a7f80d796e379000a1169e7ba +size 5817 diff --git a/tasks/earl2005/instance/tiny_instance.json b/tasks/earl2005/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..05a2d638da6f4a6074bfa7250426f43a8236a817 --- /dev/null +++ b/tasks/earl2005/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3885f615da0ba28e331ad969c65bee4ce7abd2a98c3c9421ad8e901c53fe0708 +size 1449 diff --git a/tasks/earl2005/instance_schema.json b/tasks/earl2005/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b675b797a1c94abf21fd2407f9ec059f51fe71c1 --- /dev/null +++ b/tasks/earl2005/instance_schema.json @@ -0,0 +1,31 @@ +{ + "N_D": " Number of defending robots on the playing field.", + "N_A": " Number of attacking robots on the playing field.", + "epsilon": " Weight on the defenders' cumulative control effort in the objective.", + "M_u": " Number of sides of the regular polygon approximating each defender's unit-circle control input constraint.", + "M_I": " Number of sides of the regular polygon approximating each defender's intercept region.", + "M_dz": " Number of sides of the regular polygon approximating the circular Defense Zone.", + "N_u": " Number of discrete control steps for each defender.", + "N_a": " Number of discrete sample steps for each attacker.", + "R_dz": " Radius of the circular Defense Zone centered at the origin.", + "R_I": " Inscribed radius of the regular polygon defining each defender's intercept region.", + "v_a": " Constant speed magnitude of each attacker.", + "T_a": " Uniform time interval between consecutive attacker sample steps.", + "T_u": " Uniform time interval between consecutive defender control steps.", + "defenders": [ + { + "x_s": " Initial x-coordinate of the defender's position.", + "y_s": " Initial y-coordinate of the defender's position.", + "xdot_s": " Initial x-component of the defender's velocity.", + "ydot_s": " Initial y-component of the defender's velocity." + } + ], + "attackers": [ + { + "p_s": " Initial x-coordinate of the attacker's position.", + "q_s": " Initial y-coordinate of the attacker's position.", + "v_p": " Constant x-component of the attacker's velocity toward the Defense Zone.", + "v_q": " Constant y-component of the attacker's velocity toward the Defense Zone." + } + ] +} \ No newline at end of file diff --git a/tasks/earl2005/mathematical_formulation.md b/tasks/earl2005/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..cdb32c9f882b7fd1f831a3475658a1e947b581c9 --- /dev/null +++ b/tasks/earl2005/mathematical_formulation.md @@ -0,0 +1,136 @@ +# Original Formulation: Defensive Drill 1 MILP (Earl & D’Andrea, 2005) + +**Source.** M. G. Earl and R. D’Andrea, “Multi-vehicle Cooperative Control Using Mixed Integer Linear Programming,” Sections II–IV. This file transcribes the paper’s formulation for the *one-on-one* defensive drill (one defender, one attacker). For the $N_D$-on-$N_A$ case the paper states that the constraints follow a “similar trend” but are not written out explicitly, so the one-on-one form is used here. + +## Sets and Indices + +- $i \in \{1,\ldots,N_D\}$ — defenders (here $N_D = 1$). + +- $j \in \{1,\ldots,N_A\}$ — attackers (here $N_A = 1$; the index $j$ is dropped in the one-on-one case). + +- $k \in \{0,\ldots,N_u-1\}$ — defender control steps. + +- $k \in \{0,\ldots,N_a\}$ — attacker discretization steps. + +- $k \in \{1,\ldots,N_o\}$ — obstacle (Defense Zone) avoidance checks. + +- $m \in \{1,\ldots,M_u\}$ — sides of the control-input polygon. + +- $m \in \{1,\ldots,M_I\}$ — sides of the intercept-region polygon. + +- $m \in \{1,\ldots,M_{dz}\}$ — sides of the Defense Zone polygon. + +- $m \in \{1,\ldots,M_o\}$ — sides of the obstacle polygon. + +For the released benchmark instances, the executable convention is +$N_o=N_u$, $M_o=4$, the obstacle centre is the origin, and its apothem is +$R_{dz}$. The parameters $R_{dz}$ and $R_I$ below are polygon apothems, not +Euclidean-circle radii. + +## Parameters + +$T_u[k]>0$, $T_a[k]>0$ (step durations); $R_{dz}$ (Defense Zone radius); $R_{obst}$ (obstacle radius); $R_I$ (inscribed radius of intercept polygon); $H$ (big-M); $\epsilon_c>0$ (small constant for strict inequalities); $\epsilon\ge0$ (control-effort weight); $(v_{pj},v_{qj})$ (attacker constant velocity); $\mathbf{x}_{s,i}=(x_{s,i},y_{s,i},\dot x_{s,i},\dot y_{s,i})$ (defender initial state); $(p_{s,j},q_{s,j})$ (attacker initial position). Matrices $\mathbf{A}[k],\mathbf{B}[k]$ are defined in Eq. (6) of the paper from $T_u[k]$. + +## Decision Variables + +Continuous: $\mathbf{x}_{u,i}[k] = (x_i[k],y_i[k],\dot x_i[k],\dot y_i[k])$ (defender state); $\mathbf{u}_i[k] = (u_{xi}[k], u_{yi}[k])$ (defender control); $z_{xi}[k],\, z_{yi}[k] \ge 0$ (auxiliaries for $|u_{xi}[k]|,|u_{yi}[k]|$); $p_j[k],\, q_j[k]$ (attacker position). + +Binary: $a_j[k]\in\{0,1\}$ (attack mode); $\gamma_j[k]\in\{0,1\}$ ($=1$ iff attacker $j$ is inside the Defense Zone at step $k$); $g_{mj}[k]\in\{0,1\}$ (auxiliary for $\gamma_j[k]$); $\delta_{ij}[k]\in\{0,1\}$ ($=1$ iff attacker $j$ is inside intercept region of defender $i$); $d_{mij}[k]\in\{0,1\}$ (auxiliary for $\delta_{ij}[k]$); $b_{mij}[k]\in\{0,1\}$ (auxiliary for defender obstacle avoidance). + +## Objective (Eq. 44 of the paper) + +$$\begin{align} +\min\ J \;=\; \sum_{j=1}^{N_A}\sum_{k=1}^{N_a} \gamma_j[k] +\;+\; \epsilon \sum_{i=1}^{N_D}\sum_{k=0}^{N_u-1} +\bigl(z_{xi}[k] + z_{yi}[k]\bigr). \tag{44} +\end{align}$$ + +## Constraints + +#### Defender dynamics and initial condition. + +For $i\in\{1,\ldots,N_D\}$, $k\in\{0,\ldots,N_u-1\}$: $$\begin{align} +\mathbf{x}_{u,i}[k+1] \;=\; \mathbf{A}[k]\,\mathbf{x}_{u,i}[k] + + \mathbf{B}[k]\,\mathbf{u}_i[k], \qquad +\mathbf{x}_{u,i}[0] = \mathbf{x}_{s,i}. \tag{6} +\end{align}$$ + +#### Defender control-input feasibility (polygon approximation of the unit disk). + +For each $i$, $k$, $m\in\{1,\ldots,M_u\}$: $$\begin{align} +u_{xi}[k]\sin\!\tfrac{2\pi m}{M_u} + + u_{yi}[k]\cos\!\tfrac{2\pi m}{M_u} + \;\le\; \cos\!\tfrac{\pi}{M_u}. \tag{8} +\end{align}$$ + +#### Absolute value auxiliaries for control. + +For each $i$, $k$: $$\begin{align} +-z_{xi}[k] \le u_{xi}[k] \le z_{xi}[k], \tag{10a}\\ +-z_{yi}[k] \le u_{yi}[k] \le z_{yi}[k]. \tag{10b} +\end{align}$$ + +#### Attacker dynamics. + +For $j\in\{1,\ldots,N_A\}$, $k\in\{1,\ldots,N_a\}$: $$\begin{align} +p_j[k+1] &= p_j[k] + v_{pj}\,T_a[k]\,a_j[k], \tag{17a}\\ +q_j[k+1] &= q_j[k] + v_{qj}\,T_a[k]\,a_j[k]. \tag{17b} +\end{align}$$ + +#### Attacker initial conditions. + +For each $j$: $$\begin{align} +p_j[0] = p_{s,j},\quad q_j[0] = q_{s,j},\quad a_j[0] = 1. \tag{19} +\end{align}$$ + +#### Defense Zone indicator for attacker (polygon approximation). + +For each $j$, $k\in\{1,\ldots,N_a\}$, $m\in\{1,\ldots,M_{dz}\}$: $$\begin{align} +p_j[k]\sin\!\tfrac{2\pi m}{M_{dz}} + q_j[k]\cos\!\tfrac{2\pi m}{M_{dz}} + &\le R_{dz} + H(1 - g_{mj}[k]), \tag{23a}\\ +p_j[k]\sin\!\tfrac{2\pi m}{M_{dz}} + q_j[k]\cos\!\tfrac{2\pi m}{M_{dz}} + &\ge R_{dz} + \epsilon_c - (H+\epsilon_c)\,g_{mj}[k]. \tag{23b} +\end{align}$$ For each $j$, $k$ (and each $m$ in the first inequality): $$\begin{align} +g_{mj}[k] - \gamma_j[k] &\ge 0, \tag{25a}\\ +\sum_{l=1}^{M_{dz}}\bigl(1 - g_{lj}[k]\bigr) + \gamma_j[k] &\ge 1. \tag{25b} +\end{align}$$ + +#### Intercept region indicator (defender $i$ vs. attacker $j$). + +Let $(x_{a,i}[k],y_{a,i}[k])$ denote defender $i$’s position at attacker step time $t_{a,k}=\sum_{l=0}^{k-1}T_a[l]$, computed from $\mathbf{x}_{u,i}$ via Eq. (7) of the paper. For each $i$, $j$, $k\in\{1,\ldots,N_a\}$, $m\in\{1,\ldots,M_I\}$: $$\begin{align} +(p_j[k]-x_{a,i}[k])\sin\!\tfrac{2\pi m}{M_I} + + (q_j[k]-y_{a,i}[k])\cos\!\tfrac{2\pi m}{M_I} + &\le R_I + H(1 - d_{mij}[k]), \tag{29a}\\ +(p_j[k]-x_{a,i}[k])\sin\!\tfrac{2\pi m}{M_I} + + (q_j[k]-y_{a,i}[k])\cos\!\tfrac{2\pi m}{M_I} + &\ge R_I + \epsilon_c - (H+\epsilon_c)\,d_{mij}[k]. \tag{29b} +\end{align}$$ For each $i$, $j$, $k$ (and each $m$ in the first): $$\begin{align} +d_{mij}[k] - \delta_{ij}[k] &\ge 0, \tag{31a}\\ +\sum_{l=1}^{M_I}\bigl(1 - d_{lij}[k]\bigr) + \delta_{ij}[k] &\ge 1. \tag{31b} +\end{align}$$ + +#### Attacker state machine (one-on-one, Eq. 34). + +For $k\in\{1,\ldots,N_a\}$: $$\begin{align} +a[k+1] + \delta[k] &\le 1, \tag{34a}\\ +a[k+1] - a[k] &\le 0, \tag{34b}\\ +a[k+1] + \gamma[k] &\le 1, \tag{34c}\\ +a[k] - \delta[k] - \gamma[k] - a[k+1] &\le 0. \tag{34d} +\end{align}$$ For the $N_D$-on-$N_A$ case the paper states that (34) is extended “in a similar way,” without writing the generalization explicitly. + +#### Defender obstacle (Defense Zone) avoidance. + +Let $(x_{o,i}[k],y_{o,i}[k])$ denote defender $i$’s position at obstacle check time $t_o[k]$ (from Eq. (7) of the paper), and $(x_{obst}[k],y_{obst}[k])$ the obstacle centre (taken as $(0,0)$ for the stationary Defense Zone). For each $i$, $k\in\{1,\ldots,N_o\}$, $m\in\{1,\ldots,M_o\}$: $$\begin{align} +(x_{o,i}[k]-x_{obst}[k])\sin\!\tfrac{2\pi m}{M_o} + + (y_{o,i}[k]-y_{obst}[k])\cos\!\tfrac{2\pi m}{M_o} + &\;>\; R_{obst} - H\,b_{mij}[k], \tag{14}\\ +\sum_{m=1}^{M_o} b_{mij}[k] &\;\le\; M_o - 1. \tag{15} +\end{align}$$ + +## Variable Domains + +$$\begin{align*} +& \mathbf{x}_{u,i}[k]\in\mathbb{R}^4,\ \mathbf{u}_i[k]\in\mathbb{R}^2,\ + z_{xi}[k],z_{yi}[k]\ge 0,\ (p_j[k],q_j[k])\in\mathbb{R}^2,\\ +& a_j[k],\gamma_j[k],g_{mj}[k],\delta_{ij}[k],d_{mij}[k],b_{mij}[k]\in\{0,1\}. +\end{align*}$$ diff --git a/tasks/earl2005/problem_description.txt b/tasks/earl2005/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..cbbda350f80d945e8fca002c8abfaea894dc5330 --- /dev/null +++ b/tasks/earl2005/problem_description.txt @@ -0,0 +1,15 @@ +# Problem Description + +A team of defending robots and a team of attacking robots operate on a two-dimensional playing field with a regular-polygon Defense Zone centered at the origin. Its M_dz side half-spaces have apothem R_dz. There are N_D defenders and N_A attackers. Each attacker moves in a straight line toward the Defense Zone at a constant velocity. Each defender is governed by linear discrete-time dynamics and is steered by choosing control inputs at each time step. The objective is to find a control-input sequence for every defender that minimizes the number of time steps during which attackers occupy the Defense Zone, with an optional small penalty on the defenders' cumulative control effort. + +Time is discretized. Defenders take N_u control steps at a uniform interval T_u, and attackers are tracked at N_a sample steps at a uniform interval T_a. Each defender has a two-dimensional position and two-dimensional velocity. Between consecutive control steps the defender's state evolves linearly according to the following first-order dynamics: the velocity decays toward the applied control input exponentially with time constant one, and the position is the integral of that velocity. Concretely, the next-step velocity in each coordinate equals the current velocity times exp(−T_u) plus the control input times (1 − exp(−T_u)), and the next-step position in each coordinate equals the current position plus the current velocity times (1 − exp(−T_u)) plus the control input times (T_u − 1 + exp(−T_u)). Each defender's initial position and velocity are given. + +Each defender's control input at every step is a two-component vector lying in the M_u-side regular polygon inscribed in the unit disk, using half-space right-hand side cos(pi/M_u). Each attacker moves at constant velocity while active: its position at the next sample step equals its current position plus its velocity times T_a. An attacker becomes inactive (and stops moving thereafter) as soon as it either enters the Defense Zone or is intercepted by at least one defender. + +An attacker is considered inside the Defense Zone at a given step if its position satisfies every one of the M_dz polygon half-spaces. An attacker is considered intercepted by a defender at the attacker's sample time if its relative position satisfies every one of the M_I regular-polygon half-spaces with apothem R_I, centered at the defender's interpolated position (linearly interpolated from the surrounding control-step states and inputs). + +Defender avoidance is enforced at the N_o=N_u positive control-step boundaries, as used by the released MILP. At every such boundary, each defender must lie outside at least one half-space of the four-side obstacle polygon centered at the origin with apothem R_dz. + +The objective to minimize is the total number of attacker-time-step pairs during which the attacker occupies the Defense Zone (summed over all attackers and all sample steps from 1 through N_a), plus a non-negative weight epsilon times the total control effort (summed over defenders, control steps, and control coordinates, with effort measured as the sum of absolute values of control components). The weight epsilon is zero when only zone penetration is penalized, or a small positive number (such as 0.1) when fuel conservation is an additional secondary goal. + +The input data for an instance specifies: the number of defenders N_D and attackers N_A; the polygon apothems R_dz and R_I and side counts M_u, M_I, and M_dz; the discretization step counts N_u and N_a (with obstacle checks defined as N_o=N_u); the uniform time steps T_u and T_a; the cost weight epsilon; for each defender its initial position and velocity in two dimensions; and for each attacker its initial position and constant velocity vector in two dimensions. diff --git a/tasks/earl2005/solution_logger.py b/tasks/earl2005/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/earl2005/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/earl2005/solution_schema.json b/tasks/earl2005/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3ab5784e50b99c42a88360f43eea95fa53b7ca26 --- /dev/null +++ b/tasks/earl2005/solution_schema.json @@ -0,0 +1,22 @@ +{ + "objective_value": " Total number of time steps any attacker occupies the Defense Zone, plus the weighted cumulative control effort of all defenders.", + "defenders": [ + { + "x": " X-coordinate of the defender's position at each control step.", + "y": " Y-coordinate of the defender's position at each control step.", + "xdot": " X-component of the defender's velocity at each control step.", + "ydot": " Y-component of the defender's velocity at each control step.", + "ux": " X-component of the defender's control input at each control step.", + "uy": " Y-component of the defender's control input at each control step." + } + ], + "attackers": [ + { + "p": " X-coordinate of the attacker's position at each sample step.", + "q": " Y-coordinate of the attacker's position at each sample step.", + "a": " Whether the attacker is in attack mode at each sample step (1 = attacking, 0 = inactive).", + "gamma": " Whether the attacker is inside the Defense Zone at each sample step (1 = inside, 0 = outside).", + "delta": " Per-defender interception indicator at each sample step; delta[i][k] = 1 iff defender i intercepts this attacker at step k, else 0." + } + ] +} \ No newline at end of file diff --git a/tasks/eiselt2009/feasibility_check.py b/tasks/eiselt2009/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..543496e5f3b8c153e3700a1075dadcc06ab0fbf1 --- /dev/null +++ b/tasks/eiselt2009/feasibility_check.py @@ -0,0 +1,500 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Competitive p-Hub Location Problem +with Attraction Functions. + +Reference: Eiselt & Marianov, Computers & Operations Research 36 (2009) 3128-3135. + +Original solution structure (per solution_schema.json): + { "objective_value": , "hub_locations": } + +The original problem decision is "which p nodes to open as hubs". The +auxiliary variables w_{kl} (Eqs 4-5) are a McCormick-style linearization +of the bilinear term y_k * y_l and are not part of the original solution +structure: given hub_locations, w_{kl} is fully determined as +1[k in hubs] * 1[l in hubs]. Reconstructing w from hub_locations would +make Eqs (4), (5), and the w-portion of Eq (7) vacuously satisfied, so +those reformulation artifacts are not verified here. + +The original problem's hard constraints reduce to: + Constraint 3 (Eq 6): sum_k y_k = p + Constraint 4 (Eq 7, y portion): y_k in {0, 1}, i.e. hub_locations is a + set of distinct integers in [0, n-1]. + + Constraint 5 (objective consistency -- Tier C defense): the reported + objective_value must lie inside the feasible objective + envelope [obj_min, obj_max] implied by hub_locations. + See the envelope derivation below. + +------------------------------------------------------------------------ +Constraint 5 -- objective-consistency (envelope) check +------------------------------------------------------------------------ +The eval pipeline trusts the program's self-reported objective_value. +LLM-evolved candidates can exploit this by fabricating an objective that +passes the constraint check but lies about the captured demand. This +check recomputes the objective range from hub_locations and rejects a +reported value outside it. + +The objective (Eq 3) is + z = sum_{i,j} h_ij * N_ij / (N_ij + C_ij) +where N_ij is the entering airline's total route utility and C_ij the +fixed competitor utility. N_ij has two parts: + * 1-hub routes (k == l): ALWAYS active for every open hub -- there is + no w-style toggle for them (the market-share constraint uses y_k + directly). They contribute N1_ij. + * 2-hub routes (k < l): active only when w_{kl} = 1, and w_{kl} is a + free variable bounded by w_{kl} <= min(y_k, y_l). They contribute + at most N2_ij (all hub pairs activated) and at least 0. + +z is monotone increasing in N_ij, so for a fixed hub set the feasible +objective range of model P is exactly + obj_min = sum_{i,j} h_ij * N1_ij / (N1_ij + C_ij) (all w = 0) + obj_max = sum_{i,j} h_ij * (N1_ij+N2_ij) / (N1_ij+N2_ij+C_ij) (all w = 1) +Any feasible (y, w) of model P -- including Gurobi time-limit incumbents +that did not fully activate w -- yields an objective inside this exact +envelope. A reported value outside [obj_min, obj_max] (beyond a small +relative margin that absorbs benign formula-interpretation differences) +is provably inconsistent with the reported hub_locations. + +The utility / travel-time / fare formulas below mirror gurobi_code.py +(the canonical reference implementation) exactly. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('hub_locations', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + +# Constraint 5 (objective consistency). ``w`` is intentionally not part of +# the published solution, so validate the reported objective against every +# discrete completion of those omitted hub-pair variables instead of accepting +# the entire continuous [min,max] interval. +OBJ_ABS_TOL = 1e-3 +OBJ_REL_TOL = 1e-8 + + +def objective_candidates(inst, hub_locations): + """ + Recompute every objective attainable by a binary completion of the omitted + two-hub activation variables for the given hub set. + + The dataset has at most five selected hubs (ten pair variables, 1024 + completions). A defensive cap prevents adversarial inputs from turning + this exact validation into an exponential resource attack. + """ + n = inst['n_nodes'] + nodes = inst['nodes'] + dist = inst['distance_matrix'] + demand = inst['demand_matrix'] + params = inst['parameters'] + + alpha = params['alpha'] # interhub fare discount factor + gamma = params['gamma'] # time vs. cost trade-off weight + beta = params['beta'] # time decay exponent + lam = params['lambda'] # cost decay exponent + c_sc = params['cost_scalar'] # fare proportionality constant + A_2 = params['attractiveness_2hub'] + A_1 = params['attractiveness_1hub'] # 25% higher than A_2 per paper + + comp = inst['competitor_hub_locations'] + + hubs = sorted(set(int(h) for h in hub_locations)) + if not hubs: + return None + if any(h < 0 or h >= n for h in hubs): + return None + if any(int(m) < 0 or int(m) >= n for m in comp): + return None + + def utility(t_val, c_val, A): + """Gravity utility: A / (gamma*t^beta + (1-gamma)*c^lambda) [Eq. (1)]""" + denom = gamma * (t_val ** beta) + (1.0 - gamma) * (c_val ** lam) + if denom <= 0.0: + return 0.0 + return A / denom + + def t_2hub(i, k, l, j): + return (dist[i][k] + dist[k][l] + dist[l][j] + + nodes[i]['waiting_time'] + + nodes[k]['waiting_time'] + + nodes[l]['waiting_time']) + + def c_2hub(i, k, l, j): + return c_sc * (dist[i][k] + alpha * dist[k][l] + dist[l][j]) + + def t_1hub(i, k, j): + return (dist[i][k] + dist[k][j] + + nodes[i]['waiting_time'] + + nodes[k]['waiting_time']) + + def c_1hub(i, k, j): + return c_sc * (dist[i][k] + dist[k][j]) + + comp = [int(m) for m in comp] + comp_pairs = [(m, q) for m in comp for q in comp if m <= q] + + selected_pairs = [ + (hubs[a], hubs[b]) + for a in range(len(hubs)) + for b in range(a + 1, len(hubs)) + ] + if len(selected_pairs) > 20: + return None + totals = [0.0] * (1 << len(selected_pairs)) + for i in range(n): + for j in range(n): + h = demand[i][j] + if h <= 0: + continue + # N1: 1-hub routes -- always active for every open hub. + n1 = 0.0 + for k in hubs: + n1 += utility(t_1hub(i, k, j), c_1hub(i, k, j), A_1) + # N2 contribution of each omitted binary hub-pair variable. + pair_utility = [] + for k, l in selected_pairs: + u1 = utility(t_2hub(i, k, l, j), c_2hub(i, k, l, j), A_2) + u2 = utility(t_2hub(i, l, k, j), c_2hub(i, l, k, j), A_2) + pair_utility.append(max(u1, u2)) + # C: fixed competitor utility. + c_ij = 0.0 + for (m, q) in comp_pairs: + if m == q: + c_ij += utility(t_1hub(i, m, j), c_1hub(i, m, j), A_1) + else: + u1 = utility(t_2hub(i, m, q, j), c_2hub(i, m, q, j), A_2) + u2 = utility(t_2hub(i, q, m, j), c_2hub(i, q, m, j), A_2) + c_ij += max(u1, u2) + for mask in range(len(totals)): + own_utility = n1 + sum( + pair_utility[pair_idx] + for pair_idx in range(len(pair_utility)) + if mask & (1 << pair_idx) + ) + denom = own_utility + c_ij + if denom > 0.0: + totals[mask] += h * own_utility / denom + return totals + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Competitive p-Hub Location" + ) + parser.add_argument("--instance_path", required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + with open(args.instance_path) as f: + inst = json.load(f) + with open(args.solution_path) as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + n = inst['n_nodes'] + p = inst['p'] + hub_locations = sol.get('hub_locations', []) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------ + # Constraint 3 (Eq 6): sum_k y_k = p + # In original solution structure: |hub_locations| = p + # ------------------------------------------------------------------ + lhs_val = float(len(hub_locations)) + rhs_val = float(p) + excess = abs(lhs_val - rhs_val) + if excess > TOL: + violated_constraints.add(3) + normalizer = max(abs(rhs_val), EPS) + violations.append( + f"Constraint 3 violated: |hub_locations|={int(lhs_val)} != p={int(rhs_val)}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": float(excess), + "normalizer": float(normalizer), + "ratio": float(excess / normalizer) + }) + + # ------------------------------------------------------------------ + # Constraint 4 (Eq 7, y portion + domain): hub_locations entries are + # distinct integers in [0, n-1]. This is the original-structure + # restatement of y_k in {0, 1}. + # ------------------------------------------------------------------ + # Out-of-range entries. + for h in hub_locations: + if not isinstance(h, int) or h < 0 or h >= n: + violated_constraints.add(4) + violations.append( + f"Constraint 4 violated: hub entry {h!r} not an integer in [0, {n - 1}]" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(h) if isinstance(h, (int, float)) else 0.0, + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + + # Duplicate hubs. + if len(hub_locations) != len(set(hub_locations)): + dup_count = len(hub_locations) - len(set(hub_locations)) + violated_constraints.add(4) + violations.append( + f"Constraint 4 violated: hub_locations has {dup_count} duplicate entries" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(len(hub_locations)), + "rhs": float(len(set(hub_locations))), + "raw_excess": float(dup_count), + "normalizer": max(float(len(set(hub_locations))), EPS), + "ratio": dup_count / max(float(len(set(hub_locations))), EPS), + }) + + # ------------------------------------------------------------------ + # Constraint 5 (objective consistency): because the output omits the binary + # pair activations w, existentially complete them and require the reported + # value to match one of the finitely many attainable objectives. Merely + # checking the min/max envelope admitted values that no model solution can + # produce. + # ------------------------------------------------------------------ + reported_obj = sol.get('objective_value') + reported = None + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + + hubs_indexable = ( + len(hub_locations) > 0 + and all(isinstance(h, int) and 0 <= h < n for h in hub_locations) + ) + + if reported is not None and hubs_indexable: + candidates = None + try: + candidates = objective_candidates(inst, hub_locations) + except Exception: + candidates = None + + if candidates: + expected = min(candidates, key=lambda value: abs(reported - value)) + difference = abs(reported - expected) + obj_tol = max(OBJ_ABS_TOL, OBJ_REL_TOL * max(abs(expected), 1.0)) + if difference > obj_tol: + normalizer = max(abs(expected), EPS) + violated_constraints.add(5) + violations.append( + f"Constraint 5 violated: reported objective_value={reported} " + f"does not match any of the {len(candidates)} discrete " + f"hub-pair completions for hub_locations=" + f"{sorted(hub_locations)}; nearest={expected}, " + f"difference={difference:.6g}, tolerance={obj_tol:.6g}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": float(reported), + "rhs": float(expected), + "raw_excess": float(difference), + "normalizer": float(normalizer), + "ratio": float(difference / normalizer), + }) + elif hubs_indexable: + violated_constraints.add(5) + violations.append( + "Constraint 5 could not enumerate the omitted hub-pair " + "variables within the checker resource limit" + ) + violation_magnitudes.append({ + "constraint": 5, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if feasible else "INFEASIBLE" + print(f"Result: {status}") + if not feasible: + print(f"Violated constraints: {sorted(violated_constraints)}") + for v in violations: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/eiselt2009/gurobi_code.py b/tasks/eiselt2009/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfe5651e2ef27bdf8c3d1390eba471fa9f87633 --- /dev/null +++ b/tasks/eiselt2009/gurobi_code.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Competitive p-Hub Location Problem with Attraction Functions. + +Reference: Eiselt & Marianov, "A conditional p-hub location problem with attraction +functions," Computers & Operations Research 36 (2009) 3128-3135. + +Mathematical Model P [Eqs. (3)-(7)]: + Maximize z = sum_{i,j} h_ij * sum_{k,l in Own} w_kl * u_ijklo / + (sum_{m,n in Own} w_mn * u_ijmno + sum_{s!=o} sum_{m,n in Comp} u_ijmns) + + s.t. w_kl <= y_k for all k, l in Own (4) + w_kl <= y_l for all k, l in Own (5) + sum_k y_k = p (6) + y_k, w_kl in {0,1} (7) + +The objective is a sum-of-ratios nonlinear function. Because the paper states it +"precludes using standard integer programming software," this implementation reformulates +it as a Mixed Integer Linear Program (MILP) using McCormick linearization. + +Reformulation idea: + Define r_ij = h_ij * N_ij / D_ij (captured demand for OD pair ij), where + N_ij = sum_{active pairs (k,l)} u_ijklo (own utility numerator) + D_ij = N_ij + C_ij (full denominator) + C_ij = sum_{competitor pairs} u_ijmns (fixed competitor term) + Then r_ij * D_ij = h_ij * N_ij. + Introducing x_{ij,kl} = r_ij * w_kl (continuous × binary) and applying McCormick + envelopes, this becomes a linear constraint, yielding an exact MILP. +""" + +import argparse +import json +import math +import itertools + +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 + + +# --------------------------------------------------------------------------- +# Data loading +# --------------------------------------------------------------------------- + +def load_instance(path: str) -> dict: + with open(path) as f: + return json.load(f) + + +# --------------------------------------------------------------------------- +# Utility computation +# --------------------------------------------------------------------------- + +def compute_utilities(inst: dict): + """ + Pre-compute: + u_own[(i, j, k, l)] : best-direction utility for entering airline on unordered + hub pair (k, l), k <= l, for OD pair (i, j). + C_ij[(i, j)] : total competitor utility (fixed denominator term) for (i, j). + + Returns (u_own, C_ij, Own, own_pairs_1hub, own_pairs_2hub) + """ + n = inst['n_nodes'] + nodes = inst['nodes'] + dist = inst['distance_matrix'] + params = inst['parameters'] + + alpha = params['alpha'] # interhub fare discount factor + gamma = params['gamma'] # time vs. cost trade-off weight + beta = params['beta'] # time decay exponent + lam = params['lambda'] # cost decay exponent + c_sc = params['cost_scalar'] # fare proportionality constant + A_2 = params['attractiveness_2hub'] + A_1 = params['attractiveness_1hub'] # 25% higher than A_2 per paper + + Own = list(range(n)) + Comp = inst['competitor_hub_locations'] + + def utility(t_val: float, c_val: float, A: float) -> float: + """Gravity utility: A / (gamma * t^beta + (1-gamma) * c^lambda) [Eq. (1)]""" + denom = gamma * (t_val ** beta) + (1.0 - gamma) * (c_val ** lam) + if denom <= 0.0: + return 0.0 + return A / denom + + def t_2hub(i: int, k: int, l: int, j: int) -> float: + """ + Travel time for 2-hub route i -> k -> l -> j. + Formula from paper Section 3: + t_ik + t_kl + t_lj + wait_i + wait_k + wait_l + """ + return (dist[i][k] + dist[k][l] + dist[l][j] + + nodes[i]['waiting_time'] + + nodes[k]['waiting_time'] + + nodes[l]['waiting_time']) + + def c_2hub(i: int, k: int, l: int, j: int) -> float: + """ + Travel cost for 2-hub route i -> k -> l -> j. + Formula from paper: c * (t_ik + alpha * t_kl + t_lj) + where costs are proportional to distances. + """ + return c_sc * (dist[i][k] + alpha * dist[k][l] + dist[l][j]) + + # INFERRED ASSUMPTION: For 1-hub routes (k = l), the travel time uses only one + # hub waiting time (physically, the passenger stops at hub k once). The paper + # gives the general formula t = t_ik + t_kl + t_lj + wait_i + wait_k + wait_l; + # for k = l, t_kk = 0 and mechanically this gives wait_i + 2*wait_k, but that + # double-counts the single hub dwell. We therefore use: + # t_1hub = t_ik + t_kj + wait_i + wait_k + # and c_1hub = c * (t_ik + t_kj) (no interhub leg => no alpha discount). + def t_1hub(i: int, k: int, j: int) -> float: + return (dist[i][k] + dist[k][j] + + nodes[i]['waiting_time'] + + nodes[k]['waiting_time']) + + def c_1hub(i: int, k: int, j: int) -> float: + return c_sc * (dist[i][k] + dist[k][j]) + + # ------------------------------------------------------------------ + # Build own-airline utility table (unordered pairs k <= l) + # ------------------------------------------------------------------ + own_pairs_1hub = [(k, k) for k in Own] + own_pairs_2hub = [(k, l) for k in Own for l in Own if k < l] + all_own_pairs = own_pairs_1hub + own_pairs_2hub + + u_own = {} + for i in range(n): + for j in range(n): + for (k, l) in all_own_pairs: + if k == l: + u = utility(t_1hub(i, k, j), c_1hub(i, k, j), A_1) + else: + # Take best direction between i-k-l-j and i-l-k-j [paper Section 3] + u1 = utility(t_2hub(i, k, l, j), c_2hub(i, k, l, j), A_2) + u2 = utility(t_2hub(i, l, k, j), c_2hub(i, l, k, j), A_2) + u = max(u1, u2) + u_own[(i, j, k, l)] = u + + # ------------------------------------------------------------------ + # Build competitor fixed utility C_ij + # Competitor uses hubs in Comp; all unordered pairs (m,n) with m<=n + # ------------------------------------------------------------------ + comp_pairs = [(m, q) for m in Comp for q in Comp if m <= q] + + C_ij = {} + for i in range(n): + for j in range(n): + total = 0.0 + for (m, q) in comp_pairs: + if m == q: + total += utility(t_1hub(i, m, j), c_1hub(i, m, j), A_1) + else: + u1 = utility(t_2hub(i, m, q, j), c_2hub(i, m, q, j), A_2) + u2 = utility(t_2hub(i, q, m, j), c_2hub(i, q, m, j), A_2) + total += max(u1, u2) + C_ij[(i, j)] = total + + return u_own, C_ij, Own, own_pairs_1hub, own_pairs_2hub + + +# --------------------------------------------------------------------------- +# Gurobi model +# --------------------------------------------------------------------------- + +def build_and_solve(inst: dict, time_limit: int) -> dict: + n = inst['n_nodes'] + p = inst['p'] + demand = inst['demand_matrix'] + + u_own, C_ij, Own, pairs_1hub, pairs_2hub = compute_utilities(inst) + + # OD pairs with positive demand (others contribute 0 to objective) + od_pairs = [(i, j) for i in range(n) for j in range(n) if demand[i][j] > 0] + + model = gp.Model("CompetitiveHubLocation") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + + # ------------------------------------------------------------------ + # Binary decision variables + # y[k] = 1 if hub opened at node k + # w[k, l] = 1 if hubs at both k and l (k < l, 2-hub pairs only) + # For 1-hub pairs: w_kk = y_k (handled directly) + # ------------------------------------------------------------------ + y = model.addVars(Own, vtype=GRB.BINARY, name="y") + w = {} + for (k, l) in pairs_2hub: + w[k, l] = model.addVar(vtype=GRB.BINARY, name=f"w_{k}_{l}") + model.update() + + # Hub-pair activation constraints [Eqs. (4) and (5)] + for (k, l) in pairs_2hub: + model.addConstr(w[k, l] <= y[k], name=f"wle_k_{k}_{l}") + model.addConstr(w[k, l] <= y[l], name=f"wle_l_{k}_{l}") + + # Number of hubs constraint [Eq. (6)] + model.addConstr(gp.quicksum(y[k] for k in Own) == p, name="num_hubs") + + # ------------------------------------------------------------------ + # Continuous variables + # r[i, j] = captured demand for OD pair (i, j) + # By linearization: r_ij = h_ij * N_ij / D_ij + # x1[i, j, k] = McCormick product r[i,j] * y[k] (1-hub routes) + # x2[i, j, k, l] = McCormick product r[i,j] * w[k,l] (2-hub routes) + # ------------------------------------------------------------------ + r = {} + x1 = {} + x2 = {} + for (i, j) in od_pairs: + hij = float(demand[i][j]) + r[i, j] = model.addVar(lb=0.0, ub=hij, name=f"r_{i}_{j}") + for k in Own: + x1[i, j, k] = model.addVar(lb=0.0, ub=hij, name=f"x1_{i}_{j}_{k}") + for (k, l) in pairs_2hub: + x2[i, j, k, l] = model.addVar(lb=0.0, ub=hij, name=f"x2_{i}_{j}_{k}_{l}") + model.update() + + # ------------------------------------------------------------------ + # McCormick envelopes for x1[i,j,k] = r[i,j] * y[k] + # Valid because y[k] is binary and 0 <= r[i,j] <= h_ij: + # (a) x1 <= h_ij * y[k] (x1=0 when y[k]=0) + # (b) x1 >= r - h_ij*(1 - y[k]) (x1=r when y[k]=1) + # (c) x1 <= r (x1 <= r always) + # ------------------------------------------------------------------ + for (i, j) in od_pairs: + hij = float(demand[i][j]) + for k in Own: + model.addConstr(x1[i, j, k] <= hij * y[k]) + model.addConstr(x1[i, j, k] >= r[i, j] - hij * (1.0 - y[k])) + model.addConstr(x1[i, j, k] <= r[i, j]) + + # McCormick envelopes for x2[i,j,k,l] = r[i,j] * w[k,l] + for (i, j) in od_pairs: + hij = float(demand[i][j]) + for (k, l) in pairs_2hub: + model.addConstr(x2[i, j, k, l] <= hij * w[k, l]) + model.addConstr(x2[i, j, k, l] >= r[i, j] - hij * (1.0 - w[k, l])) + model.addConstr(x2[i, j, k, l] <= r[i, j]) + + # ------------------------------------------------------------------ + # Market-share equality constraint for each OD pair: + # + # r_ij * D_ij = h_ij * N_ij + # + # Linearized (using x1/x2 as McCormick products of r with hub indicators): + # + # sum_{k in Own} x1[i,j,k] * u_own[i,j,k,k] + # + sum_{(k,l) 2hub} x2[i,j,k,l] * u_own[i,j,k,l] + # + r[i,j] * C_ij + # = + # sum_{k in Own} y[k] * h_ij * u_own[i,j,k,k] + # + sum_{(k,l) 2hub} w[k,l] * h_ij * u_own[i,j,k,l] + # + # Proof: when hub indicator = 1, x = r, so LHS becomes r*(N+C) = r*D; + # RHS = h*N; hence r = h*N/D. + # ------------------------------------------------------------------ + for (i, j) in od_pairs: + hij = float(demand[i][j]) + c_ij = C_ij[(i, j)] + + lhs = gp.LinExpr() + rhs = gp.LinExpr() + + for k in Own: + u = u_own[(i, j, k, k)] + lhs += x1[i, j, k] * u + rhs += y[k] * (hij * u) + + for (k, l) in pairs_2hub: + u = u_own[(i, j, k, l)] + lhs += x2[i, j, k, l] * u + rhs += w[k, l] * (hij * u) + + lhs += r[i, j] * c_ij + + model.addConstr(lhs == rhs, name=f"mkt_{i}_{j}") + + # ------------------------------------------------------------------ + # Objective: maximize total captured passenger demand [Eq. (3)] + # ------------------------------------------------------------------ + model.setObjective( + gp.quicksum(r[i, j] for (i, j) in od_pairs), + GRB.MAXIMIZE + ) + + model.optimize() + + # ------------------------------------------------------------------ + # Extract solution + # ------------------------------------------------------------------ + result = { + "objective_value": None, + "hub_locations": [], + "status": "no_solution" + } + + if model.SolCount > 0: + hub_locs = [k for k in Own if y[k].X > 0.5] + result["objective_value"] = model.ObjVal + result["hub_locations"] = hub_locs + if model.status == GRB.OPTIMAL: + result["status"] = "optimal" + elif model.status == GRB.TIME_LIMIT: + result["status"] = "time_limit" + else: + result["status"] = "suboptimal" + elif model.status == GRB.INFEASIBLE: + result["status"] = "infeasible" + + return result + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Competitive Hub Location Problem – Gurobi MILP Solver" + ) + parser.add_argument("--instance_path", required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", required=True, + help="Path to write the solution JSON (e.g. gurobi_solution_1.json).") + parser.add_argument("--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + inst = load_instance(args.instance_path) + result = build_and_solve(inst, 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"Status : {result['status']}") + print(f"Hub locations : {result['hub_locations']}") + print(f"Objective value : {result['objective_value']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/eiselt2009/gurobi_feasi_result/large_feasi_result_1.json b/tasks/eiselt2009/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/eiselt2009/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/eiselt2009/gurobi_feasi_result/large_feasi_result_2.json b/tasks/eiselt2009/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/eiselt2009/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/eiselt2009/gurobi_feasi_result/large_feasi_result_3.json b/tasks/eiselt2009/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/eiselt2009/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/eiselt2009/gurobi_feasi_result/large_feasi_result_4.json b/tasks/eiselt2009/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/eiselt2009/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/eiselt2009/gurobi_feasi_result/large_feasi_result_5.json b/tasks/eiselt2009/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/eiselt2009/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/eiselt2009/gurobi_feasi_result/tiny_feasi_result.json b/tasks/eiselt2009/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/eiselt2009/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/eiselt2009/gurobi_solution/large_solution_1.json b/tasks/eiselt2009/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..1cc564da959de9dc5ae9eeb4eb3086520e2ae212 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5753dbf8e47c522a4513dfeb3971090b5dc762eb75040efe4e8be8cde6137d92 +size 155 diff --git a/tasks/eiselt2009/gurobi_solution/large_solution_2.json b/tasks/eiselt2009/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..84ff6d323f0ccb6504cf6529379b4c2af00c4b79 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3f734f6185875d9fdc02720fef7950b6bd6fc1af195caf37becfd675a2b32b5 +size 152 diff --git a/tasks/eiselt2009/gurobi_solution/large_solution_3.json b/tasks/eiselt2009/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..42f34fbe293fe7b1f1439e327b0493b2afc3efe5 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30f519148551e4330c001bf484431096bea4c1ad5d3687fe95fe92e01a9dc705 +size 153 diff --git a/tasks/eiselt2009/gurobi_solution/large_solution_4.json b/tasks/eiselt2009/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..58cef549324ce61e699fae61faabaeee0a878ae6 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06b98d901ba83efbc6546f30bbabe33fb33c760a913c027c4c8ecc35ed4e95d7 +size 154 diff --git a/tasks/eiselt2009/gurobi_solution/large_solution_5.json b/tasks/eiselt2009/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f2b1cd0feada60f8714ded47226d7ac42dbf9032 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12d125b0a30e1dead6d0e88c639dced652927a579bbf433f46a29e623167aca7 +size 154 diff --git a/tasks/eiselt2009/gurobi_solution/tiny_solution.json b/tasks/eiselt2009/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..c35aba775de96dc6e81fb41536aa8fa5dd533b44 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16cfdd4411b117edb8ada16e26dfe12a6d3cfd3fcc026ade1ce438d173c77eca +size 126 diff --git a/tasks/eiselt2009/gurobi_solution_log/large_log_1.jsonl b/tasks/eiselt2009/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8c4caec5d2ca4f9884be76574f9a84e56038fdbd --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8a963467cac967f65cc501d976343f9b86448b18d11f767df16a3678d961721 +size 116 diff --git a/tasks/eiselt2009/gurobi_solution_log/large_log_2.jsonl b/tasks/eiselt2009/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..89745f7e3fd589662cc524606eb6daf8d80b40fe --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9523c5b7bf2e9abf9c8ab29d36992ff1114eb676cf9e5d560ab832d0a3b5510 +size 58 diff --git a/tasks/eiselt2009/gurobi_solution_log/large_log_3.jsonl b/tasks/eiselt2009/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/eiselt2009/gurobi_solution_log/large_log_4.jsonl b/tasks/eiselt2009/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/eiselt2009/gurobi_solution_log/large_log_5.jsonl b/tasks/eiselt2009/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..389c4ff0d9c9ecdfaa496e1ea815deb9ce817b57 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55e6211702d93fc36744524dc888cabbb8b441170d7c0bc37762402de16f6112 +size 58 diff --git a/tasks/eiselt2009/gurobi_solution_log/tiny_log.jsonl b/tasks/eiselt2009/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..122572ef7352d1d209ab691584c03b75cfde2bf3 --- /dev/null +++ b/tasks/eiselt2009/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:700351d9b0e1e5723cf41fbe2eba7172f1427e4ddab64393498f91916e636524 +size 45 diff --git a/tasks/eiselt2009/instance/large_instance_1.json b/tasks/eiselt2009/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..831634a0667dc704428b775f80e6b61df00bb293 --- /dev/null +++ b/tasks/eiselt2009/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:daf1df464443f9a6efa7ab924fa7fa45f979790cf4b65b6ee4b20835b832fad5 +size 22182 diff --git a/tasks/eiselt2009/instance/large_instance_2.json b/tasks/eiselt2009/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..abc26b6cfb473918661a1e63c75819b8cd37984d --- /dev/null +++ b/tasks/eiselt2009/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c55617439799e23db8d6f36ffef6f42797c32ffde11af8df17f9d8f9d57e0b8 +size 22219 diff --git a/tasks/eiselt2009/instance/large_instance_3.json b/tasks/eiselt2009/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c549bf9a8a4349492cce101a03bf26172e44fb9c --- /dev/null +++ b/tasks/eiselt2009/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8c1a665fc1a74087c63efd82c34f25e0f7ddce9ad17d60f0306dae23285c51f +size 22205 diff --git a/tasks/eiselt2009/instance/large_instance_4.json b/tasks/eiselt2009/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ad278859937c9466b793567b9dcb3bb9a29d1e45 --- /dev/null +++ b/tasks/eiselt2009/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13fc4f5d18829a0f0c56efde95d0a415d91b33001a210f063c51749079be92da +size 22174 diff --git a/tasks/eiselt2009/instance/large_instance_5.json b/tasks/eiselt2009/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..400bffb34e0198bdb14c173aac648463bad3e732 --- /dev/null +++ b/tasks/eiselt2009/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:072e4318c21d7e298f3771c46b2c8214ddd00a4ade175c75c9a7dcae427a242e +size 22219 diff --git a/tasks/eiselt2009/instance/tiny_instance.json b/tasks/eiselt2009/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..7a37b14b801074f3d2beaeccab8578adc195ae20 --- /dev/null +++ b/tasks/eiselt2009/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e5b69740d6531016effea751178c16f40f04cb773d92284b9a71a204f67a4ff +size 4807 diff --git a/tasks/eiselt2009/instance_schema.json b/tasks/eiselt2009/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8711fd422b29a8f44ccacbc1788352062eff17e9 --- /dev/null +++ b/tasks/eiselt2009/instance_schema.json @@ -0,0 +1,25 @@ +{ + "n_nodes": " Total number of cities in the air transportation network, each serving as an origin, destination, and candidate hub location.", + "p": " Number of hubs the entering airline must open.", + "r": " Number of hubs operated by the competing incumbent airline.", + "nodes": [ + { + "id": " Zero-based identifier of the city.", + "x": " Horizontal spatial coordinate of the city.", + "y": " Vertical spatial coordinate of the city.", + "waiting_time": " Fixed layover delay passengers experience at this city's airport." + } + ], + "demand_matrix": " Number of passengers wishing to travel from each origin city to each destination city.", + "distance_matrix": " Euclidean distance between each pair of cities.", + "competitor_hub_locations": " Node identifiers of the incumbent airline's fixed hub airports.", + "parameters": { + "alpha": " Discount factor applied to the fare on the hub-to-hub leg of a two-hub route, reflecting economies of scale.", + "gamma": " Weight controlling how much passengers value travel time relative to fare when choosing a route.", + "beta": " Exponent governing how steeply route attractiveness decays with increasing travel time.", + "lambda": " Exponent governing how steeply route attractiveness decays with increasing fare.", + "cost_scalar": " Proportionality constant converting distances into fares.", + "attractiveness_2hub": " Base attractiveness value assigned to routes passing through two distinct hubs.", + "attractiveness_1hub": " Base attractiveness value assigned to routes passing through a single hub." + } +}