diff --git a/tasks/rahmaniani2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rahmaniani2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2020/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/rahmaniani2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rahmaniani2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2020/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/rahmaniani2020/gurobi_solution/large_solution_1.json b/tasks/rahmaniani2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9e2720c8bff3a35eb6bc35ea550b07cb40578f84 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2899181e20d5b29da0f415e50e3de842d25d9e2cb141cc0a7f43a99ddeea18d1 +size 461 diff --git a/tasks/rahmaniani2020/gurobi_solution/large_solution_2.json b/tasks/rahmaniani2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a313208ce5946328db22f1b47f95cff92f3e0951 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66a080aceacd2d2512178f80b2e44e603f5b94cdd843a72cd467dae015b4d1bc +size 460 diff --git a/tasks/rahmaniani2020/gurobi_solution/large_solution_3.json b/tasks/rahmaniani2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1d9ffb55f873b34d443288d3129561981bcb8bdf --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:422563568e3cd3a9ac29c27df84e2acb1f9298631fb57e7a9bdb9cd12d9a5923 +size 460 diff --git a/tasks/rahmaniani2020/gurobi_solution/large_solution_4.json b/tasks/rahmaniani2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..586e6df5eb61126638afe05ef5b8fb7db8dd48f3 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4f0f7cc4ed11a2c708f25b6711011e9af315ff34e63181296927e784f2ead0f +size 461 diff --git a/tasks/rahmaniani2020/gurobi_solution/large_solution_5.json b/tasks/rahmaniani2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3af362b9afb26787b259ff6b7a1ab0432d51017e --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d71f2994c86df64392a1ec954fc4052cfe2bd89ad0c2d3b5d9b134d75004c8d5 +size 478 diff --git a/tasks/rahmaniani2020/gurobi_solution/tiny_solution.json b/tasks/rahmaniani2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2800a8946549a4a40f7cb8a68010ee9c1401b73b --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2312c9290e19260087b313c0aae58476f2d0d8589b7ef9c35626b02aa6e2604a +size 169 diff --git a/tasks/rahmaniani2020/gurobi_solution_log/large_log_1.jsonl b/tasks/rahmaniani2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..40f4630c10fa7b02e25523e0a69f8cf27951f6a3 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12173a542f13c917bb2e08ef35cb0ae1d1b81cef349d13c8dfd5c40a370109f4 +size 445 diff --git a/tasks/rahmaniani2020/gurobi_solution_log/large_log_2.jsonl b/tasks/rahmaniani2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b2d679556cbe281505338c87afd02be11c268283 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8b6e7c6911443a86679667e23bd69adb718caec723006897c123228de4a1858 +size 386 diff --git a/tasks/rahmaniani2020/gurobi_solution_log/large_log_3.jsonl b/tasks/rahmaniani2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a1d7a8e0f108460f0792f0fb6b55993f060ca028 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab569304953cfb5d77489c1d74d1294a1d84597c17b841f3203b2d54b94ce15c +size 278 diff --git a/tasks/rahmaniani2020/gurobi_solution_log/large_log_4.jsonl b/tasks/rahmaniani2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2193ae02e42083a1934a789a3ff4600bf1cefd49 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a0721e4ebe22c4ca6ba3b1d220a46f94492efee2cd84ec3dd9eaa20fbe85a0a +size 564 diff --git a/tasks/rahmaniani2020/gurobi_solution_log/large_log_5.jsonl b/tasks/rahmaniani2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dd2a592923b70647c10c36088a1b37a73e0f6622 --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41cd9a23d8987b16ca5911ad364dd321fe0cb39703ac143e1447fecced244a28 +size 782 diff --git a/tasks/rahmaniani2020/gurobi_solution_log/tiny_log.jsonl b/tasks/rahmaniani2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7a8a380ef26c7d78901f8b967fdea309ba01180b --- /dev/null +++ b/tasks/rahmaniani2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:074260615dedff252a18829ff34a4b1d935c8fc540695f97d6d53f3f0ff44b00 +size 54 diff --git a/tasks/rahmaniani2020/instance/large_instance_1.json b/tasks/rahmaniani2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9646bf550a6b1d3a243572016a4fe053df4f1f1f --- /dev/null +++ b/tasks/rahmaniani2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa25c299fc4f7f0da766af3bee6708f4db358c250ec9247e2718ee27daeb7e54 +size 492587 diff --git a/tasks/rahmaniani2020/instance/large_instance_2.json b/tasks/rahmaniani2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..333ab866f0954862fcfcfa24292b2a016c3aacb1 --- /dev/null +++ b/tasks/rahmaniani2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a57bc62ab3143cd1d1599d985a920ab2e1ce31f47baa63907ed99377f4c75f07 +size 492603 diff --git a/tasks/rahmaniani2020/instance/large_instance_3.json b/tasks/rahmaniani2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b94f59e7b002e59ea9ec4ba741b815c4500c9c00 --- /dev/null +++ b/tasks/rahmaniani2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1379028350c6595f958dfe5f4449da46fb85ac09309c4bbc1aecf6b3ac5e704 +size 492656 diff --git a/tasks/rahmaniani2020/instance/large_instance_4.json b/tasks/rahmaniani2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..861de3b6136238e0eff6c6da03cc874d26a8a28a --- /dev/null +++ b/tasks/rahmaniani2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc27975038f5568bece09e3859e39a0b33c0674aab1ccdcf53d875f53d63fbb1 +size 492701 diff --git a/tasks/rahmaniani2020/instance/large_instance_5.json b/tasks/rahmaniani2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..33e76e65accb3c6384ac3d9f44c91ce8a31abf03 --- /dev/null +++ b/tasks/rahmaniani2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f216f98c67ef1df6b30557a5cb54d05640bd95badfe37aba5f87347fbef2bb51 +size 492675 diff --git a/tasks/rahmaniani2020/instance/tiny_instance.json b/tasks/rahmaniani2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c566510eedcdde06eac2495df8aa247e9f8b2555 --- /dev/null +++ b/tasks/rahmaniani2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:239d1c6b63423d60477b7663440f801c464454037c11a3c448977714869d7069 +size 5591 diff --git a/tasks/rahmaniani2020/instance_schema.json b/tasks/rahmaniani2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..83945f7ca4b59c6fd30f3a02340b11718543cef8 --- /dev/null +++ b/tasks/rahmaniani2020/instance_schema.json @@ -0,0 +1,23 @@ +{ + "num_facilities": " Number of potential facility locations that may be opened.", + "num_customers": " Number of customers whose demands must be served.", + "num_scenarios": " Number of demand scenarios representing uncertainty.", + "total_capacity": " Combined service capacity across all potential facilities.", + "max_total_demand": " Highest aggregate customer demand among all scenarios.", + "facilities": { + "x_coordinates": " Horizontal coordinate of each potential facility on the service region grid.", + "y_coordinates": " Vertical coordinate of each potential facility on the service region grid.", + "fixed_costs": " One-time cost incurred for opening each facility.", + "capacities": " Maximum total flow each facility can ship to customers if opened." + }, + "customers": { + "x_coordinates": " Horizontal coordinate of each customer on the service region grid.", + "y_coordinates": " Vertical coordinate of each customer on the service region grid." + }, + "routing_costs": " Per-unit cost of shipping goods from each facility to each customer.", + "scenarios": { + "num_scenarios": " Number of demand scenarios representing uncertainty.", + "probabilities": " Likelihood of each demand scenario occurring.", + "demands": " Quantity of goods each customer requires under each scenario." + } +} diff --git a/tasks/rahmaniani2020/mathematical_formulation.md b/tasks/rahmaniani2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..522af22007d1c7cab69d6bc5a620df398d8cd25a --- /dev/null +++ b/tasks/rahmaniani2020/mathematical_formulation.md @@ -0,0 +1,36 @@ +# Original Formulation: Benders Dual Decomposition – Generic MILP and Stochastic Capacitated Facility Location (SFL) + +Rahmaniani, Ahmed, Crainic, Gendreau, Rei. “The Benders Dual Decomposition Method,” *Operations Research*, 2020. + +## Generic MILP (Problem (1), Section 1) + +The paper develops the Benders Dual Decomposition (BDD) method for a generic mixed-integer linear program of the form $$\begin{align} +\min_{y,x}\ & f^\top y + c^\top x \tag{1a} \\ +\text{s.t.}\ & B y \ge b, \tag{1b} \\ +& W x + T y \ge h, \tag{1c} \\ +& y \in \mathbb{Z}_+^n, \quad x \in \mathbb{R}_+^m, \tag{1d} +\end{align}$$ where $f\in\mathbb{R}^n$, $B\in\mathbb{R}^{k\times n}$, $b\in\mathbb{R}^k$, $c\in\mathbb{R}^m$, $W\in\mathbb{R}^{\ell\times m}$, $h\in\mathbb{R}^\ell$, $T\in\mathbb{R}^{\ell\times n}$. The problem is feasible and bounded. + +## Test Problem: Stochastic Capacitated Facility Location (SFL) (Appendix D.2) + +**Sets and indices:** $N$ set of potential facility sites (indexed by $i$); $M$ set of customers (indexed by $j$); $S$ set of scenarios (indexed by $s$). + +**Parameters:** $f_i$ fixed cost of opening facility $i$; $u_i$ capacity of facility $i$; $c_{ij}$ routing cost per unit of flow from $i$ to $j$; $p_s$ probability of scenario $s$; $d_j^s$ demand of customer $j$ in scenario $s$. + +**Decision variables:** $y_i\in\{0,1\}$ equals $1$ iff facility $i$ is opened (first stage); $x_{ij}^s\ge 0$ is the flow from facility $i$ to customer $j$ under scenario $s$ (second stage). + +**Formulation (D.4)–(D.7):** $$\begin{align} +\text{SFL}:\quad \min\ & \sum_{i\in N} f_i\, y_i + + \sum_{s\in S} p_s \sum_{i\in N}\sum_{j\in M} c_{ij}\, x_{ij}^s \tag{D.4}\\ +\text{s.t.}\ & \sum_{i\in N} x_{ij}^s \ge d_j^s, + && \forall\, j\in M,\ s\in S \tag{D.5}\\ +& \sum_{j\in M} x_{ij}^s \le u_i\, y_i, + && \forall\, i\in N,\ s\in S \tag{D.6}\\ +& \sum_{i\in N} u_i\, y_i \ge \max_{s\in S}\sum_{j\in M} d_j^s \tag{D.7}\\ +& y_i \in \{0,1\},\ \ x_{ij}^s \ge 0, + && \forall\, i\in N,\ j\in M,\ s\in S. \notag +\end{align}$$ + +**Interpretation.** Objective (D.4) combines first-stage facility opening costs with expected second-stage routing costs. Constraint (D.5) enforces demand satisfaction in every scenario; (D.6) bounds flows out of each facility by its capacity (and forces no flow from closed facilities); (D.7) is the complete-recourse property, ensuring that the total opened capacity covers the worst-case total demand. + +Matching SFL to the generic form (1): the first-stage decisions are $y$ with $f = (f_i)_{i\in N}$ and constraint (D.7) taking the role of $By\ge b$; the second-stage recourse $x=(x_{ij}^s)$ and constraints (D.5)–(D.6) correspond to $Wx+Ty\ge h$. diff --git a/tasks/rahmaniani2020/problem_description.txt b/tasks/rahmaniani2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..50a2593521f2f8318ad84672584e2ff0afa4431c --- /dev/null +++ b/tasks/rahmaniani2020/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A company must decide which facilities to open among a set of potential locations in order to serve a set of customers whose demands are uncertain. The uncertainty is represented by a finite set of scenarios, each occurring with a known probability. The input data specifies, for each potential facility, a fixed cost of opening, a service capacity, and geographic coordinates. For each customer, the data specifies geographic coordinates. For each facility-customer pair, a per-unit routing cost is given. For each scenario, a probability of occurrence is provided along with the demand of every customer under that scenario. + +The company must choose which facilities to open and, for every scenario, how much flow to ship from each open facility to each customer. The goal is to minimize the sum of two cost components: the total fixed costs of opening the selected facilities, plus the expected routing cost, where the expected routing cost is the probability-weighted sum over all scenarios of the per-unit routing costs times the flows shipped in that scenario. + +The following rules govern these decisions. In every scenario, each customer's total inbound flow from all facilities must be at least as large as that customer's demand under that scenario. In every scenario, each facility's total outbound flow to all customers must not exceed that facility's capacity if the facility is open, and must be zero if the facility is not open. Finally, the total capacity of all opened facilities must be at least as large as the maximum, taken over all scenarios, of the total demand of all customers in that scenario; this ensures that the opened facilities can collectively satisfy all customer demands regardless of which scenario is realized. diff --git a/tasks/rahmaniani2020/solution_logger.py b/tasks/rahmaniani2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rahmaniani2020/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/rahmaniani2020/solution_schema.json b/tasks/rahmaniani2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e5c536c9d7f254f969866adaf57170156df9248b --- /dev/null +++ b/tasks/rahmaniani2020/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total expected cost, combining facility opening costs and expected routing costs across scenarios.", + "y": " Whether each facility is opened (1 = opened, 0 = not opened)." +} diff --git a/tasks/rahmaniani2022/feasibility_check.py b/tasks/rahmaniani2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5788acefd9a408c540eda8ab6f99476989d7cd2b --- /dev/null +++ b/tasks/rahmaniani2022/feasibility_check.py @@ -0,0 +1,798 @@ +#!/usr/bin/env python3 +""" +Feasibility checker (Tier C variant) for the Energy Systems Planning problem. + +From: Jacobson et al. (2023) - "A computationally efficient Benders +decomposition for energy systems planning problems with detailed +operations and time-coupling constraints" + +Constraints 1-12 validate the submitted investment witness. Constraint 49 +substitutes the complete investment-and-operation vector into trusted offline +model coefficients without invoking an optimizer. + +Constraint 49 (objective consistency): trusted fixed-investment recourse solve. +""" + +import argparse +import json +import math +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from solverless_witness import require_linked_variables, validate_complete_witness + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('investments', 'model_variables', 'objective_value', 'storage_energy_investments', 'transmission_investments') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('investments', 'model_variables') +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +def check_feasibility(instance, solution, instance_path=None): + """Run all checks and return the same dict shape as the original main() + writes to result_path. Exposed as a function so the diff-test harness + can call it directly (parallel to other paper's _new.py files).""" + inst = instance + sol = solution + + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violation_details = {} # constraint_idx -> list of message strings + violation_magnitudes = [] # list of dicts + + def record_violation(constraint_idx, lhs, rhs, raw_excess, msg): + violated_constraints.add(constraint_idx) + if constraint_idx not in violation_details: + violation_details[constraint_idx] = [] + violation_details[constraint_idx].append(msg) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer + }) + + def check_leq(constraint_idx, lhs, rhs, msg): + excess = lhs - rhs + if excess > tol: + record_violation(constraint_idx, lhs, rhs, excess, msg) + + def check_geq(constraint_idx, lhs, rhs, msg): + excess = rhs - lhs + if excess > tol: + record_violation(constraint_idx, lhs, rhs, excess, msg) + + def check_eq(constraint_idx, lhs, rhs, msg): + excess = abs(lhs - rhs) + if excess > tol: + record_violation(constraint_idx, lhs, rhs, excess, msg) + + # ========================================================================= + # Check if solution has investment data + # ========================================================================= + has_investments = "investments" in sol + + if not has_investments: + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": ["No investment solution provided (null or missing)"], + "violation_magnitudes": [] + } + + # ========================================================================= + # Extract instance data + # ========================================================================= + generators = inst["generators"] + gen_params = inst["generator_parameters"] + existing_cap = inst["existing_capacity"] + trans_lines = inst["transmission_lines"] + release_convention = inst["released_investment_convention"] + + num_gen = len(generators) + G = list(range(num_gen)) + G_UC = [g for g in G if generators[g]["is_UC"]] + G_STOR = [g for g in G if generators[g]["is_storage"]] + G_HYDRO = [g for g in G if generators[g]["is_hydro"]] + G_NONRET = set(g for g in G if not generators[g]["can_retire"]) + G_UC_set = set(G_UC) + G_STOR_set = set(G_STOR) + L = list(range(len(trans_lines))) + + # Released convention: physical UC blocks and integer 1-MW non-UC blocks. + gamma_P = {} + for g in G: + if g in G_UC_set: + gamma_P[g] = generators[g]["capacity_size_MW"] + else: + gamma_P[g] = float(release_convention["non_uc_power_increment_MW"]) + + # gamma_E: energy_capacity_size_MWh for UC storage, 1.0 otherwise + gamma_E = {} + for g in G_STOR: + if g in G_UC_set: + rtype = generators[g]["resource_type"] + gamma_E[g] = gen_params[rtype]["energy_capacity_size_MWh"] + else: + gamma_E[g] = float( + release_convention["non_uc_storage_energy_increment_MWh"] + ) + + # Existing power capacity + y_P_0 = {} + for g in G: + y_P_0[g] = existing_cap.get(str(g), 0.0) + + # Existing energy capacity for storage + y_E_0 = {} + for g in G_STOR: + rtype = generators[g]["resource_type"] + bp = gen_params[rtype] + phys_cap_size = bp.get("capacity_size_MW", 1.0) + e_size = bp.get("energy_capacity_size_MWh", 1.0) + if phys_cap_size > 0: + y_E_0[g] = (y_P_0[g] / phys_cap_size) * e_size + else: + y_E_0[g] = 0.0 + + # Max capacities + y_P_max = {} + for g in G: + rtype = generators[g]["resource_type"] + y_P_max[g] = gen_params[rtype]["max_capacity_MW"] + + y_E_max = {} + for g in G_STOR: + rtype = generators[g]["resource_type"] + y_E_max[g] = gen_params[rtype]["max_energy_capacity_MWh"] + + # Storage duration limits + rho_min_stor = {} + rho_max_stor = {} + for g in G_STOR: + rtype = generators[g]["resource_type"] + rho_min_stor[g] = gen_params[rtype]["min_duration_MWh_per_MW"] + rho_max_stor[g] = gen_params[rtype]["max_duration_MWh_per_MW"] + + # ========================================================================= + # Extract solution investment variables + # ========================================================================= + inv = sol.get("investments", {}) + stor_inv = sol.get("storage_energy_investments", {}) + trans_inv = sol.get("transmission_investments", {}) + + # Power capacity variables + y_P_new = {} + y_P_ret = {} + y_P = {} + for g in G: + gs = str(g) + if gs in inv: + y_P_new[g] = inv[gs]["new_units"] + y_P_ret[g] = abs(inv[gs]["retired_units"]) + y_P[g] = inv[gs]["total_capacity_MW"] + else: + y_P_new[g] = 0.0 + y_P_ret[g] = 0.0 + y_P[g] = y_P_0[g] + + # Storage energy capacity variables + y_E_new = {} + y_E = {} + for g in G_STOR: + gs = str(g) + if gs in stor_inv: + y_E_new[g] = stor_inv[gs]["new_units"] + y_E[g] = stor_inv[gs]["total_energy_MWh"] + else: + y_E_new[g] = 0.0 + y_E[g] = y_E_0[g] + + # Derive y_E_ret from constraint (13d) + y_E_ret = {} + for g in G_STOR: + if gamma_E[g] > 0: + y_E_ret[g] = y_E_new[g] - (y_E[g] - y_E_0[g]) / gamma_E[g] + else: + y_E_ret[g] = 0.0 + + # Transmission capacity variables + y_F_new = {} + y_F = {} + for l_idx in L: + ls = str(l_idx) + if ls in trans_inv: + y_F_new[l_idx] = trans_inv[ls]["new_MW"] + y_F[l_idx] = trans_inv[ls]["total_capacity_MW"] + else: + y_F_new[l_idx] = 0.0 + y_F[l_idx] = trans_lines[l_idx]["existing_capacity_MW"] + + # MILP investment variables, including transmission expansion, are integer + # counts of the increments declared above. + if sol.get("formulation", "MILP") == "MILP": + integer_values = [ + (f"y_P_new[{g}]", y_P_new[g]) for g in G + ] + [ + (f"y_P_ret[{g}]", y_P_ret[g]) for g in G + ] + [ + (f"y_E_new[{g}]", y_E_new[g]) for g in G_STOR + ] + [ + (f"y_F_new[{line}]", y_F_new[line]) for line in L + ] + for name, value in integer_values: + difference = abs(float(value) - round(float(value))) + if difference > 1e-4: + record_violation( + 50, float(value), float(round(float(value))), difference, + f"MILP investment variable {name}={value} is not integral", + ) + + # ========================================================================= + # Check Investment Constraints (Constraints 1-12) -- unchanged from original + # ========================================================================= + + # Constraint 1 (12a) + for g in G: + lhs_val = gamma_P[g] * y_P_new[g] + rhs_val = y_P_max[g] + check_leq(1, lhs_val, rhs_val, + f"Gen {g} ({generators[g]['resource_type']}): " + f"gamma_P*y_P_new={lhs_val:.2f} exceeds max_cap={rhs_val:.2f}") + + # Constraint 2 (12b) + for g in G: + lhs_val = gamma_P[g] * y_P_ret[g] + rhs_val = y_P_0[g] + check_leq(2, lhs_val, rhs_val, + f"Gen {g} ({generators[g]['resource_type']}): " + f"gamma_P*y_P_ret={lhs_val:.2f} exceeds existing_cap={rhs_val:.2f}") + + # Constraint 3 (12c) + for g in G: + if g in G_NONRET: + lhs_val = y_P_ret[g] + rhs_val = 0.0 + check_eq(3, lhs_val, rhs_val, + f"Gen {g} ({generators[g]['resource_type']}): " + f"non-retirable but y_P_ret={lhs_val:.6f}") + + # Constraint 4 (12d) + for g in G: + lhs_val = y_P[g] + rhs_val = y_P_0[g] + gamma_P[g] * (y_P_new[g] - y_P_ret[g]) + check_eq(4, lhs_val, rhs_val, + f"Gen {g} ({generators[g]['resource_type']}): " + f"y_P={lhs_val:.4f} != y_P_0+gamma_P*(new-ret)={rhs_val:.4f}") + + # Constraint 5 (13a) + for g in G_STOR: + lhs_val = gamma_E[g] * y_E_new[g] + rhs_val = y_E_max[g] + check_leq(5, lhs_val, rhs_val, + f"Storage {g}: gamma_E*y_E_new={lhs_val:.2f} exceeds " + f"max_E_cap={rhs_val:.2f}") + + # Constraint 6 (13b) + for g in G_STOR: + lhs_val = gamma_E[g] * y_E_ret[g] + rhs_val = y_E_0[g] + check_leq(6, lhs_val, rhs_val, + f"Storage {g}: gamma_E*y_E_ret={lhs_val:.2f} exceeds " + f"existing_E_cap={rhs_val:.2f}") + + # Constraint 7 (13c) + for g in G_STOR: + if g in G_NONRET: + lhs_val = y_E_ret[g] + rhs_val = 0.0 + check_eq(7, lhs_val, rhs_val, + f"Storage {g}: non-retirable but y_E_ret={lhs_val:.6f}") + + # Constraint 8 (13d) + for g in G_STOR: + lhs_val = y_E[g] + rhs_val = y_E_0[g] + gamma_E[g] * (y_E_new[g] - y_E_ret[g]) + check_eq(8, lhs_val, rhs_val, + f"Storage {g}: y_E={lhs_val:.4f} != " + f"y_E_0+gamma_E*(new-ret)={rhs_val:.4f}") + + # Constraint 9 (13e) + for g in G_STOR: + lhs_val = rho_min_stor[g] * y_P[g] + rhs_val = y_E[g] + check_leq(9, lhs_val, rhs_val, + f"Storage {g}: rho_min*y_P={lhs_val:.2f} exceeds " + f"y_E={rhs_val:.2f}") + + # Constraint 10 (13f) + for g in G_STOR: + lhs_val = rho_max_stor[g] * y_P[g] + rhs_val = y_E[g] + check_geq(10, lhs_val, rhs_val, + f"Storage {g}: rho_max*y_P={lhs_val:.2f} less than " + f"y_E={rhs_val:.2f}") + + # Constraint 11 (14a) + for l_idx in L: + lhs_val = y_F_new[l_idx] + rhs_val = max( + 0.0, + trans_lines[l_idx]["max_capacity_MW"] + - trans_lines[l_idx]["existing_capacity_MW"], + ) + check_leq(11, lhs_val, rhs_val, + f"Line {l_idx}: y_F_new={lhs_val:.2f} exceeds " + f"max_F_cap={rhs_val:.2f}") + + # Constraint 12 (14b) + for l_idx in L: + lhs_val = y_F[l_idx] + rhs_val = trans_lines[l_idx]["existing_capacity_MW"] + y_F_new[l_idx] + check_eq(12, lhs_val, rhs_val, + f"Line {l_idx}: y_F={lhs_val:.4f} != " + f"y_F_0+y_F_new={rhs_val:.4f}") + + # ========================================================================= + # Constraints 13-48: skipped (operational variables not in solution). + # ========================================================================= + + # ========================================================================= + # Constraint 49 (NEW): Objective-value envelope (Tier C anti-exploit) + # + # obj_lower = c^FIXED (Eq. 29, exact from investment variables) + # obj_upper = obj_lower + crude upper bounds on c^VAR, c^NSE, c^START, + # c^RPS, c^CO2 (loose but data-driven). + # ========================================================================= + reported_obj = sol.get("objective_value") + try: + reported = float(reported_obj) if reported_obj is not None else None + except (TypeError, ValueError): + reported = None + + if reported is not None: + # ------ Cost / parameter lookups (same conventions as gurobi_code.py) ------ + def gp_val(g, key, default=0.0): + rtype = generators[g]["resource_type"] + return gen_params[rtype].get(key, default) + + c_P_INV = {g: gp_val(g, "investment_cost_per_MW_yr") for g in G} + c_P_FOM = {g: gp_val(g, "fixed_OM_cost_per_MW_yr") for g in G} + c_VAR = {g: gp_val(g, "variable_cost_per_MWh") for g in G} + c_START = {g: gp_val(g, "start_up_cost", 0.0) for g in G_UC} + co2_rate = {g: gp_val(g, "CO2_emission_tons_per_MWh", 0.0) for g in G} + + # Energy-side costs are explicit data, including released zeros. + if G_STOR and "battery" in gen_params: + c_E_INV_stor = {g: gen_params["battery"].get( + "energy_investment_cost_per_MWh_yr", 0.0) for g in G_STOR} + else: + c_E_INV_stor = {g: 0.0 for g in G_STOR} + c_E_FOM_stor = { + g: gen_params[generators[g]["resource_type"]].get( + "energy_fixed_OM_cost_per_MWh_yr", 0.0 + ) + for g in G_STOR + } + c_E_INV_hydro = { + g: gen_params[generators[g]["resource_type"]].get( + "energy_investment_cost_per_MWh_yr", 0.0 + ) + for g in G_HYDRO + } + c_E_FOM_hydro = { + g: gen_params[generators[g]["resource_type"]].get( + "energy_fixed_OM_cost_per_MWh_yr", 0.0 + ) + for g in G_HYDRO + } + + # Transmission investment cost. + c_F_INV = {l_idx: trans_lines[l_idx].get("investment_cost_per_MW_yr", 0.0) + for l_idx in L} + + # ------ Subperiod weights and total weighted hours / demand ------ + params = inst.get("problem_parameters", {}) + num_weeks = params.get("num_weeks", 0) + delta_w = params.get("hours_per_subperiod", 168) + total_hours = params.get("total_hours", num_weeks * delta_w) + subperiod_weights = inst.get("subperiod_weights", [1.0] * num_weeks) + + # alpha_t = beta_w / delta_w; sum over t = sum_w beta_w + if delta_w > 0: + total_weighted_hours = float(sum(subperiod_weights)) + else: + total_weighted_hours = float(total_hours) + + # Total weighted demand = sum_{w,t in H_w, z} alpha_t * d_{z,t} + # alpha is constant beta_w/delta_w within each subperiod; we collapse by week. + demand = inst.get("demand", {}) + total_weighted_demand = 0.0 + if delta_w > 0: + for z_key, dem_list in demand.items(): + # weight every hour by its subperiod's alpha + for w in range(num_weeks): + beta_w = subperiod_weights[w] if w < len(subperiod_weights) else 1.0 + alpha = beta_w / delta_w + t0 = w * delta_w + t1 = min((w + 1) * delta_w, len(dem_list)) + for t in range(t0, t1): + total_weighted_demand += alpha * float(dem_list[t]) + + # ------ obj_lower = c^FIXED (Eq. 29, exact) ------ + c_fixed = 0.0 + # Investment costs: sum_g c_P_INV * gamma_P * y_P_new = c_P_INV * new_MW + for g in G: + new_mw = gamma_P[g] * float(y_P_new[g]) + c_fixed += float(c_P_INV[g]) * new_mw + # Storage energy investment: sum c_E_INV * gamma_E * y_E_new + for g in G_STOR: + c_fixed += float(c_E_INV_stor[g]) * gamma_E[g] * float(y_E_new[g]) + c_fixed += float(c_E_FOM_stor[g]) * float(y_E[g]) + for g in G_HYDRO: + duration = float(gen_params[generators[g]["resource_type"]]["duration_MWh_per_MW"]) + c_fixed += float(c_E_INV_hydro[g]) * duration * float(y_P_new[g]) + c_fixed += float(c_E_FOM_hydro[g]) * duration * float(y_P[g]) + # Fixed O&M: sum_g c_P_FOM * y_P + for g in G: + c_fixed += float(c_P_FOM[g]) * float(y_P[g]) + # Transmission investment + for l_idx in L: + c_fixed += float(c_F_INV[l_idx]) * float(y_F_new[l_idx]) + + obj_lower = c_fixed + + # ------ obj_upper = c^FIXED + crude upper bound on operational costs ------ + # Each generator can produce at most y_P[g] MWh per hour for all hours; + # similarly storage withdrawals are bounded by y_P[g]. + c_var_max = 0.0 + for g in G: + c_var_max += float(c_VAR[g]) * float(y_P[g]) * total_weighted_hours + for g in G_STOR: + c_var_max += float(c_VAR[g]) * float(y_P[g]) * total_weighted_hours + + # NSE upper bound: every segment's max fraction of demand, at its cost + c_nse_max = 0.0 + for seg in inst.get("consumer_segments", []): + seg_zone = seg.get("zone") + seg_cost = float(seg.get("cost_per_MWh", 0.0)) + seg_frac = float(seg.get("max_nse_fraction", 0.0)) + if seg_cost <= 0.0 or seg_frac <= 0.0: + continue + zone_key = str(seg_zone) + if zone_key not in demand: + continue + dem_list = demand[zone_key] + zone_weighted_demand = 0.0 + if delta_w > 0: + for w in range(num_weeks): + beta_w = subperiod_weights[w] if w < len(subperiod_weights) else 1.0 + alpha = beta_w / delta_w + t0 = w * delta_w + t1 = min((w + 1) * delta_w, len(dem_list)) + for t in range(t0, t1): + zone_weighted_demand += alpha * float(dem_list[t]) + c_nse_max += seg_cost * seg_frac * zone_weighted_demand + + # START upper bound: each UC unit could start every hour + c_start_max = 0.0 + for g in G_UC: + if gamma_P[g] <= 0: + continue + num_units_bound = float(y_P[g]) / gamma_P[g] + c_start_max += float(c_START.get(g, 0.0)) * num_units_bound * total_weighted_hours + + # RPS / CO2 noncompliance penalties (loose upper bounds) + policy = inst.get("policy", {}) + c_RPS = float(policy.get("RPS_noncompliance_cost_per_MWh", 0.0) or 0.0) + c_CO2 = float(policy.get("CO2_noncompliance_cost_per_ton", 0.0) or 0.0) + # RPS noncompliance bounded by total weighted demand (full RPS shortfall) + c_rps_max = c_RPS * total_weighted_demand + # CO2 noncompliance bounded by max possible emissions (all gens at full) + co2_max_emissions = 0.0 + for g in G: + co2_max_emissions += float(co2_rate.get(g, 0.0)) * float(y_P[g]) * total_weighted_hours + for g in G_STOR: + co2_max_emissions += float(co2_rate.get(g, 0.0)) * float(y_P[g]) * total_weighted_hours + c_co2_max = c_CO2 * co2_max_emissions + + obj_upper = c_fixed + c_var_max + c_nse_max + c_start_max + c_rps_max + c_co2_max + + # Safety floor so even an all-zero investment doesn't make obj_upper + # too small to catch MAX_FLOAT; tied to total demand at $1/MWh. + obj_upper = max(obj_upper, 1.0 + total_weighted_demand) + + # ------ Compare ------ + tol_obj_lo = max(1e-3, 1e-3 * abs(obj_lower)) + tol_obj_hi = max(1e-3, 1e-3 * abs(obj_upper)) + + # NaN / Inf are always rejected. + if math.isnan(reported) or math.isinf(reported): + record_violation( + 49, float("nan" if math.isnan(reported) else reported), + float(obj_upper), + float("inf"), + f"Constraint 49 (Objective consistency): reported objective_value=" + f"{reported_obj!r} is not a finite number; " + f"expected value in [{obj_lower:.6g}, {obj_upper:.6g}]." + ) + else: + shortfall = obj_lower - reported + overshoot = reported - obj_upper + if shortfall > tol_obj_lo: + record_violation( + 49, float(obj_lower), float(reported), float(shortfall), + f"Constraint 49 (Objective consistency): reported objective_value=" + f"{reported:.6f} is below the lower bound obj_lower=c^FIXED=" + f"{obj_lower:.6f}; shortfall={shortfall:.6g}, tol={tol_obj_lo:.6g}" + ) + if overshoot > tol_obj_hi: + record_violation( + 49, float(reported), float(obj_upper), float(overshoot), + f"Constraint 49 (Objective consistency): reported objective_value=" + f"{reported:.6f} exceeds worst-case upper bound obj_upper=" + f"{obj_upper:.6f} (c^FIXED={c_fixed:.6f}, c^VAR_max={c_var_max:.6g}, " + f"c^NSE_max={c_nse_max:.6g}, c^START_max={c_start_max:.6g}, " + f"c^RPS_max={c_rps_max:.6g}, c^CO2_max={c_co2_max:.6g}); " + f"overshoot={overshoot:.6g}, tol={tol_obj_hi:.6g}" + ) + + # The envelope above remains a cheap early screen. For an otherwise valid + # plan, validate the complete hourly witness by direct substitution. + if not violated_constraints and reported is not None and math.isfinite(reported): + try: + if instance_path is None: + raise ValueError("instance_path is required for solverless validation") + expected, witness_errors, _ = validate_complete_witness( + instance_path, sol, Path(__file__).resolve().parent + ) + links = {} + investments = sol.get("investments", {}) + for generator in range(len(inst["generators"])): + entry = investments.get(str(generator), {}) + links[f"y_P_new[{generator}]"] = float(entry.get("new_units", 0.0)) + links[f"y_P_ret[{generator}]"] = abs(float(entry.get("retired_units", 0.0))) + if "total_capacity_MW" in entry: + links[f"y_P[{generator}]"] = float(entry["total_capacity_MW"]) + storage = sol.get("storage_energy_investments", {}) + for key, entry in storage.items(): + generator = int(key) + links[f"y_E_new[{generator}]"] = float(entry.get("new_units", 0.0)) + links[f"y_E[{generator}]"] = float(entry["total_energy_MWh"]) + transmission = sol.get("transmission_investments", {}) + for line in range(len(inst["transmission_lines"])): + entry = transmission.get(str(line), {}) + links[f"y_F_new[{line}]"] = float(entry.get("new_MW", 0.0)) + if "total_capacity_MW" in entry: + links[f"y_F[{line}]"] = float(entry["total_capacity_MW"]) + witness_errors.extend(require_linked_variables(sol, links)) + if witness_errors or expected is None: + raise ValueError("; ".join(witness_errors[:20]) or "missing witness objective") + except Exception as error: + record_violation( + 49, + 1.0, + 0.0, + 1.0, + "Constraint 49 (Objective consistency): trusted fixed-investment " + f"recourse failed: {type(error).__name__}: {str(error)[:300]}", + ) + else: + difference = abs(reported - expected) + objective_tol = max(1e-3, 1e-4 * max(1.0, abs(expected))) + if difference > objective_tol: + record_violation( + 49, + reported, + expected, + difference, + "Constraint 49 (Objective consistency): reported " + f"objective_value={reported:.6f} does not equal trusted " + f"fixed-investment cost={expected:.6f} " + f"(difference={difference:.6g}, tol={objective_tol:.6g})", + ) + + # ========================================================================= + # Build output (matches original feasibility_check.py shape) + # ========================================================================= + sorted_violated = sorted(violated_constraints) + aggregated_violations = [] + for c in sorted_violated: + msgs = violation_details[c] + if len(msgs) == 1: + aggregated_violations.append(msgs[0]) + else: + aggregated_violations.append( + f"Constraint {c}: {len(msgs)} violations. " + f"Example: {msgs[0]}") + + return { + "feasible": len(sorted_violated) == 0, + "violated_constraints": sorted_violated, + "violations": aggregated_violations, + "violation_magnitudes": violation_magnitudes + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for energy systems planning solutions") + parser.add_argument("--instance_path", type=str, required=True) + parser.add_argument("--solution_path", type=str, required=True) + parser.add_argument("--result_path", type=str, required=True) + args = parser.parse_args() + + with open(args.instance_path) 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, args.instance_path) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is FEASIBLE (investment constraints + exact recourse objective).") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {result['violated_constraints']}") + for msg in result["violations"]: + print(f" - {msg}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/rahmaniani2022/gurobi_code.py b/tasks/rahmaniani2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c59d91998c0c74c16174a87eaf6ac6eb28b44a --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_code.py @@ -0,0 +1,991 @@ +""" +Monolithic energy systems planning MILP model from Jacobson et al. (2023), +"A computationally efficient Benders decomposition for energy systems planning +problems with detailed operations and time-coupling constraints." + +Implements the full formulation (Appendix B) using Gurobi. +""" + +import argparse +import json +import time +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path) as f: + return json.load(f) + + +def build_model(inst, formulation="MILP", quiet=False): + """Build the monolithic Gurobi model from the instance data.""" + + m = gp.Model("energy_systems_planning") + m.setParam("Threads", 1) + if quiet: + m.setParam("OutputFlag", 0) + + # ========================================================================= + # Unpack instance data + # ========================================================================= + params = inst["problem_parameters"] + policy = inst["policy"] + generators = inst["generators"] + gen_params = inst["generator_parameters"] + existing_cap = inst["existing_capacity"] + demand = inst["demand"] + consumer_segs = inst["consumer_segments"] + trans_lines = inst["transmission_lines"] + availability = inst["availability"] + hydro_inflow = inst["hydro_inflow"] + subperiod_weights = inst["subperiod_weights"] + + num_zones = params["num_zones"] + num_weeks = params["num_weeks"] + delta_w = params["hours_per_subperiod"] # 168 + total_hours = params["total_hours"] + + # ========================================================================= + # Build index sets + # ========================================================================= + G = list(range(len(generators))) + G_UC = [g for g in G if generators[g]["is_UC"]] + G_nonUC = [g for g in G if not generators[g]["is_UC"]] + G_STOR = [g for g in G if generators[g]["is_storage"]] + G_HYDRO = [g for g in G if generators[g]["is_hydro"]] + G_RPS = [g for g in G if generators[g]["is_RPS_qualifying"]] + G_NONRET = [g for g in G if not generators[g]["can_retire"]] + G_NONRET_set = set(G_NONRET) + G_UC_set = set(G_UC) + G_STOR_set = set(G_STOR) + G_HYDRO_set = set(G_HYDRO) + + # Resources that have min output but are NOT UC, storage, or hydro + G_minout = [g for g in G if not generators[g]["is_UC"] + and not generators[g]["is_storage"] + and not generators[g]["is_hydro"]] + + Z = list(range(num_zones)) + W = list(range(num_weeks)) + L = list(range(len(trans_lines))) + + # G_z: generators in zone z + G_z = {z: [] for z in Z} + for g in G: + G_z[generators[g]["zone"]].append(g) + + G_z_STOR = {z: [g for g in G_z[z] if g in G_STOR_set] for z in Z} + + # Lines into / out of zone z + I_z_in = {z: [] for z in Z} + I_z_out = {z: [] for z in Z} + for l_idx, line in enumerate(trans_lines): + I_z_out[line["from_zone"]].append(l_idx) + I_z_in[line["to_zone"]].append(l_idx) + + # Subperiod structure: H_w, t_w_0 (first), t_w (last) + # Hours are 0-indexed internally + H_w = {} + t_w_0 = {} + t_w_last = {} + for w in W: + start = w * delta_w + end = (w + 1) * delta_w + H_w[w] = list(range(start, end)) + t_w_0[w] = start + t_w_last[w] = end - 1 + + T = list(range(total_hours)) + + # Map each timestep to its subperiod + t_to_w = {} + for w in W: + for t in H_w[w]: + t_to_w[t] = w + + # ========================================================================= + # Parameters + # ========================================================================= + + release_convention = inst["released_investment_convention"] + + # gamma_P: released investment increment. UC resources use their physical + # cluster size; non-UC resources use explicit 1-MW integer increments. + gamma_P = {} + for g in G: + if g in G_UC_set: + gamma_P[g] = generators[g]["capacity_size_MW"] + else: + gamma_P[g] = float(release_convention["non_uc_power_increment_MW"]) + + # gamma_E: energy capacity size for storage + gamma_E = {} + for g in G_STOR: + # Per math_model line 38: gamma_E_SIZE set to 1 for g not in G^UC + # Battery is non-UC, so gamma_E = 1.0 + if g in G_UC_set: + gamma_E[g] = gen_params["battery"]["energy_capacity_size_MWh"] + else: + gamma_E[g] = float( + release_convention["non_uc_storage_energy_increment_MWh"] + ) + + # Existing capacities + y_P_0 = {} + for g in G: + y_P_0[g] = existing_cap.get(str(g), 0.0) + + y_E_0 = {} + for g in G_STOR: + bp = gen_params["battery"] + # existing energy = (existing_MW / capacity_size_MW) * energy_capacity_size_MWh + if bp["capacity_size_MW"] > 0: + y_E_0[g] = (y_P_0[g] / bp["capacity_size_MW"]) * bp["energy_capacity_size_MWh"] + else: + y_E_0[g] = 0.0 + + # alpha_t = beta_w / delta_w + alpha = {} + for w in W: + a = subperiod_weights[w] / delta_w + for t in H_w[w]: + alpha[t] = a + + # Generator type parameters + def gp_val(g, key, default=0.0): + rtype = generators[g]["resource_type"] + p = gen_params[rtype] + return p.get(key, default) + + # Cost parameters + c_P_INV = {g: gp_val(g, "investment_cost_per_MW_yr") for g in G} + c_P_FOM = {g: gp_val(g, "fixed_OM_cost_per_MW_yr") for g in G} + c_VAR = {g: gp_val(g, "variable_cost_per_MWh") for g in G} + c_START = {g: gp_val(g, "start_up_cost") for g in G_UC} + + c_E_INV_stor = {g: gen_params["battery"]["energy_investment_cost_per_MWh_yr"] for g in G_STOR} + c_E_FOM_stor = { + g: gen_params["battery"]["energy_fixed_OM_cost_per_MWh_yr"] + for g in G_STOR + } + + # These released zero values are now explicit instance parameters. + c_E_INV_hydro = { + g: gen_params["hydro"]["energy_investment_cost_per_MWh_yr"] + for g in G_HYDRO + } + c_E_FOM_hydro = { + g: gen_params["hydro"]["energy_fixed_OM_cost_per_MWh_yr"] + for g in G_HYDRO + } + + # Hydro duration rho_g + rho_hydro = {g: gen_params["hydro"]["duration_MWh_per_MW"] for g in G_HYDRO} + + # Max capacities + y_P_max = {g: gp_val(g, "max_capacity_MW") for g in G} + y_E_max = {g: gen_params["battery"]["max_energy_capacity_MWh"] for g in G_STOR} + + # Storage parameters + eta_charge = {g: gen_params["battery"]["charging_efficiency"] for g in G_STOR} + eta_discharge = {g: gen_params["battery"]["discharging_efficiency"] for g in G_STOR} + eta_self_discharge = {g: gen_params["battery"]["self_discharge_rate_pct"] for g in G_STOR} + rho_min_stor = {g: gen_params["battery"]["min_duration_MWh_per_MW"] for g in G_STOR} + rho_max_stor = {g: gen_params["battery"]["max_duration_MWh_per_MW"] for g in G_STOR} + + # Operational parameters + min_output = {g: gp_val(g, "min_output_frac") for g in G} + ramp_up = {g: gp_val(g, "ramp_up_rate_pct_per_hr") for g in G} + ramp_down = {g: gp_val(g, "ramp_down_rate_pct_per_hr") for g in G} + min_up_time = {g: int(gp_val(g, "min_up_time_hr")) for g in G_UC} + min_down_time = {g: int(gp_val(g, "min_down_time_hr")) for g in G_UC} + + # Availability + avail = {} + for g in G: + key = str(g) + if key in availability: + avail[g] = availability[key] + else: + avail[g] = [1.0] * total_hours + + # Hydro inflow + h_inflow = {} + for g in G_HYDRO: + key = str(g) + if key in hydro_inflow: + h_inflow[g] = hydro_inflow[key] + else: + h_inflow[g] = [0.0] * total_hours + + # Demand + d_zt = {} + for z in Z: + dem = demand[str(z)] + for t in T: + d_zt[z, t] = dem[t] + + # Emissions + co2_rate = {g: gp_val(g, "CO2_emission_tons_per_MWh") for g in G} + + # Policy + RPS_share = policy["RPS_share"] + CO2_cap_rate = policy["CO2_cap_tons_per_MWh"] + c_RPS = policy["RPS_noncompliance_cost_per_MWh"] + c_CO2 = policy["CO2_noncompliance_cost_per_ton"] + + # NSE segments: list of (segment_id, zone, max_nse_fraction, cost_per_MWh) + # Build unique (s, z) pairs + nse_segments = [] + for seg in consumer_segs: + nse_segments.append((seg["segment_id"], seg["zone"], + seg["max_nse_fraction"], seg["cost_per_MWh"])) + + # Transmission + y_F_0 = {l: trans_lines[l]["existing_capacity_MW"] for l in L} + y_F_max = {l: trans_lines[l]["max_capacity_MW"] for l in L} + c_F_INV = {l: trans_lines[l]["investment_cost_per_MW_yr"] for l in L} + + # Determine variable type for investment + is_milp = (formulation == "MILP") + inv_vtype = GRB.INTEGER if is_milp else GRB.CONTINUOUS + + # ========================================================================= + # DECISION VARIABLES + # ========================================================================= + print("Creating variables...") + + # --- Investment variables --- + y_P_new = m.addVars(G, vtype=inv_vtype, lb=0, name="y_P_new") + y_P_ret = m.addVars(G, vtype=inv_vtype, lb=0, name="y_P_ret") + y_P = m.addVars(G, vtype=GRB.CONTINUOUS, lb=0, name="y_P") + + y_E_new = m.addVars(G_STOR, vtype=inv_vtype, lb=0, name="y_E_new") + y_E_ret = m.addVars(G_STOR, vtype=inv_vtype, lb=0, name="y_E_ret") + y_E = m.addVars(G_STOR, vtype=GRB.CONTINUOUS, lb=0, name="y_E") + + # Transmission expansion follows the same integer-MW MILP convention. + y_F_new = m.addVars(L, vtype=inv_vtype, lb=0, name="y_F_new") + y_F = m.addVars(L, vtype=GRB.CONTINUOUS, lb=0, name="y_F") + + # --- Operational variables --- + # x_inj[g,t]: generation injection + x_inj = m.addVars(G, T, vtype=GRB.CONTINUOUS, lb=0, name="x_inj") + + # x_wdw[g,t]: storage withdrawal (charging) + x_wdw = m.addVars(G_STOR, T, vtype=GRB.CONTINUOUS, lb=0, name="x_wdw") + + # x_nse[s_idx, t]: NSE for segment index s_idx + nse_indices = [(i, t) for i in range(len(nse_segments)) for t in T] + x_nse = m.addVars(nse_indices, vtype=GRB.CONTINUOUS, lb=0, name="x_nse") + + # x_soc[g,t]: state of charge (storage) + x_soc = m.addVars(G_STOR, T, vtype=GRB.CONTINUOUS, lb=0, name="x_soc") + + # x_lvl[g,t]: reservoir level (hydro) + x_lvl = m.addVars(G_HYDRO, T, vtype=GRB.CONTINUOUS, lb=0, name="x_lvl") + + # x_spill[g,t]: hydro spillage + x_spill = m.addVars(G_HYDRO, T, vtype=GRB.CONTINUOUS, lb=0, name="x_spill") + + # x_flow[l,t]: transmission flow (free variable) + x_flow = m.addVars(L, T, vtype=GRB.CONTINUOUS, lb=-GRB.INFINITY, name="x_flow") + + # UC variables (always continuous/relaxed) + x_commit = m.addVars(G_UC, T, vtype=GRB.CONTINUOUS, lb=0, name="x_commit") + x_start = m.addVars(G_UC, T, vtype=GRB.CONTINUOUS, lb=0, name="x_start") + x_shut = m.addVars(G_UC, T, vtype=GRB.CONTINUOUS, lb=0, name="x_shut") + + # Policy slack variables + x_RPS = m.addVars(W, vtype=GRB.CONTINUOUS, lb=0, name="x_RPS") + x_CO2 = m.addVars(W, vtype=GRB.CONTINUOUS, lb=0, name="x_CO2") + + m.update() + + # ========================================================================= + # OBJECTIVE FUNCTION (Eq. 29-34) + # ========================================================================= + print("Building objective...") + + # c^FIXED (Eq. 29) + c_fixed = gp.LinExpr() + + # Investment costs: sum_g c_P_INV * gamma_P * y_P_new + for g in G: + c_fixed += c_P_INV[g] * gamma_P[g] * y_P_new[g] + + # Storage energy investment: sum_{g in STOR} c_E_INV * gamma_E * y_E_new + for g in G_STOR: + c_fixed += c_E_INV_stor[g] * gamma_E[g] * y_E_new[g] + + # Hydro energy investment: sum_{g in HYDRO} c_E_INV_hydro * rho_g * y_P_new + for g in G_HYDRO: + c_fixed += c_E_INV_hydro[g] * rho_hydro[g] * y_P_new[g] + + # FOM: sum_g c_P_FOM * y_P + for g in G: + c_fixed += c_P_FOM[g] * y_P[g] + + # Storage energy FOM: sum_{g in STOR} c_E_FOM * y_E + for g in G_STOR: + c_fixed += c_E_FOM_stor[g] * y_E[g] + + # Hydro energy FOM: sum_{g in HYDRO} c_E_FOM_hydro * rho_g * y_P + for g in G_HYDRO: + c_fixed += c_E_FOM_hydro[g] * rho_hydro[g] * y_P[g] + + # Transmission investment: sum_l c_F_INV * y_F_new + for l in L: + c_fixed += c_F_INV[l] * y_F_new[l] + + # c^VAR (Eq. 30) + c_var = gp.LinExpr() + for g in G: + if c_VAR[g] == 0.0: + continue + for t in T: + c_var += c_VAR[g] * alpha[t] * x_inj[g, t] + for g in G_STOR: + if c_VAR[g] == 0.0: + continue + for t in T: + c_var += c_VAR[g] * alpha[t] * x_wdw[g, t] + + # c^NSE (Eq. 31) + c_nse = gp.LinExpr() + for i, (sid, z, frac, cost) in enumerate(nse_segments): + if cost == 0.0: + continue + for t in T: + c_nse += cost * alpha[t] * x_nse[i, t] + + # c^START (Eq. 32) + c_start = gp.LinExpr() + for g in G_UC: + if c_START[g] == 0.0: + continue + for t in T: + c_start += c_START[g] * alpha[t] * x_start[g, t] + + # c^RPS + c^CO2 (Eq. 33) + c_policy = gp.LinExpr() + for w in W: + c_policy += c_RPS * x_RPS[w] + c_policy += c_CO2 * x_CO2[w] + + m.setObjective(c_fixed + c_var + c_nse + c_start + c_policy, GRB.MINIMIZE) + + # ========================================================================= + # CONSTRAINTS + # ========================================================================= + + # ---- B.1 Investment Constraints ---- + print("Adding investment constraints...") + + # (12a) gamma_P * y_P_new <= y_P_max + for g in G: + m.addConstr(gamma_P[g] * y_P_new[g] <= y_P_max[g], name=f"inv_cap_{g}") + + # (12b) gamma_P * y_P_ret <= y_P_0 + for g in G: + m.addConstr(gamma_P[g] * y_P_ret[g] <= y_P_0[g], name=f"ret_cap_{g}") + + # (12c) y_P_ret = 0 for non-retirable + for g in G_NONRET: + m.addConstr(y_P_ret[g] == 0, name=f"noret_{g}") + + # (12d) y_P = y_P_0 + gamma_P * (y_P_new - y_P_ret) + for g in G: + m.addConstr(y_P[g] == y_P_0[g] + gamma_P[g] * (y_P_new[g] - y_P_ret[g]), + name=f"cap_bal_{g}") + + # (13a) gamma_E * y_E_new <= y_E_max + for g in G_STOR: + m.addConstr(gamma_E[g] * y_E_new[g] <= y_E_max[g], name=f"stor_inv_{g}") + + # (13b) gamma_E * y_E_ret <= y_E_0 + for g in G_STOR: + m.addConstr(gamma_E[g] * y_E_ret[g] <= y_E_0[g], name=f"stor_ret_{g}") + + # (13c) y_E_ret = 0 for non-retirable storage + for g in G_STOR: + if g in G_NONRET_set: + m.addConstr(y_E_ret[g] == 0, name=f"stor_noret_{g}") + + # (13d) y_E = y_E_0 + gamma_E * (y_E_new - y_E_ret) + for g in G_STOR: + m.addConstr(y_E[g] == y_E_0[g] + gamma_E[g] * (y_E_new[g] - y_E_ret[g]), + name=f"stor_bal_{g}") + + # (13e) rho_min * y_P <= y_E + for g in G_STOR: + m.addConstr(rho_min_stor[g] * y_P[g] <= y_E[g], name=f"stor_minrho_{g}") + + # (13f) rho_max * y_P >= y_E + for g in G_STOR: + m.addConstr(rho_max_stor[g] * y_P[g] >= y_E[g], name=f"stor_maxrho_{g}") + + # (14a) max_capacity_MW is total capacity after expansion. + for l in L: + m.addConstr( + y_F_new[l] <= max(0.0, y_F_max[l] - y_F_0[l]), + name=f"trans_inv_{l}", + ) + + # (14b) y_F = y_F_0 + y_F_new + for l in L: + m.addConstr(y_F[l] == y_F_0[l] + y_F_new[l], name=f"trans_bal_{l}") + + # ---- B.2 Operational Constraints ---- + print("Adding operational constraints...") + + # (15) Power balance: for each zone z, timestep t + for z in Z: + for t in T: + lhs = gp.LinExpr() + # + sum_{g in G_z} x_inj + for g in G_z[z]: + lhs += x_inj[g, t] + # - sum_{g in G_z^STOR} x_wdw + for g in G_z_STOR[z]: + lhs -= x_wdw[g, t] + # - sum_{l in I_z_out} x_flow + sum_{l in I_z_in} x_flow + for l in I_z_out[z]: + lhs -= x_flow[l, t] + for l in I_z_in[z]: + lhs += x_flow[l, t] + # + sum_s x_nse + for i, (sid, sz, frac, cost) in enumerate(nse_segments): + if sz == z: + lhs += x_nse[i, t] + m.addConstr(lhs == d_zt[z, t], name=f"pbal_{z}_{t}") + + # (16a) x_inj <= sigma * y_P for non-UC + print(" Output limits...") + for g in G_nonUC: + for t in T: + m.addConstr(x_inj[g, t] <= avail[g][t] * y_P[g], + name=f"out_lim_{g}_{t}") + + # (16b) x_wdw <= sigma * y_P for storage + for g in G_STOR: + for t in T: + m.addConstr(x_wdw[g, t] <= avail[g][t] * y_P[g], + name=f"wdw_lim_{g}_{t}") + + # (16c) x_inj + x_wdw <= y_P for storage + for g in G_STOR: + for t in T: + m.addConstr(x_inj[g, t] + x_wdw[g, t] <= y_P[g], + name=f"stor_pw_{g}_{t}") + + # (16d) x_soc <= y_E + for g in G_STOR: + for t in T: + m.addConstr(x_soc[g, t] <= y_E[g], name=f"soc_lim_{g}_{t}") + + # (16e) x_lvl <= rho * y_P for hydro + for g in G_HYDRO: + for t in T: + m.addConstr(x_lvl[g, t] <= rho_hydro[g] * y_P[g], + name=f"lvl_lim_{g}_{t}") + + # (16f) eta_charge * x_wdw <= y_E - x_soc + for g in G_STOR: + for t in T: + m.addConstr(eta_charge[g] * x_wdw[g, t] <= y_E[g] - x_soc[g, t], + name=f"chrg_room_{g}_{t}") + + # (16g) x_inj / eta_discharge <= x_soc + for g in G_STOR: + for t in T: + m.addConstr(x_inj[g, t] <= eta_discharge[g] * x_soc[g, t], + name=f"dchrg_avail_{g}_{t}") + + # (17a) x_inj >= theta * y_P for non-UC, non-storage, non-hydro + print(" Minimum output...") + for g in G_minout: + theta = min_output[g] + if theta > 0: + for t in T: + m.addConstr(x_inj[g, t] >= theta * y_P[g], + name=f"min_out_{g}_{t}") + + # (17b) x_inj + x_spill >= theta * y_P for hydro + for g in G_HYDRO: + theta = min_output[g] + if theta > 0: + for t in T: + m.addConstr(x_inj[g, t] + x_spill[g, t] >= theta * y_P[g], + name=f"hydro_min_{g}_{t}") + + # (18a, 18b) -y_F <= x_flow <= y_F + print(" Transmission limits...") + for l in L: + for t in T: + m.addConstr(x_flow[l, t] <= y_F[l], name=f"flow_ub_{l}_{t}") + m.addConstr(-x_flow[l, t] <= y_F[l], name=f"flow_lb_{l}_{t}") + + # (19) x_nse <= nu_s * d_{z,t} + print(" NSE limits...") + for i, (sid, z, frac, cost) in enumerate(nse_segments): + for t in T: + m.addConstr(x_nse[i, t] <= frac * d_zt[z, t], + name=f"nse_lim_{i}_{t}") + + # (20a, 20b) Storage dynamics + print(" Storage dynamics...") + for g in G_STOR: + ec = eta_charge[g] + ed = eta_discharge[g] + sd = eta_self_discharge[g] + for w in W: + hours = H_w[w] + first = hours[0] + last = hours[-1] + + # (20b) Wrap-around: first timestep links to last + m.addConstr( + x_soc[g, first] - x_soc[g, last] == + ec * x_wdw[g, first] - x_inj[g, first] / ed - sd * x_soc[g, last], + name=f"soc_wrap_{g}_{w}") + + # (20a) Interior timesteps + for idx in range(1, len(hours)): + t = hours[idx] + t_prev = hours[idx - 1] + m.addConstr( + x_soc[g, t] - x_soc[g, t_prev] == + ec * x_wdw[g, t] - x_inj[g, t] / ed - sd * x_soc[g, t_prev], + name=f"soc_dyn_{g}_{t}") + + # (20c, 20d) Hydro dynamics + print(" Hydro dynamics...") + for g in G_HYDRO: + for w in W: + hours = H_w[w] + first = hours[0] + last = hours[-1] + + # (20d) Wrap-around + m.addConstr( + x_lvl[g, first] - x_lvl[g, last] == + h_inflow[g][first] * y_P[g] - x_inj[g, first] - x_spill[g, first], + name=f"hydro_wrap_{g}_{w}") + + # (20c) Interior timesteps + for idx in range(1, len(hours)): + t = hours[idx] + t_prev = hours[idx - 1] + m.addConstr( + x_lvl[g, t] - x_lvl[g, t_prev] == + h_inflow[g][t] * y_P[g] - x_inj[g, t] - x_spill[g, t], + name=f"hydro_dyn_{g}_{t}") + + # (21a-21d) Non-UC ramping + print(" Non-UC ramping...") + for g in G_nonUC: + mu_up = ramp_up[g] + mu_dn = ramp_down[g] + if mu_up == 0 and mu_dn == 0: + continue + for w in W: + hours = H_w[w] + first = hours[0] + last = hours[-1] + + # (21c) wrap: x_inj[first] - x_inj[last] <= mu_up * y_P + if mu_up > 0: + m.addConstr(x_inj[g, first] - x_inj[g, last] <= mu_up * y_P[g], + name=f"ramp_up_wrap_{g}_{w}") + # (21d) wrap: x_inj[last] - x_inj[first] <= mu_dn * y_P + if mu_dn > 0: + m.addConstr(x_inj[g, last] - x_inj[g, first] <= mu_dn * y_P[g], + name=f"ramp_dn_wrap_{g}_{w}") + + # (21a, 21b) Interior + for idx in range(1, len(hours)): + t = hours[idx] + t_prev = hours[idx - 1] + if mu_up > 0: + m.addConstr(x_inj[g, t] - x_inj[g, t_prev] <= mu_up * y_P[g], + name=f"ramp_up_{g}_{t}") + if mu_dn > 0: + m.addConstr(x_inj[g, t_prev] - x_inj[g, t] <= mu_dn * y_P[g], + name=f"ramp_dn_{g}_{t}") + + # (22a-22g) UC constraints + print(" UC constraints...") + for g in G_UC: + gp_size = gamma_P[g] + theta = min_output[g] + for t in T: + # (22a) gamma * commit <= y_P + m.addConstr(gp_size * x_commit[g, t] <= y_P[g], + name=f"uc_cap_{g}_{t}") + # (22b) gamma * start <= y_P + m.addConstr(gp_size * x_start[g, t] <= y_P[g], + name=f"uc_start_cap_{g}_{t}") + # (22c) gamma * shut <= y_P + m.addConstr(gp_size * x_shut[g, t] <= y_P[g], + name=f"uc_shut_cap_{g}_{t}") + # (22d) x_inj >= commit * theta * gamma + m.addConstr(x_inj[g, t] >= x_commit[g, t] * theta * gp_size, + name=f"uc_min_{g}_{t}") + # (22e) x_inj <= commit * sigma * gamma + m.addConstr(x_inj[g, t] <= x_commit[g, t] * avail[g][t] * gp_size, + name=f"uc_max_{g}_{t}") + + # (22f, 22g) Commitment state transitions + for w in W: + hours = H_w[w] + first = hours[0] + last = hours[-1] + + # (22g) Wrap-around + m.addConstr( + x_commit[g, first] - x_commit[g, last] == + x_start[g, first] - x_shut[g, first], + name=f"uc_trans_wrap_{g}_{w}") + + # (22f) Interior + for idx in range(1, len(hours)): + t = hours[idx] + t_prev = hours[idx - 1] + m.addConstr( + x_commit[g, t] - x_commit[g, t_prev] == + x_start[g, t] - x_shut[g, t], + name=f"uc_trans_{g}_{t}") + + # (23a-23d) UC ramping + print(" UC ramping...") + for g in G_UC: + gp_size = gamma_P[g] + theta = min_output[g] + mu_up = ramp_up[g] + mu_dn = ramp_down[g] + + for w in W: + hours = H_w[w] + first = hours[0] + last = hours[-1] + + # Helper for ramp coefficients + def start_coeff_up(t_idx): + sig = avail[g][t_idx] + return min(sig, max(theta, mu_up)) + + def start_coeff_dn(t_idx): + sig = avail[g][t_idx] + return min(sig, max(theta, mu_dn)) + + # (23c) Wrap-around up: x_inj[first] - x_inj[last] <= ... + m.addConstr( + x_inj[g, first] - x_inj[g, last] <= + gp_size * mu_up * (x_commit[g, first] - x_start[g, first]) + + gp_size * start_coeff_up(first) * x_start[g, first] + - gp_size * theta * x_shut[g, first], + name=f"uc_ramp_up_wrap_{g}_{w}") + + # (23d) Wrap-around down: x_inj[last] - x_inj[first] <= ... + m.addConstr( + x_inj[g, last] - x_inj[g, first] <= + gp_size * mu_dn * (x_commit[g, first] - x_start[g, first]) + + gp_size * start_coeff_dn(first) * x_start[g, first] + - gp_size * theta * x_shut[g, first], + name=f"uc_ramp_dn_wrap_{g}_{w}") + + # (23a, 23b) Interior + for idx in range(1, len(hours)): + t = hours[idx] + t_prev = hours[idx - 1] + + # (23a) Up + m.addConstr( + x_inj[g, t] - x_inj[g, t_prev] <= + gp_size * mu_up * (x_commit[g, t] - x_start[g, t]) + + gp_size * start_coeff_up(t) * x_start[g, t] + - gp_size * theta * x_shut[g, t], + name=f"uc_ramp_up_{g}_{t}") + + # (23b) Down + m.addConstr( + x_inj[g, t_prev] - x_inj[g, t] <= + gp_size * mu_dn * (x_commit[g, t] - x_start[g, t]) + + gp_size * start_coeff_dn(t) * x_start[g, t] + - gp_size * theta * x_shut[g, t], + name=f"uc_ramp_dn_{g}_{t}") + + # (24a, 24b, 25) Minimum up/down time + print(" Min up/down time...") + for g in G_UC: + gp_size = gamma_P[g] + tau_up = min_up_time[g] + tau_dn = min_down_time[g] + + for w in W: + hours = H_w[w] + n_hours = len(hours) + + for local_idx in range(n_hours): + t = hours[local_idx] + + # (24a) x_commit[g,t] >= sum_{k in Omega_up(t)} x_start[g,k] + if tau_up > 0: + lhs = gp.LinExpr() + for step in range(tau_up + 1): # 0..tau_up + # phi_{w,step}(t): step steps before t (circular) + k_local = (local_idx - step) % n_hours + k = hours[k_local] + lhs += x_start[g, k] + m.addConstr(x_commit[g, t] >= lhs, + name=f"min_up_{g}_{t}") + + # (24b) x_commit[g,t] + sum_{k in Omega_dn(t)} x_shut[g,k] <= y_P / gamma + if tau_dn > 0: + lhs = x_commit[g, t] + for step in range(tau_dn + 1): # 0..tau_dn + k_local = (local_idx - step) % n_hours + k = hours[k_local] + lhs += x_shut[g, k] + m.addConstr(lhs <= y_P[g] / gp_size, + name=f"min_dn_{g}_{t}") + + # ---- B.3 Policy Constraints ---- + print("Adding policy constraints...") + + # Compute total weighted demand + total_weighted_demand = sum(alpha[t] * d_zt[z, t] for z in Z for t in T) + + # (26) RPS constraint + if RPS_share > 0 or c_RPS > 0: + rps_lhs = gp.LinExpr() + for w in W: + for t in H_w[w]: + for g in G_RPS: + rps_lhs += alpha[t] * x_inj[g, t] + rps_lhs += x_RPS[w] + m.addConstr(rps_lhs >= RPS_share * total_weighted_demand, name="rps") + + # (27a, 28) CO2 cap + # overline{c}^{CO2} = CO2_cap_tons_per_MWh * total_weighted_demand + # But for CO2 scenario, eq 28 says cap = 0.05 * total_weighted_demand + # The instance provides CO2_cap_tons_per_MWh which encodes this. + co2_cap = CO2_cap_rate * total_weighted_demand + + co2_lhs = gp.LinExpr() + for w in W: + for t in H_w[w]: + for g in G: + if co2_rate[g] != 0: + co2_lhs += alpha[t] * co2_rate[g] * x_inj[g, t] + for g in G_STOR: + if co2_rate[g] != 0: + co2_lhs += alpha[t] * co2_rate[g] * x_wdw[g, t] + co2_lhs -= x_CO2[w] + m.addConstr(co2_lhs <= co2_cap, name="co2_cap") + + if not quiet: + print(f"Model has {m.NumVars} variables and {m.NumConstrs} constraints.") + return m, { + "generators": generators, + "y_P_new": y_P_new, + "y_P_ret": y_P_ret, + "y_P": y_P, + "y_E_new": y_E_new, + "y_E_ret": y_E_ret, + "y_E": y_E, + "y_F_new": y_F_new, + "y_F": y_F, + "G": G, + "G_STOR": G_STOR, + "G_HYDRO": G_HYDRO, + "L": L, + "gamma_P": gamma_P, + "gamma_E": gamma_E, + } + + +def solve_model(m, time_limit=None, formulation="MILP"): + """Configure solver parameters and solve.""" + + tol = 1e-3 + + # Barrier method with crossover off (for monolithic) + m.Params.Method = 2 # Barrier + m.Params.Crossover = 0 # Crossover off + m.Params.BarConvTol = tol + m.Params.OptimalityTol = tol + m.Params.FeasibilityTol = tol + + if formulation == "MILP": + m.Params.MIPGap = 1e-4 + + if time_limit is not None: + m.Params.TimeLimit = time_limit + m.Params.MIPFocus = 1 + m.Params.NoRelHeurTime = min(60.0, time_limit * 0.05) + + print("Solving...") + start_time = time.time() + m.optimize() + elapsed = time.time() - start_time + print(f"Solve time: {elapsed:.2f} seconds") + + return elapsed + + +def extract_solution(m, model_data): + """Extract solution values and build output dict.""" + + sol = {} + + status = m.Status + sol["status"] = status + sol["status_name"] = { + 1: "LOADED", 2: "OPTIMAL", 3: "INFEASIBLE", 4: "INF_OR_UNBD", + 5: "UNBOUNDED", 6: "CUTOFF", 7: "ITERATION_LIMIT", + 8: "NODE_LIMIT", 9: "TIME_LIMIT", 10: "SOLUTION_LIMIT", + 11: "INTERRUPTED", 12: "NUMERIC", 13: "SUBOPTIMAL", + 14: "INPROGRESS", 15: "USER_OBJ_LIMIT", 16: "WORK_LIMIT", + 17: "MEM_LIMIT" + }.get(status, "UNKNOWN") + + if status in (GRB.OPTIMAL, GRB.SUBOPTIMAL, GRB.TIME_LIMIT, GRB.SOLUTION_LIMIT, + GRB.ITERATION_LIMIT, GRB.NODE_LIMIT, GRB.INTERRUPTED): + try: + sol["objective_value"] = m.ObjVal + except Exception: + sol["objective_value"] = None + else: + sol["objective_value"] = None + + if m.SolCount > 0: + try: + sol["objective_bound"] = m.ObjBound + except Exception: + sol["objective_bound"] = None + + # Extract investment decisions + investments = {} + generators = model_data["generators"] + y_P_new = model_data["y_P_new"] + y_P_ret = model_data["y_P_ret"] + y_P = model_data["y_P"] + gamma_P = model_data["gamma_P"] + + for g in model_data["G"]: + gen = generators[g] + pnew = y_P_new[g].X + pret = y_P_ret[g].X + pcap = y_P[g].X + if abs(pnew) > 1e-6 or abs(pret) > 1e-6: + investments[str(g)] = { + "resource_type": gen["resource_type"], + "zone": gen["zone"], + "new_units": pnew, + "new_MW": pnew * gamma_P[g], + "retired_units": pret, + "retired_MW": pret * gamma_P[g], + "total_capacity_MW": pcap + } + + sol["investments"] = investments + + # Storage energy investments + stor_investments = {} + y_E_new = model_data["y_E_new"] + y_E = model_data["y_E"] + gamma_E = model_data["gamma_E"] + for g in model_data["G_STOR"]: + enew = y_E_new[g].X + ecap = y_E[g].X + if abs(enew) > 1e-6: + stor_investments[str(g)] = { + "new_units": enew, + "new_MWh": enew * gamma_E[g], + "total_energy_MWh": ecap + } + sol["storage_energy_investments"] = stor_investments + + # Transmission investments + trans_investments = {} + y_F_new = model_data["y_F_new"] + y_F = model_data["y_F"] + for l in model_data["L"]: + fnew = y_F_new[l].X + if abs(fnew) > 1e-6: + trans_investments[str(l)] = { + "new_MW": fnew, + "total_capacity_MW": y_F[l].X + } + sol["transmission_investments"] = trans_investments + else: + sol["investments"] = {} + sol["storage_energy_investments"] = {} + sol["transmission_investments"] = {} + + return sol + + +def main(): + parser = argparse.ArgumentParser( + description="Monolithic energy systems planning model (Jacobson et al. 2023)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to JSON instance file") + parser.add_argument("--solution_path", type=str, default="gurobi_solution_1.json", + help="Path for output solution JSON") + parser.add_argument("--time_limit", type=int, default=None, + help="Solver time limit in seconds") + parser.add_argument("--formulation", type=str, default="MILP", + choices=["LP", "MILP"], + help="Formulation type (LP or MILP)") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print(f"Loading instance from {args.instance_path}") + inst = load_instance(args.instance_path) + + formulation = args.formulation + # If instance specifies only one formulation type, use that + form_types = inst["problem_parameters"].get("formulation_types", ["LP", "MILP"]) + if formulation not in form_types: + print(f"Warning: requested formulation {formulation} not in instance types {form_types}.") + + print(f"Building {formulation} model...") + model, model_data = build_model(inst, formulation=formulation) + + elapsed = solve_model(model, time_limit=args.time_limit, formulation=formulation) + + solution = extract_solution(model, model_data) + solution["solve_time_seconds"] = elapsed + solution["formulation"] = formulation + solution["instance_path"] = args.instance_path + + print(f"\nStatus: {solution['status_name']}") + if solution["objective_value"] is not None: + print(f"Objective value: {solution['objective_value']:.6f}") + + 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 __name__ == "__main__": + main() diff --git a/tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2022/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/rahmaniani2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2022/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/rahmaniani2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2022/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/rahmaniani2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2022/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/rahmaniani2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rahmaniani2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2022/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/rahmaniani2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rahmaniani2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rahmaniani2022/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/rahmaniani2022/gurobi_solution/large_solution_1.json b/tasks/rahmaniani2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..63b0a7baa9c954fab9933f725a4297eb0eab8576 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c31331734d4c0dc15b9607b9f6f522cfdc88b6c05853bbd32318afadc7b947e9 +size 580345 diff --git a/tasks/rahmaniani2022/gurobi_solution/large_solution_2.json b/tasks/rahmaniani2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..df82f2c03c8e5ec1754525ea5d935505f3318f80 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6418ba94f6699fabc1595e06fc247148f86c7e2abf44aa32613b7230e2bbadb4 +size 428584 diff --git a/tasks/rahmaniani2022/gurobi_solution/large_solution_3.json b/tasks/rahmaniani2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..2e48813fe35793fcabba90302c9cb6a914fb7aeb --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f37ee8b8b2b44a71825a75d538954e987d4b0ae8613f06b6c78d18263fb5657e +size 553489 diff --git a/tasks/rahmaniani2022/gurobi_solution/large_solution_4.json b/tasks/rahmaniani2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..32e08b5b79be85dd50d14c1321712a60eabb8a76 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e2c133201a1901112c439b6c0aff21e7e8751d36b5dcf8a93d6e10f5d99b7c7 +size 540634 diff --git a/tasks/rahmaniani2022/gurobi_solution/large_solution_5.json b/tasks/rahmaniani2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..5679159830e7b288c065235ffd5c1b61e9754792 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c1af973c722b25b6fb6ca79eb81a939533e80a5a04e28407e151aa6786bb6d7 +size 509345 diff --git a/tasks/rahmaniani2022/gurobi_solution/tiny_solution.json b/tasks/rahmaniani2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..2f4aa35c0b4e23b7ee9c00296f4d61bba1dcb08c --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:109626733b8280583dfe1d6f2f72db0dd7e850f754e92da47bb7d0a7067a8ed4 +size 912573 diff --git a/tasks/rahmaniani2022/gurobi_solution_log/large_log_1.jsonl b/tasks/rahmaniani2022/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..25678ae5b71751f70a1e0dd2cacf58563cfc30a6 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3abc3a128b4da4b5f3687c2d1169ebd7013bdd6f6366421f1471c60e348377b1 +size 2618 diff --git a/tasks/rahmaniani2022/gurobi_solution_log/large_log_2.jsonl b/tasks/rahmaniani2022/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ebb0282183f43ece322543019494e0eb85a41a0 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68a5613e8c0fff9218eadd6d14e1ef0970f1160e72eea7fb4bed4ea5c4587129 +size 2242 diff --git a/tasks/rahmaniani2022/gurobi_solution_log/large_log_3.jsonl b/tasks/rahmaniani2022/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..564ce9d14d5d65abca7f8c921f4df3bc7fac5297 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fc1f1d414a17bb0f0be7d20cd20b379f0998e77d009bb76559bf0373b99673c +size 57 diff --git a/tasks/rahmaniani2022/gurobi_solution_log/large_log_4.jsonl b/tasks/rahmaniani2022/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..34921b5b75653a54d1a2374c52582e7cb46c29aa --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb928790663fe1c0afb2c712ec2c1bcb4d2bd846cd4b0a1a8b21d27a891ae65e +size 114 diff --git a/tasks/rahmaniani2022/gurobi_solution_log/large_log_5.jsonl b/tasks/rahmaniani2022/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0e041e511cf7d94e1b2c21e347ba45872cbfc60c --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cb9fc0fa06ea45684e37cfdc9ea88fe30614b8710a1e101947c2a3a7f5f60fc +size 557 diff --git a/tasks/rahmaniani2022/gurobi_solution_log/tiny_log.jsonl b/tasks/rahmaniani2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb368453808fbc2190e721af124e48a7d516ecf2 --- /dev/null +++ b/tasks/rahmaniani2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc9e38e530f553ff3ed86d26b1615c19db3ee3ed0af07a37c789ebbfdc0d5490 +size 109 diff --git a/tasks/rahmaniani2022/instance/large_instance_1.json b/tasks/rahmaniani2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ba92b2106a1cb91de4465da3d5678f70d22ed940 --- /dev/null +++ b/tasks/rahmaniani2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eadcf5c89bfcd588e1825a6027e7ce42effe2ff164771ed9a12e8d36dcf6d8f7 +size 1953647 diff --git a/tasks/rahmaniani2022/instance/large_instance_2.json b/tasks/rahmaniani2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..075ee69cb9f59438db93a2b14e4bc3c99acd4ae3 --- /dev/null +++ b/tasks/rahmaniani2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdeb36375a8968da973ea273fff77c65d0f54ec471392e628e64b942dc9c429c +size 1952683 diff --git a/tasks/rahmaniani2022/instance/large_instance_3.json b/tasks/rahmaniani2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3071acec530713ab81b743627e0c568d067081fe --- /dev/null +++ b/tasks/rahmaniani2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:404f2d3c0bedf8761c024ef820118a3e4244f5da75832d5b7ca6620d9a15ef30 +size 1947572 diff --git a/tasks/rahmaniani2022/instance/large_instance_4.json b/tasks/rahmaniani2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9c5449c78504505da78ce550c08cd33bc138f3ce --- /dev/null +++ b/tasks/rahmaniani2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6887fe1608a652cdec62abd626e3dd9dee7cf820ccf42efa3292caf316747cce +size 1942600 diff --git a/tasks/rahmaniani2022/instance/large_instance_5.json b/tasks/rahmaniani2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d87332c673a2f3590f111808bb46a011467a1898 --- /dev/null +++ b/tasks/rahmaniani2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f326d6f07923a2cd0d03c1f24ef34f860705d8d809a3bc5b7812d4bce30732f1 +size 1942894 diff --git a/tasks/rahmaniani2022/instance/tiny_instance.json b/tasks/rahmaniani2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c9c2f8de3b56060282869f07d68914345a603c54 --- /dev/null +++ b/tasks/rahmaniani2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d39eb0c51c661635e8232d2f19bb754f198fc76ba20d8084771233bd43bedd42 +size 302614 diff --git a/tasks/rahmaniani2022/instance_schema.json b/tasks/rahmaniani2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..de73fd761569490192dfc14ba6ad465eff7c48b6 --- /dev/null +++ b/tasks/rahmaniani2022/instance_schema.json @@ -0,0 +1,106 @@ +{ + "problem_parameters": { + "num_zones": " Number of spatial zones in the power grid.", + "num_weeks": " Number of representative subperiods (weeks) in the planning year.", + "hours_per_subperiod": " Number of consecutive hours in each subperiod (always 168).", + "total_hours": " Total number of hourly time steps across all subperiods.", + "num_generator_clusters": " Total number of generation and storage resource clusters across all zones.", + "num_UC_generators": " Number of resource clusters subject to unit commitment constraints." + }, + "released_investment_convention": { + "uc_power_increment": " UC investment counts physical generator blocks.", + "non_uc_power_increment_MW": " Non-UC investment counts integer MW increments rather than physical cluster units.", + "uc_storage_energy_increment": ".energy_capacity_size_MWh'> UC storage energy uses its physical energy block.", + "non_uc_storage_energy_increment_MWh": " Non-UC storage energy investment counts integer MWh increments.", + "transmission_increment_MW": " MILP transmission expansion counts integer MW increments.", + "transmission_max_capacity_semantics": " transmission max_capacity_MW bounds final total line capacity.", + "milp_investment_variables_are_integer": " All released MILP investment-count variables are integral." + }, + "policy": { + "type": " Policy scenario identifier (REF, RPS, or CO2).", + "description": " Human-readable description of the active policy scenario.", + "RPS_share": " Minimum fraction of total weighted demand that must be met by RPS-qualifying generation.", + "CO2_cap_tons_per_MWh": " CO2 emissions cap expressed as tons per MWh of total weighted demand.", + "RPS_noncompliance_cost_per_MWh": " Penalty cost per MWh of shortfall below the RPS target.", + "CO2_noncompliance_cost_per_ton": " Penalty cost per ton of CO2 emissions exceeding the cap." + }, + "subperiod_weights": " Weight of each subperiod reflecting how many weeks of the year it represents.", + "generators": " List of resource cluster definitions, each containing the fields below.", + "generators[*]": { + "cluster_id": " Unique identifier for this resource cluster.", + "zone": " Zone in which this resource cluster is located.", + "resource_type": " Technology type of the resource (e.g., natural_gas_CC, solar, battery, hydro).", + "is_UC": " Whether this cluster is subject to unit commitment constraints.", + "is_VRE": " Whether this cluster is a variable renewable energy resource.", + "is_storage": " Whether this cluster is a battery storage resource.", + "is_hydro": " Whether this cluster is a hydropower resource.", + "is_RPS_qualifying": " Whether generation from this cluster counts toward the renewable portfolio standard.", + "can_retire": " Whether existing units in this cluster may be retired.", + "capacity_size_MW": " Physical power capacity of one cluster unit in MW; it is the investment block only for UC resources under released_investment_convention." + }, + "generator_parameters": { + "": { + "capacity_size_MW": " Power capacity of one unit in MW.", + "min_output_frac": " Minimum generation output as a fraction of committed capacity.", + "ramp_up_rate_pct_per_hr": " Maximum hourly increase in output as a fraction of capacity.", + "ramp_down_rate_pct_per_hr": " Maximum hourly decrease in output as a fraction of capacity.", + "min_up_time_hr": " Minimum number of consecutive hours a unit must remain online after starting.", + "min_down_time_hr": " Minimum number of consecutive hours a unit must remain offline after shutting down.", + "variable_cost_per_MWh": " Variable operating cost per MWh of generation.", + "fixed_OM_cost_per_MW_yr": " Annual fixed operations and maintenance cost per MW of installed capacity.", + "investment_cost_per_MW_yr": " Annualized capital cost per MW for building new capacity.", + "start_up_cost": " Cost incurred each time a unit is started up.", + "CO2_emission_tons_per_MWh": " CO2 emissions in tons per MWh of generation.", + "max_capacity_MW": " Maximum total new capacity in MW that can be built for this resource type per zone." + }, + "battery": { + "capacity_size_MW": " Power capacity of one battery unit in MW.", + "energy_capacity_size_MWh": " Energy capacity of one battery unit in MWh.", + "charging_efficiency": " Fraction of withdrawn energy that is stored when charging.", + "discharging_efficiency": " Fraction of stored energy that is delivered when discharging.", + "self_discharge_rate_pct": " Fraction of stored energy lost per hour due to self-discharge.", + "min_duration_MWh_per_MW": " Minimum ratio of energy capacity to power capacity in MWh per MW.", + "max_duration_MWh_per_MW": " Maximum ratio of energy capacity to power capacity in MWh per MW.", + "variable_cost_per_MWh": " Variable operating cost per MWh of storage throughput.", + "fixed_OM_cost_per_MW_yr": " Annual fixed operations and maintenance cost per MW of installed power capacity.", + "investment_cost_per_MW_yr": " Annualized capital cost per MW of new power capacity.", + "energy_investment_cost_per_MWh_yr": " Annualized capital cost per MWh of new energy capacity.", + "energy_fixed_OM_cost_per_MWh_yr": " Annual fixed energy-side O&M cost per installed MWh; explicitly zero in the released data.", + "max_capacity_MW": " Maximum total new power capacity in MW that can be built.", + "max_energy_capacity_MWh": " Maximum total new energy capacity in MWh that can be built.", + "CO2_emission_tons_per_MWh": " CO2 emissions in tons per MWh of storage throughput." + }, + "hydro": { + "capacity_size_MW": " Power capacity of one hydro unit in MW.", + "min_output_frac": " Minimum combined generation and spillage as a fraction of power capacity.", + "duration_MWh_per_MW": " Fixed ratio of reservoir energy capacity to power capacity in MWh per MW.", + "variable_cost_per_MWh": " Variable operating cost per MWh of hydro generation.", + "fixed_OM_cost_per_MW_yr": " Annual fixed operations and maintenance cost per MW of installed capacity.", + "investment_cost_per_MW_yr": " Annualized capital cost per MW for building new hydro capacity.", + "energy_investment_cost_per_MWh_yr": " Hydro reservoir energy investment cost per MWh; explicitly zero in the released data.", + "energy_fixed_OM_cost_per_MWh_yr": " Hydro reservoir fixed O&M cost per MWh; explicitly zero in the released data.", + "CO2_emission_tons_per_MWh": " CO2 emissions in tons per MWh of hydro generation.", + "max_capacity_MW": " Maximum total new hydro capacity in MW that can be built." + } + }, + "existing_capacity": " Pre-existing installed power capacity in MW for each resource cluster.", + "demand": " Hourly electricity demand in MWh for each zone, as a list of length total_hours.", + "consumer_segments": " Non-served energy segments defining curtailment tiers per zone.", + "consumer_segments[*]": { + "segment_id": " Identifier for this curtailment tier.", + "zone": " Zone to which this segment applies.", + "max_nse_fraction": " Maximum fraction of zonal hourly demand that may go unserved in this tier.", + "cost_per_MWh": " Penalty cost per MWh of unserved energy in this tier." + }, + "transmission_lines": " Inter-zonal transmission lines connecting pairs of zones.", + "transmission_lines[*]": { + "line_id": " Unique identifier for this transmission line.", + "from_zone": " Zone at one end of the transmission line.", + "to_zone": " Zone at the other end of the transmission line.", + "existing_capacity_MW": " Pre-existing transfer capacity of the line in MW.", + "max_capacity_MW": " Maximum total capacity the line can reach after expansion in MW.", + "investment_cost_per_MW_yr": " Annualized capital cost per MW of new transmission capacity." + }, + "availability": " Hourly availability factor (0 to 1) for each resource cluster, as a list of length total_hours.", + "hydro_inflow": " Hourly normalized inflow fraction for each hydro cluster, as a list of length total_hours." +} diff --git a/tasks/rahmaniani2022/mathematical_formulation.md b/tasks/rahmaniani2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..88255a9749226882359510ea8ccff956836d84e1 --- /dev/null +++ b/tasks/rahmaniani2022/mathematical_formulation.md @@ -0,0 +1,90 @@ +# Original Formulation: Energy Systems Planning Problem + +Jacobson, Pecci, Sepulveda, Xu, Jenkins. “A computationally efficient Benders decomposition for energy systems planning problems with detailed operations and time-coupling constraints.” Section 2 (compact form) and Appendix B (detailed constraints). + +## Sets and Indices + +- $G$: resources (generators, storage units); $G^{UC}$: units subject to unit commitment; $G^{NONRET}$: non-retirable; $G^{RPS}$: RPS-qualifying; $G^{STOR}$: storage; $G^{HYDRO}$: hydro. + +- $Z$: spatial zones; $S$: demand segments; $L$: transmission lines. + +- $W$: subperiods; $H_w = \{(w-1)\delta_w + 1,\dots,w\delta_w\}$: hours in subperiod $w$; $t_w^0$, $t_w$: first/last hours; $H_w^0 = H_w\setminus\{t_w^0\}$. + +- $I_z^{in}$, $I_z^{out}$: lines into/out of zone $z$; $G_z$, $G_z^{STOR}$: resources/storage in zone $z$. + +## Decision Variables + +**Investment:** $y_g^P$ (capacity MW), $y_g^E$ (storage MWh), $y_l^F$ (line MW), $y_g^{P,\text{NEW}}$, $y_g^{E,\text{NEW}}$, $y_l^{F,\text{NEW}}$ (investments; integer in MILP), $y_g^{P,\text{RET}}$, $y_g^{E,\text{RET}}$ (retirements; integer in MILP). + +**Operational (per timestep $t$):** $x_{g,t}^{\text{inj}}$ (injection), $x_{g,t}^{\text{wdw}}$ (storage withdrawal), $x_{s,z,t}^{\text{nse}}$ (non-served energy), $x_{g,t}^{\text{soc}}$ (state of charge), $x_{g,t}^{\text{lvl}}$ (hydro level), $x_{g,t}^{\text{spill}}$ (spillage), $x_{l,t}^{\text{flow}}$ (line flow, free), $x_{g,t}^{\text{commit}}$, $x_{g,t}^{\text{start}}$, $x_{g,t}^{\text{shut}}$ (UC). + +**Policy slack:** $x_w^{RPS}$, $x_w^{CO2} \geq 0$. + +## Compact Formulation (Section 2.1, Problem 1) + +Let $\mathbf{y}\in\mathbb{R}^m$ group all investment variables and $\mathbf{x}_w\in\mathbb{R}^n$ group all operational variables for subperiod $w$. Matrices $(\mathbf{A}_w,\mathbf{B}_w,\mathbf{b}_w)$ encode operational constraints (Appendix B.2, eqs. 15–24); $(\mathbf{Q}_w,\mathbf{e})$ encode time-coupling policy constraints (eqs. 26–27); $(\mathbf{R},\mathbf{r})$ encode investment-only constraints (eqs. 12–14). Vector $\mathbf{c}_I$ encodes fixed-cost objective terms (eq. 29), and $\mathbf{c}_w$ encodes operational-cost terms (eqs. 30–33). + +$$\begin{align} +\min \quad & \mathbf{c}_I^\top \mathbf{y} + \sum_{w\in W} \mathbf{c}_w^\top \mathbf{x}_w \tag{1a} \\ +\text{s.t.}\quad + & \mathbf{A}_w \mathbf{x}_w + \mathbf{B}_w \mathbf{y} \leq \mathbf{b}_w, &&\forall w \in W \tag{1b} \\ + & \sum_{w\in W} \mathbf{Q}_w \mathbf{x}_w \leq \mathbf{e} \tag{1c} \\ + & \mathbf{R}\mathbf{y} \leq \mathbf{r} \tag{1d} \\ + & \mathbf{x}_w \geq 0, &&\forall w \in W \tag{1e} \\ + & \mathbf{y} \geq 0 \tag{1f} \\ + & \mathbf{y} \in \mathbb{Z}^m \tag{1g} +\end{align}$$ + +## Objective Components (eqs. 29–34) + +$$\begin{align} +& c^{\text{FIXED}} = \sum_{g\in G} c_g^{P,\text{INV}} \gamma_g^{P,\text{SIZE}} y_g^{P,\text{NEW}} + + \sum_{g\in G^{\text{STOR}}} c_g^{E,\text{INV}} \gamma_g^{E,\text{SIZE}} y_g^{E,\text{NEW}} + \notag\\ +& \quad + \sum_{g\in G^{\text{HYDRO}}} c_g^{E,\text{INV}} \rho_g y_g^{P,\text{NEW}} + + \sum_{g\in G} c_g^{P,\text{FOM}} y_g^P + + \sum_{g\in G^{\text{STOR}}} c_g^{E,\text{FOM}} y_g^E + \notag\\ +& \quad + \sum_{g\in G^{\text{HYDRO}}} c_g^{E,\text{FOM}} \rho_g y_g^P + + \sum_{l\in L} c_l^{F,\text{INV}} y_l^{F,\text{NEW}} \tag{29} \\ +& c^{\text{VAR}} = \sum_{w,\,t\in H_w}\!\!\Big(\sum_{g\in G} c_g^{\text{VAR}} \alpha_t x_{g,t}^{\text{inj}} + + \sum_{g\in G^{\text{STOR}}} c_g^{\text{VAR}} \alpha_t x_{g,t}^{\text{wdw}}\Big) \tag{30} \\ +& c^{\text{NSE}} = \sum_{w,\,t\in H_w}\sum_{z\in Z}\sum_{s\in S} c_{s,z}^{\text{NSE}} \alpha_t x_{s,z,t}^{\text{nse}} \tag{31} \\ +& c^{\text{START}} = \sum_{w,\,t\in H_w}\sum_{g\in G^{UC}} c_g^{\text{START}} \alpha_t x_{g,t}^{\text{start}} \tag{32} \\ +& c^{\text{RPS}} + c^{\text{CO2}} = \sum_{w\in W} c^{\text{RPS}} x_w^{RPS} + + \sum_{w\in W} c^{\text{CO2}} x_w^{CO2} \tag{33} \\ +& \text{Objective:}\ c^{\text{FIXED}}+c^{\text{VAR}}+c^{\text{NSE}}+c^{\text{START}}+c^{\text{RPS}}+c^{\text{CO2}} \tag{34} +\end{align}$$ + +## Constraint Groups (Appendix B) + +**B.1 Investment (eqs. 12–14).** Capacity, retirement, and transmission-expansion bounds: $\gamma_g^{P,\text{SIZE}} y_g^{P,\text{NEW}} \leq \overline{y}_g^P$; $\gamma_g^{P,\text{SIZE}} y_g^{P,\text{RET}} \leq y_g^{P,0}$; $y_g^{P,\text{RET}}=0$ for $g\in G^{NONRET}$; $y_g^P = y_g^{P,0} + \gamma_g^{P,\text{SIZE}}(y_g^{P,\text{NEW}}-y_g^{P,\text{RET}})$; analogous for storage ($y_g^E$) with duration limits $\underline{\rho}_g y_g^P \leq y_g^E \leq \overline{\rho}_g y_g^P$; $y_l^{F,\text{NEW}} \leq \overline{y}_l^F$ and $y_l^F = y_l^{F,0} + y_l^{F,\text{NEW}}$. + +**Released data convention.** In the MILP, $\gamma_g^{P,\text{SIZE}}$ is the +physical block size for UC resources and 1 MW for non-UC resources; +$\gamma_g^{E,\text{SIZE}}$ is 1 MWh for the released non-UC storage resources. +Transmission additions are integer MW and are bounded by +$y_l^{F,\text{NEW}}\leq\max(0,\overline y_l^F-y_l^{F,0})$, because the JSON +`max_capacity_MW` field denotes final total line capacity. Energy-side fixed +O&M for storage and energy-side investment/fixed O&M for hydro are explicit +zero-valued input parameters rather than implicit implementation assumptions. + +**B.2 Operations (eqs. 15–24).** (15) Power balance: $$\begin{align*} +\sum_{g\in G_z} x_{g,t}^{\text{inj}} - \sum_{g\in G_z^{\text{STOR}}} x_{g,t}^{\text{wdw}} + - \sum_{l\in I_z^{\text{out}}} x_{l,t}^{\text{flow}} + \sum_{l\in I_z^{\text{in}}} x_{l,t}^{\text{flow}} + + \sum_{s\in S} x_{s,z,t}^{\text{nse}} = d_{z,t}. +\end{align*}$$ (16) Capacity/storage limits; (17) minimum output; (18) transmission flow bounds $-y_l^F\leq x_{l,t}^{\text{flow}}\leq y_l^F$; (19) NSE limit $x_{s,z,t}^{\text{nse}}\leq\bar\nu_s d_{z,t}$; (20) storage/hydro state-of-charge dynamics with circular indexing; (21) ramp limits for non-UC resources; (22) unit-commitment logic $x_{g,t}^{\text{commit}}-x_{g,t-1}^{\text{commit}}=x_{g,t}^{\text{start}}-x_{g,t}^{\text{shut}}$; (23) UC ramp limits; (24) minimum up/down time (circular within $H_w$). + +**B.3 Policy (eqs. 26–28).** RPS: $$\begin{align*} +\sum_{w\in W}\Big(\sum_{t\in H_w}\sum_{g\in G^{\text{RPS}}} \alpha_t x_{g,t}^{\text{inj}} + x_w^{RPS}\Big) + \geq \underline{c}^{\text{RPS}} \sum_{w,\,t,\,z} \alpha_t d_{z,t}. +\end{align*}$$ CO$_2$ cap: $$\begin{align*} +\sum_{w\in W}\Big(\sum_{t\in H_w}\big(\sum_{g\in G} \alpha_t c_g^{\text{CO2}} x_{g,t}^{\text{inj}} + + \sum_{g\in G^{\text{STOR}}} \alpha_t c_g^{\text{CO2}} x_{g,t}^{\text{wdw}}\big) - x_w^{CO2}\Big) + \leq \overline{c}^{\text{CO2}}. +\end{align*}$$ + +## Variable Domains + +Investment variables $y_g^{P,\text{NEW}}, y_g^{E,\text{NEW}}, y_g^{P,\text{RET}}, y_g^{E,\text{RET}}, +y_l^{F,\text{NEW}} \in \mathbb{Z}_{\geq 0}$ (MILP); $y_g^P, y_g^E, y_l^F \geq 0$. Operational variables non-negative, except $x_{l,t}^{\text{flow}}$ free; UC variables relaxed to $\mathbb{R}_{\geq 0}$. Policy slacks $x_w^{RPS}, x_w^{CO2} \geq 0$. diff --git a/tasks/rahmaniani2022/problem_description.txt b/tasks/rahmaniani2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa57ed8d64f8f6eb70b9d3a5d5f79be5dfd747fe --- /dev/null +++ b/tasks/rahmaniani2022/problem_description.txt @@ -0,0 +1,19 @@ +# Problem Description + +An electricity system planner must jointly determine long-term capacity investments and hourly operational dispatch for a regional power grid over a single planning year. The grid comprises a set of spatial zones connected by transmission lines, and each zone contains clusters of generation or storage resources. Resource types include thermal generators (such as natural gas combined-cycle, natural gas combustion turbine, coal, and nuclear plants), variable renewable energy sources (solar and wind), battery storage, and hydropower. In the released MILP convention, UC resources are installed or retired in physical blocks of `capacity_size_MW`, while non-UC resources use integer 1-MW investment increments; non-UC storage energy similarly uses integer 1-MWh increments. The physical cluster size remains available for operational parameters and existing-capacity bookkeeping, but it is not the non-UC investment block. Certain resource clusters are designated as non-retirable, meaning their retirement count must be zero. The final installed power and energy capacities equal pre-existing capacity plus their explicitly declared increment times net investment. New investment is bounded above and retirements cannot exceed pre-existing capacity. Storage energy capacity must lie between a minimum and a maximum duration ratio times storage power capacity. Transmission expansion uses integer 1-MW increments, and each line's `max_capacity_MW` is the maximum final total capacity after adding new investment to existing capacity. + +The planning year is divided into subperiods, each consisting of 168 consecutive hours (one week). Each subperiod carries a weight reflecting how many weeks of the year it represents. The hourly weight for each hour within a subperiod equals the subperiod weight divided by 168. The input data specifies, for every zone and every hour, the net electricity demand in MWh. For each resource cluster and hour, an availability factor between zero and one gives the fraction of installed capacity that can be dispatched; thermal and storage resources typically have availability equal to one, while solar and wind availabilities vary by hour. Each resource cluster has a per-MWh variable operating cost, a per-MW-year fixed operations and maintenance cost, a per-MW-year investment cost, and a CO2 emissions factor in tons per MWh. For storage resources, additional parameters specify charging efficiency, discharging efficiency, self-discharge rate, and per-MWh-year energy investment and fixed energy O&M costs. For hydropower resources, a fixed duration ratio (in MWh per MW) relates reservoir energy capacity to power capacity, and an hourly normalized inflow profile gives the fraction of power capacity arriving as inflow each hour. Demand may be partially curtailed: several consumer segments are defined, each with a maximum allowable fraction of zonal demand that may go unserved and an associated penalty cost per MWh. For each consumer segment, zone, and hour, the amount of unserved energy cannot exceed that segment's maximum allowable fraction of the zonal demand in that hour. + +A subset of resources is designated as unit-commitment (UC) resources (typically thermal generators). For each UC resource cluster and hour, the planner must determine how many units are committed (online), how many are starting up, and how many are shutting down, with these quantities allowed to take fractional values rather than being restricted to whole numbers. The number of committed, started-up, and shut-down units at any hour, each scaled by the unit size, cannot exceed the installed power capacity. The generation output of a UC resource in any hour must be at least the number of committed units times the unit size times the resource's minimum output fraction, and at most the number of committed units times the unit size times the hourly availability. The commitment status must satisfy a balance: the change in committed units from one hour to the next equals the number of start-ups minus the number of shutdowns, and this balance also applies with wrap-around between the last and first hours of each subperiod. For resources not subject to unit commitment, generation in each hour cannot exceed the availability factor times the installed power capacity. For non-UC, non-storage, non-hydro resources that have a positive minimum output fraction, generation must be at least that fraction times installed capacity in every hour. + +Within each subperiod, storage and hydro resources obey inventory-balance dynamics where the first hour of the subperiod wraps around to follow the last hour. For storage, the state of charge at each hour equals the previous hour's state of charge plus charging (withdrawals times charging efficiency) minus discharging (generation divided by discharging efficiency) minus self-discharge losses (the self-discharge rate times the previous hour's state of charge). The state of charge at the first hour of a subperiod links to the last hour of that same subperiod via the same balance equation. The state of charge cannot exceed the storage energy capacity. Additionally, the energy that would be added by charging cannot exceed the remaining room in the storage (energy capacity minus current state of charge), and the energy to be discharged (generation divided by discharging efficiency) cannot exceed the current state of charge. A storage resource's combined injection and withdrawal in any hour cannot exceed its power capacity, and its withdrawal is bounded by availability times power capacity. For hydropower, the reservoir level at each hour equals the previous hour's level plus inflow (the normalized inflow fraction times power capacity) minus generation minus spillage, again with wrap-around between the last and first hours within each subperiod, and the reservoir level cannot exceed the duration ratio times power capacity. Hydro resources must produce generation plus spillage at least equal to their minimum output fraction times power capacity. + +Ramping limits restrict how fast resources change output between consecutive hours. For non-UC resources, the increase in generation from one hour to the next cannot exceed the ramp-up rate (as a fraction per hour) times installed capacity, and the decrease cannot exceed the ramp-down rate times installed capacity, with the same wrap-around between the last and first hours of each subperiod. For UC resources, the ramping limits are tighter and account for start-up and shutdown transitions: the increase in output is limited by the ramp-up rate times the unit size times the number of units that were already committed (excluding those just starting), plus the unit size times the lesser of the availability and the greater of the minimum output fraction and the ramp-up rate, times the number of units starting up, minus the unit size times the minimum output fraction times the number of units shutting down. An analogous expression governs ramp-down. These UC ramping rules also apply with wrap-around between the last and first hours of each subperiod. + +Committed UC resources must remain online for at least their minimum up-time and, once shut down, must remain offline for at least their minimum down-time. These rules are enforced within each subperiod with wrap-around: the number of committed units at any hour must be at least as large as the sum of start-ups over the preceding minimum-up-time hours (wrapping around within the subperiod), and the number of committed units plus the sum of shutdowns over the preceding minimum-down-time hours cannot exceed the total number of available units (installed capacity divided by unit size). + +Power flow on each transmission line in each hour is bounded in absolute value by the line's installed capacity. In every zone and hour, total generation from local resources minus total storage withdrawals, plus net transmission imports (inflows minus outflows), plus any unserved energy across all consumer segments, must equal the zonal demand. + +The problem supports three policy scenarios. In the reference scenario, no policy rules are active. Under a renewable portfolio standard, the total weighted generation from all RPS-qualifying resources across all subperiods, plus a per-subperiod noncompliance slack, must be at least a specified share (such as 70 percent) of total weighted system demand. Under a CO2 cap, the total weighted CO2 emissions from all generation and storage withdrawals across all subperiods, minus a per-subperiod noncompliance slack, must not exceed a cap set at 0.05 tons per MWh times total weighted system demand. + +The goal is to minimize total annualized system cost. This cost is the sum of six components: fixed costs, comprising investment costs for new generation capacity (unit size times number of new units times per-MW-year investment cost, summed over all resources), plus storage energy investment costs (storage energy unit size times number of new storage energy units times per-MWh-year energy investment cost, summed over all storage resources), plus hydro energy investment costs (per-MWh-year energy investment cost times the hydro duration ratio times number of new power units, summed over all hydro resources), plus transmission line investment costs (per-MW-year transmission investment cost times new transmission capacity in MW, summed over all lines), plus fixed O&M costs on total installed power capacity (per-MW-year fixed O&M rate times installed power capacity, summed over all resources), plus fixed energy O&M costs on total installed storage energy capacity (per-MWh-year energy fixed O&M rate times installed energy capacity, summed over all storage resources), plus hydro fixed energy O&M costs (per-MWh-year energy fixed O&M rate times duration ratio times installed power capacity, summed over all hydro resources); variable operating costs, comprising the hourly-weighted variable cost times generation for each resource and the hourly-weighted variable cost times withdrawals for each storage resource, summed across all subperiods; unserved energy costs, comprising the hourly-weighted penalty cost times curtailed energy for each consumer segment, zone, and hour; start-up costs, comprising the hourly-weighted start-up cost times the number of units started for each UC resource and hour; and policy noncompliance costs, comprising the per-MWh RPS noncompliance penalty times the RPS slack and the per-ton CO2 noncompliance penalty times the CO2 slack, each summed over subperiods. diff --git a/tasks/rahmaniani2022/solution_logger.py b/tasks/rahmaniani2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rahmaniani2022/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/rahmaniani2022/solution_schema.json b/tasks/rahmaniani2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..6df8d58aafc64e5ff7bc1eee6c0c3a8b9e7eed6e --- /dev/null +++ b/tasks/rahmaniani2022/solution_schema.json @@ -0,0 +1,28 @@ +{ + "objective_value": " Total annualized system cost represented by the complete submitted plan.", + "model_variables": " Sparse complete investment and hourly-operation solution. Omitted model variables are exactly zero.", + "investments": { + "": { + "resource_type": " Technology category of the resource cluster (such as natural_gas_CT, solar, wind, coal, nuclear, battery, or hydro).", + "zone": " Zone in which the resource cluster is located.", + "new_units": " Integer investment-count variable in the MILP: physical blocks for UC clusters and 1-MW increments for non-UC clusters.", + "new_MW": " New power capacity installed in the cluster, in MW.", + "retired_units": " Number of existing units retired from the cluster.", + "retired_MW": " Power capacity retired from the cluster, in MW.", + "total_capacity_MW": " Final installed power capacity of the cluster after investments and retirements, in MW." + } + }, + "storage_energy_investments": { + "": { + "new_units": " Integer energy-investment count in the MILP; non-UC storage uses 1-MWh increments.", + "new_MWh": " New energy capacity added to the storage cluster, in MWh.", + "total_energy_MWh": " Final installed energy capacity of the storage cluster, in MWh." + } + }, + "transmission_investments": { + "": { + "new_MW": " New transmission capacity added in integer 1-MW increments in the MILP.", + "total_capacity_MW": " Final installed transmission capacity of the line after expansion, in MW." + } + } +} diff --git a/tasks/rahmaniani2022/solverless_models/404f2d3c0bedf8761c024ef820118a3e4244f5da75832d5b7ca6620d9a15ef30.npz b/tasks/rahmaniani2022/solverless_models/404f2d3c0bedf8761c024ef820118a3e4244f5da75832d5b7ca6620d9a15ef30.npz new file mode 100644 index 0000000000000000000000000000000000000000..509cd538d35482e5b7ee03dedf0c7bf76b27cf63 --- /dev/null +++ b/tasks/rahmaniani2022/solverless_models/404f2d3c0bedf8761c024ef820118a3e4244f5da75832d5b7ca6620d9a15ef30.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8aff2070357bb114df8d50703d92a18be08eeae093e4d59838802a531f85fb16 +size 1096173 diff --git a/tasks/rahmaniani2022/solverless_models/6887fe1608a652cdec62abd626e3dd9dee7cf820ccf42efa3292caf316747cce.npz b/tasks/rahmaniani2022/solverless_models/6887fe1608a652cdec62abd626e3dd9dee7cf820ccf42efa3292caf316747cce.npz new file mode 100644 index 0000000000000000000000000000000000000000..d67b9ce08922b463a7bf57f278a8698710351943 --- /dev/null +++ b/tasks/rahmaniani2022/solverless_models/6887fe1608a652cdec62abd626e3dd9dee7cf820ccf42efa3292caf316747cce.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80c25764056473d9b52698f0314e54677a976d412eb25acdc67ed68e3c35adec +size 1108239 diff --git a/tasks/rahmaniani2022/solverless_models/bdeb36375a8968da973ea273fff77c65d0f54ec471392e628e64b942dc9c429c.npz b/tasks/rahmaniani2022/solverless_models/bdeb36375a8968da973ea273fff77c65d0f54ec471392e628e64b942dc9c429c.npz new file mode 100644 index 0000000000000000000000000000000000000000..52cf08f9038aa01f5bc42cc7839f21453a8f17bb --- /dev/null +++ b/tasks/rahmaniani2022/solverless_models/bdeb36375a8968da973ea273fff77c65d0f54ec471392e628e64b942dc9c429c.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52c7f70d0dd74b703f9ea18ed02845916b1ef9d483ec18dedc54ec882cec50ba +size 1264515 diff --git a/tasks/rahmaniani2022/solverless_models/d39eb0c51c661635e8232d2f19bb754f198fc76ba20d8084771233bd43bedd42.npz b/tasks/rahmaniani2022/solverless_models/d39eb0c51c661635e8232d2f19bb754f198fc76ba20d8084771233bd43bedd42.npz new file mode 100644 index 0000000000000000000000000000000000000000..9289745873155a96e2ee2c5fc3b85848fb652bad --- /dev/null +++ b/tasks/rahmaniani2022/solverless_models/d39eb0c51c661635e8232d2f19bb754f198fc76ba20d8084771233bd43bedd42.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07b9532b7d241384b21918a15376b27591f2a5a7fc8d77d28b583d06f7292390 +size 1561890 diff --git a/tasks/rahmaniani2022/solverless_models/eadcf5c89bfcd588e1825a6027e7ce42effe2ff164771ed9a12e8d36dcf6d8f7.npz b/tasks/rahmaniani2022/solverless_models/eadcf5c89bfcd588e1825a6027e7ce42effe2ff164771ed9a12e8d36dcf6d8f7.npz new file mode 100644 index 0000000000000000000000000000000000000000..09a1d7e8f84dff98b27845982fd4cf69c0106b5d --- /dev/null +++ b/tasks/rahmaniani2022/solverless_models/eadcf5c89bfcd588e1825a6027e7ce42effe2ff164771ed9a12e8d36dcf6d8f7.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc9e69c47fed7fa375836afac104e70cc62779b9168c53be8ac214e958875854 +size 1271583 diff --git a/tasks/rahmaniani2022/solverless_models/f326d6f07923a2cd0d03c1f24ef34f860705d8d809a3bc5b7812d4bce30732f1.npz b/tasks/rahmaniani2022/solverless_models/f326d6f07923a2cd0d03c1f24ef34f860705d8d809a3bc5b7812d4bce30732f1.npz new file mode 100644 index 0000000000000000000000000000000000000000..7b33492420753fcaddb676932b38fd89ac86b3f4 --- /dev/null +++ b/tasks/rahmaniani2022/solverless_models/f326d6f07923a2cd0d03c1f24ef34f860705d8d809a3bc5b7812d4bce30732f1.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c969b62233482345c664f0343a840a1faec74928a72f9bf0c96076ac34069c65 +size 1108099 diff --git a/tasks/rahmaniani2022/solverless_witness.py b/tasks/rahmaniani2022/solverless_witness.py new file mode 100644 index 0000000000000000000000000000000000000000..6e8d1c0a2a83a5aa314a7405d6b50f6d5dacaf8c --- /dev/null +++ b/tasks/rahmaniani2022/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/reihaneh2019/feasibility_check.py b/tasks/reihaneh2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e124864f415422fee72640eb4cc10fb08a29a528 --- /dev/null +++ b/tasks/reihaneh2019/feasibility_check.py @@ -0,0 +1,666 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the VRDAP (Vehicle Routing with Demand Allocation Problem). + +Checks constraints (4b)-(4l) from Reihaneh & Ghoniem (2019), Appendix A. +Numbered as Constraint 1 through Constraint 11 (top to bottom in the formulation). + +Constraint 12: Objective-value consistency (Tier C defense against LLM +score-gaming exploits). Recomputes the obj from the routing arcs and +customer-to-site assignments in the solution and rejects when the reported +objective_value disagrees with the recomputed total cost. +""" + +import json +import argparse + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', 'customer_tours', 'objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def build_solution_variables(instance, solution): + """ + Reconstruct the decision variables (s, e, theta, q) from the solution JSON. + + Supports two solution formats: + - Gurobi format: has 'customer_tours' with {vehicle, site} per customer + - Efficient algorithm format: routes contain 'customers' mapping site -> [customer IDs] + """ + num_sites = instance["num_delivery_sites"] + num_customers = instance["num_customers"] + Q = instance["vehicle_capacity"] + num_vehicles = instance["num_vehicles"] + + customers = instance["customers"] + d = {c["id"]: c["demand"] for c in customers} + + S = list(range(1, num_sites + 1)) + K = list(range(1, num_customers + 1)) + N = [0] + S + + # --- Determine solution format and reconstruct variables --- + + # s[i, k]: customer k assigned to delivery site i + s = {} + for i in S: + for k in K: + s[i, k] = 0 + + assignments = solution.get("assignments", {}) + for k_str, site in assignments.items(): + k = int(k_str) + s[site, k] = 1 + + # e[v, i, j]: arc (i,j) in vehicle tour v + e = {} + # Collect all vehicle IDs used in routes + route_vehicles = [int(v) for v in solution["routes"].keys()] + V = list(range(1, num_vehicles + 1)) + + for v in V: + for i in N: + for j in N: + if i != j: + e[v, i, j] = 0 + + for v_str, route_data in solution["routes"].items(): + v = int(v_str) + if "arcs" in route_data: + # Gurobi format + for arc in route_data["arcs"]: + i, j = arc[0], arc[1] + e[v, i, j] = 1 + else: + # Efficient algorithm format: reconstruct arcs from sequence + seq = route_data["sequence"] + for idx in range(len(seq) - 1): + i, j = seq[idx], seq[idx + 1] + e[v, i, j] = 1 + + # theta[v, i, k]: site i visited by tour v AND customer k assigned to site i + theta = {} + for v in V: + for i in S: + for k in K: + theta[v, i, k] = 0 + + if "customer_tours" in solution: + # Gurobi format: customer_tours maps customer -> {vehicle, site} + for k_str, info in solution["customer_tours"].items(): + k = int(k_str) + v = info["vehicle"] + i = info["site"] + theta[v, i, k] = 1 + else: + # Efficient algorithm format: routes contain 'customers' mapping + for v_str, route_data in solution["routes"].items(): + v = int(v_str) + if "customers" in route_data: + for site_str, cust_list in route_data["customers"].items(): + site = int(site_str) + for k in cust_list: + theta[v, site, k] = 1 + + # q[v, i]: cumulative deliveries upon serving site i in tour v + # Reconstruct from route sequence and demand assignments + q = {} + for v in V: + for i in S: + q[v, i] = 0.0 + + for v_str, route_data in solution["routes"].items(): + v = int(v_str) + seq = route_data["sequence"] + cumulative = 0.0 + for node in seq: + if node == 0: + continue + # Add demand of all customers assigned to this site on this tour + demand_at_site = sum(d[k] for k in K if theta[v, node, k] > 0.5) + cumulative += demand_at_site + q[v, node] = cumulative + + return s, e, theta, q, S, K, V, N, d, Q + + +def check_feasibility(instance, solution): + """Check all hard constraints (4b)-(4l), numbered 1-11, plus obj + consistency (Constraint 12).""" + tol = 1e-5 + eps = 1e-5 + + s, e, theta, q, S, K, V, N, d, Q = build_solution_variables(instance, solution) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # Domain check: every node id appearing in any route's sequence/arcs + # must be in N (= [0] + delivery sites); every assignments site value + # must be in S; every customer key must be in K; every vehicle key + # must be in V. + valid_N = set(N) + valid_S = set(S) + valid_K = set(K) + valid_V = set(V) + for v_str, route_data in solution.get("routes", {}).items(): + try: + v_int = int(v_str) + except (TypeError, ValueError): + v_int = None + if v_int not in valid_V: + violated_constraints.add(0) + violations.append( + f"Domain: routes vehicle id {v_str!r} not in valid range [1, {len(V)}]" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + for arc in route_data.get("arcs", []): + for node in arc[:2]: + if node not in valid_N: + violated_constraints.add(0) + violations.append( + f"Domain: route v={v_str} arc node {node!r} not in valid set" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + for node in route_data.get("sequence", []): + if node not in valid_N: + violated_constraints.add(0) + violations.append( + f"Domain: route v={v_str} sequence node {node!r} not in valid set" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + for k_str, site in solution.get("assignments", {}).items(): + try: + k_int = int(k_str) + except (TypeError, ValueError): + k_int = None + if k_int not in valid_K: + violated_constraints.add(0) + violations.append( + f"Domain: assignments customer id {k_str!r} not a valid customer" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + if site not in valid_S: + violated_constraints.add(0) + violations.append( + f"Domain: assignments[{k_str}] = {site!r} not a valid delivery site" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + + def record_violation(constraint_idx, msg, lhs, rhs, operator="<="): + violated_constraints.add(constraint_idx) + violations.append(msg) + if operator == "<=": + violation_amount = max(lhs - rhs, 0.0) + elif operator == ">=": + violation_amount = max(rhs - lhs, 0.0) + elif operator == "=": + violation_amount = abs(lhs - rhs) + else: + violation_amount = abs(lhs - rhs) + 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 (4b): Each delivery site visited by at most one tour + # sum_v sum_{i in N\{j}} e^v_{ij} <= 1, forall j in S + # --------------------------------------------------------------- + for j in S: + lhs = sum(e[v, i, j] for v in V for i in N if i != j) + rhs = 1.0 + if lhs - rhs > tol: + record_violation(1, f"Constraint 1 (4b): Site {j} visited by {lhs} tours (max 1)", lhs, rhs, "<=") + + # --------------------------------------------------------------- + # Constraint 2 (4c): Each tour has at most one arc leaving depot + # sum_{j in S} e^v_{0j} <= 1, forall v in V + # --------------------------------------------------------------- + for v in V: + lhs = sum(e[v, 0, j] for j in S) + rhs = 1.0 + if lhs - rhs > tol: + record_violation(2, f"Constraint 2 (4c): Vehicle {v} has {lhs} arcs leaving depot (max 1)", lhs, rhs, "<=") + + # --------------------------------------------------------------- + # Constraint 3 (4d): Flow balance at each node + # sum_{i in N\{j}} e^v_{ij} - sum_{i in N\{j}} e^v_{ji} = 0, forall v, j in N + # --------------------------------------------------------------- + for v in V: + for j in N: + inflow = sum(e[v, i, j] for i in N if i != j) + outflow = sum(e[v, j, i] for i in N if i != j) + lhs = inflow - outflow + rhs = 0.0 + if abs(lhs - rhs) > tol: + record_violation(3, f"Constraint 3 (4d): Flow imbalance at node {j} on vehicle {v}: in={inflow}, out={outflow}", lhs, rhs, "=") + + # --------------------------------------------------------------- + # Constraint 4 (4e): Subtour elimination / cumulative delivery tracking + # q^v_j >= q^v_i + sum_k d_k s_{jk} - 2Q(1 - e^v_{ij}) + Q e^v_{ji} + # forall v, i,j in S, i != j + # Rewrite as: q^v_j - q^v_i - sum_k d_k s_{jk} + 2Q(1 - e^v_{ij}) - Q e^v_{ji} >= 0 + # i.e., LHS = q^v_j, RHS = q^v_i + sum_k d_k s_{jk} - 2Q(1-e^v_{ij}) + Q e^v_{ji} + # --------------------------------------------------------------- + for v in V: + for i in S: + for j in S: + if i != j: + demand_j = sum(d[k] * s[j, k] for k in K) + rhs_val = q[v, i] + demand_j - 2 * Q * (1 - e[v, i, j]) + Q * e[v, j, i] + lhs_val = q[v, j] + if rhs_val - lhs_val > tol: + record_violation( + 4, + f"Constraint 4 (4e): Subtour elimination violated for vehicle {v}, arc ({i},{j}): " + f"q[{v},{j}]={lhs_val:.4f} < RHS={rhs_val:.4f}", + lhs_val, rhs_val, ">=" + ) + + # --------------------------------------------------------------- + # Constraint 5 (4f): Linking theta and (s, e) — lower bound + # theta^v_{ik} >= s_{ik} + sum_{j in N\{i}} e^v_{ij} - 1 + # --------------------------------------------------------------- + for v in V: + for i in S: + for k in K: + rhs_val = s[i, k] + sum(e[v, i, j] for j in N if j != i) - 1 + lhs_val = theta[v, i, k] + if rhs_val - lhs_val > tol: + record_violation( + 5, + f"Constraint 5 (4f): theta[{v},{i},{k}]={lhs_val} < s[{i},{k}]+out_edges-1={rhs_val}", + lhs_val, rhs_val, ">=" + ) + + # --------------------------------------------------------------- + # Constraint 6 (4g): Linking theta and e — upper bound + # theta^v_{ik} <= sum_{j in N\{i}} e^v_{ij} + # --------------------------------------------------------------- + for v in V: + for i in S: + for k in K: + lhs_val = theta[v, i, k] + rhs_val = sum(e[v, i, j] for j in N if j != i) + if lhs_val - rhs_val > tol: + record_violation( + 6, + f"Constraint 6 (4g): theta[{v},{i},{k}]={lhs_val} > out_edges={rhs_val}", + lhs_val, rhs_val, "<=" + ) + + # --------------------------------------------------------------- + # Constraint 7 (4h): Linking theta and s — upper bound + # theta^v_{ik} <= s_{ik} + # --------------------------------------------------------------- + for v in V: + for i in S: + for k in K: + lhs_val = theta[v, i, k] + rhs_val = s[i, k] + if lhs_val - rhs_val > tol: + record_violation( + 7, + f"Constraint 7 (4h): theta[{v},{i},{k}]={lhs_val} > s[{i},{k}]={rhs_val}", + lhs_val, rhs_val, "<=" + ) + + # --------------------------------------------------------------- + # Constraint 8 (4i): Upper bound on cumulative delivery + # q^v_i <= Q * sum_{j in N\{i}} e^v_{ij} + # --------------------------------------------------------------- + for v in V: + for i in S: + lhs_val = q[v, i] + rhs_val = Q * sum(e[v, i, j] for j in N if j != i) + if lhs_val - rhs_val > tol: + record_violation( + 8, + f"Constraint 8 (4i): q[{v},{i}]={lhs_val} > Q*out_edges={rhs_val}", + lhs_val, rhs_val, "<=" + ) + + # --------------------------------------------------------------- + # Constraint 9 (4j): Lower bound on cumulative delivery + # sum_k d_k theta^v_{ik} <= q^v_i + # --------------------------------------------------------------- + for v in V: + for i in S: + lhs_val = sum(d[k] * theta[v, i, k] for k in K) + rhs_val = q[v, i] + if lhs_val - rhs_val > tol: + record_violation( + 9, + f"Constraint 9 (4j): demand on site {i} tour {v} = {lhs_val} > q[{v},{i}]={rhs_val}", + lhs_val, rhs_val, "<=" + ) + + # --------------------------------------------------------------- + # Constraint 10 (4k): Every customer assigned to exactly one site and tour + # sum_v sum_i theta^v_{ik} = 1, forall k + # --------------------------------------------------------------- + for k in K: + lhs_val = sum(theta[v, i, k] for v in V for i in S) + rhs_val = 1.0 + if abs(lhs_val - rhs_val) > tol: + record_violation( + 10, + f"Constraint 10 (4k): Customer {k} assigned to {lhs_val} (site,tour) pairs (must be 1)", + lhs_val, rhs_val, "=" + ) + + # --------------------------------------------------------------- + # Constraint 11 (4l): Variable domains + # e^v_{ij} in {0,1}, s_{ik} in {0,1}, theta^v_{ik} >= 0, q^v_i >= 0 + # --------------------------------------------------------------- + # Check binary domains for e + for v in V: + for i in N: + for j in N: + if i != j: + val = e[v, i, j] + if val < -tol or val > 1 + tol or (abs(val - round(val)) > tol): + record_violation( + 11, + f"Constraint 11 (4l): e[{v},{i},{j}]={val} not binary", + val, round(val), "=" + ) + + # Check binary domains for s + for i in S: + for k in K: + val = s[i, k] + if val < -tol or val > 1 + tol or (abs(val - round(val)) > tol): + record_violation( + 11, + f"Constraint 11 (4l): s[{i},{k}]={val} not binary", + val, round(val), "=" + ) + + # Check non-negativity of theta + for v in V: + for i in S: + for k in K: + val = theta[v, i, k] + if val < -tol: + record_violation( + 11, + f"Constraint 11 (4l): theta[{v},{i},{k}]={val} < 0", + val, 0.0, ">=" + ) + + # Check non-negativity of q + for v in V: + for i in S: + val = q[v, i] + if val < -tol: + record_violation( + 11, + f"Constraint 11 (4l): q[{v},{i}]={val} < 0", + val, 0.0, ">=" + ) + + # --------------------------------------------------------------- + # Constraint 12: Objective-value consistency (Tier C) + # Recompute obj = sum_v sum_{(i,j) in E} c_{ij} e^v_{ij} + # + sum_{i in S, k in K} f_{ik} s_{ik} + # using the routing-cost matrix and assignment-cost matrix from the + # instance. Reject when |reported - recomputed| exceeds tolerance. + # All obj-determining variables (routes -> e, assignments -> s) are + # present in the solution, so full recompute is exact. + # --------------------------------------------------------------- + c_mat = instance.get("routing_cost_matrix") + f_mat = instance.get("assignment_cost_matrix") + reported_obj = solution.get("objective_value") + if c_mat is not None and f_mat is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + routing_cost = 0.0 + for v in V: + for i in N: + for j in N: + if i != j and e[v, i, j]: + routing_cost += float(c_mat[i][j]) + assign_cost = 0.0 + for i in S: + for k in K: + if s[i, k]: + # assignment_cost_matrix is shape [num_customers][num_sites], + # rows 0-indexed by customer (k-1), cols 0-indexed by site (i-1). + assign_cost += float(f_mat[k - 1][i - 1]) + true_obj = routing_cost + assign_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( + 12, + f"Constraint 12: Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"routing_cost+assign_cost={true_obj} " + f"(routing={routing_cost}, assign={assign_cost}, " + f"|diff|={abs_diff:.3g}, tol={tol_obj:.3g})", + reported, true_obj, "=" + ) + + # --- Build result --- + feasible = len(violated_constraints) == 0 + # Aggregate violations by constraint index: keep unique messages per constraint + sorted_violated = sorted(violated_constraints) + + # Build aggregated violation messages (one per constraint index) + aggregated_violations = [] + for c_idx in sorted_violated: + msgs = [v for v, m in zip(violations, violation_magnitudes) if m["constraint"] == c_idx] + if len(msgs) <= 3: + aggregated_violations.append("; ".join(msgs)) + else: + aggregated_violations.append(f"{msgs[0]}; ... ({len(msgs)} total violations for constraint {c_idx})") + + result = { + "feasible": feasible, + "violated_constraints": sorted_violated, + "violations": aggregated_violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for VRDAP (Reihaneh & Ghoniem 2019)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"FEASIBLE - no constraint violations found. Result saved to {args.result_path}") + else: + print(f"INFEASIBLE - violated constraints: {result['violated_constraints']}. Result saved 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/reihaneh2019/gurobi_code.py b/tasks/reihaneh2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..22e2feb09b34b7cbfbeed59bf3af337fe83016c8 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_code.py @@ -0,0 +1,326 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the VRDAP (Vehicle Routing with Demand Allocation Problem). +MIP formulation from Reihaneh & Ghoniem (2019), Appendix A, Equations (4a)-(4l). + +This implements the compact (base) MIP formulation directly solvable by Gurobi. +""" + +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(instance_path): + """Load the VRDAP instance from a JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def solve_vrdap(data, time_limit): + """ + Build and solve the VRDAP MIP formulation (4a)-(4l). + + Sets: + S: delivery sites (node IDs 1..|S|) + K: customers (IDs 1..|K|) + V: vehicle tours (IDs 1..|V|) + N = S ∪ {0} (depot is node 0) + E = {(i,j) : i,j ∈ N, i ≠ j} + + Parameters read from instance: + c[i][j]: routing cost matrix (|N| x |N|), indexed by node IDs + f[k][s]: assignment cost matrix (|K| x |S|), 0-indexed + d[k]: demand of customer k + Q: vehicle capacity + """ + num_sites = data['num_delivery_sites'] + num_customers = data['num_customers'] + Q = data['vehicle_capacity'] + num_vehicles = data['num_vehicles'] + + customers = data['customers'] + c = data['routing_cost_matrix'] # c[i][j], i,j in {0,...,|S|} + f_cost = data['assignment_cost_matrix'] # f[k_idx][s_idx], 0-indexed + + # --- Index sets --- + S = list(range(1, num_sites + 1)) # delivery site node IDs + K = list(range(1, num_customers + 1)) # customer IDs + V = list(range(1, num_vehicles + 1)) # vehicle (tour) IDs + N = [0] + S # all nodes + + # Customer demands indexed by customer ID + d = {} + for cust in customers: + d[cust['id']] = cust['demand'] + + # --- Build Gurobi model --- + model = gp.Model("VRDAP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ----- Decision Variables ----- + + # s[i,k] ∈ {0,1}: customer k assigned to delivery site i + s = {} + for i in S: + for k in K: + s[i, k] = model.addVar(vtype=GRB.BINARY, name=f"s_{i}_{k}") + + # e[v,i,j] ∈ {0,1}: arc (i,j) included in vehicle tour v + e = {} + for v_idx in V: + for i in N: + for j in N: + if i != j: + e[v_idx, i, j] = model.addVar(vtype=GRB.BINARY, + name=f"e_{v_idx}_{i}_{j}") + + # theta[v,i,k] ≥ 0: site i visited by tour v AND customer k assigned to site i + # (Declared continuous; automatically binary due to constraints 4b, 4k and + # binariness of s, e — see paper's Reproduction-Critical Note 1.) + theta = {} + for v_idx in V: + for i in S: + for k in K: + theta[v_idx, i, k] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0.0, + name=f"theta_{v_idx}_{i}_{k}") + + # q[v,i] ≥ 0: cumulative deliveries upon serving site i in tour v + q = {} + for v_idx in V: + for i in S: + q[v_idx, i] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, + name=f"q_{v_idx}_{i}") + + model.update() + + # ----- Objective (4a) ----- + # min Σ_v Σ_(i,j)∈E c_ij e^v_ij + Σ_i∈S Σ_k∈K f_ik s_ik + obj = gp.LinExpr() + for v_idx in V: + for i in N: + for j in N: + if i != j: + obj += c[i][j] * e[v_idx, i, j] + for i in S: + for k in K: + # f_cost is 0-indexed: row = customer_id - 1, col = site_id - 1 + obj += f_cost[k - 1][i - 1] * s[i, k] + model.setObjective(obj, GRB.MINIMIZE) + + # ----- Constraints ----- + + # (4b) Each delivery site visited by at most one vehicle tour + # Σ_v Σ_{i∈N\{j}} e^v_ij ≤ 1, ∀ j ∈ S + for j in S: + model.addConstr( + gp.quicksum(e[v_idx, i, j] + for v_idx in V for i in N if i != j) <= 1, + name=f"c4b_{j}") + + # (4c) Each vehicle tour has at most one arc leaving the central depot + # Σ_{j∈S} e^v_{0j} ≤ 1, ∀ v ∈ V + for v_idx in V: + model.addConstr( + gp.quicksum(e[v_idx, 0, j] for j in S) <= 1, + name=f"c4c_{v_idx}") + + # (4d) Flow balance for depot and every delivery site + # Σ_{i∈N\{j}} e^v_ij − Σ_{i∈N\{j}} e^v_ji = 0, ∀ v ∈ V, j ∈ N + for v_idx in V: + for j in N: + model.addConstr( + gp.quicksum(e[v_idx, i, j] for i in N if i != j) + - gp.quicksum(e[v_idx, j, i] for i in N if i != j) == 0, + name=f"c4d_{v_idx}_{j}") + + # (4e) Subtour elimination (lifted Miller-Tucker-Zemlin) + cumulative delivery + # q^v_j ≥ q^v_i + Σ_k d_k s_{jk} − 2Q(1−e^v_ij) + Q e^v_ji, + # ∀ v ∈ V, i,j ∈ S, i ≠ j + for v_idx in V: + for i in S: + for j in S: + if i != j: + model.addConstr( + q[v_idx, j] >= q[v_idx, i] + + gp.quicksum(d[k] * s[j, k] for k in K) + - 2 * Q * (1 - e[v_idx, i, j]) + + Q * e[v_idx, j, i], + name=f"c4e_{v_idx}_{i}_{j}") + + # (4f) Linking θ and (s, e) — lower bound + # θ^v_ik ≥ s_ik + Σ_{j∈N\{i}} e^v_ij − 1 + for v_idx in V: + for i in S: + for k in K: + model.addConstr( + theta[v_idx, i, k] >= s[i, k] + + gp.quicksum(e[v_idx, i, j] for j in N if j != i) - 1, + name=f"c4f_{v_idx}_{i}_{k}") + + # (4g) Linking θ and e — upper bound + # θ^v_ik ≤ Σ_{j∈N\{i}} e^v_ij + for v_idx in V: + for i in S: + for k in K: + model.addConstr( + theta[v_idx, i, k] + <= gp.quicksum(e[v_idx, i, j] for j in N if j != i), + name=f"c4g_{v_idx}_{i}_{k}") + + # (4h) Linking θ and s — upper bound + # θ^v_ik ≤ s_ik + for v_idx in V: + for i in S: + for k in K: + model.addConstr( + theta[v_idx, i, k] <= s[i, k], + name=f"c4h_{v_idx}_{i}_{k}") + + # (4i) Upper bound on cumulative delivery at visited site + # q^v_i ≤ Q Σ_{j∈N\{i}} e^v_ij + for v_idx in V: + for i in S: + model.addConstr( + q[v_idx, i] + <= Q * gp.quicksum(e[v_idx, i, j] for j in N if j != i), + name=f"c4i_{v_idx}_{i}") + + # (4j) Lower bound on cumulative delivery (demand assigned via θ) + # Σ_k d_k θ^v_ik ≤ q^v_i + for v_idx in V: + for i in S: + model.addConstr( + gp.quicksum(d[k] * theta[v_idx, i, k] for k in K) + <= q[v_idx, i], + name=f"c4j_{v_idx}_{i}") + + # (4k) Every customer assigned to exactly one delivery site and one tour + # Σ_v Σ_i θ^v_ik = 1, ∀ k ∈ K + for k in K: + model.addConstr( + gp.quicksum(theta[v_idx, i, k] + for v_idx in V for i in S) == 1, + name=f"c4k_{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 if hasattr(model, 'MIPGap') else None + + # Extract routes per vehicle + routes = {} + for v_idx in V: + arcs = [] + for i in N: + for j in N: + if i != j and e[v_idx, i, j].X > 0.5: + arcs.append([i, j]) + if arcs: + # Reconstruct ordered route from arcs + route_seq = _reconstruct_route(arcs) + routes[str(v_idx)] = {"arcs": arcs, "sequence": route_seq} + solution['routes'] = routes + + # Extract customer-to-site assignments + assignments = {} + for k in K: + for i in S: + if s[i, k].X > 0.5: + assignments[str(k)] = i + break + solution['assignments'] = assignments + + # Extract customer-to-tour assignments via theta + customer_tours = {} + for k in K: + for v_idx in V: + for i in S: + if theta[v_idx, i, k].X > 0.5: + customer_tours[str(k)] = { + "vehicle": v_idx, + "site": i + } + break + solution['customer_tours'] = customer_tours + else: + solution['objective_value'] = None + solution['status'] = model.Status + + return solution + + +def _reconstruct_route(arcs): + """Reconstruct an ordered node sequence from a list of arcs.""" + if not arcs: + return [] + adj = {} + for (i, j) in arcs: + adj[i] = j + # Start from depot (node 0) + route = [0] + current = 0 + visited = {0} + while current in adj: + nxt = adj[current] + route.append(nxt) + if nxt in visited: + break + visited.add(nxt) + current = nxt + return route + + +def main(): + parser = argparse.ArgumentParser( + description="VRDAP solver using Gurobi (compact MIP formulation 4a-4l)") + parser.add_argument('--instance_path', type=str, required=True, + help='Path to the JSON instance file') + parser.add_argument('--solution_path', type=str, required=True, + help='Path to write the solution JSON file') + parser.add_argument('--time_limit', type=int, required=True, + help='Maximum solver runtime in seconds') + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + solution = solve_vrdap(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']}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == '__main__': + main() diff --git a/tasks/reihaneh2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/reihaneh2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/reihaneh2019/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/reihaneh2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/reihaneh2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/reihaneh2019/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/reihaneh2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/reihaneh2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/reihaneh2019/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/reihaneh2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/reihaneh2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/reihaneh2019/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/reihaneh2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/reihaneh2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/reihaneh2019/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/reihaneh2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/reihaneh2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/reihaneh2019/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/reihaneh2019/gurobi_solution/large_solution_1.json b/tasks/reihaneh2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..793efdf31d7a7f48295cab02ef8d8ea78bf4c868 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee1b1bedfb57742461893ba9bf23a5901b5009acb6e360209096ed88fa15bc4b +size 4983 diff --git a/tasks/reihaneh2019/gurobi_solution/large_solution_2.json b/tasks/reihaneh2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c938f39d7b9e56ddac892b3f36b836b69b977abe --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2709f73a43f3772644ca45d832aef55756bc46a0bd40a589ceebbca56de8e5a2 +size 5173 diff --git a/tasks/reihaneh2019/gurobi_solution/large_solution_3.json b/tasks/reihaneh2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..a7e2d121aeee528b14fece39982599402f776a79 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ba6dc951d929a0919add2840028c74cbf0225b5398bd90e5964805d7e993818 +size 5120 diff --git a/tasks/reihaneh2019/gurobi_solution/large_solution_4.json b/tasks/reihaneh2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..636632ba6c2a1cb247b99b2120fe0d2fc69b0720 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6851f8bf8ad81a8fa3b30b17af0fb11d781e097b5f3e17a0bc305ca24373d647 +size 5262 diff --git a/tasks/reihaneh2019/gurobi_solution/large_solution_5.json b/tasks/reihaneh2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..bd2aac86782c2e1bec60ad8d6611397a5090ef1a --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46b4b8ad035d762782a33e7772fe5c0340ba0287c1bebf37c97bb547d8254e94 +size 5005 diff --git a/tasks/reihaneh2019/gurobi_solution/tiny_solution.json b/tasks/reihaneh2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..44a7b0aa0bab0c10a4a44e0cdc90f690e2518637 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c5a85e51fb491362abffeb24bd91aa193b0afb39118f95f0f47357ae09d05d7 +size 1085 diff --git a/tasks/reihaneh2019/gurobi_solution_log/large_log_1.jsonl b/tasks/reihaneh2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..450ded42bdcd28b565d0153178b54ee7955cee99 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b68dd38fbad1c104ebab67c3bb2b4c404a61a3c80dd8e2599987a1b54881265b +size 1729 diff --git a/tasks/reihaneh2019/gurobi_solution_log/large_log_2.jsonl b/tasks/reihaneh2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fbcab6a91497fb2355a67b8dc770603e0de40b63 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4fd9c5c6a2a1e275e6c9ca5c83b9540e0b4aaf57c9156e13492d45179896972d +size 1586 diff --git a/tasks/reihaneh2019/gurobi_solution_log/large_log_3.jsonl b/tasks/reihaneh2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd330af16eb28f865a1f9f84c32e6bb459dc2143 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:147800291d587eb5beb23a2d4c598db83c942e3089c00120a1a0947803ff0f6a +size 3094 diff --git a/tasks/reihaneh2019/gurobi_solution_log/large_log_4.jsonl b/tasks/reihaneh2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..82216fdb3cb3bb5db8d6a680eac182330dddfa21 --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0aa9ac621ce85fded444b62820e04d1aae18403279eb9465698d5341d7fe0c6 +size 2173 diff --git a/tasks/reihaneh2019/gurobi_solution_log/large_log_5.jsonl b/tasks/reihaneh2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3dfb4eaf9f0b43798cbd683f35ff72bd1ad747ad --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb20d15c459a5ac446785fb89c281086e78b35a6dca726a70fddb0e3dcf567a0 +size 2187 diff --git a/tasks/reihaneh2019/gurobi_solution_log/tiny_log.jsonl b/tasks/reihaneh2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d14c0e21c1f1a3019e259ac6fa639b371d4aa2bf --- /dev/null +++ b/tasks/reihaneh2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3895c6d19fcdfc77e2c054b77b071251eb55acb758ee1894777b49f8b5b34f92 +size 100 diff --git a/tasks/reihaneh2019/instance/large_instance_1.json b/tasks/reihaneh2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4211d62082b5092092c94163d7ba17d359ff0e3d --- /dev/null +++ b/tasks/reihaneh2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c48ac06d585f0304448910dba5613ad5440407d25c17a84fe0a1bffb7f71415d +size 36193 diff --git a/tasks/reihaneh2019/instance/large_instance_2.json b/tasks/reihaneh2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a38561057315334b56ac86a664b5e19c2b3267e9 --- /dev/null +++ b/tasks/reihaneh2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0143af1df148ea0b6de9b5e2fdaed9ca1e037c35327f1e5ecfa34caefb68fe16 +size 36260 diff --git a/tasks/reihaneh2019/instance/large_instance_3.json b/tasks/reihaneh2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e7d760b7fbabf78277bdd3b696f0692b56bdfbee --- /dev/null +++ b/tasks/reihaneh2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:087f88de630ffaa13af756b6d7b019139d2d9a987d1a24cf23204c218266f840 +size 36436 diff --git a/tasks/reihaneh2019/instance/large_instance_4.json b/tasks/reihaneh2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2e29dad00e1df9823f2a7f9e15cc6f7a94f10fc8 --- /dev/null +++ b/tasks/reihaneh2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:116a2478c90a5fcf43970488ddcb0b850ee5c778b4f14ea83d97142ed61ca050 +size 36151 diff --git a/tasks/reihaneh2019/instance/large_instance_5.json b/tasks/reihaneh2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..57b7b4ecff177b259ade3f785721817a93bb72dc --- /dev/null +++ b/tasks/reihaneh2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24e6b54f9bc85082521cd425d1935b7526ff1a48e9ddb3a5ffcb922db69a6fe8 +size 36365 diff --git a/tasks/reihaneh2019/instance/tiny_instance.json b/tasks/reihaneh2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..574c5e7afdc2b50d4bc4c57a6732231bfec6629f --- /dev/null +++ b/tasks/reihaneh2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:227e62a44205d487f8c5bb37646b3369e3538f5ea6abb311156084d0df438715 +size 3026 diff --git a/tasks/reihaneh2019/instance_schema.json b/tasks/reihaneh2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..105abddc0021ce787c5f766e7a66fe39a871c27f --- /dev/null +++ b/tasks/reihaneh2019/instance_schema.json @@ -0,0 +1,28 @@ +{ + "num_delivery_sites": " Number of candidate delivery sites that may be activated to serve customers.", + "num_customers": " Number of customers requiring delivery service.", + "vehicle_capacity": " Maximum number of pallets a single vehicle can carry on one tour.", + "num_vehicles": " Number of identical vehicles available in the fleet.", + "depot": { + "id": " Identifier for the central depot node in the routing network.", + "x": " X-coordinate of the central depot.", + "y": " Y-coordinate of the central depot." + }, + "delivery_sites": [ + { + "id": " Identifier for this delivery site node in the routing network.", + "x": " X-coordinate of this delivery site.", + "y": " Y-coordinate of this delivery site." + } + ], + "customers": [ + { + "id": " Identifier for this customer.", + "x": " X-coordinate of this customer's location.", + "y": " Y-coordinate of this customer's location.", + "demand": " Number of pallets this customer requires." + } + ], + "routing_cost_matrix": " Travel cost between each pair of nodes in the routing network, where row and column 0 is the depot and 1 through num_delivery_sites are the delivery sites.", + "assignment_cost_matrix": " Travel cost for each customer to reach each candidate delivery site for pickup." +} diff --git a/tasks/reihaneh2019/mathematical_formulation.md b/tasks/reihaneh2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..e3c5f4bb79f6063593eed7bcebcf560e305216f8 --- /dev/null +++ b/tasks/reihaneh2019/mathematical_formulation.md @@ -0,0 +1,72 @@ +# Original Formulation: Vehicle Routing with Demand Allocation Problem (VRDAP) + +*Source: A Branch-and-Price Algorithm for a Vehicle Routing with Demand Allocation Problem, Mohammad Reihaneh and Ahmed Ghoniem, European Journal of Operational Research (2018/2019).* + +The paper presents this 0–1 MIP as the definition of the VRDAP in Appendix A (Equations (4a)–(4l)), using the notation introduced in Section 3.1 (“Problem Statement”). Section 3.1 states explicitly that “the VRDAP can be modeled as a 0–1 MIP (as in the Appendix A) or equivalently as a set partitioning model.” The set-partitioning master program (1) is the column-generation reformulation used by the branch-and-price algorithm; the compact MIP below is the original problem-definition formulation (and the model solved directly by CPLEX/Gurobi in the computational study). + +## Sets and Indices + +- $S$: set of candidate delivery sites, indexed by $i$ (or $j$). + +- $K$: set of customers, indexed by $k$. + +- $V$: set of vehicle tours of capacity $Q$ available for delivery, indexed by $v$; $|V|$ is the maximum number of vehicles/tours. + +- $N = S \cup \{0\}$: set of delivery sites augmented with node $0$, which represents the central depot. + +- $E = \{(i,j) : i,j \in N,\ i \neq j\}$: set of routing arcs. + +- $E' = \{(k,j) : k \in K,\ j \in S\}$: set of assignment arcs. + +## Parameters + +- $c_{ij}$: cost of routing arc $(i,j) \in E$. + +- $f_{kj}$: cost of assigning customer $k$ to delivery site $j$, $(k,j) \in E'$ (written $f_{ik}$ in the objective with $i \in S$). + +- $d_k$: demand of customer $k \in K$. + +- $Q$: vehicle (tour) capacity. + +## Decision Variables + +- $s_{ik} \in \{0,1\}$: $s_{ik}=1 \Leftrightarrow$ customer $k$ is assigned to site $i$, $\forall i \in S,\ k \in K$. + +- $e^{v}_{ij} \in \{0,1\}$: $e^{v}_{ij}=1 \Leftrightarrow$ arc $(i,j)$ is included in vehicle tour $v$, $\forall v \in V,\ (i,j) \in E$. + +- $\theta^{v}_{ik} \in \{0,1\}$: $\theta^{v}_{ik}=1 \Leftrightarrow$ site $i$ is visited by vehicle tour $v$ and customer $k$ is assigned to site $i$, $\forall v \in V,\ i \in S,\ k \in K$. + +- $q^{v}_{i} \ge 0$: total cumulative deliveries made upon serving site $i$ in vehicle tour $v$, $\forall v \in V,\ i \in S$. + +## Objective + +$$\begin{align} +\textbf{VRDAP}:\quad \min\ \sum_{v \in V} \sum_{(i,j) \in E} c_{ij}\, e^{v}_{ij} + + \sum_{i \in S} \sum_{k \in K} f_{ik}\, s_{ik} \tag{4a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{v \in V} \sum_{i \in N \setminus \{j\}} e^{v}_{ij} &\le 1, + & \forall j \in S \tag{4b}\\[2pt] +\sum_{j \in S} e^{v}_{0j} &\le 1, + & \forall v \in V \tag{4c}\\[2pt] +\sum_{i \in N \setminus \{j\}} e^{v}_{ij} - \sum_{i \in N \setminus \{j\}} e^{v}_{ji} &= 0, + & \forall v \in V,\ j \in N \tag{4d}\\[2pt] +q^{v}_{j} &\ge q^{v}_{i} + \sum_{k \in K} d_k\, s_{jk} - 2Q\bigl(1 - e^{v}_{ij}\bigr) + Q\, e^{v}_{ji}, + & \forall v \in V,\ i \neq j \in S \tag{4e}\\[2pt] +\theta^{v}_{ik} &\ge s_{ik} + \sum_{j \in N \setminus \{i\}} e^{v}_{ij} - 1, + & \forall v \in V,\ i \in S,\ k \in K \tag{4f}\\[2pt] +\theta^{v}_{ik} &\le \sum_{j \in N \setminus \{i\}} e^{v}_{ij}, + & \forall v \in V,\ i \in S,\ k \in K \tag{4g}\\[2pt] +\theta^{v}_{ik} &\le s_{ik}, + & \forall v \in V,\ i \in S,\ k \in K \tag{4h}\\[2pt] +q^{v}_{i} &\le Q \sum_{j \in N \setminus \{i\}} e^{v}_{ij}, + & \forall v \in V,\ i \in S \tag{4i}\\[2pt] +\sum_{k \in K} d_k\, \theta^{v}_{ik} &\le q^{v}_{i}, + & \forall v \in V,\ i \in S \tag{4j}\\[2pt] +\sum_{v \in V} \sum_{i \in S} \theta^{v}_{ik} &= 1, + & \forall k \in K \tag{4k}\\[2pt] +e,\, s \ \text{binary},\quad \theta,\, q &\ge 0. \tag{4l} +\end{align}$$ diff --git a/tasks/reihaneh2019/problem_description.txt b/tasks/reihaneh2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd3f7072f1679d57bf2254729dfed0e45166dae0 --- /dev/null +++ b/tasks/reihaneh2019/problem_description.txt @@ -0,0 +1,17 @@ +# Problem Description + +A distribution company operates a fleet of identical vehicles from a single central depot to deliver goods to geographically dispersed customers. Rather than visiting every customer directly, the company selects a subset of candidate delivery sites (such as parking lots or community centers) where customers travel to pick up their orders. The company must simultaneously decide which delivery sites to activate, which customers to assign to which activated sites, and how to route vehicles through the activated sites, so that total cost is minimized. + +The problem involves three types of entities: a central depot (labeled node zero), a set of candidate delivery sites, and a set of customers. Each customer has a known positive integer demand measured in pallets. The input data specifies the Euclidean-distance-based travel cost between every pair of nodes in the routing network (the depot and all candidate delivery sites) and the Euclidean-distance-based assignment cost between every customer and every candidate delivery site. All vehicles share a common capacity, expressed in pallets. The number of available vehicles is set to two more than the ceiling of total customer demand divided by vehicle capacity. + +The company must make three interrelated sets of choices. First, it must decide which candidate delivery sites to open. Second, it must assign every customer to exactly one opened delivery site served by exactly one vehicle tour; no customer may be left unserved. Third, it must design vehicle tours that begin at the central depot, visit a sequence of opened delivery sites to drop off goods, and return to the depot. + +Every delivery site may be visited by at most one vehicle tour, so no two tours share a delivery site. Each vehicle tour traverses at most one route segment leaving the depot. For every node in the network (depot or delivery site), the number of route segments entering it on a given tour must equal the number of route segments leaving it on that tour, ensuring each tour forms a closed loop through the depot. + +The total demand of all customers served by a single vehicle tour, computed as the sum of demands across all customers assigned to delivery sites visited on that tour, must not exceed the vehicle's capacity. In addition, each tour must form a single connected circuit through the depot rather than any collection of disconnected subloops among delivery sites. + +The cumulative quantity delivered on a tour at any delivery site must be at least as large as the total demand of all customers that are jointly assigned to that site and served by that tour. The cumulative quantity at a delivery site on a given tour must not exceed the vehicle capacity multiplied by the number of route segments leaving that site on that tour; consequently, when a site is visited on a tour the cumulative quantity is bounded by the vehicle capacity, and when a site is not visited on a tour the cumulative quantity at that site is forced to zero. + +A service-pairing quantity tracks, for each combination of customer, delivery site, and tour, whether that customer is assigned to that delivery site and that site is served by that tour. This quantity can be positive only if the site is actually served by that tour and only if the customer is actually assigned to that site. Conversely, whenever a customer is assigned to a site and that site is served by a tour, this quantity must be at least one. Each customer must be covered by exactly one such service pairing across all sites and all tours, which ensures that every customer is assigned to precisely one site on precisely one tour. + +The goal is to minimize the sum of two cost components: the total vehicle routing cost, calculated as the sum of route-segment travel costs over all route segments used across all tours, and the total customer assignment cost, calculated as the sum of assignment costs for each customer-to-site pairing that is selected. diff --git a/tasks/reihaneh2019/solution_logger.py b/tasks/reihaneh2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/reihaneh2019/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/reihaneh2019/solution_schema.json b/tasks/reihaneh2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5cd0b67ab4cefbe668fcde809f52ef4cff31c89c --- /dev/null +++ b/tasks/reihaneh2019/solution_schema.json @@ -0,0 +1,6 @@ +{ + "objective_value": " Total cost of the solution, combining vehicle routing cost across all tours and customer-to-site assignment cost.", + "routes": " For each vehicle whose tour is used, an object with 'arcs' (the list of [from_node, to_node] segments traversed between the depot and delivery sites) and 'sequence' (the ordered node IDs visited, starting and ending at the depot).", + "assignments": " Delivery site ID to which each customer is assigned for picking up its demand.", + "customer_tours": " For each customer, an object with 'vehicle' (ID of the vehicle tour serving the customer) and 'site' (ID of the delivery site at which the customer is served)." +} diff --git a/tasks/reinhardt2016/feasibility_check.py b/tasks/reinhardt2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..96d3ad5dee814ac605a4dded2e346c89eca1bc69 --- /dev/null +++ b/tasks/reinhardt2016/feasibility_check.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the ESVRPTW (Edge Set Cost Vehicle Routing Problem +with Time Windows) using the Direct Path Model (DPM) formulation. + +Based on: Reinhardt, Jepsen, & Pisinger (2016), +"The Edge Set Cost of the Vehicle Routing Problem with Time Windows", +Transportation Science, 50(2), 694-707. + +Checks all DPM constraints (15)-(27) against a given solution. +""" + +import json +import argparse +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('edge_sets_used', 'objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-4 + violations = [] + + # Handle null / infeasible solutions – when the solver found no solution, + # feasibility is indeterminate (null), not false. + status = solution.get("status", solution.get("status_name", "")) + status_lower = str(status).lower() if status else "" + has_no_solution = ( + solution.get("objective_value") is None + or "infeasible" in status_lower + or "no_solution" in status_lower + or status in ("infeasible_or_no_solution", None) + ) + if has_no_solution: + return { + "feasible": None, + "violated_constraints": ["no_solution"], + "violations": ["No feasible solution provided"], + "objective_value": None, + "recomputed_objective": None, + } + + nodes = instance["nodes"] + edge_sets = instance["edge_sets"] + dist = instance["distance_matrix"] + num_customers = instance["num_customers"] + vehicle_capacity = instance["vehicle_capacity"] + schedule_horizon = instance["schedule_horizon"] + + depot = 0 + customers = set(range(1, num_customers + 1)) + + node_data = {} + for nd in nodes: + node_data[nd["id"]] = nd + + # Build edge set membership + edge_set_arcs = {} + edge_set_customers = {} + edge_set_cost = {} + for es in edge_sets: + r = es["id"] + edge_set_cost[r] = es["access_cost"] + edge_set_arcs[r] = set() + edge_set_customers[r] = set() + for edge in es["edges"]: + u, v = edge[0], edge[1] + edge_set_arcs[r].add((u, v)) + edge_set_arcs[r].add((v, u)) + if u != depot: + edge_set_customers[r].add(u) + if v != depot: + edge_set_customers[r].add(v) + + # Map arcs to edge sets + arc_to_edge_set = {} + for es in edge_sets: + r = es["id"] + for edge in es["edges"]: + u, v = edge[0], edge[1] + arc_to_edge_set[(u, v)] = r + arc_to_edge_set[(v, u)] = r + + routes = solution.get("routes", []) + edge_sets_used = set(solution.get("edge_sets_used", [])) + + # Domain check: every node id in any route's sequence/arcs must exist + # in node_data; every node key in visit_times must be a valid node; + # every edge_sets_used id must exist in instance edge_sets. + valid_node_ids = set(node_data.keys()) + valid_edge_set_ids = set(edge_set_arcs.keys()) + for ridx, route in enumerate(routes): + for node in route.get("sequence", []): + if node not in valid_node_ids: + violations.append( + f"Domain: route {ridx} sequence node {node!r} " + f"not a valid node id" + ) + for arc in route.get("arcs", []): + for node in arc[:2]: + if node not in valid_node_ids: + violations.append( + f"Domain: route {ridx} arc node {node!r} " + f"not a valid node id" + ) + for node_key in route.get("visit_times", {}): + try: + nid = int(node_key) + except (ValueError, TypeError): + nid = None + if nid not in valid_node_ids: + violations.append( + f"Domain: route {ridx} visit_times key {node_key!r} " + f"not a valid node id" + ) + for r in edge_sets_used: + if r not in valid_edge_set_ids: + violations.append( + f"Domain: edge_sets_used contains invalid id {r!r}" + ) + + # If domain violations exist, abort downstream checks that index into + # node_data with potentially invalid ids. + if violations: + return { + "feasible": False, + "violated_constraints": ["domain"], + "violations": violations, + "objective_value": solution.get("objective_value"), + "recomputed_objective": None, + } + + # Check: number of used routes must not exceed number of vehicles |K| + num_vehicles = instance.get("num_vehicles") + if num_vehicles is not None and len(routes) > num_vehicles: + violations.append( + f"Number of used routes ({len(routes)}) exceeds number of vehicles ({num_vehicles})" + ) + + # Check: all customers visited exactly once + visited_customers = set() + for route in routes: + seq = route.get("sequence", []) + route_customers = [n for n in seq if n != depot] + for c in route_customers: + if c in visited_customers: + violations.append(f"Customer {c} visited more than once") + visited_customers.add(c) + + missing = customers - visited_customers + if missing: + violations.append(f"Customers not visited: {sorted(missing)}") + + extra = visited_customers - customers + if extra: + violations.append(f"Invalid nodes visited: {sorted(extra)}") + + # Check each route + total_arc_cost = 0.0 + needed_edge_sets = set() + + for ridx, route in enumerate(routes): + seq = route.get("sequence", []) + route_customers = [n for n in seq if n != depot] + + # Route must start and end at depot + if len(seq) < 2: + violations.append(f"Route {ridx}: too short (length {len(seq)})") + continue + if seq[0] != depot: + violations.append(f"Route {ridx}: does not start at depot") + if seq[-1] != depot: + violations.append(f"Route {ridx}: does not end at depot") + + # Capacity check + total_demand = sum(node_data[c]["demand"] for c in route_customers) + if total_demand > vehicle_capacity + tol: + violations.append( + f"Route {ridx}: demand {total_demand} exceeds capacity {vehicle_capacity}" + ) + + # Time window and travel time check + current_time = node_data[depot]["time_window_start"] + for k in range(len(seq) - 1): + i, j = seq[k], seq[k + 1] + travel_time = dist[i][j] + node_data[i]["service_time"] + arrival = current_time + travel_time + total_arc_cost += dist[i][j] + + # Track needed edge sets + if (i, j) in arc_to_edge_set: + needed_edge_sets.add(arc_to_edge_set[(i, j)]) + + if j == depot: + # Return to depot: check within schedule horizon + if arrival > schedule_horizon + tol: + violations.append( + f"Route {ridx}: return to depot at {arrival:.2f} " + f"exceeds horizon {schedule_horizon}" + ) + else: + # Check time window + tw_start = node_data[j]["time_window_start"] + tw_end = node_data[j]["time_window_end"] + arrival = max(arrival, tw_start) # wait if early + if arrival > tw_end + tol: + violations.append( + f"Route {ridx}: arrival at node {j} at {arrival:.2f} " + f"exceeds time window [{tw_start}, {tw_end}]" + ) + current_time = arrival + + # Domain check on submitted visit_times t_i^v: each value must be + # non-negative and lie within the node's time window [a_i, b_i] (paper + # constraint 22). Lower bound is 0 (start of horizon); upper bound is + # the per-node tw_end. We also flag negatives. + for ridx, route in enumerate(routes): + vt = route.get("visit_times", {}) if isinstance(route, dict) else {} + for node_key, t_val in vt.items(): + try: + node_id = int(node_key) + except (ValueError, TypeError): + node_id = node_key + if not isinstance(t_val, (int, float)): + violations.append( + f"Route {ridx}: visit_times[{node_key}]={t_val!r} " + f"is not numeric (domain violation)") + continue + if t_val < -tol: + violations.append( + f"Route {ridx}: visit_times[{node_key}]={t_val} < 0 " + f"(non-negativity violated)") + if node_id in node_data: + tw_lo = node_data[node_id].get("time_window_start") + tw_hi = node_data[node_id].get("time_window_end") + if tw_lo is not None and t_val < tw_lo - tol: + violations.append( + f"Route {ridx}: visit_times[{node_key}]={t_val} < " + f"time_window_start {tw_lo} (Eq 22 lower-bound)") + if tw_hi is not None and t_val > tw_hi + tol: + violations.append( + f"Route {ridx}: visit_times[{node_key}]={t_val} > " + f"time_window_end {tw_hi} (Eq 22 upper-bound)") + + # Check edge sets: all needed sets must be in edge_sets_used + for r in needed_edge_sets: + if r not in edge_sets_used: + violations.append( + f"Edge set {r} is needed but not marked as used" + ) + + # Recompute objective + total_edge_set_cost = sum(edge_set_cost[r] for r in edge_sets_used) + recomputed_obj = total_arc_cost + total_edge_set_cost + + reported_obj = solution.get("objective_value") + if reported_obj is not None and abs(recomputed_obj - reported_obj) > 1.0: + violations.append( + f"Objective mismatch: reported {reported_obj}, " + f"recomputed {recomputed_obj:.4f}" + ) + + violated_constraints = [] + if missing: + violated_constraints.append("visit_all_customers") + for v in violations: + if "capacity" in v.lower(): + violated_constraints.append("capacity") + if "time window" in v.lower() or "horizon" in v.lower(): + violated_constraints.append("time_windows") + if "edge set" in v.lower(): + violated_constraints.append("edge_set_linking") + if "more than once" in v.lower(): + violated_constraints.append("visit_once") + + violated_constraints = list(set(violated_constraints)) + + return { + "feasible": len(violations) == 0, + "violated_constraints": violated_constraints, + "violations": violations, + "objective_value": reported_obj, + "recomputed_objective": round(recomputed_obj, 4), + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for ESVRPTW (Reinhardt et al. 2016, DPM)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result["feasible"] is None: + print("Solution is INDETERMINATE (no solution from solver).") + elif result["feasible"]: + print("Solution is FEASIBLE.") + else: + print("Solution is INFEASIBLE.") + print(f"Violated constraints: {result['violated_constraints']}") + for msg in result["violations"]: + print(f" - {msg}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/reinhardt2016/gurobi_code.py b/tasks/reinhardt2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d71ada9c7dd06feeeb906fb4fbd8c2a1f07b4045 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_code.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Direct Path Model (DPM) for the +Edge Set Cost Vehicle Routing Problem with Time Windows (ESVRPTW). + +Based on: Reinhardt, Jepsen, & Pisinger (2016), +"The Edge Set Cost of the Vehicle Routing Problem with Time Windows", +Transportation Science, 50(2), 694-707. + +This implements the DPM formulation (Section 4) with the tightened +edge set constraints (16)-(17) and Big-M linearization (27). +""" + +import argparse +import json +import math +import os +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load the ESVRPTW instance from a JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(data, time_limit): + """ + Build and solve the DPM (Direct Path Model) for the ESVRPTW using Gurobi. + + DPM formulation from Section 4 of the paper: + min sum_{v in K} sum_{(i,j) in A} c_{ij} x_{ij}^v + sum_{r in R} c_r y_r (15) + s.t. + sum_{v in K} sum_{j:(j,i) in A_r} x_{ji}^v <= y_r for all r in R, i in C_r (16) + sum_{v in K} sum_{j:(i,j) in A_r} x_{ij}^v <= y_r for all r in R, i in C_r (17) + sum_{v in K} sum_{j:(i,j) in A} x_{ij}^v = 1 for all i in C (18) + sum_{i in C} x_{i0}^v = sum_{i in C} x_{0i}^v for all v in K (19) + sum_{j:(j,i) in A} x_{ji}^v - sum_{j:(i,j) in A} x_{ij}^v = 0 + for all i in C, v in K (20) + sum_{(i,j) in A} d_i x_{ij}^v <= D for all v in K (21) + a_i <= t_i^v <= b_i for all i in V, v in K (22) + t_i^v + theta_{ij} - t_j^v <= M(1 - x_{ij}^v) for all v in K, (i,j) in A (27) + x_{ij}^v in {0,1} for all (i,j) in A, v in K (24) + y_r in {0,1} for all r in R (25) + t_i^v >= 0 for all i in V, v in K (26) + """ + nodes = data["nodes"] + edge_sets = data["edge_sets"] + free_edges = data["free_edges"] + dist = data["distance_matrix"] + num_customers = data["num_customers"] + num_vehicles = data["num_vehicles"] + vehicle_capacity = data["vehicle_capacity"] + schedule_horizon = data["schedule_horizon"] + + # Node indices: 0 = depot, 1..num_customers = customers + depot = 0 + customers = list(range(1, num_customers + 1)) + all_nodes = list(range(num_customers + 1)) # V = {0} union C + + # Build node data lookup + node_data = {} + for nd in nodes: + node_data[nd["id"]] = nd + + # Vehicles + K = list(range(num_vehicles)) + + # Build arc set A: all directed arcs (i,j) for i,j in V, i != j + # In the direct path model, there is exactly one edge between each pair of nodes. + # Each undirected edge {i,j} gives two directed arcs (i,j) and (j,i). + arcs = [] + for i in all_nodes: + for j in all_nodes: + if i != j: + arcs.append((i, j)) + arc_set = set(arcs) + + # Cost and travel time for each arc (i,j) + # The distance_matrix provides distances. In DPM, c_{ij} = dist[i][j] and theta_{ij} = dist[i][j]. + # **INFERRED ASSUMPTION**: The paper does not explicitly state separate cost and travel time + # matrices. Following Solomon benchmark convention, we use Euclidean distance for both + # arc cost and travel time. Service time is added to travel time for time window propagation. + c = {} + theta = {} + for i in all_nodes: + for j in all_nodes: + if i != j: + c[(i, j)] = dist[i][j] + # Travel time = distance + service time at node i + # **INFERRED ASSUMPTION**: Following standard VRPTW convention (Solomon benchmarks), + # travel time on arc (i,j) includes service time at node i. + theta[(i, j)] = dist[i][j] + node_data[i]["service_time"] + + # Build edge set membership: for each edge set r, which arcs belong to A_r + # and which customers are covered (C_r). + # An undirected edge [i,j] in edge set r means arcs (i,j) and (j,i) are in A_r. + edge_set_arcs = {} # r -> set of arcs + edge_set_customers = {} # r -> set of customers covered + arc_to_edge_sets = {} # (i,j) -> list of edge set ids containing this arc + + for es in edge_sets: + r = es["id"] + edge_set_arcs[r] = set() + edge_set_customers[r] = set() + for edge in es["edges"]: + u, v = edge[0], edge[1] + edge_set_arcs[r].add((u, v)) + edge_set_arcs[r].add((v, u)) + # Customers covered: non-depot endpoints + if u != depot: + edge_set_customers[r].add(u) + if v != depot: + edge_set_customers[r].add(v) + # Track arc->edge_set mapping + for arc in [(u, v), (v, u)]: + if arc not in arc_to_edge_sets: + arc_to_edge_sets[arc] = [] + arc_to_edge_sets[arc].append(r) + + R = [es["id"] for es in edge_sets] + edge_set_cost = {es["id"]: es["access_cost"] for es in edge_sets} + + # Big-M value: must be greater than the duration of any route. + # **INFERRED ASSUMPTION**: M = schedule_horizon + max service time is a safe upper bound, + # since no route can exceed the schedule horizon. The paper states M should be + # "greater than the duration of any route" but does not specify the exact value. + M = schedule_horizon + max(nd["service_time"] for nd in nodes) + + # ---- Build Gurobi Model ---- + model = gp.Model("ESVRPTW_DPM") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x[i,j,v]: binary, 1 if vehicle v uses arc (i,j) + x = {} + for (i, j) in arcs: + for v in K: + x[i, j, v] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}_{v}") + + # y[r]: binary, 1 if edge set r is accessed + y = {} + for r in R: + y[r] = model.addVar(vtype=GRB.BINARY, name=f"y_{r}") + + # t[i,v]: continuous, time vehicle v visits node i + t = {} + for i in all_nodes: + for v in K: + a_i = node_data[i]["time_window_start"] + b_i = node_data[i]["time_window_end"] + t[i, v] = model.addVar( + lb=a_i, ub=b_i, vtype=GRB.CONTINUOUS, name=f"t_{i}_{v}" + ) + + model.update() + + # ---- Objective (15) ---- + # min sum_{v in K} sum_{(i,j) in A} c_{ij} x_{ij}^v + sum_{r in R} c_r y_r + obj = gp.LinExpr() + for (i, j) in arcs: + for v in K: + obj += c[(i, j)] * x[i, j, v] + for r in R: + obj += edge_set_cost[r] * y[r] + model.setObjective(obj, GRB.MINIMIZE) + + # ---- Constraints ---- + + # (16) sum_{v in K} sum_{j:(j,i) in A_r} x_{ji}^v <= y_r for all r in R, i in C_r + for r in R: + for i in edge_set_customers[r]: + lhs = gp.LinExpr() + for (jj, ii) in edge_set_arcs[r]: + if ii == i: + for v in K: + lhs += x[jj, ii, v] + model.addConstr(lhs <= y[r], name=f"edge_set_in_{r}_{i}") + + # (17) sum_{v in K} sum_{j:(i,j) in A_r} x_{ij}^v <= y_r for all r in R, i in C_r + for r in R: + for i in edge_set_customers[r]: + lhs = gp.LinExpr() + for (ii, jj) in edge_set_arcs[r]: + if ii == i: + for v in K: + lhs += x[ii, jj, v] + model.addConstr(lhs <= y[r], name=f"edge_set_out_{r}_{i}") + + # (18) sum_{v in K} sum_{j:(i,j) in A} x_{ij}^v = 1 for all i in C + for i in customers: + lhs = gp.LinExpr() + for j in all_nodes: + if j != i: + for v in K: + lhs += x[i, j, v] + model.addConstr(lhs == 1, name=f"visit_{i}") + + # (19) sum_{i in C} x_{i0}^v = sum_{i in C} x_{0i}^v for all v in K + for v in K: + lhs = gp.LinExpr() + rhs = gp.LinExpr() + for i in customers: + lhs += x[i, depot, v] + rhs += x[depot, i, v] + model.addConstr(lhs == rhs, name=f"depot_balance_{v}") + + # (20) sum_{j:(j,i) in A} x_{ji}^v - sum_{j:(i,j) in A} x_{ij}^v = 0 + # for all i in C, v in K + for i in customers: + for v in K: + inflow = gp.LinExpr() + outflow = gp.LinExpr() + for j in all_nodes: + if j != i: + inflow += x[j, i, v] + outflow += x[i, j, v] + model.addConstr(inflow - outflow == 0, name=f"flow_{i}_{v}") + + # (21) sum_{(i,j) in A} d_i x_{ij}^v <= D for all v in K + for v in K: + lhs = gp.LinExpr() + for (i, j) in arcs: + lhs += node_data[i]["demand"] * x[i, j, v] + model.addConstr(lhs <= vehicle_capacity, name=f"capacity_{v}") + + # (22) a_i <= t_i^v <= b_i -- already handled by variable bounds + + # (27) t_i^v + theta_{ij} - t_j^v <= M(1 - x_{ij}^v) for all v in K, (i,j) in A + # NOTE: We skip arcs returning to the depot (j == depot) because the single + # depot time variable t[0,v] represents the departure time. Applying the + # constraint on return arcs would force t[0,v] >= arrival-back-at-depot, + # conflicting with the departure-time semantics and making the model + # infeasible whenever a route finishes later than it starts. + for (i, j) in arcs: + if j == depot: + continue + for v in K: + model.addConstr( + t[i, v] + theta[(i, j)] - t[j, v] <= M * (1 - x[i, j, v]), + name=f"time_{i}_{j}_{v}", + ) + + # ---- Single-tour-per-vehicle ---- + # Without this, the formulation lets a vehicle have multiple disjoint + # depot->...->depot sub-tours (the MTZ-style time constraint (27) is + # explicitly skipped on return-to-depot arcs, so the time variable doesn't + # tie sub-tours together). Force each vehicle to leave the depot at most + # once. Combined with depot balance (19), each vehicle is then a single + # depot->customers->depot chain. + for v in K: + model.addConstr( + gp.quicksum(x[depot, j, v] for j in customers) <= 1, + name=f"single_departure_{v}", + ) + + # ---- Symmetry breaking (optional but helpful) ---- + # **INFERRED ASSUMPTION**: The paper does not discuss symmetry breaking among + # identical vehicles, but it is standard practice to break symmetry by ordering + # vehicle usage. We order vehicles by the smallest customer index served. + # We add: if vehicle v does not leave the depot, then vehicle v+1 doesn't either. + for v in range(len(K) - 1): + leaves_v = gp.LinExpr() + leaves_v1 = gp.LinExpr() + for i in customers: + leaves_v += x[depot, i, K[v]] + leaves_v1 += x[depot, i, K[v + 1]] + model.addConstr(leaves_v >= leaves_v1, name=f"sym_break_{v}") + + # ---- Solve ---- + model.optimize() + + # ---- Extract solution ---- + result = { + "objective_value": None, + "status": None, + "routes": [], + "edge_sets_used": [], + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = ( + "optimal" if model.Status == GRB.OPTIMAL else "feasible" + ) + + # Extract routes + for v in K: + route_arcs = [] + for (i, j) in arcs: + if x[i, j, v].X > 0.5: + route_arcs.append((i, j)) + if route_arcs: + visit_times = {} + for i in all_nodes: + if t[i, v].X is not None: + visit_times[i] = t[i, v].X + route_obj = { + "vehicle": v, + "arcs": route_arcs, + "visit_times": visit_times, + } + try: + route_obj["sequence"] = reconstruct_route(route_arcs, depot) + except RouteReconstructionError as e: + route_obj["sequence"] = None + route_obj["warning"] = f"reconstruction_failed: {e}" + result["routes"].append(route_obj) + + # Extract which edge sets are used + for r in R: + if y[r].X > 0.5: + result["edge_sets_used"].append(r) + else: + result["status"] = "infeasible_or_no_solution" + result["objective_value"] = None + + return result + + +class RouteReconstructionError(ValueError): + """Raised when arcs assigned to one vehicle do not form a single + depot->customers->depot tour. Under the corrected DPM (with the + single_departure_per_vehicle constraint) this should never happen; + if it does, surface it instead of silently dropping arcs.""" + + +def reconstruct_route(route_arcs, depot): + """Walk the arcs assigned to a single vehicle into one ordered route. + + Asserts a single depot-departure and that every arc is consumed; raises + RouteReconstructionError otherwise so model regressions cannot hide as + "missing customers" downstream. + """ + if not route_arcs: + return [] + + from collections import defaultdict + out = defaultdict(list) + for (i, j) in route_arcs: + out[i].append(j) + + depot_starts = list(out[depot]) + if len(depot_starts) > 1: + raise RouteReconstructionError( + f"vehicle has {len(depot_starts)} depot-departures: {depot_starts}; " + f"single_departure_per_vehicle constraint missing or violated" + ) + if len(depot_starts) == 0: + raise RouteReconstructionError( + f"vehicle has {len(route_arcs)} arcs but no depot-departure: " + f"{route_arcs} — likely customer-only cycle (MTZ inactive)" + ) + + used = set() + route = [depot] + current = depot + while True: + succs = out[current] + if not succs: + break + if len(succs) > 1: + raise RouteReconstructionError( + f"node {current} has multiple successors {succs} on one vehicle" + ) + nxt = succs[0] + if (current, nxt) in used: + break + used.add((current, nxt)) + route.append(nxt) + if nxt == depot: + break + current = nxt + + if len(used) != len(route_arcs): + unreached = [a for a in route_arcs if a not in used] + raise RouteReconstructionError( + f"walked {len(used)}/{len(route_arcs)} arcs; unreached={unreached} " + f"(disconnected component in vehicle's arc set)" + ) + return route + + +def main(): + parser = argparse.ArgumentParser( + description="Solve ESVRPTW using Gurobi (DPM 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 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 + data = load_instance(args.instance_path) + + # Build and solve model + result = build_and_solve(data, args.time_limit) + + # Convert any non-serializable types for JSON output + def make_serializable(obj): + if isinstance(obj, dict): + return {str(k): make_serializable(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return [make_serializable(item) for item in obj] + elif isinstance(obj, float): + if math.isnan(obj) or math.isinf(obj): + return str(obj) + return obj + else: + return obj + + output = make_serializable(result) + + # Write solution + with open(args.solution_path, "w") as f: + output["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(output, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status']}") + print(f"Number of routes: {len(result['routes'])}") + print(f"Edge sets used: {result['edge_sets_used']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3a8833a62bcb72aff563dfff397a9547cb9a0d72 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf5b4dd300c3e8ded69748f426681da039a42a649cffe4470981086c3240fb49 +size 135 diff --git a/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1263c1f22205b33d757111e3644100cda3bf03bb --- /dev/null +++ b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12cafea070abef0c9a0f665635e5cda31bd7619eb01d79229d7b7c36901c1234 +size 145 diff --git a/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8272177b04d3230660e9169077ff8463230f4478 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c097ace83cbd379d8bc3030ee08b96e4b8317e2fc816f3d4aea3a2dbf3baea0 +size 147 diff --git a/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4bdc5dd4605402cc1390e684637a61090003c93d --- /dev/null +++ b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80993cd4153876bf48bae7d98f263de085ae46c74253e81a8322397b0fc6f7c0 +size 133 diff --git a/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c6decdebc8d3c7456f44d27347b01995b923aaaf --- /dev/null +++ b/tasks/reinhardt2016/gurobi_feasi_result/large_feasi_result_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d01a46c20c3dcfa69391a7d870eaf90d44457b260f6042d5edc9903f59f69a5 +size 147 diff --git a/tasks/reinhardt2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/reinhardt2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..cd0d306e2bfc4d01e1315a5808bfc345cfb8b683 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_feasi_result/tiny_feasi_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ea8b54795034aec241e1cca4e93985b15b667823e10c75565d5f1ec7e6d32a3 +size 146 diff --git a/tasks/reinhardt2016/gurobi_solution/large_solution_1.json b/tasks/reinhardt2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..1199cfa7d410ebcdacdfce3fe362792dd5f40c48 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd4207c0ca65c635018bb33ac6349a0cdbf0b105eb8a78c5a401bfcbd1589d28 +size 8680 diff --git a/tasks/reinhardt2016/gurobi_solution/large_solution_2.json b/tasks/reinhardt2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f7c249c8dee8f90042a03f15910153f70e8f15db --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4d859b3f8255cc01bf32ff04bf443f1e2944b9d2704ab0f8b677b671b3ecca1 +size 7600 diff --git a/tasks/reinhardt2016/gurobi_solution/large_solution_3.json b/tasks/reinhardt2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..d7140d837ec38ae1733a6c7ac2165f220e9aed56 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83531c9ab85cf5fc4d64971e9c2737c52dc87904816537ff7ea6406f9eca189c +size 10741 diff --git a/tasks/reinhardt2016/gurobi_solution/large_solution_4.json b/tasks/reinhardt2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..71b244a9e278ae28e659f21f3e1c6fc79efc2b9d --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf56a1e1bfd86e2f3733b3ebef8aa1028d59824d3990360268ed54bf6e3d2e66 +size 8604 diff --git a/tasks/reinhardt2016/gurobi_solution/large_solution_5.json b/tasks/reinhardt2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c503da5bff476f762eccb7e217c43a12c2d83256 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4bd4999929cdf7abde2d8853fe6fbe902eacdb1e313dafa0ddbd7612505d1df9 +size 7674 diff --git a/tasks/reinhardt2016/gurobi_solution/tiny_solution.json b/tasks/reinhardt2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..613907cc6df8c0895b39629d58ddcb7473a3d183 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:891f6053e0f28fc80c328b4665ac629b0c07de81307e10495f2c967a63341a6c +size 2031 diff --git a/tasks/reinhardt2016/gurobi_solution_log/large_log_1.jsonl b/tasks/reinhardt2016/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3b1350c84763c598d73b2c069bc7898ef2d043d0 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:966bd6dde80aa718743fc994f0867ec85a438bf11056adfc79c3067cbafaae8f +size 1682 diff --git a/tasks/reinhardt2016/gurobi_solution_log/large_log_2.jsonl b/tasks/reinhardt2016/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6333fd55c322f7bdd97024ff6378c4cf62313d1a --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f57b85a93af06b6ef53c09bbd4fb788e2294ab564b1080df90ed1824abf6b59a +size 1607 diff --git a/tasks/reinhardt2016/gurobi_solution_log/large_log_3.jsonl b/tasks/reinhardt2016/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3d24efb90a192f42db01ec81f6ce7b8694afba25 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:623ba1e664d8f4122a1c24c3fd625f3d3988a442e2163d49a48e031956c31335 +size 3523 diff --git a/tasks/reinhardt2016/gurobi_solution_log/large_log_4.jsonl b/tasks/reinhardt2016/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..872d6d5494f3cc9aaa12c7630fdf51eca23e2f7e --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee82c67fb9830905e7ff139d3446c358a34322b69a63ec03ed106e63608e96d2 +size 2527 diff --git a/tasks/reinhardt2016/gurobi_solution_log/large_log_5.jsonl b/tasks/reinhardt2016/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b9bd899514fe24872d9f015a01d06e6a31be7d98 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e954c9dfa1eb0c937c66c329c0e7d5a9f2ab77806e07f6c674b9354afb1774f +size 1733 diff --git a/tasks/reinhardt2016/gurobi_solution_log/tiny_log.jsonl b/tasks/reinhardt2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1fe30c78ebe1eb9184e84a65253b77a3dae2c265 --- /dev/null +++ b/tasks/reinhardt2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8aa24177dff4ae5b604e684dafe494f204324c2e5056410c2323c645ebc4723 +size 572 diff --git a/tasks/reinhardt2016/instance/large_instance_1.json b/tasks/reinhardt2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0a5ad1b99c0093180e868d5ab12e6de210954937 --- /dev/null +++ b/tasks/reinhardt2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:658c26dc5f9fc3a9864f0e3ec9c92d8697e32c498750a1396b57508a7880feaf +size 60838 diff --git a/tasks/reinhardt2016/instance/large_instance_2.json b/tasks/reinhardt2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..234cc16f05616e6031b33d266c4b9753bf60e107 --- /dev/null +++ b/tasks/reinhardt2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:130c1f45a128cac99e0fd014b5d69c0513ae3035d2c03cb0679a57edc0ea4dbd +size 60929 diff --git a/tasks/reinhardt2016/instance/large_instance_3.json b/tasks/reinhardt2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ab8988445c1f4b1ac0a8522cd0177b443b43eac4 --- /dev/null +++ b/tasks/reinhardt2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3715e0d5a49081edcdfd44e9bf0d1510499fede4467d802d035bbc6ba8c5b1ab +size 60911 diff --git a/tasks/reinhardt2016/instance/large_instance_4.json b/tasks/reinhardt2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..fbeff588146708d27fd8a157d1945268b07cb14a --- /dev/null +++ b/tasks/reinhardt2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f35cdb132b7c143e44a9217ed85b016bf34efc67cdeea8c11c6a69213ce2f626 +size 60890 diff --git a/tasks/reinhardt2016/instance/large_instance_5.json b/tasks/reinhardt2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..1b91b6724157414ddcfbb6459a347d2a79098921 --- /dev/null +++ b/tasks/reinhardt2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1971e964137d51d8cb6f1c1a371109839bdb2f40e410c14c5bea2e2dc41f52e3 +size 56823 diff --git a/tasks/reinhardt2016/instance/tiny_instance.json b/tasks/reinhardt2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..e0447c0682f2bc7a4482d98a0a261b74b142a31a --- /dev/null +++ b/tasks/reinhardt2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29135f03fe3c10b122f0a594b52d3974f3e2ab489288c4906874baea1d4964a8 +size 11220 diff --git a/tasks/reinhardt2016/instance_schema.json b/tasks/reinhardt2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..4ab9f07c0f1c89c413c556284cff84ba66350a20 --- /dev/null +++ b/tasks/reinhardt2016/instance_schema.json @@ -0,0 +1,27 @@ +{ + "num_customers": " Total number of customers to be served.", + "num_vehicles": " Maximum number of vehicles available in the fleet.", + "vehicle_capacity": " Maximum total demand that a single vehicle can carry on its route.", + "num_edge_sets": " Number of edge sets in the road network partition.", + "schedule_horizon": " End of the scheduling window within which all vehicles must return to the depot.", + "nodes": [ + { + "id": " Unique identifier for this node, where 0 is the depot and 1 through num_customers are customers.", + "x": " Horizontal coordinate of this node's location.", + "y": " Vertical coordinate of this node's location.", + "demand": " Quantity of goods to be delivered to this node (0 for the depot).", + "time_window_start": " Earliest time at which service may begin at this node.", + "time_window_end": " Latest time at which service may begin at this node.", + "service_time": " Time a vehicle must spend at this node before departing." + } + ], + "edge_sets": [ + { + "id": " Unique identifier for this edge set.", + "access_cost": " Fixed cost the company must pay to use any edge in this set.", + "edges": " Pairs of node identifiers representing undirected edges belonging to this set." + } + ], + "free_edges": " Pairs of node identifiers representing undirected edges that can be traversed without paying any access cost.", + "distance_matrix": " Euclidean distance between each pair of nodes, used as both traversal cost and travel time." +} \ No newline at end of file diff --git a/tasks/reinhardt2016/mathematical_formulation.md b/tasks/reinhardt2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..7304670960dba2aa6abb59c26fa0cd9d3154b768 --- /dev/null +++ b/tasks/reinhardt2016/mathematical_formulation.md @@ -0,0 +1,61 @@ +# Original Formulation: Edge Set Cost Vehicle Routing Problem with Time Windows (ESVRPTW) + +*Source: The Edge Set Cost of the Vehicle Routing Problem with Time Windows, Line Blander Reinhardt, Mads Kehlet Jepsen, David Pisinger, Transportation Science 50(2), 2016.* + +## Sets and Indices + +$$\begin{align*} +R &: \text{the set of all edge sets} \\ +C &: \text{the set of customers; } C_r \text{ are the customers covered by the edges in set } r \in R \\ +V &: \text{the set of nodes representing the customers in } C \text{ and the depot, defined as } 0 \;\; (V = \{0\} \cup C) \\ +\mathbf{A} &: \text{the set of arcs } (i,j) \text{ in } V; \;\; \mathbf{A}_r \text{ is the set of arcs } (i,j) \text{ belonging to set } r \in R \\ +K &: \text{the set of vehicles, where } |K| \leq |C| \text{ as usual for VRPTW problems} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +D &: \text{the capacity of the vehicles} \\ +d_i &: \text{the demand which must be delivered to node } i \in V \text{ (the demand at the depot is zero)} \\ +a_i &: \text{the availability (earliest service) time for customer } i \in C, \;\; a_i \geq 0 \\ +b_i &: \text{the required completion (latest service) time for customer } i \in C, \;\; b_i \geq a_i \\ +c_{ij} &: \text{the cost of using arc } (i,j) \in \mathbf{A} \\ +\theta_{ij}&: \text{the time it takes to travel on arc } (i,j) \in \mathbf{A} \\ +c_r &: \text{the cost of accessing the arcs in edge set } r \in R \\ +M &: \text{a large constant greater than the duration of any route} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x_{ij}^{v} &\in \{0,1\} : \text{one if arc } (i,j) \in \mathbf{A} \text{ is used by vehicle } v \in K, \text{ zero otherwise} \\ +y_r &\in \{0,1\} : \text{one if an edge from edge set } r \in R \text{ is used, zero otherwise} \\ +t_i^{v} &\in \mathbb{R}_0^{+} : \text{the time vehicle } v \in K \text{ visits node } i \in V +\end{align*}$$ + +## Objective + +$$\begin{align} +\textbf{DPM:} \quad \min \quad & \sum_{v \in K} \sum_{(i,j) \in \mathbf{A}} c_{ij}\, x_{ij}^{v} \;+\; \sum_{r \in R} c_r\, y_r \tag{15} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.} \quad +& \sum_{v \in K} \sum_{j:(j,i) \in \mathbf{A}_r} x_{ji}^{v} \leq y_r & \forall r \in R,\; i \in C_r \tag{16} \\ +& \sum_{v \in K} \sum_{j:(i,j) \in \mathbf{A}_r} x_{ij}^{v} \leq y_r & \forall r \in R,\; i \in C_r \tag{17} \\ +& \sum_{v \in K} \sum_{j:(i,j) \in \mathbf{A}} x_{ij}^{v} = 1 & \forall i \in C \tag{18} \\ +& \sum_{i \in C} x_{i0}^{v} = \sum_{i \in C} x_{0i}^{v} & \forall v \in K \tag{19} \\ +& \sum_{j:(j,i) \in \mathbf{A}} x_{ji}^{v} - \sum_{j:(i,j) \in \mathbf{A}} x_{ij}^{v} = 0 & \forall i \in C,\; \forall v \in K \tag{20} \\ +& \sum_{(i,j) \in \mathbf{A}} d_i\, x_{ij}^{v} \leq D & \forall v \in K \tag{21} \\ +& a_i \leq t_i^{v} \leq b_i & \forall i \in V,\; v \in K \tag{22} \\ +& (t_i^{v} + \theta_{ij})\, x_{ij}^{v} - t_j^{v} \leq 0 & \forall v \in K,\; (i,j) \in \mathbf{A} \tag{23} \\ +& x_{ij}^{v} \in \{0,1\} & \forall (i,j) \in \mathbf{A},\; v \in K \tag{24} \\ +& y_r \in \{0,1\} & \forall r \in R \tag{25} \\ +& t_i^{v} \in \mathbb{R}_0^{+} & \forall i \in V,\; v \in K \tag{26} +\end{align}$$ + +The nonlinear time-propagation constraint (23) can be replaced by the linear big-$M$ constraints: $$\begin{align} +& t_i^{v} + \theta_{ij} - t_j^{v} \leq M\,(1 - x_{ij}^{v}) & \forall v \in K,\; (i,j) \in \mathbf{A} \tag{27} +\end{align}$$ where $M$ is a large constant greater than the duration of any route. diff --git a/tasks/reinhardt2016/problem_description.txt b/tasks/reinhardt2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f7e6a297b8b9f07565e00d9c080bf662a0799dc --- /dev/null +++ b/tasks/reinhardt2016/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A fleet of identical vehicles operates out of a single depot to deliver goods to a set of customers. Each vehicle has the same carrying capacity. Each customer has a known demand, a location specified by coordinates, and a time window defined by an earliest service time and a latest service time. The depot also has a time window spanning the full scheduling horizon, and the demand at the depot is zero. Each customer additionally has a fixed service time that must be spent at the customer location before the vehicle can depart. + +The road network connecting the depot and customers is partitioned into edge sets. Every pair of nodes (including the depot) is connected by exactly one undirected edge, and each such edge either belongs to one of the edge sets or is a free edge that does not belong to any edge set. Each edge set has a fixed access cost that the company must pay if any vehicle traverses any edge belonging to that set; once the access cost for an edge set is paid, all vehicles may use all edges in that set at no additional access charge. Edges that are free may be used by any vehicle without paying an access cost. In addition to the access costs, every arc between two nodes carries a per-use traversal cost equal to the Euclidean distance between the two nodes, incurred each time any vehicle travels that arc. The travel time on an arc from one node to another equals the Euclidean distance between the two nodes plus the service time at the origin node. + +The company must decide which vehicles to deploy, which route each deployed vehicle follows, and which edge sets to access. Every customer must be visited exactly once by exactly one vehicle. Each deployed vehicle starts at the depot, visits a sequence of customers, and returns to the depot. For each customer, the total flow into that customer by a given vehicle must equal the total flow out of that customer by the same vehicle. The number of vehicles leaving the depot must equal the number returning. The total demand of all customers served by a single vehicle must not exceed the vehicle capacity. Every vehicle is assigned a visit time at every node, and that visit time must fall within the node's time window, regardless of whether the vehicle actually visits that node. If a vehicle travels directly from one node to another, the vehicle's visit time at the destination must be no earlier than the vehicle's visit time at the origin plus the travel time on that arc. An edge belonging to an edge set may only be traversed if the company has chosen to pay the access cost for that edge set; specifically, for each edge set and each customer covered by that edge set, the total number of times all vehicles enter that customer via arcs in the edge set, and separately the total number of times all vehicles leave that customer via arcs in the edge set, must each not exceed one if the edge set is accessed, and must be zero if it is not. The number of available vehicles is at most equal to the number of customers. + +The goal is to minimize the total cost, which is the sum of the traversal costs over all arcs used by all vehicles plus the sum of the access costs over all edge sets that are accessed. diff --git a/tasks/reinhardt2016/solution_logger.py b/tasks/reinhardt2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/reinhardt2016/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/reinhardt2016/solution_schema.json b/tasks/reinhardt2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fd6bad7cc476cabd8a9bf476baee875b688c4e44 --- /dev/null +++ b/tasks/reinhardt2016/solution_schema.json @@ -0,0 +1,12 @@ +{ + "objective_value": " Total cost of the solution, summing the per-arc traversal costs over all arcs used by all vehicles plus the access costs of every accessed edge set.", + "routes": [ + { + "vehicle": " Identifier of the vehicle that performs this route.", + "sequence": " Ordered list of node ids visited by the vehicle, starting and ending at the depot.", + "arcs": " Directed arcs traversed by the vehicle, each given as an [origin_node, destination_node] pair.", + "visit_times": " Time at which the vehicle visits each node, lying within that node's time window." + } + ], + "edge_sets_used": " Identifiers of the edge sets whose access cost is paid so that vehicles may traverse the edges they contain." +} diff --git a/tasks/ribeiro1994/feasibility_check.py b/tasks/ribeiro1994/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..046f5a2db9714e677f11eead65b5871defa0f520 --- /dev/null +++ b/tasks/ribeiro1994/feasibility_check.py @@ -0,0 +1,583 @@ +""" +Feasibility checker for the Multiple-Depot Vehicle Scheduling Problem (MDVSP). + +Checks a candidate solution against the mathematical formulation from +Ribeiro & Soumis (1994). + +Hard constraints checked (numbered as in the paper): + Constraint (1): Trip coverage — each trip j in N covered exactly once. + Constraint (2): Flow conservation — each route is a valid depot-out, + compatible-trip-sequence, depot-in path. + Constraint (3): Depot capacity — vehicles from depot k <= r_k. + Constraint (4): Nonnegativity — flow variables >= 0. + Constraint (5): Integrality — flow variables are integer. + Constraint (6): Objective consistency — reported objective_value matches + the recomputed sum of pull-out, trip-to-trip, and pull-in + arc costs across every route. +""" + +import json +import argparse +import math +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('num_vehicles', 'objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('num_vehicles',) +_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_constraint_set = set() + + n_trips = instance["parameters"]["n_trips"] + m_depots = instance["parameters"]["m_depots"] + vehicle_caps = instance["vehicle_capacities"] + trips_data = instance["trips"] + + # Build trip lookup: trip_id -> trip dict + trip_by_id = {t["trip_id"]: t for t in trips_data} + + # Build compatible arc set for quick lookup + compatible_set = set() + for arc in instance["compatible_arcs"]: + compatible_set.add((arc["from_trip"], arc["to_trip"])) + + routes = solution.get("routes", []) + + # ------------------------------------------------------------------ + # Constraint (1): Trip coverage — each trip must be covered exactly once + # sum_{k=1}^{m} sum_{i in V^k} x^k_{ij} = 1 for all j in N + # In the path formulation: each trip j appears in exactly one route. + # ------------------------------------------------------------------ + trip_coverage = defaultdict(int) + for route in routes: + for t in route["trips"]: + trip_coverage[t] += 1 + + for j in range(1, n_trips + 1): + count = trip_coverage.get(j, 0) + if abs(count - 1) > tol: + lhs = float(count) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + + violated_constraint_set.add(1) + if count == 0: + violations.append(f"Constraint (1): Trip {j} is not covered by any route") + else: + violations.append( + f"Constraint (1): Trip {j} is covered {count} times (expected 1)" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # ------------------------------------------------------------------ + # Constraint (2): Flow conservation — for each depot k and node j, + # inflow = outflow. In the path formulation this means each route must + # be a valid path: the vehicle leaves its depot, traverses a sequence + # of compatible trips, and returns to the same depot. + # + # Specifically, consecutive trips (T_i, T_j) in a route must satisfy + # compatibility: e_i + tau_{ij} <= s_j, i.e., (i, j) must be in the + # compatible arc set. + # ------------------------------------------------------------------ + for route_idx, route in enumerate(routes): + trip_list = route["trips"] + depot_k = route["depot"] + + # Check depot is valid + if depot_k < 1 or depot_k > m_depots: + violated_constraint_set.add(2) + violations.append( + f"Constraint (2): Route {route_idx + 1} uses invalid depot {depot_k}" + ) + lhs = float(depot_k) + rhs_val = float(m_depots) + violation_amount = abs(lhs - rhs_val) if depot_k < 1 else max(lhs - rhs_val, 0.0) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + continue + + # Check each consecutive pair in the trip sequence is compatible + for pos in range(len(trip_list) - 1): + ti = trip_list[pos] + tj = trip_list[pos + 1] + + if (ti, tj) not in compatible_set: + # Compute how much the compatibility constraint is violated + trip_i = trip_by_id.get(ti) + trip_j = trip_by_id.get(tj) + if trip_i is not None and trip_j is not None: + # Compatibility requires e_i + tau_{ij} <= s_j + # We don't have tau_{ij} directly for incompatible arcs, + # but we know the arc is not in the compatible set, + # meaning e_i + tau_{ij} > s_j. + # For the violation, use the time gap: e_i - s_j + # (if positive, it means trip i ends after trip j starts). + e_i = trip_i["end_time"] + s_j = trip_j["start_time"] + # The flow conservation is violated: the arc doesn't exist + # in the graph, so the flow variable on a non-existent arc + # is being used. LHS (flow on non-arc) = 1, RHS = 0. + lhs = 1.0 + rhs = 0.0 + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + else: + lhs = 1.0 + rhs = 0.0 + violation_amount = 1.0 + normalizer = eps + ratio = violation_amount / normalizer + + violated_constraint_set.add(2) + violations.append( + f"Constraint (2): Route {route_idx + 1} has incompatible " + f"consecutive trips ({ti} -> {tj})" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio, + }) + + # Check that all trip IDs in the route are valid + for t in trip_list: + if t < 1 or t > n_trips: + violated_constraint_set.add(2) + violations.append( + f"Constraint (2): Route {route_idx + 1} references invalid trip {t}" + ) + lhs = float(t) + rhs_val = float(n_trips) + violation_amount = max(lhs - rhs_val, 0.0) if t > n_trips else abs(lhs) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (3): Depot capacity — sum_{j in N} x^k_{n+k,j} <= r_k + # In the path formulation: number of routes from depot k <= r_k. + # ------------------------------------------------------------------ + depot_vehicle_count = defaultdict(int) + for route in routes: + depot_vehicle_count[route["depot"]] += 1 + + for k in range(1, m_depots + 1): + count = depot_vehicle_count.get(k, 0) + r_k = vehicle_caps[k - 1] + lhs = float(count) + rhs = float(r_k) + violation_amount = max(lhs - rhs, 0.0) + if violation_amount > tol: + violated_constraint_set.add(3) + violations.append( + f"Constraint (3): Depot {k} uses {count} vehicles but capacity is {r_k}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (4): Nonnegativity — x^k_{ij} >= 0 + # In the path formulation, each route implicitly sets x = 1 on its arcs + # and x = 0 elsewhere, so nonnegativity is automatically satisfied by + # any route-based solution. We verify route counts are non-negative. + # ------------------------------------------------------------------ + for route_idx, route in enumerate(routes): + if len(route["trips"]) < 1: + violated_constraint_set.add(4) + lhs = 0.0 + rhs = 1.0 + violation_amount = max(rhs - lhs, 0.0) + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint (4): Route {route_idx + 1} has no trips (empty route)" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (5): Integrality — x^k_{ij} integer + # In the path formulation each y_p should be 0 or 1. A route-based + # solution inherently has integer y_p = 1 for selected routes. We check + # that no trip appears fractionally (already caught by constraint 1). + # We additionally check that the number of routes is a whole number + # (which it always is by construction, but we verify). + # ------------------------------------------------------------------ + total_vehicles = len(routes) + if total_vehicles != int(total_vehicles): + violated_constraint_set.add(5) + lhs = float(total_vehicles) + rhs = float(round(total_vehicles)) + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint (5): Number of vehicles {total_vehicles} is not integer" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + reported_num_vehicles = solution.get("num_vehicles") + if (isinstance(reported_num_vehicles, bool) + or not isinstance(reported_num_vehicles, (int, float)) + or abs(float(reported_num_vehicles) - total_vehicles) > tol): + violated_constraint_set.add(5) + lhs = (float(reported_num_vehicles) + if isinstance(reported_num_vehicles, (int, float)) + and not isinstance(reported_num_vehicles, bool) else 0.0) + rhs = float(total_vehicles) + violation_amount = abs(lhs - rhs) if lhs != rhs else 1.0 + normalizer = max(abs(rhs), eps) + violations.append( + f"Constraint (5): reported num_vehicles=" + f"{reported_num_vehicles!r} does not equal len(routes)=" + f"{total_vehicles}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (6): Objective consistency — Tier C defence against + # score-gaming exploits that lie about the reported objective_value. + # + # The MDVSP objective is fully determined by the routes: for each + # route with depot k and trip sequence (t_1, ..., t_m), + # cost(route) = c_{n+k, t_1} + sum_p c_{t_p, t_{p+1}} + c_{t_m, n+k} + # i.e. depot pull-out + trip-to-trip arc costs + depot pull-in. + # All three cost components are provided in the instance, so we can + # recompute the true objective exactly and compare to the value + # reported in the solution. Skipped silently when any arc lookup is + # missing (e.g. infeasible route — caught by constraints 1/2). + # ------------------------------------------------------------------ + reported_obj_raw = solution.get("objective_value") + if reported_obj_raw is not None: + try: + reported_obj = float(reported_obj_raw) + except (TypeError, ValueError): + reported_obj = None + else: + reported_obj = None + + if reported_obj is not None: + depot_to_trip_cost = {} + for entry in instance.get("depot_to_trip_costs", []): + depot_to_trip_cost[(entry["depot"], entry["trip"])] = entry["cost"] + trip_to_depot_cost = {} + for entry in instance.get("trip_to_depot_costs", []): + trip_to_depot_cost[(entry["trip"], entry["depot"])] = entry["cost"] + arc_cost = {} + for arc in instance["compatible_arcs"]: + arc_cost[(arc["from_trip"], arc["to_trip"])] = arc["cost"] + + true_obj = 0.0 + lookup_failed = False + for route in routes: + trip_list = route.get("trips", []) + depot_k = route.get("depot") + if not trip_list or depot_k is None: + lookup_failed = True + break + first_trip = trip_list[0] + last_trip = trip_list[-1] + pull_out = depot_to_trip_cost.get((depot_k, first_trip)) + pull_in = trip_to_depot_cost.get((last_trip, depot_k)) + if pull_out is None or pull_in is None: + lookup_failed = True + break + true_obj += float(pull_out) + float(pull_in) + for pos in range(len(trip_list) - 1): + ti = trip_list[pos] + tj = trip_list[pos + 1] + c_ij = arc_cost.get((ti, tj)) + if c_ij is None: + lookup_failed = True + break + true_obj += float(c_ij) + if lookup_failed: + break + + if not lookup_failed: + abs_diff = abs(reported_obj - true_obj) + # Costs are integer-valued (floor of mixed travel/idle terms), + # so a 0.5 absolute tolerance catches any integer-magnitude + # mismatch while staying robust to float-from-int round-trips. + obj_tol = max(0.5, 1e-6 * abs(true_obj)) + if abs_diff > obj_tol: + lhs = float(reported_obj) + rhs = float(true_obj) + violation_amount = abs_diff + normalizer = max(abs(rhs), eps) + violated_constraint_set.add(6) + violations.append( + f"Constraint (6): Objective consistency violated: " + f"reported objective_value={reported_obj} differs from " + f"recomputed total arc cost={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + feasible = len(violated_constraint_set) == 0 + violated_constraints = sorted(violated_constraint_set) + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MDVSP (Ribeiro & Soumis 1994)" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance" + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution" + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result" + ) + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print("Solution is INFEASIBLE.") + 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/ribeiro1994/gurobi_code.py b/tasks/ribeiro1994/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..50d38976d07389ad604c8685dbe0e6cbb94880b6 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_code.py @@ -0,0 +1,245 @@ +""" +Gurobi implementation of the Multiple-Depot Vehicle Scheduling Problem (MDVSP) +using the integer multicommodity flow formulation from: + +Ribeiro & Soumis (1994), "A Column Generation Approach to the Multiple-Depot +Vehicle Scheduling Problem", Operations Research 42(1):41-52. + +Formulation (Problem MDVSP): + Minimize sum_{k=1}^{m} sum_{(i,j) in A^k} c_{ij} * x^k_{ij} + s.t. + (1) sum_{k=1}^{m} sum_{i in V^k} x^k_{ij} = 1 for all j in N + (2) sum_{i in V^k} x^k_{ij} - sum_{i in V^k} x^k_{ji} = 0 + for all k in K, j in V^k + (3) sum_{j in N} x^k_{n+k,j} <= r_k for all k in K + x^k_{ij} >= 0, integer for all k, (i,j) in A^k +""" + +import json +import argparse +import math +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def solve_mdvsp(data, time_limit): + n_trips = data["parameters"]["n_trips"] + m_depots = data["parameters"]["m_depots"] + trips = data["trips"] + depots = data["depots"] + relief_points = data["relief_points"] + vehicle_capacities = data["vehicle_capacities"] + + # Build lookup for compatible arcs: (from_trip, to_trip) -> cost + compatible_arc_costs = {} + for arc in data["compatible_arcs"]: + i = arc["from_trip"] + j = arc["to_trip"] + compatible_arc_costs[(i, j)] = arc["cost"] + + # Build lookup for depot-to-trip costs: (depot_1indexed, trip) -> cost + depot_to_trip_cost = {} + for entry in data["depot_to_trip_costs"]: + depot_to_trip_cost[(entry["depot"], entry["trip"])] = entry["cost"] + + # Build lookup for trip-to-depot costs: (trip, depot_1indexed) -> cost + trip_to_depot_cost = {} + for entry in data["trip_to_depot_costs"]: + trip_to_depot_cost[(entry["trip"], entry["depot"])] = entry["cost"] + + # Create model + model = gp.Model("MDVSP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x[k, i, j] = flow of type k through arc (i, j) + # Nodes: trips are 1..n, depot k is represented as node (n+k) + # k is 1-indexed (1..m), trips are 1-indexed (1..n) + + x = {} + + for k in range(1, m_depots + 1): + depot_node = n_trips + k + + # Depot-to-trip arcs + for j in range(1, n_trips + 1): + cost = depot_to_trip_cost[(k, j)] + x[k, depot_node, j] = model.addVar( + vtype=GRB.INTEGER, lb=0, obj=cost, + name=f"x_{k}_{depot_node}_{j}" + ) + + # Trip-to-depot arcs + for j in range(1, n_trips + 1): + cost = trip_to_depot_cost[(j, k)] + x[k, j, depot_node] = model.addVar( + vtype=GRB.INTEGER, lb=0, obj=cost, + name=f"x_{k}_{j}_{depot_node}" + ) + + # Trip-to-trip arcs (only compatible pairs) + for (i, j), cost in compatible_arc_costs.items(): + x[k, i, j] = model.addVar( + vtype=GRB.INTEGER, lb=0, obj=cost, + name=f"x_{k}_{i}_{j}" + ) + + model.update() + + # Constraint (1): Each trip j is covered exactly once + for j in range(1, n_trips + 1): + expr = gp.LinExpr() + for k in range(1, m_depots + 1): + depot_node = n_trips + k + # Arcs entering trip j: from depot k, or from other trips + if (k, depot_node, j) in x: + expr += x[k, depot_node, j] + for i in range(1, n_trips + 1): + if (k, i, j) in x: + expr += x[k, i, j] + model.addConstr(expr == 1, name=f"cover_{j}") + + # Constraint (2): Flow conservation for each depot k and each node j in V^k + for k in range(1, m_depots + 1): + depot_node = n_trips + k + + # Flow conservation at each trip node j + for j in range(1, n_trips + 1): + inflow = gp.LinExpr() + outflow = gp.LinExpr() + + # Inflow to j: from depot_node or from other trips + if (k, depot_node, j) in x: + inflow += x[k, depot_node, j] + for i in range(1, n_trips + 1): + if (k, i, j) in x: + inflow += x[k, i, j] + + # Outflow from j: to depot_node or to other trips + if (k, j, depot_node) in x: + outflow += x[k, j, depot_node] + for i in range(1, n_trips + 1): + if (k, j, i) in x: + outflow += x[k, j, i] + + model.addConstr(inflow - outflow == 0, + name=f"flow_{k}_{j}") + + # Flow conservation at depot node: + # The paper notes that x_{n+k,n+k} represents idle vehicles, + # and equations (9)/(10) follow from (2). + # We enforce: outflow from depot = inflow to depot + depot_outflow = gp.LinExpr() + depot_inflow = gp.LinExpr() + for j in range(1, n_trips + 1): + if (k, depot_node, j) in x: + depot_outflow += x[k, depot_node, j] + if (k, j, depot_node) in x: + depot_inflow += x[k, j, depot_node] + model.addConstr(depot_outflow - depot_inflow == 0, + name=f"flow_depot_{k}") + + # Constraint (3): Depot capacity + for k in range(1, m_depots + 1): + depot_node = n_trips + k + expr = gp.LinExpr() + for j in range(1, n_trips + 1): + if (k, depot_node, j) in x: + expr += x[k, depot_node, j] + model.addConstr(expr <= vehicle_capacities[k - 1], + name=f"capacity_{k}") + + model.optimize() + + # Extract solution + result = {} + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = model.Status + result["mip_gap"] = model.MIPGap if model.Status != GRB.OPTIMAL else 0.0 + + # Extract vehicle routes + routes = [] + for k in range(1, m_depots + 1): + depot_node = n_trips + k + # Find trips that start from this depot + for j in range(1, n_trips + 1): + if (k, depot_node, j) in x and x[k, depot_node, j].X > 0.5: + # Trace the route from depot through trips + route = {"depot": k, "trips": [j]} + current = j + while True: + next_trip = None + # Check trip-to-trip arcs + for jj in range(1, n_trips + 1): + if (k, current, jj) in x and x[k, current, jj].X > 0.5: + next_trip = jj + break + if next_trip is None: + break + route["trips"].append(next_trip) + current = next_trip + routes.append(route) + result["routes"] = routes + result["num_vehicles"] = len(routes) + else: + result["objective_value"] = None + result["status"] = model.Status + result["routes"] = [] + result["num_vehicles"] = 0 + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for MDVSP (Ribeiro & Soumis 1994)" + ) + 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 output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + result = solve_mdvsp(data, args.time_limit) + + with open(args.solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Number of vehicles: {result['num_vehicles']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/ribeiro1994/gurobi_feasi_result/large_feasi_result_1.json b/tasks/ribeiro1994/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ribeiro1994/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/ribeiro1994/gurobi_feasi_result/large_feasi_result_2.json b/tasks/ribeiro1994/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ribeiro1994/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/ribeiro1994/gurobi_feasi_result/large_feasi_result_3.json b/tasks/ribeiro1994/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ribeiro1994/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/ribeiro1994/gurobi_feasi_result/large_feasi_result_4.json b/tasks/ribeiro1994/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ribeiro1994/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/ribeiro1994/gurobi_feasi_result/large_feasi_result_5.json b/tasks/ribeiro1994/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ribeiro1994/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/ribeiro1994/gurobi_feasi_result/tiny_feasi_result.json b/tasks/ribeiro1994/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ribeiro1994/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/ribeiro1994/gurobi_solution/large_solution_1.json b/tasks/ribeiro1994/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..136d95bc931d9eda327697f82e540fa49fd705b6 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14245d084890dab22b2a159846243213df6494f3cd513f53d44ce4c467cdf3d4 +size 13186 diff --git a/tasks/ribeiro1994/gurobi_solution/large_solution_2.json b/tasks/ribeiro1994/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6b66f72cf6d9e48b76916a58a4a132011cb331c7 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69e117398d32197c8d506cdec4cdf0326d3e97ed4dbaacf6e9c73f13fe2d3ccc +size 12800 diff --git a/tasks/ribeiro1994/gurobi_solution/large_solution_3.json b/tasks/ribeiro1994/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..67985974ce7108d5a70728cf0d6efcbf0f0def3f --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35b721fd8a0f3f39d5f95b4a0661220058ce91fa982b0e7f10bae01f2a6130a3 +size 12471 diff --git a/tasks/ribeiro1994/gurobi_solution/large_solution_4.json b/tasks/ribeiro1994/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..970060fd01af97f266dcf26ad43c549d0a45f835 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acaabb2db650a9f7848c1c84eef88654d62ede87958a64513404a445c939f48d +size 13077 diff --git a/tasks/ribeiro1994/gurobi_solution/large_solution_5.json b/tasks/ribeiro1994/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..86d64c505e6e6e3e4b13f2112caa5c1559bc91e3 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45659fc34abc73d40e663e17ef2a98ee3d68a34f097c293b2ab183b4eea88f2d +size 12307 diff --git a/tasks/ribeiro1994/gurobi_solution/tiny_solution.json b/tasks/ribeiro1994/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..8382035dfb9fcbcd98043073d0e200ad968735a1 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d4cb803296b2d5e9c45c0de9733e48283a218fd2cde0d69082da09ebc94d4d2 +size 1027 diff --git a/tasks/ribeiro1994/gurobi_solution_log/large_log_1.jsonl b/tasks/ribeiro1994/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8a059ff3286078772291c80663e2530b10ddced6 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2306ffd23db567c42e50796d41f446d1941d8b34181a1b3a8d8131d361306873 +size 140 diff --git a/tasks/ribeiro1994/gurobi_solution_log/large_log_2.jsonl b/tasks/ribeiro1994/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f0755f742ac9dc698b1cb4d6f5260d211200329c --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39724857d45b085bf4ed716f6e8dc456b77197dd91ca21a83614dda121cad53f +size 281 diff --git a/tasks/ribeiro1994/gurobi_solution_log/large_log_3.jsonl b/tasks/ribeiro1994/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..231c2b6868651433429ed2b0ca8e7ea7a70f3d5e --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:91bebfe0151f2bb4622042c0fd72d35486eca5ca2f49dc02e58736968975fe7e +size 141 diff --git a/tasks/ribeiro1994/gurobi_solution_log/large_log_4.jsonl b/tasks/ribeiro1994/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..157f9e63eb7af79d735a3d139a9d9fe7a5c90cd0 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3ab27c2a59e69634e747c4ce63989bd3cba3e71f725c2dc04ba82512ee5f560 +size 424 diff --git a/tasks/ribeiro1994/gurobi_solution_log/large_log_5.jsonl b/tasks/ribeiro1994/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..85636f7c50ab3f026dc60aef8f6e19e31f469b33 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93413d72d3a68ec7bb412c0f41aac1904886ff9a43ee78dca97296c07d7ca6b1 +size 479 diff --git a/tasks/ribeiro1994/gurobi_solution_log/tiny_log.jsonl b/tasks/ribeiro1994/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b3e668f78af76b98b4a28513421309bbcce08209 --- /dev/null +++ b/tasks/ribeiro1994/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e6bd421b8c141326d1b3e72acf8be4aee88a13279378d381f9c69f627c4c53f +size 45 diff --git a/tasks/ribeiro1994/instance/large_instance_1.json b/tasks/ribeiro1994/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..2d3772c3d28cb5dcbb7857d657e4bbf70727a49c --- /dev/null +++ b/tasks/ribeiro1994/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed0200da2d33f2087f6f5cc36f321c6e85ae451328f77f752c0e687335252188 +size 7154792 diff --git a/tasks/ribeiro1994/instance/large_instance_2.json b/tasks/ribeiro1994/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..40b51266fce9ce34a6638845c6de774632f5d533 --- /dev/null +++ b/tasks/ribeiro1994/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bd02ce4bcbcc92932ef6790f7563ea4061fb201bbd1c78750496e3d25cce971 +size 7303286 diff --git a/tasks/ribeiro1994/instance/large_instance_3.json b/tasks/ribeiro1994/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c71f5894980b04aa89152924f7b0ad1e91ab5b7f --- /dev/null +++ b/tasks/ribeiro1994/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45ebd468fb06ef9ab0cdbd83058efa00c930e6f47c9fe3fa67efe5475d0f8944 +size 7320223 diff --git a/tasks/ribeiro1994/instance/large_instance_4.json b/tasks/ribeiro1994/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..35e1d5d4d842ddb5aa8dc80668f4a4b318893ca3 --- /dev/null +++ b/tasks/ribeiro1994/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33b7758d7410d82f9acd8dcea1bfe80488b8710b0f422b997094f5dd4dcce7f1 +size 7377598 diff --git a/tasks/ribeiro1994/instance/large_instance_5.json b/tasks/ribeiro1994/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ad9269d7057cdfc8bcfb0fdafb9d2b6bc9d15e4b --- /dev/null +++ b/tasks/ribeiro1994/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59157c37995e5f41a247f7ec67d18b5cc77553a5e7f3109ae8a0818ab632e6de +size 7606304 diff --git a/tasks/ribeiro1994/instance/tiny_instance.json b/tasks/ribeiro1994/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..3b77dfe88ce95db07c5f3a2a24fb27dae191b3f6 --- /dev/null +++ b/tasks/ribeiro1994/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:001549fba888cfeeda74a041367ce3ec8826100eebe2f8a4c22c5ed5e6e16c66 +size 52907 diff --git a/tasks/ribeiro1994/instance_schema.json b/tasks/ribeiro1994/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..0941ce479e8335f8b80e6e5f2197c556cd17e9a1 --- /dev/null +++ b/tasks/ribeiro1994/instance_schema.json @@ -0,0 +1,53 @@ +{ + "parameters": { + "n_trips": " Total number of trips to be scheduled.", + "m_depots": " Number of depots from which vehicles are dispatched.", + "class_type": " Depot placement class governing how depot locations are chosen within the service area.", + "square_size": " Side length of the square service area in which relief points and depots are located.", + "n_relief_points": " Number of distinct relief points where drivers can start or end trips." + }, + "relief_points": " Two-dimensional coordinates of each relief point within the service area.", + "depots": " Two-dimensional coordinates of each depot within the service area.", + "vehicle_capacities": " Maximum number of vehicles available at each depot.", + "trips": [ + { + "trip_id": " Unique identifier for the trip (1-indexed).", + "trip_type": " Whether the trip is 'short' (non-circular) or 'long' (circular, returning to its starting relief point).", + "start_relief_point_index": " Index into the relief_points array for the location where this trip begins (0-indexed).", + "end_relief_point_index": " Index into the relief_points array for the location where this trip ends (0-indexed).", + "start_time": " Scheduled departure time of the trip in minutes from midnight.", + "end_time": " Scheduled arrival time of the trip in minutes from midnight.", + "travel_time_within_trip": " Euclidean distance between the starting and ending relief points of this trip." + } + ], + "compatible_arcs": [ + { + "from_trip": " Trip identifier of the preceding trip in a consecutive pairing (1-indexed).", + "to_trip": " Trip identifier of the following trip in a consecutive pairing (1-indexed).", + "travel_time": " Euclidean distance from the ending relief point of the preceding trip to the starting relief point of the following trip.", + "cost": " Cost of assigning these two trips consecutively to the same vehicle, combining travel and idle time." + } + ], + "depot_to_trip_costs": [ + { + "depot": " Depot identifier (1-indexed).", + "trip": " Trip identifier (1-indexed).", + "distance": " Euclidean distance from the depot to the trip's starting relief point.", + "cost": " Cost for a vehicle to depart from the depot to begin this trip, including a fixed vehicle usage charge." + } + ], + "trip_to_depot_costs": [ + { + "trip": " Trip identifier (1-indexed).", + "depot": " Depot identifier (1-indexed).", + "distance": " Euclidean distance from the trip's ending relief point to the depot.", + "cost": " Cost for a vehicle to return from this trip to the depot, including a fixed vehicle usage charge." + } + ], + "summary": { + "total_vehicles_available": " Total number of vehicles available across all depots.", + "n_compatible_arcs": " Number of feasible consecutive trip pairings where a vehicle can transition from one trip to another.", + "n_short_trips": " Number of short (non-circular) trips in the instance.", + "n_long_trips": " Number of long (circular) trips in the instance." + } +} diff --git a/tasks/ribeiro1994/mathematical_formulation.md b/tasks/ribeiro1994/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..8ab018200ed83d5c3c158b9bc1f88b2655b37ed4 --- /dev/null +++ b/tasks/ribeiro1994/mathematical_formulation.md @@ -0,0 +1,53 @@ +# Original Formulation: Multiple-Depot Vehicle Scheduling Problem (MDVSP) + +*Source: A Column Generation Approach to the Multiple-Depot Vehicle Scheduling Problem, Celso C. Ribeiro and François Soumis, 1994 (Operations Research 42(1):41–52).* + +The formulation below is the integer multicommodity flow program “Problem MDVSP” given first in Section 2 (“Model Formulation and Lower Bounds”) as the definition of the problem the paper studies; its notation ($x^k_{ij}$, $A^k$, $V^k$, $r_k$) is carried into every subsequent section. + +## Sets and Indices + +- $N = \{1,\dots,n\}$: set of trips, with index $j$ (or $i$). + +- $K = \{1,\dots,m\}$: set of depots, with index $k$. + +- For each depot $k \in K$ a graph $G^k = (V^k, A^k)$ is associated, where: + + - $V^k = N \cup \{n+k\}$: node set (trips of $N$ plus the depot node $n+k$). + + - $A^k = N \times N \;\cup\; \{n+k\} \times N \;\cup\; N \times \{n+k\}$: arc set (trip-to-trip arcs, depot-to-trip arcs, and trip-to-depot arcs). + +## Parameters + +- $n$: number of trips; $m$: number of depots. + +- Trip $T_j$ starts at time $s_j$ and ends at time $e_j$, $j = 1,\dots,n$. + +- $\tau_{ij}$: travel time from the ending point of trip $T_i$ to the starting point of trip $T_j$. + +- Compatibility: an ordered pair $(T_i, T_j)$ is *compatible* iff $e_i + \tau_{ij} \le s_j$; only compatible trip-to-trip arcs are included in $A^k$. + +- $r_k$: number of vehicles stationed at depot $D_k$, for each $k \in K$. + +- $c_{ij}$: finite cost incurred if a vehicle performs trip $T_j$ immediately after trip $T_i$. + +- $c_{n+k,j}$ (resp. $c_{j,n+k}$): finite cost incurred if a vehicle stationed at depot $D_k$ starts (resp. ends) with trip $T_j$. + +## Decision Variables + +- $x^k_{ij}$: flow of type $k$ (i.e., number of vehicles from depot $k$) through arc $(i,j) \in A^k$, for all $k \in K$ and all $(i,j) \in A^k$. Nonnegative and integer. + +## Objective + +$$\text{Minimize} \quad \sum_{k=1}^{m} \sum_{(i,j) \in A^k} c_{ij}\, x^k_{ij}$$ + +## Constraints + +$$\begin{align} +& \sum_{k=1}^{m} \sum_{i \in V^k} x^k_{ij} = 1 && \text{for all } j \in N \tag{1}\\[4pt] +& \sum_{i \in V^k} x^k_{ij} - \sum_{i \in V^k} x^k_{ji} = 0 && \text{for all } k \in K,\ \text{for all } j \in V^k \tag{2}\\[4pt] +& \sum_{j \in N} x^k_{n+k,j} \le r_k && \text{for all } k \in K \notag\\[4pt] +& x^k_{ij} \ge 0 && \text{for all } k \in K,\ \text{for all } (i,j) \in A^k \tag{3}\\[4pt] +& x^k_{ij}\ \text{integer} && \text{for all } k \in K,\ \text{for all } (i,j) \in A^k \notag +\end{align}$$ + +Constraint (1) ensures that each trip is performed exactly once. Constraints (2) are the flow-conservation constraints, and the capacity constraints $\sum_{j\in N} x^k_{n+k,j}\le r_k$ limit the number of vehicles leaving each depot. As remarked by the paper, $x^k_{ij}$ takes binary values for all $i,j \in N$ once (1) is imposed; the integrality requirement is stated on all arcs. diff --git a/tasks/ribeiro1994/problem_description.txt b/tasks/ribeiro1994/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..30f404113a81578f02e25eb7511574eec9f3beff --- /dev/null +++ b/tasks/ribeiro1994/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A public transit company operates a set of predefined trips using vehicles stationed at multiple depots. There are n trips and m depots. Each trip has a known start time, end time, starting relief point, and ending relief point, where relief points are locations in a two-dimensional plane identified by their coordinates. Each depot also has a known location given by its two-dimensional coordinates, and each depot has a specified number of vehicles available. + +The input data specifies, for each trip, a unique identifier, the indices of the starting and ending relief points among a set of known relief point locations, the trip's start time, and the trip's end time. For each depot, the input provides its location coordinates and the number of vehicles stationed there. The travel time between any two points is given by their Euclidean distance. Two trips are compatible in sequence when a vehicle can finish the first trip and travel from its ending relief point to the starting relief point of the second trip before that second trip's scheduled start time; specifically, the end time of the first trip plus the travel time between the two relevant relief points must not exceed the start time of the second trip. + +The company must assign every trip to exactly one vehicle from exactly one depot, such that each vehicle's schedule forms a complete duty: the vehicle departs its home depot, performs a sequence of pairwise compatible trips in chronological order, and returns to the same depot it departed from. The number of vehicles dispatched from any depot must not exceed the number of vehicles available at that depot. + +The cost of assigning two consecutive compatible trips to the same vehicle is computed as the floor of ten times the travel time between the ending relief point of the first trip and the starting relief point of the second trip, plus two times the idle time, where idle time is the difference between the start time of the second trip and the sum of the end time of the first trip and the intervening travel time. The cost for a vehicle to leave a depot and begin a trip equals the floor of ten times the Euclidean distance from the depot to the trip's starting relief point, plus a fixed charge of 5000. Similarly, the cost for a vehicle to return from a trip to a depot equals the floor of ten times the Euclidean distance from the trip's ending relief point to the depot, plus the same fixed charge of 5000. The large fixed charge on depot-departure and depot-return arcs ensures that the total number of vehicles used is minimized as the primary objective, with travel and idle time costs serving as a secondary tiebreaker. + +The goal is to determine an assignment of all trips to vehicle duties, specifying which depot each vehicle originates from, which sequence of trips each vehicle performs, and which depot it returns to, so that every trip is covered exactly once, no depot exceeds its vehicle capacity, every duty consists of sequentially compatible trips forming a round-trip from and back to the same depot, and the total cost across all duties is minimized. diff --git a/tasks/ribeiro1994/solution_logger.py b/tasks/ribeiro1994/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/ribeiro1994/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/ribeiro1994/solution_schema.json b/tasks/ribeiro1994/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b83a509b59b13dc145a0cdc8e78fc43bb8544ed0 --- /dev/null +++ b/tasks/ribeiro1994/solution_schema.json @@ -0,0 +1,10 @@ +{ + "objective_value": " Total operating cost across all vehicle duties, summing depot pull-out, trip-to-trip transition, and depot pull-in costs.", + "routes": [ + { + "depot": " Identifier of the depot from which this vehicle is pulled out and to which it returns at the end of the day (1-indexed).", + "trips": " Ordered sequence of trip identifiers performed consecutively by this vehicle between leaving and returning to the depot (1-indexed)." + } + ], + "num_vehicles": " Total number of vehicles dispatched across all depots to cover every trip." +} diff --git a/tasks/riley2025/feasibility_check.py b/tasks/riley2025/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..51ed352a019a73487177006d6c04f01e9a1b9502 --- /dev/null +++ b/tasks/riley2025/feasibility_check.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Solver-free complete-witness checker for Riley et al. (2025).""" + +import argparse +from collections import defaultdict +import json +import math +import re +import sys + +TOL = 1e-5 +VARIABLE = re.compile(r"^([A-Za-z_]+)\[([^]]+)\]$") + + +def rejection(kind, messages): + return {"feasible": False, "violated_constraints": [kind], + "violations": messages[:30], "violation_magnitudes": []} + + +def check_feasibility(data, solution): + if not isinstance(solution, dict): + return rejection("solution_schema", ["solution must be a JSON object"]) + missing = [key for key in ("objective_value", "y", "model_variables") if key not in solution] + if missing: + return rejection("solution_schema", ["missing required field(s): " + ", ".join(missing)]) + witness = solution["model_variables"] + if not isinstance(witness, dict) or not witness: + return rejection("solution_schema", ["model_variables must be a nonempty sparse object"]) + + I_n, J_n = int(data["num_demand_sites"]), int(data["num_production_sites"]) + S_n, T_n = int(data["num_scenarios"]), int(data["num_time_periods"]) + M_n, K_n = int(data["num_module_sizes"]), int(data["units_per_module_size"]) + shapes = { + "y": (M_n, K_n), "z": (M_n, S_n), "x": (I_n, J_n, T_n, S_n), + "q": (I_n, T_n, S_n), "v": (J_n, M_n, T_n, S_n), + "v_depot": (M_n, T_n, S_n), "w": (J_n, J_n, M_n, T_n, S_n), + "w_fd": (J_n, M_n, T_n, S_n), "w_td": (J_n, M_n, T_n, S_n), + } + values = {name: {} for name in shapes} + errors = [] + for name, raw in witness.items(): + match = VARIABLE.match(str(name)) + if not match or match.group(1) not in shapes: + errors.append(f"unknown model variable {name!r}") + continue + family = match.group(1) + try: + key = tuple(int(part) for part in match.group(2).split(",")) + value = float(raw) + except (TypeError, ValueError): + errors.append(f"invalid model variable {name!r}") + continue + if len(key) != len(shapes[family]) or any(i < 0 or i >= bound for i, bound in zip(key, shapes[family])): + errors.append(f"out-of-range model variable {name!r}") + continue + if family == "w" and key[0] == key[1]: + errors.append(f"invalid self-relocation variable {name!r}") + continue + if not math.isfinite(value) or value < -TOL: + errors.append(f"invalid value for {name}: {raw}") + continue + if family in ("x", "q"): + if value > 1 + TOL: + errors.append(f"upper bound violated for {name}: {value}") + elif abs(value - round(value)) > TOL or (family == "y" and value > 1 + TOL): + errors.append(f"integrality/domain violated for {name}: {value}") + values[family][key] = value + if errors: + return rejection("solution_schema", errors) + + get = lambda family, *key: values[family].get(tuple(key), 0.0) + public_y = solution["y"] + expected_keys = {f"y_{m}_{k}" for m in range(M_n) for k in range(K_n)} + if not isinstance(public_y, dict) or set(public_y) != expected_keys: + return rejection("solution_schema", ["y must cover every module-size/unit pair"]) + violations = [] + y = {} + for m in range(M_n): + for k in range(K_n): + raw = float(public_y[f"y_{m}_{k}"]) + if abs(raw - round(raw)) > TOL or round(raw) not in (0, 1): + violations.append(f"public y_{m}_{k} must be binary") + y[m, k] = round(raw) + if abs(get("y", m, k) - raw) > TOL: + violations.append(f"public y_{m}_{k} disagrees with complete witness") + if k and y[m, k] > y[m, k - 1]: + violations.append(f"symmetry constraint violated at y[{m},{k}]") + + for m in range(M_n): + count = sum(y[m, k] for k in range(K_n)) + for s in range(S_n): + if abs(get("z", m, s) - count) > TOL: + violations.append(f"z definition violated at ({m},{s})") + + demand_sum = defaultdict(float) + production = defaultdict(float) + objective = 0.0 + scenarios = data["scenarios"] + probabilities = [float(scenario["probability"]) for scenario in scenarios] + demand = [scenario["demands"] for scenario in scenarios] + for (i, j, t, s), value in values["x"].items(): + demand_sum[i, t, s] += value + amount = float(demand[s][i][t]) * value + production[j, t, s] += amount + objective += probabilities[s] * float(data["production_costs"][i][j]) * amount + for (i, t, s), value in values["q"].items(): + demand_sum[i, t, s] += value + objective += probabilities[s] * float(data["penalty_costs"][i][t]) * float(demand[s][i][t]) * value + for i in range(I_n): + for t in range(T_n): + for s in range(S_n): + if abs(demand_sum[i, t, s] - 1.0) > TOL: + violations.append(f"demand balance violated at ({i},{t},{s})") + if len(violations) >= 30: + return rejection("constraints", violations) + + depot_net, site_net = defaultdict(float), defaultdict(float) + for (j, m, t, s), value in values["w_fd"].items(): + depot_net[m, t, s] -= value + site_net[j, m, t, s] += value + for (j, m, t, s), value in values["w_td"].items(): + depot_net[m, t, s] += value + site_net[j, m, t, s] -= value + relocation = data["relocation_costs"] + for (j, jp, m, t, s), value in values["w"].items(): + site_net[j, m, t, s] -= value + site_net[jp, m, t, s] += value + objective += probabilities[s] * float(relocation[j][jp][m]) * value + for m in range(M_n): + for s in range(S_n): + previous = get("z", m, s) + for t in range(T_n): + current = get("v_depot", m, t, s) + if abs(current - previous - depot_net[m, t, s]) > TOL: + violations.append(f"depot balance violated at ({m},{t},{s})") + previous = current + for j in range(J_n): + for m in range(M_n): + for s in range(S_n): + previous = 0.0 + for t in range(T_n): + current = get("v", j, m, t, s) + if abs(current - previous - site_net[j, m, t, s]) > TOL: + violations.append(f"site balance violated at ({j},{m},{t},{s})") + previous = current + + capacities = [float(entry["capacity"]) for entry in data["module_sizes"]] + for j in range(J_n): + for t in range(T_n): + for s in range(S_n): + used = production[j, t, s] + available = sum(get("v", j, m, t, s) * capacities[m] for m in range(M_n)) + tolerance = TOL + 1e-7 * max(1.0, abs(used), abs(available)) + if used > available + tolerance: + violations.append(f"module capacity violated at ({j},{t},{s})") + if used > float(data["u_max"]) + tolerance: + violations.append(f"global site capacity violated at ({j},{t},{s})") + + capital = {(int(x["module_size_id"]), int(x["unit_id"])): float(x["capital_cost"]) for x in data["module_units"]} + objective += sum(capital[m, k] * y[m, k] for m in range(M_n) for k in range(K_n)) + reported = solution["objective_value"] + if isinstance(reported, bool) or not isinstance(reported, (int, float)) or not math.isfinite(float(reported)): + violations.append("objective_value must be finite") + else: + difference = abs(float(reported) - objective) + tolerance = max(1e-3, 1e-6 * max(1.0, abs(objective))) + if difference > tolerance: + violations.append(f"objective mismatch: reported={reported}, recomputed={objective}, difference={difference}") + return {"feasible": not violations, "violated_constraints": [] if not violations else [12, 13, 14, 15, 16, 17, 18], + "violations": violations[:30], "violation_magnitudes": []} + + +def main(): + parser = argparse.ArgumentParser() + 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 handle: + instance = json.load(handle) + with open(args.solution_path) as handle: + solution = json.load(handle) + result = check_feasibility(instance, solution) + with open(args.result_path, "w") as handle: + json.dump(result, handle, indent=2) + + +if __name__ == "__main__": + try: + main() + except Exception as error: + path = None + for index, arg in enumerate(sys.argv): + if arg == "--result_path" and index + 1 < len(sys.argv): + path = sys.argv[index + 1] + elif arg.startswith("--result_path="): + path = arg.split("=", 1)[1] + if path is None: + raise + with open(path, "w") as handle: + json.dump(rejection("malformed_solution", [f"{type(error).__name__}: {error}"]), handle, indent=2) diff --git a/tasks/riley2025/gurobi_code.py b/tasks/riley2025/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..0086875c53529bd232e68ebbd35684e90b62e190 --- /dev/null +++ b/tasks/riley2025/gurobi_code.py @@ -0,0 +1,323 @@ +#!/usr/bin/env python3 +""" +Full-space deterministic equivalent (P) for the supply chain with +relocatable manufacturing facilities — solved directly with Gurobi. + +Reference: Riley, Daoutidis, Zhang (arXiv:2511.06340), Case Study 1. +Model equations (11)-(24) from the paper. + +Usage: + python gurobi_code.py --instance_path instance_1.json \ + --solution_path gurobi_solution_1.json \ + --time_limit 3600 +""" + +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 + + +# --------------------------------------------------------------------------- +# Data loading +# --------------------------------------------------------------------------- + +def load_instance(path): + with open(path) as f: + return json.load(f) + + +# --------------------------------------------------------------------------- +# Model builder & solver +# --------------------------------------------------------------------------- + +def build_and_solve(data, time_limit, fixed_y=None, output_flag=1): + I_n = data['num_demand_sites'] + J_n = data['num_production_sites'] + S_n = data['num_scenarios'] + T_n = data['num_time_periods'] + M_n = data['num_module_sizes'] + K_n = data['units_per_module_size'] # K_m (same for all m in this instance) + u_max = data['u_max'] + + scenarios = data['scenarios'] + p_s = [sc['probability'] for sc in scenarios] + # d[s][i][t] : demand at site i in period t under scenario s + d = [[[sc['demands'][i][t] for t in range(T_n)] + for i in range(I_n)] + for sc in scenarios] + + # u_m[m]: production capacity of a single unit of size m + u_m = [ms['capacity'] for ms in data['module_sizes']] + + # g[m][k]: capital cost for selecting unit k of size m + g = [[0.0] * K_n for _ in range(M_n)] + for mu in data['module_units']: + g[mu['module_size_id']][mu['unit_id']] = mu['capital_cost'] + + # c_prod[i][j]: unit production/transport cost — time-invariant in this instance + # (paper has c_{ijt}; instance provides one value per (i,j) used for all t) + c_prod = data['production_costs'] + + # h[j][jp][m]: relocation cost per unit of size m from production site j to jp + # (paper has h_{jj'mt}; instance provides one value per (j,jp,m) for all t) + # INFERRED ASSUMPTION: relocations between depot and production sites cost 0, + # since the instance only provides a J×J×M matrix (production sites only). + h = data['relocation_costs'] + + # pen[i][t]: penalty for unmet demand at site i in period t + pen = data['penalty_costs'] + + I = range(I_n) + J = range(J_n) + S = range(S_n) + T = range(T_n) + M = range(M_n) + K = range(K_n) + + model = gp.Model("supply_chain_full_space") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", output_flag) + if fixed_y is not None: + model.setParam("MIPGap", 1e-4) + model.setParam("MIPGapAbs", 1e-6) + + # ----------------------------------------------------------------------- + # First-stage binary variables + # y[m,k] ∈ {0,1}: select manufacturing unit k of size m [Constraint (19)] + # ----------------------------------------------------------------------- + y = model.addVars(M_n, K_n, vtype=GRB.BINARY, name="y") + if fixed_y is not None: + for m in range(M_n): + for k in range(K_n): + model.addConstr(y[m, k] == int(round(fixed_y[m][k]))) + + # ----------------------------------------------------------------------- + # Second-stage variables (per scenario) + # ----------------------------------------------------------------------- + # z[m,s] ∈ Z+: number of units of size m selected (auxiliary) [Constraint (22)] + z = model.addVars(M_n, S_n, vtype=GRB.INTEGER, lb=0, name="z") + + # x[i,j,t,s] ∈ [0,1]: fraction of demand at i served from j at t, s [Constraint (21)] + x = model.addVars(I_n, J_n, T_n, S_n, lb=0.0, ub=1.0, name="x") + + # q[i,t,s] ∈ [0,1]: fraction of unmet demand [Constraint (20)] + q = model.addVars(I_n, T_n, S_n, lb=0.0, ub=1.0, name="q") + + # v[j,m,t,s] ∈ Z+: units of size m at production site j at time t [Constraint (23)] + v = model.addVars(J_n, M_n, T_n, S_n, vtype=GRB.INTEGER, lb=0, name="v") + + # v_depot[m,t,s] ∈ Z+: units at depot at time t (tracked via constraint 15) + v_depot = model.addVars(M_n, T_n, S_n, vtype=GRB.INTEGER, lb=0, name="v_depot") + + # w[j,jp,m,t,s] ∈ Z+: relocations between production sites [Constraint (24)] + w = model.addVars( + [(j, jp, m, t, s) + for j in J for jp in J for m in M for t in T for s in S if j != jp], + vtype=GRB.INTEGER, lb=0, name="w" + ) + + # Depot ↔ production site movements (cost assumed 0 — NOT SPECIFIED IN PAPER) + # w_fd[j,m,t,s]: units from depot → production site j + # w_td[j,m,t,s]: units from production site j → depot + w_fd = model.addVars(J_n, M_n, T_n, S_n, vtype=GRB.INTEGER, lb=0, name="w_fd") + w_td = model.addVars(J_n, M_n, T_n, S_n, vtype=GRB.INTEGER, lb=0, name="w_td") + + # ----------------------------------------------------------------------- + # Objective (11): + # min Σ_s p_s [ Σ_j Σ_t ( Σ_i c_{ijt} d_{its} x_{ijts} + # + Σ_{j',m} h_{jj'mt} w_{jj'mts} ) + # + Σ_{i,t} p_{it} d_{its} q_{its} ] + # + Σ_m Σ_k g_{mk} y_{mk} + # ----------------------------------------------------------------------- + obj = gp.LinExpr() + + # Capital costs (first-stage) + for m in M: + for k in K: + obj += g[m][k] * y[m, k] + + # Scenario-weighted operating costs + for s in S: + ps = p_s[s] + for j in J: + for t in T: + for i in I: + obj += ps * c_prod[i][j] * d[s][i][t] * x[i, j, t, s] + for jp in J: + if j != jp: + for m in M: + obj += ps * h[j][jp][m] * w[j, jp, m, t, s] + for i in I: + for t in T: + obj += ps * pen[i][t] * d[s][i][t] * q[i, t, s] + + model.setObjective(obj, GRB.MINIMIZE) + + # ----------------------------------------------------------------------- + # Constraint (12): Symmetry breaking y_{mk} <= y_{m,k-1} for k >= 2 + # ----------------------------------------------------------------------- + for m in M: + for k in range(1, K_n): + model.addConstr(y[m, k] <= y[m, k - 1], name=f"sym_{m}_{k}") + + # ----------------------------------------------------------------------- + # Constraint (13): z_{ms} = Σ_k y_{mk} for all m, s + # ----------------------------------------------------------------------- + for m in M: + for s in S: + model.addConstr( + z[m, s] == gp.quicksum(y[m, k] for k in K), + name=f"z_def_{m}_{s}" + ) + + # ----------------------------------------------------------------------- + # Constraint (14): Σ_j x_{ijts} + q_{its} = 1 for all i, t, s + # ----------------------------------------------------------------------- + for i in I: + for t in T: + for s in S: + model.addConstr( + gp.quicksum(x[i, j, t, s] for j in J) + q[i, t, s] == 1, + name=f"demand_{i}_{t}_{s}" + ) + + # ----------------------------------------------------------------------- + # Constraint (15): Depot balance (recursive form) + # v_depot[m,0,s] = z[m,s] + Σ_j w_td - Σ_j w_fd + # v_depot[m,t,s] = v_depot[m,t-1,s] + Σ_j w_td - Σ_j w_fd for t > 0 + # ----------------------------------------------------------------------- + for m in M: + for s in S: + for t in T: + net = (gp.quicksum(w_td[j, m, t, s] for j in J) + - gp.quicksum(w_fd[j, m, t, s] for j in J)) + if t == 0: + model.addConstr( + v_depot[m, t, s] == z[m, s] + net, + name=f"depot_bal_{m}_{t}_{s}" + ) + else: + model.addConstr( + v_depot[m, t, s] == v_depot[m, t - 1, s] + net, + name=f"depot_bal_{m}_{t}_{s}" + ) + + # ----------------------------------------------------------------------- + # Constraint (16): Production site balance (recursive form) + # v[j,m,0,s] = in_flow - out_flow + # v[j,m,t,s] = v[j,m,t-1,s] + in_flow - out_flow for t > 0 + # ----------------------------------------------------------------------- + for j in J: + for m in M: + for s in S: + for t in T: + in_f = (w_fd[j, m, t, s] + + gp.quicksum(w[jp, j, m, t, s] for jp in J if jp != j)) + out_f = (w_td[j, m, t, s] + + gp.quicksum(w[j, jp, m, t, s] for jp in J if jp != j)) + if t == 0: + model.addConstr( + v[j, m, t, s] == in_f - out_f, + name=f"site_bal_{j}_{m}_{t}_{s}" + ) + else: + model.addConstr( + v[j, m, t, s] == v[j, m, t - 1, s] + in_f - out_f, + name=f"site_bal_{j}_{m}_{t}_{s}" + ) + + # ----------------------------------------------------------------------- + # Constraint (17): Production capacity per site + # Σ_i d_{its} x_{ijts} <= Σ_m v_{jmts} u_m + # ----------------------------------------------------------------------- + for j in J: + for t in T: + for s in S: + model.addConstr( + gp.quicksum(d[s][i][t] * x[i, j, t, s] for i in I) + <= gp.quicksum(v[j, m, t, s] * u_m[m] for m in M), + name=f"cap_{j}_{t}_{s}" + ) + + # ----------------------------------------------------------------------- + # Constraint (18): Global production capacity + # Σ_i d_{its} x_{ijts} <= u^max + # ----------------------------------------------------------------------- + for j in J: + for t in T: + for s in S: + model.addConstr( + gp.quicksum(d[s][i][t] * x[i, j, t, s] for i in I) <= u_max, + name=f"maxcap_{j}_{t}_{s}" + ) + + model.optimize() + return model, y, M_n, K_n + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Solve supply chain MILP (full-space) with Gurobi." + ) + parser.add_argument('--instance_path', required=True, + help="Path to instance JSON file.") + parser.add_argument('--solution_path', required=True, + help="Path for output solution JSON file.") + parser.add_argument('--time_limit', type=int, required=True, + help="Solver time limit in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + model, y, M_n, K_n = build_and_solve(data, args.time_limit) + + result = {} + if model.SolCount > 0: + result['objective_value'] = model.ObjVal + result['status'] = 'Optimal' if model.Status == GRB.OPTIMAL else 'Feasible' + result['optimality_gap'] = model.MIPGap + result['best_bound'] = model.ObjBound + result['y'] = { + f"y_{m}_{k}": round(y[m, k].X) + for m in range(M_n) + for k in range(K_n) + } + else: + result['objective_value'] = None + result['status'] = 'NoSolution' + result['optimality_gap'] = None + result['best_bound'] = model.ObjBound + + 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']}") + if result['objective_value'] is not None: + print(f"Objective value: {result['objective_value']:.4f}") + print(f"Optimality gap: {result['optimality_gap']:.4%}") + + +if __name__ == '__main__': + main() diff --git a/tasks/riley2025/gurobi_feasi_result/large_feasi_result_1.json b/tasks/riley2025/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/riley2025/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/riley2025/gurobi_feasi_result/large_feasi_result_2.json b/tasks/riley2025/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/riley2025/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/riley2025/gurobi_feasi_result/large_feasi_result_3.json b/tasks/riley2025/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/riley2025/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/riley2025/gurobi_feasi_result/large_feasi_result_4.json b/tasks/riley2025/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/riley2025/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/riley2025/gurobi_feasi_result/large_feasi_result_5.json b/tasks/riley2025/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/riley2025/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/riley2025/gurobi_feasi_result/tiny_feasi_result.json b/tasks/riley2025/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/riley2025/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/riley2025/gurobi_solution/large_solution_1.json b/tasks/riley2025/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..3c612e1bb35327b4f65349f4afb381e1f633ed1b --- /dev/null +++ b/tasks/riley2025/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6819cab2d713435c343ee144bd00bd9a003f87ed3287188cf354ed4755748316 +size 4351672 diff --git a/tasks/riley2025/gurobi_solution/large_solution_2.json b/tasks/riley2025/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..7ad1c1671b343302fe43dd070294ee0865c0c5c2 --- /dev/null +++ b/tasks/riley2025/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24b05399a72340f2c1d99a9f4d56da88460cc466697f9a504a9d8bccf1eb62e0 +size 4351655 diff --git a/tasks/riley2025/gurobi_solution/large_solution_3.json b/tasks/riley2025/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..2ce9562cc13c054788316bfde0ed7c4bcd848a17 --- /dev/null +++ b/tasks/riley2025/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26de0076cc80e89ce5025a7d169ccf1136a5b719927e7e5cdaede199d0f019a1 +size 4351672 diff --git a/tasks/riley2025/gurobi_solution/large_solution_4.json b/tasks/riley2025/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..fed626a7dbe0ce9e478902a0eaeaedacaf341ac7 --- /dev/null +++ b/tasks/riley2025/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0b89e6921346d3eb9b4b374d1baf1dc5e2241231745fe5e79590cae6a2f6629 +size 4351673 diff --git a/tasks/riley2025/gurobi_solution/large_solution_5.json b/tasks/riley2025/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..61dac4a220af540ac0cc852cd57a2bdd8efe16e2 --- /dev/null +++ b/tasks/riley2025/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:554b62ed039ce0dfe4fab014c73b89c3a8f1a78db0a367d7655a577eef3d2977 +size 4351671 diff --git a/tasks/riley2025/gurobi_solution/tiny_solution.json b/tasks/riley2025/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..7ef93675e504a18a56f8550201c033c07804e55f --- /dev/null +++ b/tasks/riley2025/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c969f73c652e17f888529e65cbe96869da3c763b2237207b4a46781958e0b38 +size 89553 diff --git a/tasks/riley2025/gurobi_solution_log/large_log_1.jsonl b/tasks/riley2025/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1334803da71db9d1e03a953fac4f30b94438ef02 --- /dev/null +++ b/tasks/riley2025/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0df85c69b01a02263db398528c889d9e7fa91e0e5feea0ff076c338edb2c5a62 +size 55 diff --git a/tasks/riley2025/gurobi_solution_log/large_log_2.jsonl b/tasks/riley2025/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3c0346329a21992ccc954f77d06c5ad1aa9a7ba1 --- /dev/null +++ b/tasks/riley2025/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e036687562150e7b2ec0c03e18e1bd418dce33712a3c8152f8917eb69643531 +size 55 diff --git a/tasks/riley2025/gurobi_solution_log/large_log_3.jsonl b/tasks/riley2025/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c8edab88fccc55e03338047677084ca1be8994d8 --- /dev/null +++ b/tasks/riley2025/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49e376f5b6b5e769e9f9cbec49f60a28a4dd0daec68ce4d0a9efa947957ff112 +size 56 diff --git a/tasks/riley2025/gurobi_solution_log/large_log_4.jsonl b/tasks/riley2025/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6c24e2fd3455d7b94d9ace055b841175035ecf6a --- /dev/null +++ b/tasks/riley2025/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:418f1078e4cd18f3b4988a508b73c9e422cfb0cb15f1db796284b9d62ea52c97 +size 56 diff --git a/tasks/riley2025/gurobi_solution_log/large_log_5.jsonl b/tasks/riley2025/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b26394629aaaece73f47184dcc1c8cc0be2746f --- /dev/null +++ b/tasks/riley2025/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c52fdf5a4f274327410ec6899b1459f44467640204707ed747bcc443a164db67 +size 57 diff --git a/tasks/riley2025/gurobi_solution_log/tiny_log.jsonl b/tasks/riley2025/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..83d2b357a287e3866368d07d352de92083de91ac --- /dev/null +++ b/tasks/riley2025/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bf5ca48e69a4daf4e0afec9abd047467afd9ec5ea23dffc8534b698f6997994 +size 54 diff --git a/tasks/riley2025/instance/large_instance_1.json b/tasks/riley2025/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..7711638d76af914e8d0d140737b55572d13ac59e --- /dev/null +++ b/tasks/riley2025/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf8ec41b9c12aab6c18f2a5a89774929eab9ceca66c4c6786b5d534d84af0df2 +size 6392800 diff --git a/tasks/riley2025/instance/large_instance_2.json b/tasks/riley2025/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..99afeebd50c39b1171ab7e08c0ca5f50ffa5af12 --- /dev/null +++ b/tasks/riley2025/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f87e52acbd5b50ddb0a323fbdc88e1dd638c4ead7a7bb2183664dcde70952bb +size 6403333 diff --git a/tasks/riley2025/instance/large_instance_3.json b/tasks/riley2025/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..5571721b8918add94ad46aa4110366feaa4cb7c1 --- /dev/null +++ b/tasks/riley2025/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a433be4c1bcc81cc9294ed6482b0824bdbb8c08621d62b80c3b18c55ec5c9b2 +size 6395262 diff --git a/tasks/riley2025/instance/large_instance_4.json b/tasks/riley2025/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..31385ca65b17d8a194a936e7878592f3a3cc2e97 --- /dev/null +++ b/tasks/riley2025/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:512b9cc9cbc02010b61549d5a5db98578a373918cb2ead387f5055a01d600bba +size 6392863 diff --git a/tasks/riley2025/instance/large_instance_5.json b/tasks/riley2025/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c82ba8a61511f935469c4e21c64df4029e66c7f9 --- /dev/null +++ b/tasks/riley2025/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d316b508c1270fd5bfe0073af0560ed169253dff66969edccda2b2127e703fb +size 6394465 diff --git a/tasks/riley2025/instance/tiny_instance.json b/tasks/riley2025/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..4a7ea30d9078c85271e324cabcaa207e7b7e39ee --- /dev/null +++ b/tasks/riley2025/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca0a52a4b86d463a9fa7539591e46e536e88ed2f773d782fd17952327181a72a +size 148936 diff --git a/tasks/riley2025/instance_schema.json b/tasks/riley2025/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a439af37f513a147cb51457caaaa9a11f42a69f4 --- /dev/null +++ b/tasks/riley2025/instance_schema.json @@ -0,0 +1,49 @@ +{ + "num_demand_sites": " Number of customer demand sites in the supply chain network.", + "num_production_sites": " Number of production sites where modular manufacturing units can be stationed.", + "num_scenarios": " Number of demand scenarios representing possible future realizations of customer demand.", + "num_time_periods": " Number of time periods in the planning horizon.", + "num_module_sizes": " Number of available manufacturing module sizes.", + "units_per_module_size": " Maximum number of individual manufacturing units that can be purchased for each module size.", + "u_max": " Global maximum total production allowed at any single production site in any period.", + "scenario_probabilities": " Probability of each demand scenario occurring.", + "demand_sites": [ + { + "id": " Zero-based index identifying this demand site.", + "x": " Horizontal coordinate of the demand site location.", + "y": " Vertical coordinate of the demand site location." + } + ], + "production_sites": [ + { + "id": " Zero-based index identifying this production site.", + "x": " Horizontal coordinate of the production site location.", + "y": " Vertical coordinate of the production site location." + } + ], + "module_sizes": [ + { + "id": " Zero-based index identifying this module size category.", + "name": " Descriptive name of this module size category.", + "capacity": " Amount of demand a single unit of this module size can serve per time period when stationed at a production site.", + "capital_cost_per_unit": " One-time purchase cost for acquiring a single manufacturing unit of this module size." + } + ], + "module_units": [ + { + "module_size_id": " Module size category this unit belongs to.", + "unit_id": " Index of this individual unit within its module size category.", + "capital_cost": " One-time purchase cost for acquiring this specific manufacturing unit." + } + ], + "production_costs": " Per-unit cost of serving demand at each demand site from each production site.", + "relocation_costs": " Cost of relocating one manufacturing unit of each module size between each ordered pair of production sites.", + "penalty_costs": " Penalty cost per unit of demand left unserved at each demand site in each time period.", + "scenarios": [ + { + "id": " Zero-based index identifying this demand scenario.", + "probability": " Probability of this demand scenario occurring.", + "demands": " Customer demand quantity at each demand site in each time period under this scenario." + } + ] +} diff --git a/tasks/riley2025/mathematical_formulation.md b/tasks/riley2025/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..38a435a60ba9c4fa6f352af58bb5c6c0f112960f --- /dev/null +++ b/tasks/riley2025/mathematical_formulation.md @@ -0,0 +1,73 @@ +# Original Formulation (Case Study 1, Eqs. 11–24) + +## Sets and Indices + +- $\mathcal{I}$: set of demand sites, indexed by $i$. + +- $\mathcal{J}$: set of production sites, indexed by $j$ (also $j' \in \mathcal{J}$). + +- $\mathcal{M}$: set of module sizes, indexed by $m$. + +- $\mathcal{T}$: set of time periods, indexed by $t$. + +- $\mathcal{S}$: set of scenarios, indexed by $s$. + +- $\mathcal{K}_m$: set of investment levels for module size $m$, indexed by $k$. + +- $\mathcal{K}_1 \subseteq \mathcal{K}_m$: first investment level per size. + +## Parameters + +- $p_s$: probability of scenario $s$. + +- $c_{ijt}$: unit cost of satisfying demand at site $i$ from site $j$ in period $t$. + +- $d_{its}$: demand at site $i$ in period $t$ under scenario $s$. + +- $h_{jj'mt}$: unit cost of relocating a module of size $m$ from site $j$ to $j'$ in period $t$. + +- $p_{it}$: unit penalty for unmet demand at site $i$ in period $t$. + +- $g_{mk}$: capital cost for selecting manufacturing unit $k$ of size $m$. + +- $u_m$: production capacity of a single unit of size $m$. + +- $u^{\max}$: maximum total production at any site $j$ in any period. + +## Decision Variables + +First-stage (binary investment decisions): + +- $y_{mk} \in \{0,1\}$: 1 if manufacturing unit $k$ of size $m$ is selected. + +Second-stage (scenario-dependent operational decisions): + +- $z_{ms} \in \mathbb{Z}_+$: number of units of size $m$ (selected) in scenario $s$. + +- $x_{ijts} \in [0,1]$: fraction of demand at site $i$ satisfied from site $j$ in period $t$, scenario $s$. + +- $q_{its} \in [0,1]$: fraction of demand at site $i$ not delivered in period $t$, scenario $s$. + +- $v_{jmts} \in \mathbb{Z}_+$: number of units of size $m$ at site $j$ at time $t$, scenario $s$. + +- $w_{jj'mts} \in \mathbb{Z}_+$: number of units of size $m$ relocated from $j$ to $j'$ at time $t$, scenario $s$. + +## Objective and Constraints + +$$\begin{align} +\min \quad & \sum_{s \in \mathcal{S}} p_s \Bigg( \sum_{j \in \mathcal{J}} \sum_{t \in \mathcal{T}} \bigg( \sum_{i \in \mathcal{I}} c_{ijt} d_{its} x_{ijts} + \sum_{j' \in \mathcal{J}, m \in \mathcal{M}} h_{jj'mt} w_{jj'mts} \bigg) \notag \\ +& \qquad\qquad + \sum_{i \in \mathcal{I}, t \in \mathcal{T}} p_{it} q_{its} d_{its} \Bigg) + \sum_{m \in \mathcal{M}} \sum_{k \in \mathcal{K}_m} g_{mk} y_{mk} \tag{11} \\ +\text{s.t.}\quad & y_{mk} \leq y_{m,k-1} && \forall m \in \mathcal{M},\ k = 2,\ldots,|\mathcal{K}_m| \tag{12} \\ +& z_{ms} = \sum_{k \in \mathcal{K}_m} y_{mk} && \forall m \in \mathcal{M},\ s \in \mathcal{S} \tag{13} \\ +& \sum_{j \in \mathcal{J}} x_{ijts} + q_{its} = 1 && \forall i \in \mathcal{I},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{14} \\ +& v_{0mts} = z_{ms} + \sum_{t'=1}^{t} \bigg( \sum_{j' \in \mathcal{J}} w_{j'0mts'} - \sum_{j' \in \mathcal{J}} w_{0j'mts'} \bigg) && \forall m \in \mathcal{M},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{15} \\ +& v_{jmts} = \sum_{t'=1}^{t} \bigg( \sum_{j' \in \mathcal{J}} w_{j'jmts'} - \sum_{j' \in \mathcal{J}} w_{jj'mts'} \bigg) && \forall j \in \mathcal{J},\ m \in \mathcal{M},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{16} \\ +& \sum_{i \in \mathcal{I}} d_{its} x_{ijts} \leq \sum_{m \in \mathcal{M}} v_{jmts} u_m && \forall j \in \mathcal{J},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{17} \\ +& \sum_{i \in \mathcal{I}} d_{its} x_{ijts} \leq u^{\max} && \forall j \in \mathcal{J},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{18} \\ +& y_{mk} \in \{0, 1\} && \forall m \in \mathcal{M},\ k \in \mathcal{K}_m \tag{19} \\ +& 0 \leq q_{its} \leq 1 && \forall i \in \mathcal{I},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{20} \\ +& 0 \leq x_{ijts} \leq 1 && \forall i \in \mathcal{I},\ j \in \mathcal{J},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{21} \\ +& z_{jms} \in \mathbb{Z}_+ && \forall j \in \mathcal{J},\ m \in \mathcal{M},\ s \in \mathcal{S} \tag{22} \\ +& v_{jmts} \in \mathbb{Z}_+ && \forall j \in \mathcal{J},\ m \in \mathcal{M},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{23} \\ +& w_{jj'mts} \in \mathbb{Z}_+ && \forall j \in \mathcal{J},\ j' \in \mathcal{J},\ m \in \mathcal{M},\ t \in \mathcal{T},\ s \in \mathcal{S} \tag{24} +\end{align}$$ diff --git a/tasks/riley2025/problem_description.txt b/tasks/riley2025/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..c607bb6ba99782e53168dd2af2752a2115167aa2 --- /dev/null +++ b/tasks/riley2025/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A company operates a supply chain consisting of a set of demand sites (customers), a set of production sites, and a central depot. The company must decide which modular manufacturing units to purchase and, under each demand scenario, how to deploy and relocate those units across sites over a multi-period planning horizon to serve uncertain customer demands at minimum total cost. + +Manufacturing modules come in several sizes, and for each size up to a fixed number of individual units may be purchased. All units of the same size are physically identical and interchangeable. Each unit of a given size has a known capital cost and a known production capacity, representing the maximum amount of demand that a single unit of that size can help satisfy when stationed at a production site. The input data specifies the number of demand sites, the number of production sites, the number of module sizes, the maximum number of purchasable units per size, the production capacity per unit of each size, the capital cost per unit of each size, a global maximum production limit per site per period, and a set of demand scenarios each with an associated probability. For every demand site, production site, and time period combination, a unit cost of serving demand at that demand site from that production site in that period is given (applied per unit of demand served). For every ordered pair of production sites, every module size, and every time period, a per-unit relocation cost is given for moving a module of that size between those two sites in that period. For every demand site and every time period, a penalty cost rate for unmet demand is given, applied per unit of demand left unserved. Each scenario specifies a demand quantity for every demand site in every time period. + +The company must make two kinds of decisions. First, before uncertainty is resolved, the company decides for each module size how many units of that size to purchase (between zero and the size's maximum). Second, after a demand scenario is revealed, the company decides for each scenario how to operate: specifically, what fraction of each demand site's demand in each period is served from each production site, what fraction of each demand site's demand in each period goes unmet, how many units of each size are stationed at each production site and at the depot in each period, and how many units of each size are relocated between each ordered pair of sites (including moves between the depot and production sites) in each period. The fractions of demand served and unmet can take any value between zero and one, while the counts of units stationed and relocated are whole numbers. + +All purchased units of a given size are initially pooled at the depot and become available to be deployed across sites in every scenario. For every demand site, every period, and every scenario, the fractions of demand served from all production sites plus the fraction left unmet must sum to exactly one. The number of units of each size at the depot in each period equals the number of purchased units of that size plus the cumulative net inflow to the depot from all production sites across all periods up to and including the current one, where net inflow is defined as units arriving at the depot minus units departing the depot in each period. Similarly, the number of units of each size at each production site in each period equals the cumulative net inflow to that site from all other sites (including the depot) across all periods up to and including the current one. At each production site, in each period and scenario, the total demand-weighted production (the sum over all demand sites of the demand quantity times the served fraction) must not exceed the aggregate capacity of the units stationed there, computed as the sum over all sizes of the number of units of that size at the site times the capacity per unit of that size. Additionally, the total demand-weighted production at any single production site in any period and scenario must not exceed a global maximum production limit. + +The goal is to minimize total cost, which consists of two components. The first component is the total capital expenditure, computed as the sum over all module sizes of the capital cost per unit of that size times the number of purchased units of that size. The second component is the expected operating cost across all scenarios, weighted by scenario probabilities, which itself is the sum of three terms: the demand-weighted production and transportation cost (the sum over all production sites, time periods, and demand sites of the unit serving cost times the demand times the served fraction), the relocation cost (the sum over all ordered pairs of production sites, all module sizes, and all time periods of the per-unit relocation cost times the number of units relocated), and the unmet demand penalty (the sum over all demand sites and time periods of the penalty rate times the demand times the unmet fraction). diff --git a/tasks/riley2025/solution_logger.py b/tasks/riley2025/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/riley2025/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/riley2025/solution_schema.json b/tasks/riley2025/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..96432ee701f94849db4124d2f6191be789080211 --- /dev/null +++ b/tasks/riley2025/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total expected supply chain cost represented by the complete submitted witness.", + "model_variables": " Sparse complete first- and second-stage solution. Omitted model variables are exactly zero.", + "y": " Whether each candidate manufacturing unit of a given size is purchased and placed into service (1 = selected, 0 = not selected)." +} diff --git a/tasks/roberti2015/feasibility_check.py b/tasks/roberti2015/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5fed1d1de808e7e95a67b29aec509972090ff482 --- /dev/null +++ b/tasks/roberti2015/feasibility_check.py @@ -0,0 +1,478 @@ +""" +Feasibility checker for the Fixed Charge Transportation Problem (FCTP). + +Checks the candidate solution against Formulation F0 from Roberti, Bartolini, +Mingozzi (2014). + +Hard constraints (numbered per the paper): + (2) Supply: sum_j x_{ij} = a_i, for all i in S + (3) Demand: sum_i x_{ij} = b_j, for all j in T + (4) Linking: x_{ij} <= m_{ij} * y_{ij}, for all (i,j) in A + (5) Non-neg: x_{ij} >= 0, for all (i,j) in A + (6) Binary: y_{ij} in {0, 1}, for all (i,j) in A + (7) Objective consistency (Tier C): reported objective_value must equal + sum_{i,j} (c_{ij} * x_{ij} + f_{ij} * y_{ij}) within tolerance. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('arcs_used', 'flow', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, "r") as fh: + return json.load(fh) + + +def check_feasibility(instance, solution): + m = instance["num_sources"] + n = instance["num_sinks"] + a = instance["supply"] + b = instance["demand"] + cap = instance["capacity"] # m_{ij} = min(a_i, b_j) + + flow_raw = solution["flow"] + swapped = solution.get("swapped", False) + + # Domain pre-check: flow and arcs_used must be 2D arrays of the right + # shape (m x n in non-swapped orientation, n x m if swapped). Fail + # cleanly here rather than crashing with IndexError downstream. + expected_outer = n if swapped else m + expected_inner = m if swapped else n + _shape_violations = [] + if not isinstance(flow_raw, list) or len(flow_raw) != expected_outer: + _shape_violations.append( + f"flow has outer length {len(flow_raw) if isinstance(flow_raw, list) else 'non-list'}, " + f"expected {expected_outer}" + ) + else: + for i, row in enumerate(flow_raw): + if not isinstance(row, list) or len(row) != expected_inner: + _shape_violations.append( + f"flow row {i} length {len(row) if isinstance(row, list) else 'non-list'}, " + f"expected {expected_inner}" + ) + break + if "arcs_used" in solution: + au = solution["arcs_used"] + if not isinstance(au, list) or len(au) != expected_outer: + _shape_violations.append( + f"arcs_used has outer length {len(au) if isinstance(au, list) else 'non-list'}, " + f"expected {expected_outer}" + ) + else: + for i, row in enumerate(au): + if not isinstance(row, list) or len(row) != expected_inner: + _shape_violations.append( + f"arcs_used row {i} length {len(row) if isinstance(row, list) else 'non-list'}, " + f"expected {expected_inner}" + ) + break + if _shape_violations: + return { + "feasible": False, + "violated_constraints": [0], + "violations": [f"Domain: {m_msg}" for m_msg in _shape_violations], + "violation_magnitudes": [{ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + } for _ in _shape_violations], + } + + # If the solution was produced in swapped orientation, transpose the flow + # matrix back to the original (sources x sinks) layout. + if swapped: + # flow_raw is (n x m) when swapped; transpose to (m x n) + x = [[float(flow_raw[j][i]) for j in range(n)] for i in range(m)] + else: + x = [[float(flow_raw[i][j]) for j in range(n)] for i in range(m)] + + # Derive y_{ij}: 1 if x_{ij} > 0, else 0 + # If arcs_used is provided, use it; otherwise infer from flow. + if "arcs_used" in solution and not swapped: + y = solution["arcs_used"] + elif "arcs_used" in solution and swapped: + arcs_raw = solution["arcs_used"] + y = [[arcs_raw[j][i] for j in range(n)] for i in range(m)] + else: + y = [[1 if x[i][j] > TOL else 0 for j in range(n)] for i in range(m)] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------ + # Constraint (2): Supply — sum_j x_{ij} = a_i, for all i + # ------------------------------------------------------------------ + for i in range(m): + lhs = sum(x[i][j] for j in range(n)) + rhs = float(a[i]) + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(2) + violations.append( + f"Constraint (2): Supply violation at source {i}: " + f"sum_j x[{i}][j] = {lhs}, but a[{i}] = {rhs}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (3): Demand — sum_i x_{ij} = b_j, for all j + # ------------------------------------------------------------------ + for j in range(n): + lhs = sum(x[i][j] for i in range(m)) + rhs = float(b[j]) + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(3) + violations.append( + f"Constraint (3): Demand violation at sink {j}: " + f"sum_i x[i][{j}] = {lhs}, but b[{j}] = {rhs}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (4): Linking — x_{ij} <= m_{ij} * y_{ij}, for all (i,j) + # ------------------------------------------------------------------ + for i in range(m): + for j in range(n): + m_ij = float(cap[i][j]) + lhs = x[i][j] + rhs = m_ij * float(y[i][j]) + violation_amount = lhs - rhs # LHS - RHS for <= constraint + if violation_amount > TOL: + violated_constraints.add(4) + violations.append( + f"Constraint (4): Linking violation on arc ({i},{j}): " + f"x[{i}][{j}] = {lhs} > m[{i}][{j}]*y[{i}][{j}] = {rhs}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (5): Non-negativity — x_{ij} >= 0, for all (i,j) + # ------------------------------------------------------------------ + for i in range(m): + for j in range(n): + lhs = x[i][j] + rhs = 0.0 + violation_amount = rhs - lhs # RHS - LHS for >= constraint + if violation_amount > TOL: + violated_constraints.add(5) + violations.append( + f"Constraint (5): Non-negativity violation on arc ({i},{j}): " + f"x[{i}][{j}] = {lhs} < 0" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (6): Binary domain — y_{ij} in {0, 1}, for all (i,j) + # ------------------------------------------------------------------ + for i in range(m): + for j in range(n): + y_val = float(y[i][j]) + # Check if y_val is 0 or 1 within tolerance + dist_0 = abs(y_val - 0.0) + dist_1 = abs(y_val - 1.0) + violation_amount = min(dist_0, dist_1) + if violation_amount > TOL: + violated_constraints.add(6) + # For binary domain, treat as equality to nearest binary value + nearest = 0.0 if dist_0 <= dist_1 else 1.0 + lhs = y_val + rhs = nearest + violations.append( + f"Constraint (6): Binary violation on arc ({i},{j}): " + f"y[{i}][{j}] = {y_val} not in {{0, 1}}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint (7): Objective consistency (Tier C defense) — the reported + # objective_value must equal sum_{i,j} (c_{ij} x_{ij} + f_{ij} y_{ij}) + # within tolerance. All variables in this formula are present in the + # solution (flow -> x, arcs_used -> y) and the instance (variable_cost -> + # c, fixed_cost -> f), so this is a FULL recompute. + # ------------------------------------------------------------------ + c = instance.get("variable_cost") + f = instance.get("fixed_cost") + reported_obj = solution.get("objective_value") + if c is not None and f is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None and math.isfinite(reported): + true_obj = 0.0 + for i in range(m): + for j in range(n): + true_obj += float(c[i][j]) * x[i][j] + float(f[i][j]) * float(y[i][j]) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(7) + violations.append( + f"Constraint (7): Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_ij(c_ij*x_ij + f_ij*y_ij)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + normalizer = max(abs(true_obj), EPS) + violation_magnitudes.append({ + "constraint": 7, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + elif reported is not None and not math.isfinite(reported): + # Non-finite reported obj (inf / nan / sys.float_info.max-style) is + # never a valid FCTP cost — reject as obj-consistency violation. + violated_constraints.add(7) + violations.append( + f"Constraint (7): Objective consistency violated: reported " + f"objective_value={reported} is non-finite or out of range" + ) + violation_magnitudes.append({ + "constraint": 7, + "lhs": reported, + "rhs": 0.0, + "raw_excess": float("inf"), + "normalizer": 1.0, + "ratio": float("inf"), + }) + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for FCTP (Formulation F0)" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON instance file" + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON candidate solution file" + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON feasibility result" + ) + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as fh: + json.dump(result, fh, indent=2) + + if result["feasible"]: + print(f"FEASIBLE — no constraint violations found.") + 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/roberti2015/gurobi_code.py b/tasks/roberti2015/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4f0eb8468d11c21975cf1a916eee46ae425096 --- /dev/null +++ b/tasks/roberti2015/gurobi_code.py @@ -0,0 +1,162 @@ +""" +Gurobi implementation of the Fixed Charge Transportation Problem (FCTP) +using the standard MIP formulation F0 from: + +Roberti, Bartolini, Mingozzi (2014) +"The Fixed Charge Transportation Problem: An Exact Algorithm Based on a +New Integer Programming Formulation", Management Science. + +Formulation F0: + min sum_{i,j} (c_{ij} * x_{ij} + f_{ij} * y_{ij}) + s.t. sum_j x_{ij} = a_i, for all i in S (supply) + sum_i x_{ij} = b_j, for all j in T (demand) + x_{ij} <= m_{ij} * y_{ij}, for all (i,j) in A (linking) + x_{ij} >= 0, for all (i,j) in A + y_{ij} in {0,1}, for all (i,j) in A + +where m_{ij} = min(a_i, b_j). +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def solve_fctp(data, time_limit): + m = data["num_sources"] + n = data["num_sinks"] + a = data["supply"] + b = data["demand"] + f = data["fixed_cost"] + c = data["variable_cost"] + cap = data["capacity"] # m_{ij} = min(a_i, b_j), precomputed + + model = gp.Model("FCTP_F0") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + x = {} + y = {} + for i in range(m): + for j in range(n): + x[i, j] = model.addVar(lb=0.0, ub=cap[i][j], vtype=GRB.CONTINUOUS, + name=f"x_{i}_{j}") + y[i, j] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}_{j}") + + model.update() + + # Objective: min sum (c_ij * x_ij + f_ij * y_ij) + model.setObjective( + gp.quicksum(c[i][j] * x[i, j] + f[i][j] * y[i, j] + for i in range(m) for j in range(n)), + GRB.MINIMIZE + ) + + # Supply constraints: sum_j x_{ij} = a_i + for i in range(m): + model.addConstr( + gp.quicksum(x[i, j] for j in range(n)) == a[i], + name=f"supply_{i}" + ) + + # Demand constraints: sum_i x_{ij} = b_j + for j in range(n): + model.addConstr( + gp.quicksum(x[i, j] for i in range(m)) == b[j], + name=f"demand_{j}" + ) + + # Linking constraints: x_{ij} <= m_{ij} * y_{ij} + for i in range(m): + for j in range(n): + model.addConstr( + x[i, j] <= cap[i][j] * y[i, j], + name=f"link_{i}_{j}" + ) + + model.optimize() + + # Extract solution + solution = {} + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + solution["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + solution["mip_gap"] = model.MIPGap + + # Extract flow and arc usage + flow = [] + arcs_used = [] + for i in range(m): + flow_row = [] + arc_row = [] + for j in range(n): + flow_row.append(x[i, j].X) + arc_row.append(int(round(y[i, j].X))) + flow.append(flow_row) + arcs_used.append(arc_row) + + solution["flow"] = flow + solution["arcs_used"] = arcs_used + solution["num_sources"] = m + solution["num_sinks"] = n + else: + solution["objective_value"] = None + solution["status"] = "infeasible_or_no_solution" + + if model.Status == GRB.TIME_LIMIT and model.SolCount > 0: + solution["status"] = "time_limit_with_feasible" + + return solution + + +def main(): + parser = argparse.ArgumentParser(description="FCTP Solver using Gurobi (F0 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 to write the solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + solution = solve_fctp(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']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/roberti2015/gurobi_feasi_result/large_feasi_result_1.json b/tasks/roberti2015/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2015/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/roberti2015/gurobi_feasi_result/large_feasi_result_2.json b/tasks/roberti2015/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2015/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/roberti2015/gurobi_feasi_result/large_feasi_result_3.json b/tasks/roberti2015/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2015/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/roberti2015/gurobi_feasi_result/large_feasi_result_4.json b/tasks/roberti2015/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2015/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/roberti2015/gurobi_feasi_result/large_feasi_result_5.json b/tasks/roberti2015/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2015/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/roberti2015/gurobi_feasi_result/tiny_feasi_result.json b/tasks/roberti2015/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2015/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/roberti2015/gurobi_solution/large_solution_1.json b/tasks/roberti2015/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9cdd4a07a798d1bf6b4884b970806b33ac2bac46 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24f1112ec7a766ef79b07d9f8a6b65f3c7b921cf8ca5b07f52d4ff79b357e236 +size 99924 diff --git a/tasks/roberti2015/gurobi_solution/large_solution_2.json b/tasks/roberti2015/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e4577fbc82aa4774dcfe959bd9eecebd4a20688c --- /dev/null +++ b/tasks/roberti2015/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95db223ae7ac834ea49386ba5d0a4387d0cd3b411a1b806714bc4a84aa09cbf7 +size 99927 diff --git a/tasks/roberti2015/gurobi_solution/large_solution_3.json b/tasks/roberti2015/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..f295c4b2410d24f0e104a14f8dd2c70e19341da2 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c21c9082924725a582ba2f9309fd02eedadd7bbeebf4acc9122be23b13591be6 +size 99931 diff --git a/tasks/roberti2015/gurobi_solution/large_solution_4.json b/tasks/roberti2015/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f9d1977d027970d8d94e76cf3e42568bc9c4e733 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9193e4224e0367a436dd0f8acc3e4ec6cc3796537cd677400a0365fc1194d5d2 +size 99960 diff --git a/tasks/roberti2015/gurobi_solution/large_solution_5.json b/tasks/roberti2015/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e0663e21404a0c0518fe78a0d27e7a9299dc03c5 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61b6b8ffcaf3d6016062b949c29c44732f4e3ca65fbb3db0dbf56cd6751c28b9 +size 99970 diff --git a/tasks/roberti2015/gurobi_solution/tiny_solution.json b/tasks/roberti2015/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..d9c06f9582008eb38fa0b471794a2e2d68a8ad86 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c699b7902008f995e85555e8bf0441e6088b07fe8809833127dcdc801fc419ec +size 2412 diff --git a/tasks/roberti2015/gurobi_solution_log/large_log_1.jsonl b/tasks/roberti2015/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b61ef9a337d0bdba9f82b1c2160611a8bde9328c --- /dev/null +++ b/tasks/roberti2015/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c20c9b5a65a0a698fc1f08f4a482c46ee7c027f377beb7e62236052c5a99dc1b +size 2418 diff --git a/tasks/roberti2015/gurobi_solution_log/large_log_2.jsonl b/tasks/roberti2015/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a524e965027570f107ce4c2e20646b4b3b920e3f --- /dev/null +++ b/tasks/roberti2015/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fca26b719001401759fff8e765947b9e38b5b6c321fa9bdf009a48489c2ee94 +size 1960 diff --git a/tasks/roberti2015/gurobi_solution_log/large_log_3.jsonl b/tasks/roberti2015/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0b5d9ea4b90568cf57f5420365a1464656166934 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:461acd704633e0fdfb5bdcf609473c462b3ff48a7489c7587871586f406cec0f +size 2217 diff --git a/tasks/roberti2015/gurobi_solution_log/large_log_4.jsonl b/tasks/roberti2015/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..48be0e62b6ced66d113c0cb7a9b253ca53532001 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f231c6307ba6ab915762a378850d9089d5bad2166724f5dbca15b07d99a909db +size 1894 diff --git a/tasks/roberti2015/gurobi_solution_log/large_log_5.jsonl b/tasks/roberti2015/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..174ce629752a5bdea7749072a4e75b02e030de80 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5822dd34637530fdb03a712865f7de3bb7edee519a4e5b4f5224e8bd0d0d406 +size 1490 diff --git a/tasks/roberti2015/gurobi_solution_log/tiny_log.jsonl b/tasks/roberti2015/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7d18096b5bae9c92fa4f87fd18a78d352b6c94b1 --- /dev/null +++ b/tasks/roberti2015/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d7ac335f33dc5973b20925291a0a722a75ab214ef7a771099d4bcfa7dbddd0e +size 98 diff --git a/tasks/roberti2015/instance/large_instance_1.json b/tasks/roberti2015/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..16578468014ee5ad987ea2b133b0bb0f8bfe64cd --- /dev/null +++ b/tasks/roberti2015/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e4ed1a5ee7ae25df617b949d68550d5bb8d119d7b93f3a58b55fcc2dc09b319 +size 172880 diff --git a/tasks/roberti2015/instance/large_instance_2.json b/tasks/roberti2015/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b63898baa3c4f0337fca452122ced194eb4d977e --- /dev/null +++ b/tasks/roberti2015/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb71da0e01e60df70aeec5ff9ee19f818a12ddf15c4501b85797dae3afcbc33c +size 226843 diff --git a/tasks/roberti2015/instance/large_instance_3.json b/tasks/roberti2015/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..eda3ddd8e3756ddcb054576ed73c5bc702259fd7 --- /dev/null +++ b/tasks/roberti2015/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd15af43070b40a9ce431f82f0605334a64735681e4785194a109dc51f976ae4 +size 226777 diff --git a/tasks/roberti2015/instance/large_instance_4.json b/tasks/roberti2015/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..5fc69bd3ea5ab77fc7c5640dd95b84ac73211d37 --- /dev/null +++ b/tasks/roberti2015/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03263e8d298abe69991d7a15d9f4b48e3d032e5529f965a0d44830051979fea7 +size 159535 diff --git a/tasks/roberti2015/instance/large_instance_5.json b/tasks/roberti2015/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..510f7934d32f081e81d6aad1edd6c0290e2ab08a --- /dev/null +++ b/tasks/roberti2015/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd8f4547f0bd963e80ed9a8d079a7b3531400c94b48083855768d3b19963ec54 +size 230824 diff --git a/tasks/roberti2015/instance/tiny_instance.json b/tasks/roberti2015/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..537e99e8873f90364d749ac8c412206395fbb0f7 --- /dev/null +++ b/tasks/roberti2015/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f432708a3d9dcbc5e2ebc578cd48384d6876f0b05e8c30524fbfed911df05295 +size 4384 diff --git a/tasks/roberti2015/instance_schema.json b/tasks/roberti2015/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..109a54b8b7087d7a6d21e2103ea651dd5ab1b663 --- /dev/null +++ b/tasks/roberti2015/instance_schema.json @@ -0,0 +1,12 @@ +{ + "num_sources": " Number of sources in the logistics network.", + "num_sinks": " Number of sinks in the logistics network.", + "B": " Upper bound on individual supply and demand values.", + "delta": " Ratio controlling the proportion of per-unit transportation cost relative to fixed cost.", + "total_supply": " Total supply across all sources, which equals total demand across all sinks.", + "supply": " Quantity of goods available at each source that must be shipped out entirely.", + "demand": " Quantity of goods required at each sink that must be satisfied exactly.", + "fixed_cost": " Fixed cost charged for using the route from each source to each sink, incurred whenever any goods are shipped along that route.", + "variable_cost": " Per-unit transportation cost for shipping goods along the route from each source to each sink.", + "capacity": " Maximum quantity of goods that can be shipped along the route from each source to each sink." +} diff --git a/tasks/roberti2015/mathematical_formulation.md b/tasks/roberti2015/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..6d25272667ca937f05e790923d45f99b7835eb65 --- /dev/null +++ b/tasks/roberti2015/mathematical_formulation.md @@ -0,0 +1,53 @@ +# Original Formulation: Fixed Charge Transportation Problem (FCTP) + +*Source: The Fixed Charge Transportation Problem: An Exact Algorithm Based on a New Integer Programming Formulation, Roberto Roberti, Enrico Bartolini, Aristide Mingozzi, 2014 (Management Science).* + +The paper defines the FCTP it studies through the standard mixed integer programming formulation **(F0)**, written first in §1 with the variables $x_{ij}$ and $y_{ij}$ that state the problem. The exponential set-partitioning formulation (F1) introduced in §2 is the paper’s new reformulation and the basis of its branch-and-price algorithm; it is recorded under *Remarks* but is not the original problem definition. + +## Sets and Indices + +- $S = \{1, 2, \dots, m\}$: set of $m$ sources, indexed by $i$. + +- $T = \{1, 2, \dots, n\}$: set of $n$ sinks, indexed by $j$. + +- $A = \{(i,j) : i \in S,\, j \in T\}$: arc set of the complete bipartite graph $G = (S, T, A)$. + +## Parameters + +- $a_i$: integer supply available at source $i \in S$. + +- $b_j$: integer demand required at sink $j \in T$. + +- $c_{ij}$: unit (continuous) transportation cost on arc $(i,j) \in A$. + +- $f_{ij}$: fixed cost incurred for using arc $(i,j) \in A$. + +- $m_{ij} = \min(a_i, b_j)$, $(i,j) \in A$: arc capacity. + +Balance assumption (without loss of generality): $\sum_{i \in S} a_i = \sum_{j \in T} b_j$. + +## Decision Variables + +- $x_{ij} \ge 0$: continuous quantity of goods transported along arc $(i,j) \in A$. + +- $y_{ij} \in \{0,1\}$: equal to $1$ if and only if $x_{ij}$ is positive (i.e., arc $(i,j)$ is used). + +## Objective + +$$\begin{equation} +z_{F0} = \min \sum_{i \in S} \sum_{j \in T} + \bigl( c_{ij}\, x_{ij} + f_{ij}\, y_{ij} \bigr) +\tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{j \in T} x_{ij} &= a_i, & &\forall\, i \in S \tag{2}\\[4pt] +\sum_{i \in S} x_{ij} &= b_j, & &\forall\, j \in T \tag{3}\\[4pt] +x_{ij} &\le m_{ij}\, y_{ij}, & &\forall\, (i,j) \in A \tag{4}\\[4pt] +x_{ij} &\ge 0, & &\forall\, (i,j) \in A \tag{5}\\[4pt] +y_{ij} &\in \{0,1\}, & &\forall\, (i,j) \in A \tag{6} +\end{align}$$ + +Constraints (2) ship all of each source’s supply; constraints (3) meet each sink’s demand exactly; linking constraints (4) allow positive flow on an arc only when it is opened ($y_{ij}=1$) and bound it by $m_{ij}$; (5)–(6) give the variable domains. diff --git a/tasks/roberti2015/problem_description.txt b/tasks/roberti2015/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..26f41785888cbf8d6a864796b844496c1e68de10 --- /dev/null +++ b/tasks/roberti2015/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A logistics network consists of m sources and n sinks. Each source has a known positive integer supply of goods that must be shipped out entirely, and each sink has a known positive integer demand that must be satisfied exactly. The total supply across all sources equals the total demand across all sinks. Every source may ship goods to every sink, forming a complete bipartite shipping network of m times n possible routes. + +Two types of costs are associated with each route from a source to a sink. First, a per-unit transportation cost is incurred for every unit of goods shipped along that route. Second, a fixed cost is charged whenever any positive quantity of goods is shipped along that route, regardless of the quantity sent. The fixed cost represents charges such as toll fees, landing fees, setup costs, or road-building costs that are triggered by the mere use of a route. Each route also has a capacity equal to the smaller of the source's supply and the sink's demand, so that no route can carry more goods than the source has available or the sink requires. + +The planner must determine how many units of goods to ship along each route. Every unit of supply at each source must be dispatched to one or more sinks, and every sink must receive exactly the quantity it demands. A route may carry any quantity from zero up to its capacity, but if any goods are shipped along a route, the corresponding fixed cost is incurred in full. The goal is to minimize the total cost, which is the sum over all used routes of the per-unit transportation cost times the quantity shipped plus the fixed cost for opening that route. diff --git a/tasks/roberti2015/solution_logger.py b/tasks/roberti2015/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/roberti2015/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/roberti2015/solution_schema.json b/tasks/roberti2015/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d4e123f40cfcf0fa57329ade9567019c0f7d5733 --- /dev/null +++ b/tasks/roberti2015/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total cost of shipping, including both per-unit transportation costs and fixed route-opening costs across all used routes.", + "flow": " Quantity of goods shipped from each source to each sink.", + "arcs_used": " Whether each route from a source to a sink is used for shipping (1 = used, 0 = not used)." +} diff --git a/tasks/roberti2018/feasibility_check.py b/tasks/roberti2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..ffdea55b401ad264f706a33b7d412db3209445df --- /dev/null +++ b/tasks/roberti2018/feasibility_check.py @@ -0,0 +1,689 @@ +#!/usr/bin/env python3 +"""Feasibility checker for the 2E-CVRPGC problem. + +Checks constraints (2)-(23) from the mathematical formulation in math_model.txt, +plus constraint 24: objective-value consistency (recompute the obj from the +decision variables and reject if the reported value disagrees). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('first_echelon_routes', 'group_assignments', 'objective_value', 'second_echelon_routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('group_assignments',) +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(inst, sol): + """Run the full feasibility check and return a result dict.""" + tol = 1e-5 + eps = 1e-5 + + # ---- Instance data ---- + depot_id = inst['depot']['id'] + sat_ids = [s['id'] for s in inst['satellites']] + cust_ids = [c['id'] for c in inst['customers']] + sat_ids_set = set(sat_ids) + cust_ids_set = set(cust_ids) + + Q1 = inst['Q1'] + Q2 = inst['Q2'] + T1 = inst['T1'] + T2 = inst['T2'] + n_sat = len(sat_ids) + + demand = {c['id']: c['demand'] for c in inst['customers']} + sat_capacity = {s['id']: s['capacity'] for s in inst['satellites']} + sat_max_vehicles = {s['id']: s['max_vehicles'] for s in inst['satellites']} + sat_handling_cost = {s['id']: s['handling_cost'] for s in inst['satellites']} + + groups = {g['group_id']: g['customer_ids'] for g in inst['groups']} + cust_to_group = {c['id']: c['group'] for c in inst['customers']} + + V0_VS = [depot_id] + sat_ids + VS_VC = sat_ids + cust_ids + + # Node coordinate lookup (depot + satellites + customers) used by the obj + # recomputation to recover Euclidean travel costs c_{i,j}. + coords = {inst['depot']['id']: (inst['depot']['x'], inst['depot']['y'])} + for s in inst['satellites']: + coords[s['id']] = (s['x'], s['y']) + for c in inst['customers']: + coords[c['id']] = (c['x'], c['y']) + + def edge_cost(i, j): + xi, yi = coords[i] + xj, yj = coords[j] + return math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2) + + # ---- Reconstruct decision variables from solution ---- + + # First echelon: x[i,j,k] and w[s,k] + x = {} + w = {} + for s in sat_ids: + for k in range(T1): + w[s, k] = 0.0 + + for route_info in sol.get('first_echelon_routes', []): + k = route_info['vehicle'] + route = route_info['route'] + for idx in range(len(route) - 1): + x[route[idx], route[idx + 1], k] = 1 + for s_str, amount in route_info.get('deliveries', {}).items(): + w[int(s_str), k] = float(amount) + + # Second echelon: y[i,j] and f[i,j] + y = {} + f_var = {} + cust_satellite = {} + + for route_info in sol.get('second_echelon_routes', []): + sat = route_info['satellite'] + route = route_info['route'] + + for idx in range(len(route) - 1): + y[route[idx], route[idx + 1]] = 1 + + for node in route: + if node in cust_ids_set: + cust_satellite[node] = sat + + # Compute flow along route + route_custs = [n for n in route if n in cust_ids_set] + total_demand = sum(demand[c] for c in route_custs) + current_flow = total_demand + for idx in range(len(route) - 1): + i_node, j_node = route[idx], route[idx + 1] + if i_node in cust_ids_set: + current_flow -= demand[i_node] + f_var[i_node, j_node] = current_flow + + # z[i,s]: customer i assigned to satellite s + z = {} + for cid in cust_ids: + for s in sat_ids: + z[cid, s] = 1 if cust_satellite.get(cid) == s else 0 + + # v[h,s]: group h assigned to satellite s + # Derive v from z using the first member of each group, since constraint 15 + # requires z[i,s] = v[C_h,s] for all i in C_h. The solution's + # group_assignments field may be absent or stale, so we reconstruct v from + # the actual customer-satellite assignments (z) instead. + v = {} + for h, members in groups.items(): + representative = members[0] + for s in sat_ids: + v[h, s] = z.get((representative, s), 0) + + # u[s,k]: MTZ position variables (derived from route order) + u = {} + for s in sat_ids: + for k in range(T1): + u[s, k] = 0.0 + for route_info in sol.get('first_echelon_routes', []): + k = route_info['vehicle'] + route = route_info['route'] + pos = 0 + for node in route: + if node in sat_ids_set: + pos += 1 + u[node, k] = float(pos) + + # ---- Check constraints ---- + violations = [] + violation_magnitudes = [] + violated_set = set() + + # Domain check: every node id appearing in any first-echelon route must + # be in V0_VS (depot + satellites); every node id in any second-echelon + # route must be in VS_VC (satellites + customers); every group_id and + # customer_id in group_assignments must be valid. + valid_V0_VS = set(V0_VS) + valid_VS_VC = set(VS_VC) + for r_idx, route_info in enumerate(sol.get('first_echelon_routes', [])): + for node in route_info.get('route', []): + if node not in valid_V0_VS: + violated_set.add(0) + violations.append( + f"Domain: first_echelon_routes[{r_idx}] node {node!r} " + f"not depot/satellite" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + for s_str in route_info.get('deliveries', {}): + try: + s_int = int(s_str) + except (TypeError, ValueError): + s_int = None + if s_int not in sat_ids_set: + violated_set.add(0) + violations.append( + f"Domain: first_echelon_routes[{r_idx}] deliveries key " + f"{s_str!r} not a valid satellite id" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + for r_idx, route_info in enumerate(sol.get('second_echelon_routes', [])): + if route_info.get('satellite') not in sat_ids_set: + violated_set.add(0) + violations.append( + f"Domain: second_echelon_routes[{r_idx}] satellite " + f"{route_info.get('satellite')!r} not a valid satellite id" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + for node in route_info.get('route', []): + if node not in valid_VS_VC: + violated_set.add(0) + violations.append( + f"Domain: second_echelon_routes[{r_idx}] node {node!r} " + f"not satellite/customer" + ) + violation_magnitudes.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + if violated_set: + # Domain failure: skip downstream checks that index node ids + return { + "feasible": False, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + def add_violation(cnum, msg, lhs_val, rhs_val, viol_amount): + violated_set.add(cnum) + violations.append(msg) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": cnum, + "lhs": float(lhs_val), + "rhs": float(rhs_val), + "raw_excess": float(viol_amount), + "normalizer": float(normalizer), + "ratio": float(viol_amount / normalizer) + }) + + # ------ Constraint 2: Flow conservation first echelon ------ + for i in V0_VS: + for k in range(T1): + out_flow = sum(x.get((i, j, k), 0) for j in V0_VS if j != i) + in_flow = sum(x.get((j, i, k), 0) for j in V0_VS if j != i) + diff = abs(out_flow - in_flow) + if diff > tol: + add_violation(2, + f"Flow conservation violated at node {i}, vehicle {k}: out={out_flow}, in={in_flow}", + out_flow, in_flow, diff) + + # ------ Constraint 3: Each satellite visited at most once per vehicle ------ + for i in sat_ids: + for k in range(T1): + lhs = sum(x.get((i, j, k), 0) for j in V0_VS if j != i) + rhs_val = 1.0 + if lhs > rhs_val + tol: + add_violation(3, + f"Satellite {i} visited more than once by vehicle {k}: out-degree={lhs}", + lhs, rhs_val, lhs - rhs_val) + + # ------ Constraint 4: MTZ subtour elimination ------ + for k in range(T1): + for i in V0_VS: + for j in V0_VS: + if i == j: + continue + xval = x.get((i, j, k), 0) + if i == depot_id and j in sat_ids_set: + lhs = 1.0 + rhs_val = u.get((j, k), 0) + n_sat * (1 - xval) + if lhs > rhs_val + tol: + add_violation(4, + f"MTZ violated: depot->{j}, vehicle {k}: 1 > {rhs_val}", + lhs, rhs_val, lhs - rhs_val) + elif i in sat_ids_set and j in sat_ids_set: + lhs = u.get((i, k), 0) + 1 + rhs_val = u.get((j, k), 0) + n_sat * (1 - xval) + if lhs > rhs_val + tol: + add_violation(4, + f"MTZ violated: {i}->{j}, vehicle {k}: u[{i}]+1={lhs} > {rhs_val}", + lhs, rhs_val, lhs - rhs_val) + + # ------ Constraint 5: Delivery only if satellite is visited ------ + for s in sat_ids: + for k in range(T1): + visit = sum(x.get((s, j, k), 0) for j in V0_VS if j != s) + rhs_val = sat_capacity[s] * visit + lhs = w.get((s, k), 0) + if lhs > rhs_val + tol: + add_violation(5, + f"Delivery to satellite {s} by vehicle {k} without visit: w={lhs}, limit={rhs_val}", + lhs, rhs_val, lhs - rhs_val) + + # ------ Constraint 6: Vehicle capacity first echelon ------ + for k in range(T1): + lhs = sum(w.get((s, k), 0) for s in sat_ids) + rhs_val = float(Q1) + if lhs > rhs_val + tol: + add_violation(6, + f"First echelon vehicle {k} capacity exceeded: {lhs} > {rhs_val}", + lhs, rhs_val, lhs - rhs_val) + + # ------ Constraint 7: Satellite capacity ------ + for s in sat_ids: + lhs = sum(w.get((s, k), 0) for k in range(T1)) + rhs_val = float(sat_capacity[s]) + if lhs > rhs_val + tol: + add_violation(7, + f"Satellite {s} capacity exceeded: {lhs} > {rhs_val}", + lhs, rhs_val, lhs - rhs_val) + + # ------ Constraint 8: Each customer visited exactly once (second echelon) ------ + for i in cust_ids: + out_deg = sum(y.get((i, j), 0) for j in VS_VC + if i != j and not (i in sat_ids_set and j in sat_ids_set)) + in_deg = sum(y.get((j, i), 0) for j in VS_VC + if i != j and not (j in sat_ids_set and i in sat_ids_set)) + if abs(out_deg - 1) > tol: + add_violation(8, + f"Customer {i} out-degree={out_deg}, expected 1", + float(out_deg), 1.0, abs(out_deg - 1)) + if abs(in_deg - 1) > tol: + add_violation(8, + f"Customer {i} in-degree={in_deg}, expected 1", + float(in_deg), 1.0, abs(in_deg - 1)) + + # ------ Constraint 9: Vehicle limit per satellite (second echelon) ------ + for s in sat_ids: + lhs = sum(y.get((s, j), 0) for j in cust_ids) + rhs_val = float(sat_max_vehicles[s]) + if lhs > rhs_val + tol: + add_violation(9, + f"Satellite {s} second-echelon vehicle limit exceeded: {lhs} > {rhs_val}", + lhs, rhs_val, lhs - rhs_val) + + # ------ Constraint 10: Total vehicle limit (second echelon) ------ + total_routes = sum(y.get((s, j), 0) for s in sat_ids for j in cust_ids) + rhs_val = float(T2) + if total_routes > rhs_val + tol: + add_violation(10, + f"Total second-echelon vehicles exceeded: {total_routes} > {rhs_val}", + float(total_routes), rhs_val, total_routes - rhs_val) + + # ------ Constraint 11: Flow conservation for demand ------ + for i in cust_ids: + flow_in = sum(f_var.get((j, i), 0) for j in VS_VC + if j != i and not (j in sat_ids_set and i in sat_ids_set)) + flow_out = sum(f_var.get((i, j), 0) for j in VS_VC + if j != i and not (i in sat_ids_set and j in sat_ids_set)) + lhs = flow_in + rhs_val = flow_out + demand[i] + diff = abs(lhs - rhs_val) + if diff > tol: + add_violation(11, + f"Flow conservation violated at customer {i}: flow_in={lhs}, flow_out+demand={rhs_val}", + lhs, rhs_val, diff) + + # ------ Constraint 12: Flow bounds (Gavish) ------ + for i in VS_VC: + for j in VS_VC: + if i == j or (i in sat_ids_set and j in sat_ids_set): + continue + yval = y.get((i, j), 0) + fval = f_var.get((i, j), 0.0) + d_i = demand.get(i, 0) + d_j = demand.get(j, 0) + + lb = d_j * yval + if fval < lb - tol: + add_violation(12, + f"Flow lower bound violated on arc ({i},{j}): f={fval} < d_j*y={lb}", + fval, lb, lb - fval) + + ub = (Q2 - d_i) * yval + if fval > ub + tol: + add_violation(12, + f"Flow upper bound violated on arc ({i},{j}): f={fval} > (Q2-d_i)*y={ub}", + fval, ub, fval - ub) + + # ------ Constraint 13: Satellite assignment propagation ------ + for i in VS_VC: + for j in VS_VC: + if i == j or (i in sat_ids_set and j in sat_ids_set): + continue + yval = y.get((i, j), 0) + if yval == 0: + continue + for s in sat_ids: + if i in cust_ids_set: + z_is = z.get((i, s), 0) + elif i == s: + z_is = 1 + else: + z_is = 0 + + if j not in cust_ids_set: + continue + z_js = z.get((j, s), 0) + + rhs_val = z_is + yval - 1 + if z_js < rhs_val - tol: + add_violation(13, + f"Assignment propagation violated: z[{j},{s}]={z_js} < z[{i},{s}]+y[{i},{j}]-1={rhs_val}", + float(z_js), rhs_val, rhs_val - z_js) + + # ------ Constraint 14: z[s,s] = 1; route start/end satellite ------ + for r_idx, route_info in enumerate(sol.get('second_echelon_routes', [])): + sat = route_info['satellite'] + route = route_info['route'] + if not route: + continue + if route[0] != sat or route[-1] != sat: + add_violation(14, + f"Second-echelon route {r_idx} does not start and end at satellite {sat}: start={route[0]}, end={route[-1]}", + 0.0, 0.0, 1.0) + + # ------ Constraint 15: Grouping constraint ------ + for h, members in groups.items(): + for cid in members: + for s in sat_ids: + z_val = z.get((cid, s), 0) + v_val = v.get((h, s), 0) + diff = abs(z_val - v_val) + if diff > tol: + add_violation(15, + f"Grouping violated: customer {cid} (group {h}), satellite {s}: z={z_val}, v={v_val}", + float(z_val), float(v_val), diff) + + # ------ Constraint 16: Linking constraint ------ + for s in sat_ids: + lhs = sum(w.get((s, k), 0) for k in range(T1)) + rhs_val = sum(f_var.get((s, j), 0) for j in cust_ids) + diff = abs(lhs - rhs_val) + if diff > tol: + add_violation(16, + f"Linking constraint violated at satellite {s}: sum_w={lhs}, sum_f={rhs_val}", + lhs, rhs_val, diff) + + # ------ Constraint 17: x binary ------ + for key, val in x.items(): + if val not in (0, 1): + add_violation(17, f"x{key} not binary: {val}", + float(val), round(val), abs(val - round(val))) + + # ------ Constraint 18: w >= 0 ------ + for key, val in w.items(): + if val < -tol: + add_violation(18, f"w{key} negative: {val}", float(val), 0.0, -val) + + # ------ Constraint 19: u >= 0 ------ + for key, val in u.items(): + if val < -tol: + add_violation(19, f"u{key} negative: {val}", float(val), 0.0, -val) + + # ------ Constraint 20: f >= 0 ------ + for key, val in f_var.items(): + if val < -tol: + add_violation(20, f"f{key} negative: {val}", float(val), 0.0, -val) + + # ------ Constraint 21: y binary ------ + for key, val in y.items(): + if val not in (0, 1): + add_violation(21, f"y{key} not binary: {val}", + float(val), round(val), abs(val - round(val))) + + # ------ Constraint 22: z binary ------ + for key, val in z.items(): + if val not in (0, 1): + add_violation(22, f"z{key} not binary: {val}", + float(val), round(val), abs(val - round(val))) + + # ------ Constraint 23: v binary ------ + for key, val in v.items(): + if val not in (0, 1): + add_violation(23, f"v{key} not binary: {val}", + float(val), round(val), abs(val - round(val))) + + # ------ Constraint 24: Objective consistency (Tier C) ------ + # Recompute the total cost from the reconstructed decision variables and + # reject when the reported objective_value disagrees beyond tolerance. + # obj = sum_{k,(i,j)} c[i,j] * x[i,j,k] (echelon 1 routing) + # + sum_s h_s * sum_k w[s,k] (handling at satellites) + # + sum_{(i,j) in A2} c[i,j] * y[i,j] (echelon 2 routing) + reported_obj = sol.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None and math.isfinite(reported): + echelon1_cost = sum(edge_cost(i, j) for (i, j, k) in x) + handling_cost = sum( + sat_handling_cost[s] * w.get((s, k), 0.0) + for s in sat_ids for k in range(T1) + ) + echelon2_cost = sum(edge_cost(i, j) for (i, j) in y) + true_obj = float(echelon1_cost + handling_cost + echelon2_cost) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + add_violation(24, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed total cost=" + f"{true_obj} (echelon1={echelon1_cost:.6g}, " + f"handling={handling_cost:.6g}, echelon2={echelon2_cost:.6g}; " + f"|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported, true_obj, abs_diff) + elif reported is not None: + # Non-finite reported obj (nan, inf): reject as a Tier-C exploit. + echelon1_cost = sum(edge_cost(i, j) for (i, j, k) in x) + handling_cost = sum( + sat_handling_cost[s] * w.get((s, k), 0.0) + for s in sat_ids for k in range(T1) + ) + echelon2_cost = sum(edge_cost(i, j) for (i, j) in y) + true_obj = float(echelon1_cost + handling_cost + echelon2_cost) + add_violation(24, + f"Objective consistency violated: reported objective_value=" + f"{reported} is not finite; recomputed total cost={true_obj}", + reported, true_obj, float('inf')) + + # ---- Build result ---- + return { + "feasible": len(violated_set) == 0, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + +def main(): + parser = argparse.ArgumentParser(description="Feasibility checker for 2E-CVRPGC") + parser.add_argument('--instance_path', type=str, required=True) + parser.add_argument('--solution_path', type=str, required=True) + parser.add_argument('--result_path', type=str, required=True) + args = parser.parse_args() + + with open(args.instance_path) as fh: + inst = json.load(fh) + with open(args.solution_path) as fh: + sol = json.load(fh) + _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 fh: + json.dump(result, fh, indent=2) + + if not result['feasible'] and 0 in result['violated_constraints'] and \ + all(c == 0 for c in result['violated_constraints']): + print("INFEASIBLE: domain violations") + for v in result['violations']: + print(f" - {v}") + return + + print(f"Feasibility: {result['feasible']}") + if result['violated_constraints']: + print(f"Violated constraints: {result['violated_constraints']}") + + +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/roberti2018/gurobi_code.py b/tasks/roberti2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..584faa8cab2c2101a1a8379bce4a0f1d0ea48fde --- /dev/null +++ b/tasks/roberti2018/gurobi_code.py @@ -0,0 +1,596 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Two-Echelon Capacitated Vehicle Routing Problem +with Grouping Constraints (2E-CVRPGC). + +Based on: Liu, Luo, Qin, Lim (2018). "A branch-and-cut algorithm for the +two-echelon capacitated vehicle routing problem with grouping constraints." +European Journal of Operational Research, 266(2), 487-497. + +This implements the arc-flow MILP formulation (constraints 1-23) from the paper. +""" + +import argparse +import json +import math +import sys +from itertools import combinations + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load a 2E-CVRPGC instance from a JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def euclidean_distance(n1, n2): + """Compute Euclidean distance between two nodes.""" + return math.sqrt((n1['x'] - n2['x'])**2 + (n1['y'] - n2['y'])**2) + + +def solve_2e_cvrpgc(instance_path, solution_path, time_limit): + """Build and solve the 2E-CVRPGC MILP model using Gurobi.""" + data = load_instance(instance_path) + + # ------------------------------------------------------------------------- + # Extract instance data + # ------------------------------------------------------------------------- + depot = data['depot'] + satellites = data['satellites'] + customers = data['customers'] + groups = data['groups'] + + Q1 = data['Q1'] # First echelon vehicle capacity + Q2 = data['Q2'] # Second echelon vehicle capacity + T1 = data['T1'] # Max first echelon vehicles + T2 = data['T2'] # Max second echelon vehicles + + num_satellites = data['num_satellites'] + num_customers = data['num_customers'] + num_groups = data['num_groups'] + + # Build node dictionaries indexed by id + all_nodes = {} + all_nodes[depot['id']] = depot + + for s in satellites: + all_nodes[s['id']] = s + + for c in customers: + all_nodes[c['id']] = c + + depot_id = depot['id'] + sat_ids = [s['id'] for s in satellites] + cust_ids = [c['id'] for c in customers] + + # Satellite parameters + sat_capacity = {s['id']: s['capacity'] for s in satellites} # Q_s + sat_max_vehicles = {s['id']: s['max_vehicles'] for s in satellites} # T_s + sat_handling_cost = {s['id']: s['handling_cost'] for s in satellites} # h_s + + # Customer parameters + cust_demand = {c['id']: c['demand'] for c in customers} # d_i + + # Group membership: group_id -> list of customer ids + group_members = {} + for g in groups: + group_members[g['group_id']] = g['customer_ids'] + + # Customer to group mapping + cust_to_group = {} + for c in customers: + cust_to_group[c['id']] = c['group'] + + # ------------------------------------------------------------------------- + # Compute travel costs (Euclidean distances) + # ------------------------------------------------------------------------- + # NOTE: The paper does not specify whether distances are rounded. + # **INFERRED ASSUMPTION**: We use continuous floating-point Euclidean distances. + cost = {} + for i_id in all_nodes: + for j_id in all_nodes: + if i_id != j_id: + cost[i_id, j_id] = euclidean_distance(all_nodes[i_id], all_nodes[j_id]) + + # ------------------------------------------------------------------------- + # Define arc sets + # ------------------------------------------------------------------------- + # A_1: arcs connecting depot and satellites (both directions) + # A_1 = {(i,j) | i, j in V_0 ∪ V_S} + V0_VS = [depot_id] + sat_ids + A1 = [(i, j) for i in V0_VS for j in V0_VS if i != j] + + # A_2: arcs connecting satellites to customers and between customers + # A_2 = {(i,j) | i, j in V_S ∪ V_C, i ≠ j} \ {(i,j) | i, j in V_S, i ≠ j} + VS_VC = sat_ids + cust_ids + A2 = [(i, j) for i in VS_VC for j in VS_VC + if i != j and not (i in sat_ids and j in sat_ids)] + + # Vehicle set for first echelon + K1 = list(range(T1)) + + # |V_S| for MTZ big-M + n_sat = len(sat_ids) + + # ------------------------------------------------------------------------- + # Create Gurobi model + # ------------------------------------------------------------------------- + model = gp.Model("2E-CVRPGC") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ------------------------------------------------------------------------- + # Decision variables + # ------------------------------------------------------------------------- + # x[i,j,k] ∈ {0,1}: arc (i,j) traveled by first-echelon vehicle k + x = {} + for (i, j) in A1: + for k in K1: + x[i, j, k] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}_{k}") + + # w[s,k] >= 0: quantity delivered to satellite s by vehicle k + w = {} + for s in sat_ids: + for k in K1: + w[s, k] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"w_{s}_{k}") + + # u[s,k] >= 0: position of satellite s in route of vehicle k (MTZ) + u = {} + for s in sat_ids: + for k in K1: + u[s, k] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"u_{s}_{k}") + + # f[i,j] >= 0: load on arc (i,j) in second echelon + f = {} + for (i, j) in A2: + f[i, j] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"f_{i}_{j}") + + # y[i,j] ∈ {0,1}: second echelon vehicle travels arc (i,j) + y = {} + for (i, j) in A2: + y[i, j] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}_{j}") + + # z[i,s] ∈ {0,1}: customer i served by vehicle from satellite s + z = {} + for i in cust_ids: + for s in sat_ids: + z[i, s] = model.addVar(vtype=GRB.BINARY, name=f"z_{i}_{s}") + + # v[h,s] ∈ {0,1}: group h assigned to satellite s + v = {} + for g in groups: + h = g['group_id'] + for s in sat_ids: + v[h, s] = model.addVar(vtype=GRB.BINARY, name=f"v_{h}_{s}") + + model.update() + + # ------------------------------------------------------------------------- + # Objective function (1): minimize routing + handling + routing costs + # ------------------------------------------------------------------------- + obj = gp.LinExpr() + + # First echelon routing cost + for (i, j) in A1: + for k in K1: + obj += cost[i, j] * x[i, j, k] + + # Handling cost at satellites + for s in sat_ids: + for k in K1: + obj += sat_handling_cost[s] * w[s, k] + + # Second echelon routing cost + for (i, j) in A2: + obj += cost[i, j] * y[i, j] + + model.setObjective(obj, GRB.MINIMIZE) + + # ------------------------------------------------------------------------- + # Constraints + # ------------------------------------------------------------------------- + + # (2) Flow conservation for first echelon + # For each node i in V_0 ∪ V_S, for each vehicle k: + # sum_{(i,j) in A1} x[i,j,k] = sum_{(j,i) in A1} x[j,i,k] + for i in V0_VS: + for k in K1: + out_arcs = [(i, j) for j in V0_VS if j != i] + in_arcs = [(j, i) for j in V0_VS if j != i] + model.addConstr( + gp.quicksum(x[a[0], a[1], k] for a in out_arcs) == + gp.quicksum(x[a[0], a[1], k] for a in in_arcs), + name=f"flow_cons1_{i}_{k}" + ) + + # (3) Each satellite visited at most once per vehicle + # For each satellite i, vehicle k: sum_{(i,j) in A1} x[i,j,k] <= 1 + for i in sat_ids: + for k in K1: + out_arcs = [(i, j) for j in V0_VS if j != i] + model.addConstr( + gp.quicksum(x[a[0], a[1], k] for a in out_arcs) <= 1, + name=f"visit_once_{i}_{k}" + ) + + # (4) Subtour elimination (MTZ) for first echelon + # u[i,k] + 1 <= u[j,k] + |V_S| * (1 - x[i,j,k]) + # for all (i,j) in A1, k in K1 + # Note: We apply MTZ only for arcs between satellites (and from depot to satellites) + # The position variables u are only defined for satellites. + # For arcs (i,j) where i is the depot, we need to handle specially. + for (i, j) in A1: + for k in K1: + if i == depot_id and j in sat_ids: + # u[j,k] >= 1 - n_sat*(1 - x[i,j,k]) => 0 + 1 <= u[j,k] + n_sat*(1-x) + # We treat depot position as 0 + model.addConstr( + 1 <= u[j, k] + n_sat * (1 - x[i, j, k]), + name=f"mtz_{i}_{j}_{k}" + ) + elif i in sat_ids and j in sat_ids: + model.addConstr( + u[i, k] + 1 <= u[j, k] + n_sat * (1 - x[i, j, k]), + name=f"mtz_{i}_{j}_{k}" + ) + # Arcs (sat, depot) and (depot, depot) don't need MTZ + # as depot is the start/end point + + # Upper bound on u variables + for s in sat_ids: + for k in K1: + model.addConstr(u[s, k] <= n_sat, name=f"u_ub_{s}_{k}") + + # (5) Delivery only if satellite is visited + # w[s,k] <= Q_s * sum_{(s,i) in A1} x[s,i,k] + for s in sat_ids: + for k in K1: + out_arcs = [(s, j) for j in V0_VS if j != s] + model.addConstr( + w[s, k] <= sat_capacity[s] * gp.quicksum(x[a[0], a[1], k] for a in out_arcs), + name=f"delivery_visit_{s}_{k}" + ) + + # (6) Vehicle capacity constraint (first echelon) + # sum_{s in V_S} w[s,k] <= Q1 + for k in K1: + model.addConstr( + gp.quicksum(w[s, k] for s in sat_ids) <= Q1, + name=f"veh_cap1_{k}" + ) + + # (7) Satellite capacity constraint + # sum_{k in K1} w[s,k] <= Q_s + for s in sat_ids: + model.addConstr( + gp.quicksum(w[s, k] for k in K1) <= sat_capacity[s], + name=f"sat_cap_{s}" + ) + + # (8) Flow conservation for second echelon: each customer visited exactly once + # sum_{(i,j) in A2} y[i,j] = 1 for all i in V_C (out-degree) + # sum_{(j,i) in A2} y[j,i] = 1 for all i in V_C (in-degree) + for i in cust_ids: + out_arcs = [(i, j) for j in VS_VC if (i, j) in y] + in_arcs = [(j, i) for j in VS_VC if (j, i) in y] + model.addConstr( + gp.quicksum(y[a] for a in out_arcs) == 1, + name=f"cust_out_{i}" + ) + model.addConstr( + gp.quicksum(y[a] for a in in_arcs) == 1, + name=f"cust_in_{i}" + ) + + # (9) Vehicle limit per satellite (second echelon) + # sum_{(s,i) in A2} y[s,i] <= T_s + for s in sat_ids: + out_arcs = [(s, j) for j in cust_ids if (s, j) in y] + model.addConstr( + gp.quicksum(y[a] for a in out_arcs) <= sat_max_vehicles[s], + name=f"veh_limit_sat_{s}" + ) + + # (10) Total vehicle limit (second echelon) + # sum_{s in V_S} sum_{(s,i) in A2} y[s,i] <= T2 + model.addConstr( + gp.quicksum( + y[s, j] + for s in sat_ids + for j in cust_ids + if (s, j) in y + ) <= T2, + name="total_veh_limit2" + ) + + # (11) Flow conservation for demand satisfaction + # sum_{(j,i) in A2} f[j,i] = sum_{(i,j) in A2} f[i,j] + d_i, for i in V_C + for i in cust_ids: + in_arcs = [(j, i) for j in VS_VC if (j, i) in f] + out_arcs = [(i, j) for j in VS_VC if (i, j) in f] + model.addConstr( + gp.quicksum(f[a] for a in in_arcs) == + gp.quicksum(f[a] for a in out_arcs) + cust_demand[i], + name=f"flow_demand_{i}" + ) + + # (12) Flow bounds (Gavish) for second echelon + # d_j * y[i,j] <= f[i,j] <= (Q2 - d_i) * y[i,j] + for (i, j) in A2: + d_i = cust_demand.get(i, 0) # satellites have 0 demand + d_j = cust_demand.get(j, 0) + model.addConstr( + f[i, j] >= d_j * y[i, j], + name=f"flow_lb_{i}_{j}" + ) + model.addConstr( + f[i, j] <= (Q2 - d_i) * y[i, j], + name=f"flow_ub_{i}_{j}" + ) + + # (13) If two customers are successively visited, same satellite assignment + # z[j,s] >= z[i,s] + y[i,j] - 1, for (i,j) in A2 + # This only applies when both i and j are in V_C (customers) + # and also for arcs from satellite to customer + for (i, j) in A2: + for s in sat_ids: + if i in cust_ids and j in cust_ids: + # Both customers + model.addConstr( + z[j, s] >= z[i, s] + y[i, j] - 1, + name=f"same_sat_{i}_{j}_{s}" + ) + elif i in sat_ids and j in cust_ids: + # Arc from satellite i to customer j + # z[j,s] >= z[i,s] + y[i,j] - 1 + # z[i,s] for satellite: use constraint (14) z[s,s] = 1 + # So if i == s: z[j,s] >= 1 + y[i,j] - 1 = y[i,j] + # If i != s: z[j,s] >= 0 + y[i,j] - 1 (trivially satisfied when y=0 or y=1) + if i == s: + model.addConstr( + z[j, s] >= y[i, j], + name=f"same_sat_{i}_{j}_{s}" + ) + # If i != s, the constraint is z[j,s] >= 0 + y[i,j] - 1 + # which is trivially satisfied for binary z, so we can skip it. + # But let's add it for completeness. + else: + model.addConstr( + z[j, s] >= y[i, j] - 1, + name=f"same_sat_{i}_{j}_{s}" + ) + elif i in cust_ids and j in sat_ids: + # Arc from customer i back to satellite j: z[j,s] >= z[i,s] + y[i,j] - 1. + # s == j case: z[j,j] = 1 by (14), trivially satisfied. + # s != j case: z[j,s] = 0 (a satellite is not assigned to another + # satellite), so the constraint reduces to z[i,s] + y[i,j] <= 1, + # which forces the route to terminate at the satellite where + # customer i is assigned (enforces 13-14 on returns). + if s != j: + model.addConstr( + z[i, s] + y[i, j] <= 1, + name=f"same_sat_{i}_{j}_{s}" + ) + + # (14) Each satellite is assigned to itself: z[s,s] = 1 + # Note: z is defined for customers only in the model, but the paper says + # z_{s,s} = 1 for s in V_S. We handle this via constraint (13) above + # by checking when arc source is a satellite. + # The paper defines z_{i,s} for i in V_C, s in V_S. + # Constraint (14) z_{s,s} = 1 means the satellite node is assigned to itself. + # This is implicitly handled above in constraint (13) for satellite->customer arcs. + + # (15) Grouping constraint: customers in same group -> same satellite + # z[i,s] = v[h,s] for all i in C_h, C_h in C, s in V_S + for g in groups: + h = g['group_id'] + for cid in g['customer_ids']: + for s in sat_ids: + model.addConstr( + z[cid, s] == v[h, s], + name=f"group_{h}_{cid}_{s}" + ) + + # Each customer is assigned to exactly one satellite. + # This is implied by the paper's formulation but must be stated explicitly + # to prevent z (and v) variables from being trivially over-assigned (all 1s), + # which would decouple the grouping constraint (15) from the actual routing. + for i in cust_ids: + model.addConstr( + gp.quicksum(z[i, s] for s in sat_ids) == 1, + name=f"assign_one_{i}" + ) + + # (16) Linking constraint: quantity delivered = flow out to customers + # sum_{k in K1} w[s,k] = sum_{(s,i) in A2} f[s,i] + for s in sat_ids: + out_arcs = [(s, j) for j in cust_ids if (s, j) in f] + model.addConstr( + gp.quicksum(w[s, k] for k in K1) == + gp.quicksum(f[a] for a in out_arcs), + name=f"link_{s}" + ) + + # ------------------------------------------------------------------------- + # Symmetry breaking for first echelon vehicles (optional, helps performance) + # **INFERRED ASSUMPTION**: We add a simple symmetry-breaking constraint + # ordering the usage of vehicles. This is not specified in the paper but + # is a standard technique to help Gurobi. + # ------------------------------------------------------------------------- + for k in range(len(K1) - 1): + out_arcs_k = [(depot_id, j) for j in sat_ids] + out_arcs_k1 = [(depot_id, j) for j in sat_ids] + model.addConstr( + gp.quicksum(x[depot_id, j, K1[k]] for j in sat_ids) >= + gp.quicksum(x[depot_id, j, K1[k + 1]] for j in sat_ids), + name=f"sym_break_{k}" + ) + + # ------------------------------------------------------------------------- + # Optimize + # ------------------------------------------------------------------------- + model.optimize() + + # ------------------------------------------------------------------------- + # Extract solution + # ------------------------------------------------------------------------- + solution = {} + + if model.SolCount > 0: + solution['objective_value'] = model.ObjVal + solution['status'] = 'optimal' if model.Status == GRB.OPTIMAL else 'feasible' + solution['mip_gap'] = model.MIPGap if hasattr(model, 'MIPGap') else None + solution['runtime'] = model.Runtime + + # Extract first echelon routes + first_echelon_routes = [] + for k in K1: + route_arcs = [] + for (i, j) in A1: + if x[i, j, k].X > 0.5: + route_arcs.append((i, j)) + if route_arcs: + # Reconstruct route from arcs + route = reconstruct_route(route_arcs, depot_id) + deliveries = {} + for s in sat_ids: + if w[s, k].X > 1e-6: + deliveries[str(s)] = round(w[s, k].X, 4) + first_echelon_routes.append({ + 'vehicle': k, + 'route': route, + 'deliveries': deliveries + }) + solution['first_echelon_routes'] = first_echelon_routes + + # Extract second echelon routes + second_echelon_routes = [] + # Find routes starting from each satellite + for s in sat_ids: + # Find arcs leaving this satellite + start_arcs = [(s, j) for j in cust_ids if (s, j) in y and y[s, j].X > 0.5] + for (_, first_cust) in start_arcs: + route = [s, first_cust] + current = first_cust + while current not in sat_ids: + for j in VS_VC: + if (current, j) in y and y[current, j].X > 0.5: + route.append(j) + current = j + break + else: + break + second_echelon_routes.append({ + 'satellite': s, + 'route': route + }) + solution['second_echelon_routes'] = second_echelon_routes + + # Extract group-satellite assignments from actual routes. + # NOTE: The v and z variables may be over-assigned (all 1s) because + # the formulation lacks a constraint sum_s z[i,s] = 1, and z/v do not + # appear in the objective. Instead, derive assignments from the + # second-echelon routes: each customer is assigned to the satellite + # that starts its route (constraint 13 + 14 ensure this). + cust_to_satellite = {} + for route_info in second_echelon_routes: + sat = route_info['satellite'] + for node in route_info['route']: + if node in cust_ids: + cust_to_satellite[node] = sat + group_assignments = {} + for g in groups: + h = g['group_id'] + for cid in g['customer_ids']: + if cid in cust_to_satellite: + group_assignments[str(h)] = cust_to_satellite[cid] + break + solution['group_assignments'] = group_assignments + + else: + solution['objective_value'] = None + solution['status'] = 'infeasible' + solution['runtime'] = model.Runtime + + # Write solution to file + with open(solution_path, 'w') as f_out: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f_out, indent=2) + + print(f"Solution written to {solution_path}") + if model.SolCount > 0: + print(f"Objective value: {solution['objective_value']}") + print(f"Status: {solution['status']}") + else: + print("No feasible solution found.") + + return solution + + +def reconstruct_route(arcs, depot_id): + """Reconstruct a route from a list of arcs starting and ending at depot.""" + if not arcs: + return [] + + adj = {} + for (i, j) in arcs: + adj[i] = j + + route = [depot_id] + current = depot_id + visited = set() + while current in adj and adj[current] not in visited: + nxt = adj[current] + route.append(nxt) + visited.add(nxt) + current = nxt + if current == depot_id: + break + + return route + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the 2E-CVRPGC using Gurobi (MILP 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 to write the solution JSON file' + ) + parser.add_argument( + '--time_limit', type=int, required=True, + help='Maximum solver runtime in seconds' + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_2e_cvrpgc(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == '__main__': + main() diff --git a/tasks/roberti2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/roberti2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2018/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/roberti2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/roberti2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2018/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/roberti2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/roberti2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2018/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/roberti2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/roberti2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2018/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/roberti2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/roberti2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2018/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/roberti2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/roberti2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2018/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/roberti2018/gurobi_solution/large_solution_1.json b/tasks/roberti2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..47867afad62cf5467e14e504fc68e25b7adfc357 --- /dev/null +++ b/tasks/roberti2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1dba9b1a0167182e3155d2b1f2698e3076e3153992370340b53b2611a43e32c3 +size 3336 diff --git a/tasks/roberti2018/gurobi_solution/large_solution_2.json b/tasks/roberti2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..843fbe1ee7269486c207bbd2f174e181327d4d2c --- /dev/null +++ b/tasks/roberti2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a49e655f98587d77f62cfae476ce7da1d110679dcf70e10196238ac6d4bd9fe9 +size 3591 diff --git a/tasks/roberti2018/gurobi_solution/large_solution_3.json b/tasks/roberti2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..0fd073c0b1ebacad5d245aef39c6d3ff5ed5335c --- /dev/null +++ b/tasks/roberti2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9daafe5d6d2d1fefe382b2a5845f49c48918b7c5eb0132dc632a0c39177f322a +size 3210 diff --git a/tasks/roberti2018/gurobi_solution/large_solution_4.json b/tasks/roberti2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d840de109c2349f13a9577fa305fb36db677acbf --- /dev/null +++ b/tasks/roberti2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d91cb330ce16a514572c0ad75b5cc782df8230a7220e64dc60c85bad398d3859 +size 3192 diff --git a/tasks/roberti2018/gurobi_solution/large_solution_5.json b/tasks/roberti2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d6d47eed264faf02008eefdfecf28ba1983f74a8 --- /dev/null +++ b/tasks/roberti2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:926a828101aadad78b2dcae035ef1081001db10a020255c56bf13a66779bcc94 +size 3009 diff --git a/tasks/roberti2018/gurobi_solution/tiny_solution.json b/tasks/roberti2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..160319c04579d183865b6f59dcd7d5537d3841db --- /dev/null +++ b/tasks/roberti2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2cad78afbe50ec51e7ff41926ed6bfed2d724e8f2624ab0dc98d484a9f666cd +size 1300 diff --git a/tasks/roberti2018/gurobi_solution_log/large_log_1.jsonl b/tasks/roberti2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b8bb33c041e27731b92d0b669b3d8b9da5b706b2 --- /dev/null +++ b/tasks/roberti2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:623f00e44aae69d01148c2fb34a4c6e2f20094e7064c3cb00e314aa5c0a29ebd +size 2436 diff --git a/tasks/roberti2018/gurobi_solution_log/large_log_2.jsonl b/tasks/roberti2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e5f8df228fed357589d5a8dedd5e90aac62fa2c2 --- /dev/null +++ b/tasks/roberti2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9acbf11712909cab6e1d31d237e743fecac397ac21712775896def758a01196 +size 2868 diff --git a/tasks/roberti2018/gurobi_solution_log/large_log_3.jsonl b/tasks/roberti2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..33476ce1f89b7342dd3af02cc04aed6aa6075922 --- /dev/null +++ b/tasks/roberti2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79b12ff2176d9ac9e50304ccee5454c290f943fd0786ca39c0a42646a1795171 +size 1110 diff --git a/tasks/roberti2018/gurobi_solution_log/large_log_4.jsonl b/tasks/roberti2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3c8005643a764f9b445abeac6202058e7ad4416d --- /dev/null +++ b/tasks/roberti2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85002f13b22fb2c0f0d9d903588a838bec6e9070f6b6e9cb152c4a2cdd5ed1d1 +size 1358 diff --git a/tasks/roberti2018/gurobi_solution_log/large_log_5.jsonl b/tasks/roberti2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b21b7f62a8cd317204191e2bd3365aa9ffa28596 --- /dev/null +++ b/tasks/roberti2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1f689f2516d05899d7b0c996bd164ca9c595ebf525a9557c1d76516a21c0b6b +size 1817 diff --git a/tasks/roberti2018/gurobi_solution_log/tiny_log.jsonl b/tasks/roberti2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8ace1c4825e2f5b0b969d1acadc2914f97d72ed3 --- /dev/null +++ b/tasks/roberti2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:caecca9ece1ad1530e2f6d0d03328c608e3af192eed32a3cee12388ad35874ad +size 320 diff --git a/tasks/roberti2018/instance/large_instance_1.json b/tasks/roberti2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..821fc5559d41107daf9e7145e0063ad34acb9f67 --- /dev/null +++ b/tasks/roberti2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f4e53bb58bd0afb6445344850ac0c785e3444a01a71d4fce0ad8fc10a5f4a5b +size 6976 diff --git a/tasks/roberti2018/instance/large_instance_2.json b/tasks/roberti2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ee447c3b33f868080c03325ab3a1f27b509268e4 --- /dev/null +++ b/tasks/roberti2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac4750c6cc4f6d3175e5c15d519f335a2f7caee1d72a94725d9606ebc94a32a7 +size 6970 diff --git a/tasks/roberti2018/instance/large_instance_3.json b/tasks/roberti2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..9b660cb1d41d1adad9a5df7e77091d6f81414adb --- /dev/null +++ b/tasks/roberti2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25fa2718e55036918c368e7e207203df7630de92667c033f18805247fadd88c9 +size 6962 diff --git a/tasks/roberti2018/instance/large_instance_4.json b/tasks/roberti2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ebe6a73c61840fb2dab40c55634a0f85f39fde11 --- /dev/null +++ b/tasks/roberti2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4dce56cc1f9db35357e2f97cbc71548321518779166d18d14f71877fdd72b90 +size 6971 diff --git a/tasks/roberti2018/instance/large_instance_5.json b/tasks/roberti2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..dcb62348c7fdd8a8151840d8498474a1839ce711 --- /dev/null +++ b/tasks/roberti2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:678aa2d532d197d355bfc6d14d6e023c2bc5f5763b46dfeafd488b4104f1ce3e +size 6978 diff --git a/tasks/roberti2018/instance/tiny_instance.json b/tasks/roberti2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..edd8536e55703b2c30c9f170ddb8a132736b33b6 --- /dev/null +++ b/tasks/roberti2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6454c0426a226003f3dcfa5025f72e5dcd98307f722115cd418fc913ee0546eb +size 2962 diff --git a/tasks/roberti2018/instance_schema.json b/tasks/roberti2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..cdf1ea847d10f35a715cdf06abf3d11cf7d5f27b --- /dev/null +++ b/tasks/roberti2018/instance_schema.json @@ -0,0 +1,39 @@ +{ + "num_satellites": " Number of satellite transshipment facilities in the distribution network.", + "num_customers": " Number of customers to be served.", + "num_groups": " Number of disjoint customer groups that must each be served from a single satellite.", + "Q1": " Carrying capacity of each first-echelon (large) vehicle.", + "Q2": " Carrying capacity of each second-echelon (small) vehicle.", + "T1": " Total number of first-echelon vehicles available at the depot.", + "T2": " Total number of second-echelon vehicles available across the entire system.", + "depot": { + "id": " Unique node identifier for the depot.", + "x": " Horizontal coordinate of the depot.", + "y": " Vertical coordinate of the depot." + }, + "satellites": [ + { + "id": " Unique node identifier for this satellite.", + "x": " Horizontal coordinate of this satellite.", + "y": " Vertical coordinate of this satellite.", + "capacity": " Maximum total freight throughput this satellite can handle.", + "max_vehicles": " Maximum number of second-echelon vehicles that may operate from this satellite.", + "handling_cost": " Per-unit cost incurred for each unit of freight passing through this satellite." + } + ], + "customers": [ + { + "id": " Unique node identifier for this customer.", + "x": " Horizontal coordinate of this customer.", + "y": " Vertical coordinate of this customer.", + "demand": " Quantity of freight required by this customer.", + "group": " Identifier of the customer group to which this customer belongs." + } + ], + "groups": [ + { + "group_id": " Unique identifier for this customer group.", + "customer_ids": " Node identifiers of all customers belonging to this group." + } + ] +} diff --git a/tasks/roberti2018/mathematical_formulation.md b/tasks/roberti2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..2a35b87b7667376b77fe29bdaed8592ba538c22c --- /dev/null +++ b/tasks/roberti2018/mathematical_formulation.md @@ -0,0 +1,110 @@ +# Original Formulation: Two-Echelon Capacitated Vehicle Routing Problem with Grouping Constraints (2E-CVRPGC) + +*Source: A branch-and-cut algorithm for the two-echelon capacitated vehicle routing problem with grouping constraints, Tian Liu, Zhixing Luo, Hu Qin, Andrew Lim, European Journal of Operational Research (2018).* + +## Sets and Indices + +- $G=(V,A)$: undirected graph on which the 2E-CVRPGC is defined. + +- $V = V_0 \cup V_S \cup V_C$: node set, where $V_0=\{0\}$ is the depot, $V_S$ is the set of satellites, and $V_C$ is the set of customers. + +- $A = A_1 \cup A_2$: arc set, where $A_1 = \{(i,j)\mid i,j\in V_0\cup V_S\}$ are the arcs connecting the depot and the satellites, and $A_2 = \{(i,j)\mid i,j\in V_S\cup V_C,\, i\neq j\}\setminus + \{(i,j)\mid i,j\in V_S,\, i\neq j\}$ are the arcs connecting the satellites and the customers. + +- $V_C = C_1 \cup \cdots \cup C_m$ with $C_i\cap C_j=\emptyset$ for all $i\neq j$: the $m$ disjoint customer groups; $\mathbb{C}=\{C_1,\ldots,C_m\}$ is the collection of all groups. + +- $K_1$: set of available vehicles in the first echelon. + +## Parameters + +- $d_i$: demand of customer $i\in V_C$. + +- $c_{i,j}$: travel cost of vehicles on arc $(i,j)\in A$. + +- $Q_1$: capacity of vehicles in the first echelon. + +- $Q_2$: capacity of vehicles in the second echelon. + +- $Q_s$: capacity (throughput) of satellite $s\in V_S$. + +- $h_s$: handling cost per unit of freight at satellite $s\in V_S$. + +- $T_1$: number of available vehicles in the first echelon. + +- $T_2$: number of available vehicles in the second echelon. + +- $T_s$: maximum number of vehicles associated with satellite $s\in V_S$. + +- $|V_S|$: number of satellites (used as the big-$M$ in the MTZ constraints). + +## Decision Variables + +- $x_{i,j,k}\in\{0,1\}$, $(i,j)\in A_1$, $k\in K_1$: equal to $1$ if arc $(i,j)$ is traveled by first-echelon vehicle $k$, and $0$ otherwise. + +- $w_{s,k}\geq 0$, $s\in V_S$, $k\in K_1$: quantity delivered to satellite $s$ by first-echelon vehicle $k$. + +- $u_{s,k}\geq 0$, $s\in V_S$, $k\in K_1$: position of satellite $s$ in the route of first-echelon vehicle $k$. + +- $f_{i,j}\geq 0$, $(i,j)\in A_2$: load of the vehicle when it travels through arc $(i,j)$. + +- $y_{i,j}\in\{0,1\}$, $(i,j)\in A_2$: equal to $1$ if a second-echelon vehicle travels through arc $(i,j)$, and $0$ otherwise. + +- $z_{i,s}\in\{0,1\}$, $i\in V_C$, $s\in V_S$: equal to $1$ if customer $i$ is served by a vehicle from satellite $s$, and $0$ otherwise. + +- $v_{C_h,s}\in\{0,1\}$, $h=1,\ldots,m$, $s\in V_S$: equal to $1$ if customer group $C_h\in\mathbb{C}$ is assigned to satellite $s$, and $0$ otherwise. + +## Objective + +$$\begin{align} +\min\ \sum_{k\in K_1}\sum_{(i,j)\in A_1} c_{i,j}\,x_{i,j,k} + + \sum_{s\in V_S} h_s \sum_{k\in K_1} w_{s,k} + + \sum_{(i,j)\in A_2} c_{i,j}\,y_{i,j} \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{(i,j)\in A_1} x_{i,j,k} &= \sum_{(j,i)\in A_1} x_{j,i,k}, + && \forall\, i\in V_0\cup V_S,\; k\in K_1 \tag{2}\\[2pt] +\sum_{(i,j)\in A_1} x_{i,j,k} &\leq 1, + && \forall\, i\in V_S,\; k\in K_1 \tag{3}\\[2pt] +u_{i,k} + 1 &\leq u_{j,k} + |V_S|\,(1 - x_{i,j,k}), + && \forall\, (i,j)\in A_1,\; k\in K_1 \tag{4}\\[2pt] +w_{s,k} &\leq Q_s \sum_{(s,i)\in A_1} x_{s,i,k}, + && \forall\, s\in V_S,\; k\in K_1 \tag{5}\\[2pt] +\sum_{s\in V_S} w_{s,k} &\leq Q_1, + && \forall\, k\in K_1 \tag{6}\\[2pt] +\sum_{k\in K_1} w_{s,k} &\leq Q_s, + && \forall\, s\in V_S \tag{7}\\[2pt] +\sum_{(i,j)\in A_2} y_{i,j} &= \sum_{(j,i)\in A_2} y_{j,i} = 1, + && \forall\, i\in V_C \tag{8}\\[2pt] +\sum_{(s,i)\in A_2} y_{s,i} &\leq T_s, + && \forall\, s\in V_S \tag{9}\\[2pt] +\sum_{s\in V_S}\sum_{(s,i)\in A_2} y_{s,i} &\leq T_2, && \tag{10}\\[2pt] +\sum_{(j,i)\in A_2} f_{j,i} &= \sum_{(i,j)\in A_2} f_{i,j} + d_i, + && \forall\, i\in V_C \tag{11}\\[2pt] +d_j\,y_{i,j} \leq f_{i,j} &\leq (Q_2 - d_i)\,y_{i,j}, + && \forall\, (i,j)\in A_2 \tag{12}\\[2pt] +z_{j,s} &\geq z_{i,s} + y_{i,j} - 1, + && \forall\, (i,j)\in A_2 \tag{13}\\[2pt] +z_{s,s} &= 1, + && \forall\, s\in V_S \tag{14}\\[2pt] +z_{i,s} &= v_{C_h,s}, + && \forall\, i\in C_h,\; C_h\in\mathbb{C},\; s\in V_S \tag{15}\\[2pt] +\sum_{k\in K_1} w_{s,k} &= \sum_{(s,i)\in A_2} f_{s,i}, + && \forall\, s\in V_S \tag{16}\\[2pt] +x_{i,j,k} &\in \{0,1\}, + && \forall\, (i,j)\in A_1,\; k\in K_1 \tag{17}\\[2pt] +w_{s,k} &\geq 0, + && \forall\, s\in V_S,\; k\in K_1 \tag{18}\\[2pt] +u_{s,k} &\geq 0, + && \forall\, s\in V_S,\; k\in K_1 \tag{19}\\[2pt] +f_{i,j} &\geq 0, + && \forall\, (i,j)\in A_2 \tag{20}\\[2pt] +y_{i,j} &\in \{0,1\}, + && \forall\, (i,j)\in A_2 \tag{21}\\[2pt] +z_{i,s} &\in \{0,1\}, + && \forall\, i\in V_C,\; s\in V_S \tag{22}\\[2pt] +v_{C_h,s} &\in \{0,1\}, + && \forall\, C_h\in\mathbb{C},\; s\in V_S \tag{23} +\end{align}$$ diff --git a/tasks/roberti2018/problem_description.txt b/tasks/roberti2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..45441616bed1777733146887161ed836c5bd7302 --- /dev/null +++ b/tasks/roberti2018/problem_description.txt @@ -0,0 +1,17 @@ +# Problem Description + +A freight distribution system operates over two echelons. The system comprises a single depot, a set of satellites (intermediate transshipment facilities), and a set of customers. Each customer has a known demand and belongs to exactly one predefined group; the groups are disjoint and collectively cover all customers. The locations of the depot, satellites, and customers are given as coordinates in a plane, and the travel cost between any two locations equals the Euclidean distance between them. + +In the first echelon, a fleet of identical large vehicles departs from the depot, visits a subset of the satellites to deliver freight, and returns to the depot. Each first-echelon vehicle has a carrying capacity, and the total freight delivered by a single first-echelon vehicle across all satellites it visits cannot exceed that capacity. The total number of first-echelon vehicles available is given. A first-echelon vehicle may visit multiple satellites in a single tour, but each satellite may be visited at most once by any given first-echelon vehicle. A satellite need not be visited at all if it is not needed. A first-echelon vehicle can only deliver freight to a satellite that it visits on its route, and the quantity delivered by any single vehicle to any single satellite cannot exceed that satellite's throughput capacity. Each satellite has a throughput capacity limiting the total quantity of freight it can handle across all first-echelon deliveries. Each satellite has a per-unit handling cost incurred on every unit of freight passing through it. + +In the second echelon, a fleet of identical small vehicles operates from the satellites to serve customers. Each second-echelon vehicle departs from a satellite, visits one or more customers along a route, and returns to the same satellite. Every customer must be visited exactly once by exactly one second-echelon vehicle, meaning that for each customer the number of incoming trips equals the number of outgoing trips and both equal one. Each second-echelon vehicle has a carrying capacity, the total number of second-echelon vehicles available across the entire system is given, and each satellite has a limit on the maximum number of second-echelon vehicles that may depart from it. + +Each customer is assigned to the satellite from which its serving vehicle departs. Each satellite is assigned to itself. If a second-echelon vehicle travels directly from one location to another, and the origin is assigned to a particular satellite, then the destination must also be assigned to that same satellite. + +The grouping requirement mandates that all customers belonging to the same group must be assigned to the same satellite. For every customer in a group and every satellite, the customer's assignment to that satellite equals the group's assignment to that satellite. Different groups may be assigned to different satellites, or multiple groups may share a satellite, but a single group must not be split across satellites. + +The quantity of freight delivered to each satellite by first-echelon vehicles must equal the total load departing that satellite on second-echelon trips. On each second-echelon trip between two locations, the load of goods must be consistent with customer demands: the total load arriving at a customer minus the total load departing from that customer equals that customer's demand. The load on any trip segment is zero if the segment is not traversed. When a segment is traversed, the load on it must be at least the demand of the destination customer and at most the second-echelon vehicle capacity minus the demand of the origin location, where the demand of a satellite is zero. + +Each first-echelon vehicle's set of traversed arcs must form a single connected tour that begins and ends at the depot; disconnected cycles among satellites (subtours that do not pass through the depot) are not allowed. + +The goal is to minimize the total cost, which is the sum of three components: the total travel cost of all first-echelon vehicle routes, the total handling cost at all satellites (proportional to the freight volume processed at each), and the total travel cost of all second-echelon vehicle routes. diff --git a/tasks/roberti2018/solution_logger.py b/tasks/roberti2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/roberti2018/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/roberti2018/solution_schema.json b/tasks/roberti2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7cf46e0c3f1d7e37847571c5544da67dc4a3c52a --- /dev/null +++ b/tasks/roberti2018/solution_schema.json @@ -0,0 +1,17 @@ +{ + "objective_value": " Total cost combining first-echelon travel cost, satellite handling cost, and second-echelon travel cost.", + "first_echelon_routes": [ + { + "vehicle": " Identifier of the first-echelon vehicle performing this tour.", + "route": " Ordered sequence of node ids visited by the first-echelon vehicle, starting and ending at the depot.", + "deliveries": " Quantity of freight delivered by this first-echelon vehicle to each satellite it visits." + } + ], + "second_echelon_routes": [ + { + "satellite": " Identifier of the satellite from which this second-echelon vehicle departs and returns.", + "route": " Ordered sequence of node ids visited by the second-echelon vehicle, starting and ending at the originating satellite." + } + ], + "group_assignments": " Satellite identifier to which each customer group is assigned for second-echelon service." +} diff --git a/tasks/roberti2021/feasibility_check.py b/tasks/roberti2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..0a0dfb2911af51babb8e746437dd29a67a608741 --- /dev/null +++ b/tasks/roberti2021/feasibility_check.py @@ -0,0 +1,781 @@ +""" +Feasibility checker for TSP-D (Roberti & Ruthmair, 2021). + +Checks the hard constraints (1b)-(1o) from the compact MILP formulation, +plus an objective-consistency check (constraint 15) that recomputes the +true tour-completion time a_{0'} from the truck/drone routes and the +instance travel times, and rejects the solution if the reported +objective_value deviates from the recomputed value. + +Supports both efficient_algorithm and Gurobi solution formats. + +Usage: + python feasibility_check_new.py \ + --instance_path instance_1.json \ + --solution_path efficient_solution_1.json \ + --result_path efficient_feasi_result_1.json +""" + +import argparse +import json +import sys +from itertools import permutations + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('arrival_times', 'customer_types', 'drone_route', 'objective_value', 'truck_route') +_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_instance(path): + with open(path, "r") as f: + return json.load(f) + + +def load_solution(path): + with open(path, "r") as f: + return json.load(f) + + +def _is_binary(val): + return abs(val - 0.0) <= TOL or abs(val - 1.0) <= TOL + + +# ------------------------------------------------------------------ # +# Reconstruct MILP decision variables from compact solutions +# ------------------------------------------------------------------ # + +def reconstruct_variables_efficient(instance, solution): + """ + Directly read MILP variables from the ORIGINAL TSP-D solution + structure (truck_route, drone_route, customer_types, arrival_times). + + The earlier DP-based reconstruction searched for a minimum-cost + feasible assignment of drone customers to truck segments instead + of verifying the solution as given; that could accept an + algorithm's infeasible assignment whenever some other assignment + of the same drone_customers happened to be feasible. + """ + return reconstruct_variables_gurobi(instance, solution) + + +def reconstruct_variables_gurobi(instance, solution): + """ + Reconstruct x^T, x^D, y^T, y^D, y^C, a from Gurobi solution format. + Gurobi provides: truck_route, drone_route, customer_types, arrival_times. + """ + n = instance["num_customers"] + + truck_route = solution["truck_route"] + drone_route = solution["drone_route"] + customer_types = solution.get("customer_types", {}) + arrival_times_raw = solution.get("arrival_times", {}) + + y_T = {} + y_D = {} + y_C = {} + for i in range(1, n + 1): + ct = customer_types.get(str(i), "") + y_T[i] = 1 if ct == "truck" else 0 + y_D[i] = 1 if ct == "drone" else 0 + y_C[i] = 1 if ct == "combined" else 0 + + # Build truck arcs + x_T = {} + for idx in range(len(truck_route) - 1): + u, v = truck_route[idx], truck_route[idx + 1] + x_T[(u, v)] = 1 + + # Build drone arcs + x_D = {} + for idx in range(len(drone_route) - 1): + u, v = drone_route[idx], drone_route[idx + 1] + x_D[(u, v)] = 1 + + # Arrival times: Gurobi uses node n+1 for depot copy 0' + a = {} + for key, val in arrival_times_raw.items(): + node = int(key) + if node <= n: + a[node] = val + else: + a["0prime"] = val + + return x_T, x_D, y_T, y_D, y_C, a + + +def detect_solution_type(solution): + """Detect whether this is an efficient_algorithm or Gurobi solution.""" + if "solver" in solution and solution["solver"] == "Gurobi": + return "gurobi" + if "drone_customers" in solution: + return "efficient" + return "efficient" + + +# ------------------------------------------------------------------ # +# Objective recompute (Tier C anti-exploit) +# ------------------------------------------------------------------ # + +def _recompute_a_0prime(instance, solution): + """ + Recompute the true tour-completion time a_{0'} from the routes and + travel times. Truck and drone are synchronized at the depot and at + every combined customer; between consecutive sync points each + vehicle travels its sub-route independently, and the arrival time + at the next sync point is the max of the two cumulative travel + times. Returns the recomputed a_{0'}, or None if the routes are + malformed or their sync-point sequences do not agree (in which + case other constraints will already catch the infeasibility). + """ + truck_times = instance.get("truck_travel_times") + drone_times = instance.get("drone_travel_times") + truck_route = solution.get("truck_route") or [] + drone_route = solution.get("drone_route") or [] + customer_types = solution.get("customer_types") or {} + + if truck_times is None or drone_times is None: + return None + if len(truck_route) < 2 or len(drone_route) < 2: + return None + + combined = set() + for k, v in customer_types.items(): + if v == "combined": + try: + combined.add(int(k)) + except (TypeError, ValueError): + pass + + def sync_idxs(route): + idxs = [0] + for i in range(1, len(route) - 1): + if route[i] in combined: + idxs.append(i) + idxs.append(len(route) - 1) + return idxs + + t_idxs = sync_idxs(truck_route) + d_idxs = sync_idxs(drone_route) + if len(t_idxs) != len(d_idxs): + return None + if [truck_route[i] for i in t_idxs] != [drone_route[i] for i in d_idxs]: + return None + + total = 0.0 + for k in range(len(t_idxs) - 1): + try: + t_seg = sum( + float(truck_times[truck_route[i]][truck_route[i + 1]]) + for i in range(t_idxs[k], t_idxs[k + 1]) + ) + d_seg = sum( + float(drone_times[drone_route[i]][drone_route[i + 1]]) + for i in range(d_idxs[k], d_idxs[k + 1]) + ) + except (IndexError, TypeError, ValueError): + return None + total += max(t_seg, d_seg) + return total + + +# ------------------------------------------------------------------ # +# Constraint checking +# ------------------------------------------------------------------ # + +def add_violation(violations_list, magnitudes_list, constraint_idx, message, lhs, rhs, raw_excess): + """Record a constraint violation.""" + violations_list.append(message) + normalizer = max(abs(rhs), EPS) + ratio = raw_excess / normalizer + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(raw_excess), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +def check_feasibility(instance, solution): + """Check all hard constraints of the TSP-D MILP formulation.""" + n = instance["num_customers"] + truck_times = instance["truck_travel_times"] + drone_times = instance["drone_travel_times"] + + sol_type = detect_solution_type(solution) + + # Check for empty/null solutions (e.g., Gurobi timeout with no solution) + if solution.get("objective_value") is None: + return { + "feasible": False, + "violated_constraints": [7], + "violations": [ + "No solution found (objective_value is null); " + "all customers unserved." + ], + "violation_magnitudes": [{ + "constraint": 7, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }], + } + + truck_route = solution.get("truck_route", []) + if not truck_route or len(truck_route) < 2: + return { + "feasible": False, + "violated_constraints": [3], + "violations": ["Truck route is empty or trivial."], + "violation_magnitudes": [{ + "constraint": 3, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }], + } + + # Domain check: nodes are 0 (depot origin), 1..n (customers), n+1 (depot + # destination, encoded as "0prime" internally). Truck and drone route + # entries, customer_types keys, and arrival_times keys must all lie in + # this set. + valid_nodes = set(range(0, n + 2)) + customers_set = set(range(1, n + 1)) + drone_route = solution.get("drone_route", []) + customer_types = solution.get("customer_types", {}) + arrival_times_raw = solution.get("arrival_times", {}) + + domain_violations = [] + for node in truck_route: + if node not in valid_nodes: + domain_violations.append( + f"truck_route node {node!r} not in valid set [0, {n + 1}]" + ) + for node in drone_route: + if node not in valid_nodes: + domain_violations.append( + f"drone_route node {node!r} not in valid set [0, {n + 1}]" + ) + for k_str in customer_types: + try: + k_int = int(k_str) + except (TypeError, ValueError): + k_int = None + if k_int not in customers_set: + domain_violations.append( + f"customer_types key {k_str!r} not a valid customer id" + ) + valid_type_set = {"truck", "drone", "combined"} + for v in customer_types.values(): + if v not in valid_type_set: + domain_violations.append( + f"customer_types value {v!r} not in {valid_type_set}" + ) + for k_str in arrival_times_raw: + try: + k_int = int(k_str) + except (TypeError, ValueError): + k_int = None + if k_int not in valid_nodes: + domain_violations.append( + f"arrival_times key {k_str!r} not in valid set [0, {n + 1}]" + ) + + if domain_violations: + return { + "feasible": False, + "violated_constraints": [0], + "violations": [f"Domain: {m}" for m in domain_violations], + "violation_magnitudes": [{ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + } for _ in domain_violations], + } + + if sol_type == "gurobi": + x_T, x_D, y_T, y_D, y_C, a = reconstruct_variables_gurobi(instance, solution) + else: + x_T, x_D, y_T, y_D, y_C, a = reconstruct_variables_efficient(instance, solution) + + customers = list(range(1, n + 1)) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def x_T_val(i, j): + return x_T.get((i, j), 0) + + def x_D_val(i, j): + return x_D.get((i, j), 0) + + def a_val(node): + if node == "0prime": + return a.get("0prime", 0) + return a.get(node, 0) + + # Big-M + total_truck = sum(sum(row) for row in truck_times) + M = total_truck + + # ------------------------------------------------------------------ + # Constraint 1 (1b): Truck flow conservation + # sum_{(i,j) in A} x^T_{ij} = sum_{(j,i) in A} x^T_{ji} for all i in N + # ------------------------------------------------------------------ + for i in customers: + out_flow = sum(x_T_val(i, j) for j in customers if j != i) + x_T_val(i, 0) + in_flow = x_T_val(0, i) + sum(x_T_val(j, i) for j in customers if j != i) + diff = abs(out_flow - in_flow) + if diff > TOL: + violated_constraints.add(1) + add_violation(violations, violation_magnitudes, 1, + f"Truck flow conservation violated at customer {i}: " + f"out_flow={out_flow}, in_flow={in_flow}", + out_flow, in_flow, diff) + + # ------------------------------------------------------------------ + # Constraint 2 (1c): Truck arc-customer linking + # sum_{(i,j) in A} x^T_{ij} = y^T_i + y^C_i for all i in N + # ------------------------------------------------------------------ + for i in customers: + out_flow = sum(x_T_val(i, j) for j in customers if j != i) + x_T_val(i, 0) + rhs_val = y_T.get(i, 0) + y_C.get(i, 0) + diff = abs(out_flow - rhs_val) + if diff > TOL: + violated_constraints.add(2) + add_violation(violations, violation_magnitudes, 2, + f"Truck arc-customer linking violated at customer {i}: " + f"out_flow={out_flow}, y^T+y^C={rhs_val}", + out_flow, rhs_val, diff) + + # ------------------------------------------------------------------ + # Constraint 3 (1d): Truck leaves and returns to depot exactly once + # ------------------------------------------------------------------ + truck_out_depot = sum(x_T_val(0, j) for j in customers) + if abs(truck_out_depot - 1) > TOL: + violated_constraints.add(3) + add_violation(violations, violation_magnitudes, 3, + f"Truck does not leave depot exactly once: " + f"sum x^T_{{0j}} = {truck_out_depot}", + truck_out_depot, 1.0, abs(truck_out_depot - 1)) + + truck_in_depot = sum(x_T_val(i, 0) for i in customers) + if abs(truck_in_depot - 1) > TOL: + violated_constraints.add(3) + add_violation(violations, violation_magnitudes, 3, + f"Truck does not return to depot exactly once: " + f"sum x^T_{{i0'}} = {truck_in_depot}", + truck_in_depot, 1.0, abs(truck_in_depot - 1)) + + # ------------------------------------------------------------------ + # Constraint 4 (1e): Drone flow conservation + # ------------------------------------------------------------------ + for i in customers: + out_flow = sum(x_D_val(i, j) for j in customers if j != i) + x_D_val(i, 0) + in_flow = x_D_val(0, i) + sum(x_D_val(j, i) for j in customers if j != i) + diff = abs(out_flow - in_flow) + if diff > TOL: + violated_constraints.add(4) + add_violation(violations, violation_magnitudes, 4, + f"Drone flow conservation violated at customer {i}: " + f"out_flow={out_flow}, in_flow={in_flow}", + out_flow, in_flow, diff) + + # ------------------------------------------------------------------ + # Constraint 5 (1f): Drone arc-customer linking + # ------------------------------------------------------------------ + for i in customers: + out_flow = sum(x_D_val(i, j) for j in customers if j != i) + x_D_val(i, 0) + rhs_val = y_D.get(i, 0) + y_C.get(i, 0) + diff = abs(out_flow - rhs_val) + if diff > TOL: + violated_constraints.add(5) + add_violation(violations, violation_magnitudes, 5, + f"Drone arc-customer linking violated at customer {i}: " + f"out_flow={out_flow}, y^D+y^C={rhs_val}", + out_flow, rhs_val, diff) + + # ------------------------------------------------------------------ + # Constraint 6 (1g): Drone leaves and returns to depot exactly once + # ------------------------------------------------------------------ + drone_out_depot = sum(x_D_val(0, j) for j in customers) + if abs(drone_out_depot - 1) > TOL: + violated_constraints.add(6) + add_violation(violations, violation_magnitudes, 6, + f"Drone does not leave depot exactly once: " + f"sum x^D_{{0j}} = {drone_out_depot}", + drone_out_depot, 1.0, abs(drone_out_depot - 1)) + + drone_in_depot = sum(x_D_val(i, 0) for i in customers) + if abs(drone_in_depot - 1) > TOL: + violated_constraints.add(6) + add_violation(violations, violation_magnitudes, 6, + f"Drone does not return to depot exactly once: " + f"sum x^D_{{i0'}} = {drone_in_depot}", + drone_in_depot, 1.0, abs(drone_in_depot - 1)) + + # ------------------------------------------------------------------ + # Constraint 7 (1h): Each customer visited exactly once + # ------------------------------------------------------------------ + for i in customers: + total = y_T.get(i, 0) + y_D.get(i, 0) + y_C.get(i, 0) + diff = abs(total - 1) + if diff > TOL: + violated_constraints.add(7) + add_violation(violations, violation_magnitudes, 7, + f"Customer {i} not visited exactly once: " + f"y^T+y^D+y^C={total}", + total, 1.0, diff) + + # ------------------------------------------------------------------ + # Constraint 8 (1i): Truck arrival time / subtour elimination + # a_i + t^T_{ij} <= a_j + M(1 - x^T_{ij}) for all (i,j) in A + # ------------------------------------------------------------------ + for (i, j), val in x_T.items(): + if val < 0.5: + continue + ai = a_val(i) + aj = a_val("0prime") if j == 0 else a_val(j) + t_ij = truck_times[i][j] + lhs = ai + t_ij + rhs_val = aj + M * (1 - val) + excess = lhs - rhs_val + if excess > TOL: + violated_constraints.add(8) + j_label = "0'" if j == 0 else str(j) + add_violation(violations, violation_magnitudes, 8, + f"Truck subtour/timing on arc ({i},{j_label}): " + f"a[{i}]={ai} + t^T={t_ij} = {lhs} > a[{j_label}]={aj}", + lhs, rhs_val, excess) + + # ------------------------------------------------------------------ + # Constraint 9 (1j): Drone arrival time / subtour elimination + # a_i + t^D_{ij} <= a_j + M(1 - x^D_{ij}) for all (i,j) in A + # ------------------------------------------------------------------ + for (i, j), val in x_D.items(): + if val < 0.5: + continue + ai = a_val(i) + aj = a_val("0prime") if j == 0 else a_val(j) + t_ij = drone_times[i][j] + lhs = ai + t_ij + rhs_val = aj + M * (1 - val) + excess = lhs - rhs_val + if excess > TOL: + violated_constraints.add(9) + j_label = "0'" if j == 0 else str(j) + add_violation(violations, violation_magnitudes, 9, + f"Drone subtour/timing on arc ({i},{j_label}): " + f"a[{i}]={ai} + t^D={t_ij} = {lhs} > a[{j_label}]={aj}", + lhs, rhs_val, excess) + + # ------------------------------------------------------------------ + # Constraint 10 (1k): Drone leg single drone customer + # x^D_{ij} + x^D_{ji} <= y^C_i + y^C_j for all i,j in N, i < j + # ------------------------------------------------------------------ + for i in customers: + for j in customers: + if i >= j: + continue + lhs = x_D_val(i, j) + x_D_val(j, i) + rhs_val = y_C.get(i, 0) + y_C.get(j, 0) + excess = lhs - rhs_val + if excess > TOL: + violated_constraints.add(10) + add_violation(violations, violation_magnitudes, 10, + f"Drone leg constraint violated for ({i},{j}): " + f"x^D_ij+x^D_ji={lhs} > y^C_i+y^C_j={rhs_val}", + lhs, rhs_val, excess) + + # ------------------------------------------------------------------ + # Constraint 11 (1l): No loops rooted at depot + # x^D_{0i} + x^D_{i0'} <= 1 for all i in N + # ------------------------------------------------------------------ + for i in customers: + lhs = x_D_val(0, i) + x_D_val(i, 0) + if lhs - 1 > TOL: + violated_constraints.add(11) + add_violation(violations, violation_magnitudes, 11, + f"Drone depot loop for customer {i}: " + f"x^D_{{0,{i}}} + x^D_{{{i},0'}} = {lhs} > 1", + lhs, 1.0, lhs - 1) + + # ------------------------------------------------------------------ + # Constraint 12 (1m): Binary domain x^T, x^D + # ------------------------------------------------------------------ + for (i, j), val in x_T.items(): + if not _is_binary(val): + violated_constraints.add(12) + add_violation(violations, violation_magnitudes, 12, + f"x^T_{{{i},{j}}} = {val} not binary", + val, round(val), abs(val - round(val))) + for (i, j), val in x_D.items(): + if not _is_binary(val): + violated_constraints.add(12) + add_violation(violations, violation_magnitudes, 12, + f"x^D_{{{i},{j}}} = {val} not binary", + val, round(val), abs(val - round(val))) + + # ------------------------------------------------------------------ + # Constraint 13 (1n): Binary domain y^T, y^D, y^C + # ------------------------------------------------------------------ + for i in customers: + for label, ydict in [("y^T", y_T), ("y^D", y_D), ("y^C", y_C)]: + val = ydict.get(i, 0) + if not _is_binary(val): + violated_constraints.add(13) + add_violation(violations, violation_magnitudes, 13, + f"{label}_{i} = {val} not binary", + val, round(val), abs(val - round(val))) + + # ------------------------------------------------------------------ + # Constraint 14 (1o): Non-negative arrival times + # a_i >= 0 for all i in V + # ------------------------------------------------------------------ + for node, val in a.items(): + if isinstance(val, (int, float)) and val < -TOL: + violated_constraints.add(14) + node_label = "0'" if node == "0prime" else str(node) + add_violation(violations, violation_magnitudes, 14, + f"Arrival time a[{node_label}] = {val} < 0", + val, 0.0, abs(val)) + + # ------------------------------------------------------------------ + # Constraint 15: Objective consistency (Tier C anti-exploit) + # Reported objective_value must equal the tour-completion time + # a_{0'} recomputed from the truck/drone routes and the instance + # travel times, with truck and drone synchronised at the depot and + # at every combined customer. The recompute is exact when the two + # routes share a common sync-point sequence; if not, the routes are + # already infeasible under the other constraints and we skip this + # check (no false positives). + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value") + true_obj = _recompute_a_0prime(instance, solution) + if true_obj is not None and reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor; travel + # times are integers so an honest solution matches exactly + # modulo Gurobi's float-arithmetic noise. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(15) + add_violation( + violations, violation_magnitudes, 15, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed a_{{0'}}={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={tol:.3g})", + reported, true_obj, abs_diff, + ) + + violated_list = sorted(violated_constraints) + feasible = len(violated_list) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_list, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for TSP-D (Roberti & Ruthmair, 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_instance(args.instance_path) + solution = load_solution(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + 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}") + + +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/roberti2021/gurobi_code.py b/tasks/roberti2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5efd559cb643f27483a5868cdad75cbfe62817 --- /dev/null +++ b/tasks/roberti2021/gurobi_code.py @@ -0,0 +1,450 @@ +""" +Compact MILP formulation for the Traveling Salesman Problem with Drone (TSP-D). + +Implements formulation (1a)-(1o) plus valid inequalities from Section 3.1.1 of: + Roberti & Ruthmair (2021), "Exact Methods for the Traveling Salesman Problem + with Drone", Transportation Science, 55(2):315-335. + +Solver: Gurobi (matching CPLEX settings from paper: single thread, IntFeasTol=1e-10, + time limit 3600s). + +Usage: + python gurobi_code.py --instance_path instance_1.json --solution_path solution_1.json +""" + +import argparse +import json +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path: str) -> dict: + """Load a TSP-D instance from a JSON file.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def build_and_solve(data: dict, time_limit: int = 3600) -> dict: + """ + Build and solve the compact MILP formulation for TSP-D. + + Node indexing convention: + - Node 0 : depot origin + - Nodes 1..n : customers (set N) + - Node n+1 : depot destination (0' in the paper) + + Arc set A: + {(0, j) | j in N} U {(i, j) | i, j in N, i != j} U {(i, 0') | i in N} + + Travel time lookups for arcs involving 0' use row/column 0 of the matrices, + since 0' is the same physical location as the depot. + """ + n = data["num_customers"] + customers = list(range(1, n + 1)) # N = {1, ..., n} + depot_origin = 0 + depot_dest = n + 1 # virtual node 0' + + truck_times = data["truck_travel_times"] # (n+1) x (n+1), indexed 0..n + drone_times = data["drone_travel_times"] # (n+1) x (n+1), indexed 0..n + + # Helper: map model node to matrix index (0' -> 0, all others unchanged) + def mx(node): + return 0 if node == depot_dest else node + + # ------------------------------------------------------------------ + # Build arc set A + # ------------------------------------------------------------------ + arcs = [] + # Arcs from depot origin to each customer + for j in customers: + arcs.append((depot_origin, j)) + # Arcs between customers + for i in customers: + for j in customers: + if i != j: + arcs.append((i, j)) + # Arcs from each customer to depot destination + for i in customers: + arcs.append((i, depot_dest)) + + # Precompute travel times on arcs + t_T = {(i, j): truck_times[mx(i)][mx(j)] for (i, j) in arcs} + t_D = {(i, j): drone_times[mx(i)][mx(j)] for (i, j) in arcs} + + # Big-M: sum of all truck travel times (safe upper bound on makespan). + # ASSUMPTION (not specified in paper): M = sum of all entries in truck + # travel time matrix. + big_M = sum(truck_times[i][j] for i in range(n + 1) for j in range(n + 1)) + + # All nodes in V = {0, 1, ..., n, n+1} + all_nodes = [depot_origin] + customers + [depot_dest] + + # ------------------------------------------------------------------ + # Build Gurobi model + # ------------------------------------------------------------------ + model = gp.Model("TSP-D") + + # Solver settings (matching paper's CPLEX configuration) + model.setParam("TimeLimit", time_limit) + model.setParam("Threads", 1) + model.setParam("IntFeasTol", 1e-9) + # Suppress Gurobi output for cleaner console; remove for debugging + model.setParam("OutputFlag", 1) + + # ------------------------------------------------------------------ + # Decision variables + # ------------------------------------------------------------------ + # x^T_{ij}: truck traverses arc (i,j) + x_T = model.addVars(arcs, vtype=GRB.BINARY, name="xT") + # x^D_{ij}: drone traverses arc (i,j) + x_D = model.addVars(arcs, vtype=GRB.BINARY, name="xD") + # y^T_i: customer i is a truck customer + y_T = model.addVars(customers, vtype=GRB.BINARY, name="yT") + # y^D_i: customer i is a drone customer + y_D = model.addVars(customers, vtype=GRB.BINARY, name="yD") + # y^C_i: customer i is a combined customer + y_C = model.addVars(customers, vtype=GRB.BINARY, name="yC") + # a_i: arrival time at node i + a = model.addVars(all_nodes, vtype=GRB.CONTINUOUS, lb=0.0, name="a") + + # ------------------------------------------------------------------ + # Objective (1a): minimize a_{0'} (completion time) + # ------------------------------------------------------------------ + model.setObjective(a[depot_dest], GRB.MINIMIZE) + + # ------------------------------------------------------------------ + # Constraint (1b): Truck flow conservation for each customer + # sum_{(i,j) in A} x^T_{ij} = sum_{(j,i) in A} x^T_{ji} for all i in N + # ------------------------------------------------------------------ + for i in customers: + out_arcs = [(i, j) for (ii, j) in arcs if ii == i] + in_arcs = [(j, i) for (j, ii) in arcs if ii == i] + model.addConstr( + gp.quicksum(x_T[a_] for a_ in out_arcs) == + gp.quicksum(x_T[a_] for a_ in in_arcs), + name=f"truck_flow_{i}" + ) + + # ------------------------------------------------------------------ + # Constraint (1c): Truck arc-customer linking + # sum_{(i,j) in A} x^T_{ij} = y^T_i + y^C_i for all i in N + # ------------------------------------------------------------------ + for i in customers: + out_arcs = [(i, j) for (ii, j) in arcs if ii == i] + model.addConstr( + gp.quicksum(x_T[a_] for a_ in out_arcs) == y_T[i] + y_C[i], + name=f"truck_link_{i}" + ) + + # ------------------------------------------------------------------ + # Constraint (1d): Truck leaves and returns to depot exactly once + # sum_{(0,j) in A} x^T_{0j} = 1 + # sum_{(i,0') in A} x^T_{i0'} = 1 + # ------------------------------------------------------------------ + depot_out_arcs = [(depot_origin, j) for j in customers] + depot_in_arcs = [(i, depot_dest) for i in customers] + model.addConstr( + gp.quicksum(x_T[a_] for a_ in depot_out_arcs) == 1, + name="truck_leave_depot" + ) + model.addConstr( + gp.quicksum(x_T[a_] for a_ in depot_in_arcs) == 1, + name="truck_return_depot" + ) + + # ------------------------------------------------------------------ + # Constraint (1e): Drone flow conservation for each customer + # sum_{(i,j) in A} x^D_{ij} = sum_{(j,i) in A} x^D_{ji} for all i in N + # ------------------------------------------------------------------ + for i in customers: + out_arcs = [(i, j) for (ii, j) in arcs if ii == i] + in_arcs = [(j, i) for (j, ii) in arcs if ii == i] + model.addConstr( + gp.quicksum(x_D[a_] for a_ in out_arcs) == + gp.quicksum(x_D[a_] for a_ in in_arcs), + name=f"drone_flow_{i}" + ) + + # ------------------------------------------------------------------ + # Constraint (1f): Drone arc-customer linking + # sum_{(i,j) in A} x^D_{ij} = y^D_i + y^C_i for all i in N + # ------------------------------------------------------------------ + for i in customers: + out_arcs = [(i, j) for (ii, j) in arcs if ii == i] + model.addConstr( + gp.quicksum(x_D[a_] for a_ in out_arcs) == y_D[i] + y_C[i], + name=f"drone_link_{i}" + ) + + # ------------------------------------------------------------------ + # Constraint (1g): Drone leaves and returns to depot exactly once + # sum_{(0,j) in A} x^D_{0j} = 1 + # sum_{(i,0') in A} x^D_{i0'} = 1 + # ------------------------------------------------------------------ + model.addConstr( + gp.quicksum(x_D[a_] for a_ in depot_out_arcs) == 1, + name="drone_leave_depot" + ) + model.addConstr( + gp.quicksum(x_D[a_] for a_ in depot_in_arcs) == 1, + name="drone_return_depot" + ) + + # ------------------------------------------------------------------ + # Constraint (1h): Each customer visited exactly once + # y^T_i + y^D_i + y^C_i = 1 for all i in N + # ------------------------------------------------------------------ + for i in customers: + model.addConstr( + y_T[i] + y_D[i] + y_C[i] == 1, + name=f"visit_once_{i}" + ) + + # ------------------------------------------------------------------ + # Constraint (1i): Truck arrival time / subtour elimination + # a_i + t^T_{ij} <= a_j + M(1 - x^T_{ij}) for all (i,j) in A + # ------------------------------------------------------------------ + for (i, j) in arcs: + model.addConstr( + a[i] + t_T[i, j] <= a[j] + big_M * (1 - x_T[i, j]), + name=f"truck_time_{i}_{j}" + ) + + # ------------------------------------------------------------------ + # Constraint (1j): Drone arrival time / subtour elimination + # a_i + t^D_{ij} <= a_j + M(1 - x^D_{ij}) for all (i,j) in A + # ------------------------------------------------------------------ + for (i, j) in arcs: + model.addConstr( + a[i] + t_D[i, j] <= a[j] + big_M * (1 - x_D[i, j]), + name=f"drone_time_{i}_{j}" + ) + + # ------------------------------------------------------------------ + # Constraint (1k): Drone leg = single drone customer + # x^D_{ij} + x^D_{ji} <= y^C_i + y^C_j for all i,j in N: i < j + # ------------------------------------------------------------------ + for i in customers: + for j in customers: + if i < j: + model.addConstr( + x_D[i, j] + x_D[j, i] <= y_C[i] + y_C[j], + name=f"drone_leg_{i}_{j}" + ) + + # ------------------------------------------------------------------ + # Constraint (1l): No depot loops for drone + # x^D_{0,i} + x^D_{i,0'} <= 1 for all i in N + # ------------------------------------------------------------------ + for i in customers: + model.addConstr( + x_D[depot_origin, i] + x_D[i, depot_dest] <= 1, + name=f"no_depot_loop_{i}" + ) + + # ------------------------------------------------------------------ + # Fix depot origin arrival time: a_0 = 0 + # ------------------------------------------------------------------ + model.addConstr(a[depot_origin] == 0, name="depot_start") + + # ------------------------------------------------------------------ + # Valid Inequalities (Section 3.1.1) + # ------------------------------------------------------------------ + # sum_{(i,j) in A} t^T_{ij} * x^T_{ij} <= a_{0'} + model.addConstr( + gp.quicksum(t_T[i, j] * x_T[i, j] for (i, j) in arcs) <= a[depot_dest], + name="valid_ineq_truck" + ) + # sum_{(i,j) in A} t^D_{ij} * x^D_{ij} <= a_{0'} + model.addConstr( + gp.quicksum(t_D[i, j] * x_D[i, j] for (i, j) in arcs) <= a[depot_dest], + name="valid_ineq_drone" + ) + + # ------------------------------------------------------------------ + # Solve + # ------------------------------------------------------------------ + model.optimize() + + # ------------------------------------------------------------------ + # Extract solution + # ------------------------------------------------------------------ + result = { + "solver": "Gurobi", + "status": model.Status, + "status_name": _status_name(model.Status), + "objective_value": None, + "best_bound": None, + "mip_gap": None, + "solve_time_seconds": model.Runtime, + "truck_route": [], + "drone_route": [], + "customer_types": {}, + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["mip_gap"] = model.MIPGap + + # Extract truck route + truck_route = _extract_route(x_T, arcs, depot_origin, depot_dest, n) + result["truck_route"] = truck_route + + # Extract drone route + drone_route = _extract_route(x_D, arcs, depot_origin, depot_dest, n) + result["drone_route"] = drone_route + + # Extract customer types + for i in customers: + if y_T[i].X > 0.5: + result["customer_types"][str(i)] = "truck" + elif y_D[i].X > 0.5: + result["customer_types"][str(i)] = "drone" + elif y_C[i].X > 0.5: + result["customer_types"][str(i)] = "combined" + + # Report arrival times for debugging / verification + arrival_times = {} + for node in all_nodes: + arrival_times[str(node)] = a[node].X + result["arrival_times"] = arrival_times + + return result + + +def _extract_route(x_vars, arcs, depot_origin, depot_dest, n): + """ + Extract an ordered route from binary arc variables. + + Returns a list of node ids from depot_origin to depot_dest. + The depot destination (n+1) is mapped back to 0 in the output + to represent the return to the physical depot. + """ + # Build adjacency from selected arcs + successors = {} + for (i, j) in arcs: + if x_vars[i, j].X > 0.5: + successors[i] = j + + # Trace route from depot_origin + route = [0] # start at depot (physical node 0) + current = depot_origin + visited = set() + visited.add(current) + max_steps = n + 2 # safety bound + + for _ in range(max_steps): + if current not in successors: + break + nxt = successors[current] + if nxt == depot_dest: + route.append(0) # return to depot (physical node 0) + break + if nxt in visited: + # Should not happen in a valid solution; break to avoid loop + break + visited.add(nxt) + route.append(nxt) + current = nxt + + return route + + +def _status_name(status_code): + """Map Gurobi status code to human-readable name.""" + status_map = { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.CUTOFF: "CUTOFF", + GRB.ITERATION_LIMIT: "ITERATION_LIMIT", + GRB.NODE_LIMIT: "NODE_LIMIT", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SOLUTION_LIMIT: "SOLUTION_LIMIT", + GRB.INTERRUPTED: "INTERRUPTED", + GRB.NUMERIC: "NUMERIC", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + GRB.LOADED: "LOADED", + } + return status_map.get(status_code, f"UNKNOWN_{status_code}") + + +def main(): + parser = argparse.ArgumentParser( + description="Solve TSP-D using compact MILP formulation with Gurobi." + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the input instance JSON file.", + ) + parser.add_argument( + "--solution_path", + type=str, + required=True, + help="Path to write the output solution JSON file.", + ) + parser.add_argument( + "--time_limit", + type=int, + default=3600, + help="Maximum solver runtime in seconds.", + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # Load instance + data = load_instance(args.instance_path) + print(f"Loaded instance: {data.get('problem_name', 'TSP-D')} with " + f"{data['num_customers']} customers") + + # Solve + result = build_and_solve(data, args.time_limit) + + # Print summary + print("\n" + "=" * 60) + print("SOLUTION SUMMARY") + print("=" * 60) + print(f"Status: {result['status_name']}") + print(f"Objective value: {result['objective_value']}") + print(f"Best bound: {result['best_bound']}") + print(f"MIP gap: {result['mip_gap']}") + print(f"Solve time (s): {result['solve_time_seconds']:.2f}") + if result["truck_route"]: + print(f"Truck route: {result['truck_route']}") + if result["drone_route"]: + print(f"Drone route: {result['drone_route']}") + if result["customer_types"]: + print(f"Customer types: {result['customer_types']}") + print("=" * 60) + + # Write solution to file + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + print(f"\nSolution written to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/roberti2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/roberti2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2021/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/roberti2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/roberti2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2021/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/roberti2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/roberti2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2021/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/roberti2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/roberti2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2021/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/roberti2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/roberti2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2021/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/roberti2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/roberti2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roberti2021/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/roberti2021/gurobi_solution/large_solution_1.json b/tasks/roberti2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a914a819c7fe0e975a1ff17b2853b428b1105dd0 --- /dev/null +++ b/tasks/roberti2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44ead174c6aa0ce651c3e984e5bd67725409d4e99368b6d8554cae96c77aee30 +size 1179 diff --git a/tasks/roberti2021/gurobi_solution/large_solution_2.json b/tasks/roberti2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..19c9f90b271ee2975a9d3b31420079ce06d65652 --- /dev/null +++ b/tasks/roberti2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b54a5622c0f1ec7fcd05cbf95d9550e004330643598f5e66c472e69632abbc6a +size 1039 diff --git a/tasks/roberti2021/gurobi_solution/large_solution_3.json b/tasks/roberti2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8fcda054cea8d8c2b64dfa491374ce322c45dbca --- /dev/null +++ b/tasks/roberti2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97492c3c545c681368abcac91953e1e3d0d44364704eac82ac7edcc4ab25c91c +size 1001 diff --git a/tasks/roberti2021/gurobi_solution/large_solution_4.json b/tasks/roberti2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a9c8101330658401db3bcc9c1d92b71e6056dd37 --- /dev/null +++ b/tasks/roberti2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2304ba5b5ae5b30db738ac83598beda75a28b90fc5202e3c01be5eb5483ec6d +size 1029 diff --git a/tasks/roberti2021/gurobi_solution/large_solution_5.json b/tasks/roberti2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9be360561f22426b8ba9a76fae00d4a3fa80589e --- /dev/null +++ b/tasks/roberti2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84f035ab86710bc15498051aae0ddb5e49ec40c1830c7082658db48ed3d24630 +size 992 diff --git a/tasks/roberti2021/gurobi_solution/tiny_solution.json b/tasks/roberti2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..f71318fe1e51788f07c031bf7c84b0f121d019fb --- /dev/null +++ b/tasks/roberti2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b2ada8eb96c92ed452b55bee36df782269d8d9efafae779a22a9caab5671acd +size 563 diff --git a/tasks/roberti2021/gurobi_solution_log/large_log_1.jsonl b/tasks/roberti2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8fb77359aa769da5229621962f9394c284274382 --- /dev/null +++ b/tasks/roberti2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c33581653ce920cf4042c38bced286bfc20b83efefa17775c899f5c76f996a9 +size 1099 diff --git a/tasks/roberti2021/gurobi_solution_log/large_log_2.jsonl b/tasks/roberti2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..67195c662a2d0d54af8eeb2ca2430a224990816b --- /dev/null +++ b/tasks/roberti2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d67629a4ebb8695accf55677c5e7ad69d764e25cab40c1141cfb59d4fd27fc3 +size 804 diff --git a/tasks/roberti2021/gurobi_solution_log/large_log_3.jsonl b/tasks/roberti2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b721068f3f0e9aed3969922b50ed6a8c2d512b2a --- /dev/null +++ b/tasks/roberti2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ec66fe9112ac9adb51ec6b39b5a7cbe0c23f29081236c12b74eb2ce8eb6cf0b +size 456 diff --git a/tasks/roberti2021/gurobi_solution_log/large_log_4.jsonl b/tasks/roberti2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cf8ec45a69680a731d42f77795c3a8cf0851563b --- /dev/null +++ b/tasks/roberti2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8388499b8d20d3d15606446c1b69e91904863ee32802ec8d0e8f33df24a0dc8 +size 1411 diff --git a/tasks/roberti2021/gurobi_solution_log/large_log_5.jsonl b/tasks/roberti2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c38d444f55aba7b84efcbe8d048cc8f52515ca5c --- /dev/null +++ b/tasks/roberti2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40c01e59b179a7443d96a1ac878e3615bdfa042700b57bcc2fffb866b19d62de +size 1190 diff --git a/tasks/roberti2021/gurobi_solution_log/tiny_log.jsonl b/tasks/roberti2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..60cf4f4971ab3d877ae1fa29023c3dabe937e4b5 --- /dev/null +++ b/tasks/roberti2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8ed3a0308397beef565942bc9ac0fcab69c9daf47269d9091a3197b4748a308 +size 42 diff --git a/tasks/roberti2021/instance/large_instance_1.json b/tasks/roberti2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6e5fd174c4b15d0598da6e23525ecbd76cb82960 --- /dev/null +++ b/tasks/roberti2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0107b9350059f29c6ddd426dd5f00a79d7bdd0bd65bfc1c53e65a26c1a78878 +size 14628 diff --git a/tasks/roberti2021/instance/large_instance_2.json b/tasks/roberti2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4a495f03c05a8fe037cd5f5c0ec97367049a1f40 --- /dev/null +++ b/tasks/roberti2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf8fc6a7a7a39e2cad8e2f0ad162307f9d94a8926449ecd45da2cbf265fbf4af +size 15237 diff --git a/tasks/roberti2021/instance/large_instance_3.json b/tasks/roberti2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..abd965cd01cdcc1a7b2c13873c3873ba01a27d16 --- /dev/null +++ b/tasks/roberti2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2ef9fe311559d9390e83c088b0b1af436ac471ee7481ba49690f34bed7eeb5c +size 14900 diff --git a/tasks/roberti2021/instance/large_instance_4.json b/tasks/roberti2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..3f45957206ad0ddbf5ea7434a2547b7f0be1ab81 --- /dev/null +++ b/tasks/roberti2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f5e52b8d0c5af40c827121bfc56b692bea15a1118ed5725934611f895cf4efa +size 14850 diff --git a/tasks/roberti2021/instance/large_instance_5.json b/tasks/roberti2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..28e55fde8ad21a92ed3206a3f7950ed8fcd2b9ac --- /dev/null +++ b/tasks/roberti2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02483b84a1014d485d3454f196ea95455f30aab50119b95b9391a67214bea650 +size 14227 diff --git a/tasks/roberti2021/instance/tiny_instance.json b/tasks/roberti2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..0c8807c15b27402d6891e54dfe202baf16a52752 --- /dev/null +++ b/tasks/roberti2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86e088af55484d6172ae32db44d245624be0243025a86e7ee3f09cdbdccbda4a +size 1805 diff --git a/tasks/roberti2021/instance_schema.json b/tasks/roberti2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..37bb61052fc184673b61a8f0318e9e8912a3b83b --- /dev/null +++ b/tasks/roberti2021/instance_schema.json @@ -0,0 +1,15 @@ +{ + "num_customers": " Number of customers to be served by the truck-drone team.", + "num_nodes": " Total number of locations including the depot and all customers.", + "alpha": " Drone speed multiplier relative to the truck, used to scale Euclidean distances for drone travel times.", + "nodes": [ + { + "id": " Unique identifier for this location, where 0 is the depot and 1 through num_customers are customers.", + "label": " Human-readable name for this location.", + "x": " Horizontal coordinate of this location on the grid.", + "y": " Vertical coordinate of this location on the grid." + } + ], + "truck_travel_times": " Travel time for the truck between each pair of locations using the Manhattan distance metric.", + "drone_travel_times": " Travel time for the drone between each pair of locations using the Euclidean distance scaled by the drone speed factor." +} diff --git a/tasks/roberti2021/mathematical_formulation.md b/tasks/roberti2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..c32c3fc8d55dcbe0ab060ed69646066be20a7c1f --- /dev/null +++ b/tasks/roberti2021/mathematical_formulation.md @@ -0,0 +1,75 @@ +# Original Formulation: Traveling Salesman Problem with Drone (TSP-D) + +*Source: Exact Methods for the Traveling Salesman Problem with Drone, Roberto Roberti and Mario Ruthmair, Transportation Science, 55(2):315–335, 2021.* + +## Sets and Indices + +- $V = \{0, 0'\} \cup N$ : vertex set of the complete directed graph $\mathcal{G} = (V, \mathcal{A})$; both $0$ and $0'$ represent the single depot ($0$ origin, $0'$ destination). + +- $N$ : set of $n$ customers to be served, with $n = |N| \geq 2$. + +- $N_0 = N \cup \{0\}$, $N'_0 = N \cup \{0'\}$. + +- $\mathcal{A} = \{(0,j)\mid j \in N\} \cup \{(i,j)\mid i,j \in N : i \neq j\} \cup \{(i,0')\mid i \in N\}$ : arc set. + +## Parameters + +- $t^T_{ij}$ : time for the truck to traverse arc $(i,j) \in \mathcal{A}$. + +- $t^D_{ij}$ : time for the drone to traverse arc $(i,j) \in \mathcal{A}$. (In general $t^D_{ij} \leq t^T_{ij}$, but this is not required by the model.) + +- $M$ : a sufficiently large constant (big-M). + +## Decision Variables + +- $x^T_{ij} \in \{0,1\}$ : $1$ if the truck traverses arc $(i,j) \in \mathcal{A}$ (regardless of whether the drone is on-board or airborne). + +- $x^D_{ij} \in \{0,1\}$ : $1$ if the drone traverses arc $(i,j) \in \mathcal{A}$ (regardless of whether it is on-board or airborne). + +- $y^T_i \in \{0,1\}$ : $1$ if customer $i \in N$ is a truck customer. + +- $y^D_i \in \{0,1\}$ : $1$ if customer $i \in N$ is a drone customer. + +- $y^C_i \in \{0,1\}$ : $1$ if customer $i \in N$ is a combined customer. + +- $a_i \in \mathbb{R}_+$ : arrival time of the truck or the drone (or both) at node $i \in V$. + +## Objective + +$$\begin{align} +t^* = \min \quad & a_{0'} \tag{1a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.}\quad +& \sum_{(i,j) \in \mathcal{A}} x^T_{ij} = \sum_{(j,i) \in \mathcal{A}} x^T_{ji} + && \forall\, i \in N, \tag{1b}\\ +& \sum_{(i,j) \in \mathcal{A}} x^T_{ij} = y^T_i + y^C_i + && \forall\, i \in N, \tag{1c}\\ +& \sum_{(0,j) \in \mathcal{A}} x^T_{0j} = \sum_{(i,0') \in \mathcal{A}} x^T_{i0'} = 1, + && \tag{1d}\\ +& \sum_{(i,j) \in \mathcal{A}} x^D_{ij} = \sum_{(j,i) \in \mathcal{A}} x^D_{ji} + && \forall\, i \in N, \tag{1e}\\ +& \sum_{(i,j) \in \mathcal{A}} x^D_{ij} = y^D_i + y^C_i + && \forall\, i \in N, \tag{1f}\\ +& \sum_{(0,j) \in \mathcal{A}} x^D_{0j} = \sum_{(i,0') \in \mathcal{A}} x^D_{i0'} = 1, + && \tag{1g}\\ +& y^T_i + y^D_i + y^C_i = 1 + && \forall\, i \in N, \tag{1h}\\ +& a_i + t^T_{ij} \leq a_j + M\bigl(1 - x^T_{ij}\bigr) + && \forall\, (i,j) \in \mathcal{A}, \tag{1i}\\ +& a_i + t^D_{ij} \leq a_j + M\bigl(1 - x^D_{ij}\bigr) + && \forall\, (i,j) \in \mathcal{A}, \tag{1j}\\ +& x^D_{ij} + x^D_{ji} \leq y^C_i + y^C_j + && \forall\, i,j \in N : i < j, \tag{1k}\\ +& x^D_{0i} + x^D_{i0'} \leq 1 + && \forall\, i \in N, \tag{1l}\\ +& x^T_{ij},\, x^D_{ij} \in \{0,1\} + && \forall\, (i,j) \in \mathcal{A}, \tag{1m}\\ +& y^T_i,\, y^D_i,\, y^C_i \in \{0,1\} + && \forall\, i \in N, \tag{1n}\\ +& a_i \in \mathbb{R}_+ + && \forall\, i \in V. \tag{1o} +\end{align}$$ diff --git a/tasks/roberti2021/problem_description.txt b/tasks/roberti2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd88249153ab4bba800968abdf32aa054d90ac18 --- /dev/null +++ b/tasks/roberti2021/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A single truck, equipped with a single drone, is located at a depot and must serve a set of at least two customers. The input data specifies the number of customers, the location of the depot and each customer in a two-dimensional plane, a truck travel time for every ordered pair of locations (including the depot), and a drone travel time for every ordered pair of locations. Truck travel times follow the taxicab (Manhattan) metric and drone travel times follow the Euclidean metric scaled by a speed factor, so the two time matrices are generally different, with the drone typically being faster. The network is represented as a directed graph whose nodes comprise the depot (appearing as both an origin node and a distinct destination node) and all customers. Arcs exist from the depot origin to each customer, between every ordered pair of distinct customers, and from each customer to the depot destination. No arc connects the depot origin directly to the depot destination, and no arcs lead from the depot destination to any other node or from any node back to the depot origin. + +Each customer must be served exactly once, and its service is classified into one of three types: it is served by the truck alone, by the drone alone, or by both the truck and the drone arriving together (a combined visit). The truck must depart from the depot origin exactly once and return to the depot destination exactly once, traversing a sequence of arcs through customer nodes. The drone must likewise depart from the depot origin exactly once and return to the depot destination exactly once, traversing its own sequence of arcs. At every customer node, the number of truck arcs entering that node equals the number leaving it, and independently the number of drone arcs entering that node equals the number leaving it. For the truck, the total number of arcs leaving a customer equals one if that customer is either a truck-only customer or a combined customer, and zero otherwise. Symmetrically, the total number of drone arcs leaving a customer equals one if that customer is either a drone-only customer or a combined customer, and zero otherwise. + +Each node is assigned an arrival time that is at least zero. If the truck uses an arc from one node to another, the arrival time at the arc's end node must be at least the arrival time at the arc's start node plus the truck travel time on that arc. If the drone uses an arc from one node to another, the arrival time at the arc's end node must be at least the arrival time at the arc's start node plus the drone travel time on that arc. At a combined customer, where both vehicles visit, the arrival time therefore reflects whichever vehicle arrives later. These timing requirements also prevent either vehicle from forming a closed loop that bypasses the depot, because arrival times must strictly increase along each vehicle's path. + +For any pair of distinct customers, the number of drone arcs connecting them, counting both directions, cannot exceed the number of those two customers that have combined status. This means that if the drone uses an arc between two customers in one direction, at least one of them must be a combined customer, and if the drone uses arcs between two customers in both directions, then both must be combined customers. Additionally, the drone cannot depart from the depot origin to serve a single customer and return directly to the depot destination on the same trip; that is, for any customer, the drone cannot simultaneously use the arc from the depot origin to that customer and the arc from that customer to the depot destination. + +The total tour duration equals the arrival time at the depot destination node. The goal is to determine the assignment of each customer to truck-only, drone-only, or combined status, the routing of the truck and the drone through their respective sequences of customers, and the arrival time at each node, so as to minimize the total tour completion time. diff --git a/tasks/roberti2021/solution_logger.py b/tasks/roberti2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/roberti2021/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/roberti2021/solution_schema.json b/tasks/roberti2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c174d4a6c1ee956bfa6afc1860a6df6858f25a8f --- /dev/null +++ b/tasks/roberti2021/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Total tour completion time, equal to the moment the later of the truck and drone returns to the depot.", + "truck_route": " Ordered sequence of node identifiers visited by the truck, starting at the depot and ending at the depot.", + "drone_route": " Ordered sequence of node identifiers visited by the drone, starting at the depot and ending at the depot.", + "customer_types": " Service type assigned to each customer, valued 'truck' if served by the truck alone, 'drone' if served by the drone alone, or 'combined' if both vehicles meet at that customer.", + "arrival_times": " Time at which service begins at each node, where node 0 is the depot origin, nodes 1..num_customers are the customers, and node num_customers+1 is the depot destination whose value equals the tour completion time." +} diff --git a/tasks/ropke2009/feasibility_check.py b/tasks/ropke2009/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..969c4339f44af110dc6a82e1dc1d46e49a0efa7a --- /dev/null +++ b/tasks/ropke2009/feasibility_check.py @@ -0,0 +1,688 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Pickup and Delivery Problem with Time Windows (PDPTW). + +Verifies a candidate solution against the three-index formulation from: + Ropke & Cordeau (2009), "Branch and Cut and Price for the Pickup and + Delivery Problem with Time Windows", Transportation Science 43(3):267-286. + +Constraints checked (numbered as in the paper formulation): + (2) Each request served exactly once + (3) Pickup and delivery by same vehicle + (4) Each vehicle leaves origin depot + (5) Flow conservation at P ∪ D nodes + (6) Each vehicle returns to destination depot + (7) Time consistency + (8) Load consistency + (9) Precedence (pickup before delivery) + (10) Time windows + (11) Capacity bounds + (12) Integrality of x + (13) Fleet size: len(routes) <= num_vehicles + (14) Objective consistency: reported objective_value equals the + recomputed routing cost Σ_k Σ_{i,j} c_{ij} x^k_{ij}. +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def euclidean_distance(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def build_instance_data(instance): + """Extract all needed data from the instance JSON.""" + n = instance["num_requests"] + Q = instance["vehicle_capacity"] + num_vehicles = instance["num_vehicles"] + + depot_origin = 0 + depot_dest = 2 * n + 1 + P = list(range(1, n + 1)) + D = list(range(n + 1, 2 * n + 1)) + N = list(range(2 * n + 2)) + + # Node data indexed by node id + nodes = {} + for nd in instance["nodes"]: + nodes[nd["id"]] = nd + + x_coord = {nid: nd["x"] for nid, nd in nodes.items()} + y_coord = {nid: nd["y"] for nid, nd in nodes.items()} + demand = {nid: nd["demand"] for nid, nd in nodes.items()} + service_time = {nid: nd.get("service_time", 0) for nid, nd in nodes.items()} + tw_a = {nid: nd["time_window"][0] for nid, nd in nodes.items()} + tw_b = {nid: nd["time_window"][1] for nid, nd in nodes.items()} + + # Cost and travel time matrices + # Per paper: t_{ij} includes service time d_i at node i + cost = {} + travel_time = {} + for i in N: + for j in N: + if i == j: + continue + dist = euclidean_distance(x_coord[i], y_coord[i], x_coord[j], y_coord[j]) + cost[i, j] = dist + travel_time[i, j] = dist + service_time[i] + + return { + "n": n, + "Q": Q, + "num_vehicles": num_vehicles, + "depot_origin": depot_origin, + "depot_dest": depot_dest, + "P": P, + "D": D, + "N": N, + "demand": demand, + "service_time": service_time, + "tw_a": tw_a, + "tw_b": tw_b, + "cost": cost, + "travel_time": travel_time, + } + + +def extract_solution_routes(solution, n): + """ + Extract routes from the solution JSON. Handles two formats: + - "routes" as list of lists of node ids (efficient_algorithm) + - "routes" as list of dicts with "nodes" key (gurobi) + Returns list of lists of node ids. + """ + raw_routes = solution.get("routes", []) + routes = [] + for r in raw_routes: + if isinstance(r, list): + routes.append(r) + elif isinstance(r, dict): + routes.append(r["nodes"]) + else: + routes.append(list(r)) + return routes + + +def reconstruct_variables(routes, d): + """ + From the list of routes (each a node sequence), reconstruct: + - x[k][(i,j)]: binary arc usage per vehicle k + - B[k][i]: service start time at node i for vehicle k + - Qload[k][i]: load of vehicle k upon leaving node i + + Returns (x_vars, B_vars, Qload_vars). + """ + n = d["n"] + x_vars = {} # k -> dict of (i,j) -> 1 + B_vars = {} # k -> dict of node -> time + Qload_vars = {} # k -> dict of node -> load + + for k, route in enumerate(routes): + x_k = {} + B_k = {} + Q_k = {} + + # Build arcs + for idx in range(len(route) - 1): + i, j = route[idx], route[idx + 1] + x_k[(i, j)] = 1 + + # Simulate timing and load along route + current_time = d["tw_a"][d["depot_origin"]] + current_load = 0 + + for idx, node in enumerate(route): + if idx > 0: + prev = route[idx - 1] + tt = d["travel_time"].get((prev, node), 0.0) + arrival = current_time + tt + current_time = max(arrival, d["tw_a"][node]) + else: + current_time = max(d["tw_a"][node], current_time) + + B_k[node] = current_time + current_load += d["demand"][node] + Q_k[node] = current_load + + x_vars[k] = x_k + B_vars[k] = B_k + Qload_vars[k] = Q_k + + return x_vars, B_vars, Qload_vars + + +def check_feasibility(instance, solution): + """ + Check all hard constraints of the PDPTW three-index formulation. + + Returns dict with feasibility result. + """ + tol = 1e-5 + eps = 1e-5 + + d = build_instance_data(instance) + n = d["n"] + Q = d["Q"] + num_vehicles_K = d["num_vehicles"] + depot_origin = d["depot_origin"] + depot_dest = d["depot_dest"] + P = d["P"] + D = d["D"] + N = d["N"] + + routes = extract_solution_routes(solution, n) + K_used = len(routes) + + # Pad to num_vehicles_K with empty depot-to-depot routes if fewer routes + all_routes = list(routes) + while len(all_routes) < num_vehicles_K: + all_routes.append([depot_origin, depot_dest]) + K = list(range(len(all_routes))) + + x_vars, B_vars, Qload_vars = reconstruct_variables(all_routes, d) + + violations = [] # list of message strings + violated_set = set() # set of constraint indices + violation_magnitudes = [] # list of dicts + + def record_violation(constraint_idx, message, lhs, rhs, operator): + """Record a constraint violation with normalized magnitude.""" + if operator == "eq": + violation_amount = abs(lhs - rhs) + elif operator in ("leq", "lt"): + violation_amount = max(0.0, lhs - rhs) + elif operator in ("geq", "gt"): + violation_amount = max(0.0, rhs - lhs) + else: + violation_amount = 0.0 + + if violation_amount > tol: + violated_set.add(constraint_idx) + violations.append(message) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ========================================================================= + # Fleet size bound: len(routes) <= |K| = num_vehicles + # (Implicit in the formulation: x^k_{ij} is indexed by k in K; + # the solution cannot use more vehicles than the fleet provides.) + # ========================================================================= + record_violation( + 13, + f"Fleet size: len(routes)={K_used} exceeds num_vehicles={num_vehicles_K}", + float(K_used), float(num_vehicles_K), "leq" + ) + + # ========================================================================= + # Constraint (2): Each request served exactly once + # Σ_k Σ_j x^k_{ij} = 1 ∀ i ∈ P + # ========================================================================= + for i in P: + total = 0 + for k in K: + for (a, b), val in x_vars[k].items(): + if a == i: + total += val + record_violation( + 2, + f"Constraint (2): Request {i} pickup visited {total} time(s) (expected 1)", + float(total), 1.0, "eq" + ) + + # ========================================================================= + # Constraint (3): Pickup and delivery by same vehicle + # Σ_j x^k_{ij} - Σ_j x^k_{n+i,j} = 0 ∀ i ∈ P, k ∈ K + # ========================================================================= + for i in P: + for k in K: + out_pickup = sum( + v for (a, b), v in x_vars[k].items() if a == i + ) + out_delivery = sum( + v for (a, b), v in x_vars[k].items() if a == (n + i) + ) + diff = out_pickup - out_delivery + record_violation( + 3, + f"Constraint (3): Vehicle {k}, request {i}: " + f"pickup outflow={out_pickup}, delivery outflow={out_delivery} " + f"(difference={diff}, expected 0)", + float(diff), 0.0, "eq" + ) + + # ========================================================================= + # Constraint (4): Each vehicle leaves origin depot exactly once + # Σ_j x^k_{0,j} = 1 ∀ k ∈ K + # ========================================================================= + for k in K: + out_depot = sum( + v for (a, b), v in x_vars[k].items() if a == depot_origin + ) + record_violation( + 4, + f"Constraint (4): Vehicle {k} leaves depot {out_depot} time(s) " + f"(expected 1)", + float(out_depot), 1.0, "eq" + ) + + # ========================================================================= + # Constraint (5): Flow conservation at pickup and delivery nodes + # Σ_j x^k_{ji} - Σ_j x^k_{ij} = 0 ∀ i ∈ P ∪ D, k ∈ K + # ========================================================================= + for i in (P + D): + for k in K: + inflow = sum( + v for (a, b), v in x_vars[k].items() if b == i + ) + outflow = sum( + v for (a, b), v in x_vars[k].items() if a == i + ) + diff = inflow - outflow + record_violation( + 5, + f"Constraint (5): Vehicle {k}, node {i}: " + f"inflow={inflow}, outflow={outflow} " + f"(difference={diff}, expected 0)", + float(diff), 0.0, "eq" + ) + + # ========================================================================= + # Constraint (6): Each vehicle returns to destination depot exactly once + # Σ_i x^k_{i,2n+1} = 1 ∀ k ∈ K + # ========================================================================= + for k in K: + in_depot = sum( + v for (a, b), v in x_vars[k].items() if b == depot_dest + ) + record_violation( + 6, + f"Constraint (6): Vehicle {k} enters destination depot {in_depot} " + f"time(s) (expected 1)", + float(in_depot), 1.0, "eq" + ) + + # ========================================================================= + # Constraint (7): Time consistency (linearized) + # B^k_j ≥ B^k_i + t_{ij} - M(1 - x^k_{ij}) ∀ i,j ∈ N, k ∈ K + # When x^k_{ij}=1: B^k_j ≥ B^k_i + t_{ij} + # ========================================================================= + for k in K: + for (i, j), val in x_vars[k].items(): + if val < 0.5: + continue + if i not in B_vars[k] or j not in B_vars[k]: + continue + tt = d["travel_time"].get((i, j), 0.0) + lhs = B_vars[k][j] + rhs_val = B_vars[k][i] + tt + record_violation( + 7, + f"Constraint (7): Vehicle {k}, arc ({i},{j}): " + f"B[{j}]={lhs:.4f} < B[{i}]+t_{{{i},{j}}}={rhs_val:.4f}", + rhs_val, lhs, "leq" + ) + + # ========================================================================= + # Constraint (8): Load consistency (linearized) + # Q^k_j ≥ Q^k_i + q_j - M(1 - x^k_{ij}) ∀ i,j ∈ N, k ∈ K + # When x^k_{ij}=1: Q^k_j ≥ Q^k_i + q_j + # ========================================================================= + for k in K: + for (i, j), val in x_vars[k].items(): + if val < 0.5: + continue + if i not in Qload_vars[k] or j not in Qload_vars[k]: + continue + q_j = d["demand"][j] + lhs = Qload_vars[k][j] + rhs_val = Qload_vars[k][i] + q_j + record_violation( + 8, + f"Constraint (8): Vehicle {k}, arc ({i},{j}): " + f"Q[{j}]={lhs:.4f} < Q[{i}]+q_{j}={rhs_val:.4f}", + rhs_val, lhs, "leq" + ) + + # ========================================================================= + # Constraint (9): Precedence – pickup before delivery + # B^k_i + t_{i,n+i} ≤ B^k_{n+i} ∀ i ∈ P, k ∈ K + # ========================================================================= + for i in P: + delivery = n + i + for k in K: + if i not in B_vars[k] or delivery not in B_vars[k]: + continue + tt = d["travel_time"].get((i, delivery), 0.0) + lhs = B_vars[k][i] + tt + rhs_val = B_vars[k][delivery] + record_violation( + 9, + f"Constraint (9): Vehicle {k}, request {i}: " + f"B[{i}]+t_{{{i},{delivery}}}={lhs:.4f} > B[{delivery}]={rhs_val:.4f}", + lhs, rhs_val, "leq" + ) + + # ========================================================================= + # Constraint (10): Time windows + # a_i ≤ B^k_i ≤ b_i ∀ i ∈ N, k ∈ K + # ========================================================================= + for k in K: + for node, B_val in B_vars[k].items(): + a_i = d["tw_a"][node] + b_i = d["tw_b"][node] + # Check a_i ≤ B^k_i + record_violation( + 10, + f"Constraint (10): Vehicle {k}, node {node}: " + f"B={B_val:.4f} < a={a_i:.4f} (early arrival)", + a_i, B_val, "leq" + ) + # Check B^k_i ≤ b_i + record_violation( + 10, + f"Constraint (10): Vehicle {k}, node {node}: " + f"B={B_val:.4f} > b={b_i:.4f} (late arrival)", + B_val, b_i, "leq" + ) + + # ========================================================================= + # Constraint (11): Capacity bounds + # max{0, q_i} ≤ Q^k_i ≤ min{Q, Q+q_i} ∀ i ∈ N, k ∈ K + # ========================================================================= + for k in K: + for node, Q_val in Qload_vars[k].items(): + q_i = d["demand"][node] + lb = max(0, q_i) + ub = min(Q, Q + q_i) + # Check lb ≤ Q^k_i + record_violation( + 11, + f"Constraint (11): Vehicle {k}, node {node}: " + f"Q={Q_val:.4f} < lower bound {lb:.4f}", + float(lb), float(Q_val), "leq" + ) + # Check Q^k_i ≤ ub + record_violation( + 11, + f"Constraint (11): Vehicle {k}, node {node}: " + f"Q={Q_val:.4f} > upper bound {ub:.4f}", + float(Q_val), float(ub), "leq" + ) + + # ========================================================================= + # Constraint (12): Integrality of x + # x^k_{ij} ∈ {0, 1} ∀ i,j ∈ N, k ∈ K + # (By construction from routes, x values are 0 or 1, but check anyway) + # ========================================================================= + for k in K: + for (i, j), val in x_vars[k].items(): + frac = abs(val - round(val)) + record_violation( + 12, + f"Constraint (12): Vehicle {k}, arc ({i},{j}): " + f"x={val} not binary (fractional part={frac:.6f})", + float(frac), 0.0, "leq" + ) + + # ========================================================================= + # Constraint (14): Objective consistency + # The reported objective_value must match the recomputed routing cost + # Σ_k Σ_{i,j ∈ route_k} c_{ij} + # where c_{ij} is the Euclidean distance between nodes i and j (per the + # paper's three-index objective (1) and the solution_schema description + # "Total routing distance traveled by all vehicles"). + # Sum only over user-provided routes; padded depot→depot routes contribute + # zero cost (depot_origin and depot_dest share coordinates) but are an + # artifact of constraint checking, not part of the reported solution. + # ========================================================================= + 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 route in routes: + for idx in range(len(route) - 1): + i, j = route[idx], route[idx + 1] + true_obj += d["cost"].get((i, j), 0.0) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_set.add(14) + violations.append( + f"Constraint (14): Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed Σ_k Σ_{{i,j}} c_{{ij}} x^k_{{ij}}={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 14, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + # ========================================================================= + # Compile results + # ========================================================================= + violated_constraints = sorted(violated_set) + feasible = len(violated_constraints) == 0 + + # Deduplicate violation messages per constraint index + seen_constraints_msg = {} + deduped_violations = [] + for msg in violations: + # Use the message directly; already unique per check + deduped_violations.append(msg) + + return { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": deduped_violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for PDPTW (Ropke & Cordeau 2009)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path 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" + n_violated = len(result["violated_constraints"]) + n_magnitudes = len(result["violation_magnitudes"]) + print(f"[{status}] violated_constraints={result['violated_constraints']} " + f"({n_magnitudes} violation instances)") + + +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/ropke2009/gurobi_code.py b/tasks/ropke2009/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..416d0b68810a5d28545d487d18124f1147e8a15b --- /dev/null +++ b/tasks/ropke2009/gurobi_code.py @@ -0,0 +1,409 @@ +#!/usr/bin/env python3 +""" +Gurobi MIP implementation of the Pickup and Delivery Problem with Time Windows (PDPTW). + +Three-index formulation from: + Ropke & Cordeau (2009), "Branch and Cut and Price for the Pickup and Delivery + Problem with Time Windows", Transportation Science 43(3):267-286. + +Implements constraints (1)-(12) with big-M linearization for (7)-(8). +""" + +import argparse +import json +import math +import time +import sys +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("ERROR: gurobipy is not installed. Please install Gurobi.") + sys.exit(1) + + +def euclidean_distance(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def load_instance(instance_path): + """Load a PDPTW instance from JSON.""" + with open(instance_path, "r") as f: + data = json.load(f) + return data + + +def solve_pdptw(data, time_limit): + """ + Solve the PDPTW using the three-index formulation (1)-(12). + + The objective is hierarchical: + Minimize total routing distance (paper Eq. 1: min sum c_ij * x_ij^k). + """ + n = data["num_requests"] + num_vehicles = data["num_vehicles"] + Q = data["vehicle_capacity"] + + nodes = {node["id"]: node for node in data["nodes"]} + num_nodes = 2 * n + 2 # 0, 1..n, n+1..2n, 2n+1 + + # Node indices: + # 0 = origin depot + # 1..n = pickup nodes + # n+1..2n = delivery nodes + # 2n+1 = destination depot + depot_origin = 0 + depot_dest = 2 * n + 1 + P = list(range(1, n + 1)) # pickup nodes + D = list(range(n + 1, 2 * n + 1)) # delivery nodes + N = list(range(num_nodes)) # all nodes + K = list(range(num_vehicles)) # vehicles + + # Extract node data + x_coord = {} + y_coord = {} + demand = {} + service_time = {} + tw_a = {} + tw_b = {} + + for node in data["nodes"]: + nid = node["id"] + x_coord[nid] = node["x"] + y_coord[nid] = node["y"] + demand[nid] = node["demand"] + service_time[nid] = node.get("service_time", 0) + tw_a[nid] = node["time_window"][0] + tw_b[nid] = node["time_window"][1] + + # Compute cost and travel time matrices + # Per the paper: t_{ij} includes service time d_i at node i + # c_{ij} = Euclidean distance + # For depot arcs, add fixed cost to outgoing arcs from origin depot + cost = {} + travel_time = {} + for i in N: + for j in N: + if i == j: + continue + dist = euclidean_distance(x_coord[i], y_coord[i], x_coord[j], y_coord[j]) + cost[i, j] = dist + # Travel time includes service time at node i + travel_time[i, j] = dist + service_time[i] + + # Arc elimination: remove arcs where time window is infeasible + # Arc (i,j) is infeasible if a_i + t_{ij} > b_j + A = [] + for i in N: + for j in N: + if i == j: + continue + # No arcs from destination depot + if i == depot_dest: + continue + # No arcs to origin depot + if j == depot_origin: + continue + # No arc from delivery i back to its own pickup + # (self-loop on request pair) + if i in D and j in P: + req_i = i - n + if j == req_i: + # This would be n+i -> i, which doesn't exist per paper + continue + # Time window feasibility check + if tw_a[i] + travel_time[i, j] > tw_b[j]: + continue + A.append((i, j)) + + arc_set = set(A) + + # Build model + model = gp.Model("PDPTW") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + # Focus on finding feasible solutions quickly (MIPFocus=1) + model.setParam("MIPFocus", 1) + + # Decision variables + # x[i,j,k] binary: vehicle k travels from i to j + x = {} + for (i, j) in A: + for k in K: + x[i, j, k] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}_{k}") + + # B[i,k]: time vehicle k begins service at node i + B = {} + for i in N: + for k in K: + B[i, k] = model.addVar(lb=tw_a[i], ub=tw_b[i], vtype=GRB.CONTINUOUS, + name=f"B_{i}_{k}") + + # Qvar[i,k]: load of vehicle k upon leaving node i + Qvar = {} + for i in N: + for k in K: + lb_q = max(0, demand[i]) + ub_q = min(Q, Q + demand[i]) + Qvar[i, k] = model.addVar(lb=lb_q, ub=ub_q, vtype=GRB.CONTINUOUS, + name=f"Q_{i}_{k}") + + model.update() + + # Objective (1): minimize total routing cost + model.setObjective( + gp.quicksum(cost[i, j] * x[i, j, k] for (i, j) in A for k in K), + GRB.MINIMIZE + ) + + # Constraint (2): Each request served exactly once + for i in P: + model.addConstr( + gp.quicksum(x[i, j, k] for k in K for j in N + if (i, j) in arc_set) == 1, + name=f"serve_{i}" + ) + + # Constraint (3): Pickup and delivery by same vehicle + for i in P: + for k in K: + model.addConstr( + gp.quicksum(x[i, j, k] for j in N if (i, j) in arc_set) - + gp.quicksum(x[n + i, j, k] for j in N if (n + i, j) in arc_set) == 0, + name=f"pair_{i}_{k}" + ) + + # Constraint (4): Each vehicle leaves origin depot + for k in K: + model.addConstr( + gp.quicksum(x[depot_origin, j, k] for j in N + if (depot_origin, j) in arc_set) == 1, + name=f"leave_depot_{k}" + ) + + # Constraint (5): Flow conservation at pickup and delivery nodes + for i in (P + D): + for k in K: + model.addConstr( + gp.quicksum(x[j, i, k] for j in N if (j, i) in arc_set) - + gp.quicksum(x[i, j, k] for j in N if (i, j) in arc_set) == 0, + name=f"flow_{i}_{k}" + ) + + # Constraint (6): Each vehicle returns to destination depot + for k in K: + model.addConstr( + gp.quicksum(x[i, depot_dest, k] for i in N + if (i, depot_dest) in arc_set) == 1, + name=f"return_depot_{k}" + ) + + # Constraint (7) linearized: B_j >= B_i + t_{ij} - M*(1 - x_{ij}^k) + # Big-M for time: M_{ij} = max(0, b_i + t_{ij} - a_j) + for (i, j) in A: + M_time = max(0, tw_b[i] + travel_time[i, j] - tw_a[j]) + for k in K: + model.addConstr( + B[j, k] >= B[i, k] + travel_time[i, j] - M_time * (1 - x[i, j, k]), + name=f"time_{i}_{j}_{k}" + ) + + # Constraint (8) linearized: Q_j >= Q_i + q_j - M*(1 - x_{ij}^k) + # Big-M for load: M = Q + for (i, j) in A: + for k in K: + model.addConstr( + Qvar[j, k] >= Qvar[i, k] + demand[j] - Q * (1 - x[i, j, k]), + name=f"load_{i}_{j}_{k}" + ) + + # Constraint (9): Precedence - pickup before delivery + for i in P: + for k in K: + model.addConstr( + B[i, k] + travel_time[i, n + i] <= B[n + i, k], + name=f"prec_{i}_{k}" + ) + + # Constraints (10) and (11) are handled by variable bounds + + # Symmetry breaking: vehicles are identical, so we can impose ordering + # INFERRED ASSUMPTION: Not in paper; added to help solver performance. + # This does not change the feasible solution set (just removes symmetry). + # We order by the smallest pickup node index served by each vehicle. + # Implemented as: if vehicle k doesn't serve any request, then vehicle k+1 + # doesn't either. + for k in range(len(K) - 1): + model.addConstr( + gp.quicksum(x[depot_origin, j, k] for j in P + D + if (depot_origin, j) in arc_set) >= + gp.quicksum(x[depot_origin, j, k + 1] for j in P + D + if (depot_origin, j) in arc_set), + name=f"sym_{k}" + ) + + # Provide MIP start: assign each request to its own vehicle + # This gives a trivial feasible solution (n vehicles, each serving one request) + for k_idx, req in enumerate(P): + if k_idx >= num_vehicles: + break + pickup = req + delivery = req + n + # Set the arcs for this route: depot->pickup->delivery->depot_dest + if ((depot_origin, pickup) in arc_set and + (pickup, delivery) in arc_set and + (delivery, depot_dest) in arc_set): + x[depot_origin, pickup, k_idx].Start = 1.0 + x[pickup, delivery, k_idx].Start = 1.0 + x[delivery, depot_dest, k_idx].Start = 1.0 + # Unused vehicles go directly depot_origin -> depot_dest + for k_idx in range(n, num_vehicles): + if (depot_origin, depot_dest) in arc_set: + x[depot_origin, depot_dest, k_idx].Start = 1.0 + + # Optimize + model.optimize() + + # Extract solution + result = { + "problem": "PDPTW", + "instance": data.get("instance_name", "unknown"), + "solver": "Gurobi", + "formulation": "three-index", + } + + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + result["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + result["runtime_seconds"] = model.Runtime + + # Extract routes + routes = [] + for k in K: + route = [] + current = depot_origin + visited = {depot_origin} + while current != depot_dest: + found_next = False + for j in N: + if (current, j) in arc_set and j not in visited: + if x[current, j, k].X > 0.5: + if current != depot_origin or j != depot_dest: + route.append({ + "from": current, + "to": j, + "time": B[current, k].X if current in [nd["id"] for nd in data["nodes"]] else 0, + "load": Qvar[current, k].X + }) + visited.add(j) + current = j + found_next = True + break + if not found_next: + # Try depot_dest + if (current, depot_dest) in arc_set and x[current, depot_dest, k].X > 0.5: + route.append({ + "from": current, + "to": depot_dest, + "time": B[current, k].X, + "load": Qvar[current, k].X + }) + current = depot_dest + else: + break + + # Only include non-trivial routes (not just depot->depot) + if len(route) > 1 or (len(route) == 1 and route[0]["to"] != depot_dest): + route_nodes = [depot_origin] + cur = depot_origin + vis = {depot_origin} + while cur != depot_dest: + found = False + for j in N: + if (cur, j) in arc_set and j not in vis: + if x[cur, j, k].X > 0.5: + route_nodes.append(j) + vis.add(j) + cur = j + found = True + break + if not found: + if (cur, depot_dest) in arc_set and x[cur, depot_dest, k].X > 0.5: + route_nodes.append(depot_dest) + cur = depot_dest + else: + break + + # Only add if route visits at least one customer + if len(route_nodes) > 2: # more than just depot_origin -> depot_dest + routes.append({ + "vehicle": k, + "nodes": route_nodes, + }) + + result["num_vehicles_used"] = len(routes) + result["routes"] = routes + else: + result["objective_value"] = None + result["status"] = "infeasible" if model.Status == GRB.INFEASIBLE else "no_solution" + result["runtime_seconds"] = model.Runtime + + return result + + +def main(): + parser = argparse.ArgumentParser(description="PDPTW Gurobi MIP Solver") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, default="gurobi_solution_1.json", + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print(f"Loading instance from: {args.instance_path}") + data = load_instance(args.instance_path) + + print(f"Instance: {data.get('instance_name', 'unknown')}") + print(f" Requests: {data['num_requests']}") + print(f" Vehicles: {data['num_vehicles']}") + print(f" Capacity: {data['vehicle_capacity']}") + print(f" Time limit: {args.time_limit}s") + + result = solve_pdptw(data, args.time_limit) + + # 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"\nSolution saved to: {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Vehicles used: {result.get('num_vehicles_used', 'N/A')}") + print(f"Status: {result['status']}") + else: + print(f"Status: {result['status']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/ropke2009/gurobi_feasi_result/large_feasi_result_1.json b/tasks/ropke2009/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ropke2009/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/ropke2009/gurobi_feasi_result/large_feasi_result_2.json b/tasks/ropke2009/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ropke2009/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/ropke2009/gurobi_feasi_result/large_feasi_result_3.json b/tasks/ropke2009/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ropke2009/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/ropke2009/gurobi_feasi_result/large_feasi_result_4.json b/tasks/ropke2009/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ropke2009/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/ropke2009/gurobi_feasi_result/large_feasi_result_5.json b/tasks/ropke2009/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ropke2009/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/ropke2009/gurobi_feasi_result/tiny_feasi_result.json b/tasks/ropke2009/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ropke2009/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/ropke2009/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/ropke2009/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ropke2009/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/ropke2009/gurobi_solution/large_solution_1.json b/tasks/ropke2009/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..29c9daf5684f10d3100ecc1c1033b76623a701f0 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b673ad143bb2a5a331fa79c5efecdff421a635205de2b57afd09a8fee15ebd5f +size 4799 diff --git a/tasks/ropke2009/gurobi_solution/large_solution_2.json b/tasks/ropke2009/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..bb7d8ef921d1566b486fa5e980fee9785fca7360 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c4fe954f3186983add9bbf2f50146cf9d957d01342a39d0343b9a11c8cdd8fc +size 3424 diff --git a/tasks/ropke2009/gurobi_solution/large_solution_3.json b/tasks/ropke2009/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..eb7fc62f447fa79efd478be38bb89cb95a366d92 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1cd2e4b507a84add2fd9c016b99b9d7b96089fd0949e7b8833edb5f6af50e39 +size 2281 diff --git a/tasks/ropke2009/gurobi_solution/large_solution_4.json b/tasks/ropke2009/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..bfc507a7c16b72a9822aa92acacfe71bf5037e56 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3205a60e6f8d3f3fad0967b1b95a920229034f32ac7416887a7864306e9d392 +size 3102 diff --git a/tasks/ropke2009/gurobi_solution/large_solution_5.json b/tasks/ropke2009/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..762a90c1187fedd1e49817c606da796cfe6c62b3 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2653461b1eb665a01f01457b7dc3856b994eba256704b4e884940a24f35d181 +size 2617 diff --git a/tasks/ropke2009/gurobi_solution/tiny_solution.json b/tasks/ropke2009/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..82f249b58e5945c65a937cb722f3483a5a3ba39d --- /dev/null +++ b/tasks/ropke2009/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00ebec82eefb8206bf58b70456916f8bd545b8a05ef0b16ac1dd5293de9f8cc2 +size 756 diff --git a/tasks/ropke2009/gurobi_solution/tiny_solution_2.json b/tasks/ropke2009/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..80fe1ed66eb4ed8abe9d61e85de0b736a28ed30a --- /dev/null +++ b/tasks/ropke2009/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:782c10289b1959fb38010c87261438f82189b9c61e5f4ac34dc76cd2cd923c42 +size 1910 diff --git a/tasks/ropke2009/gurobi_solution_log/large_log_1.jsonl b/tasks/ropke2009/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9765901c73249eb022cc0b89630b20976a1fa664 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83ad1c78c657dce89176b8e6b31e27d7e3dafacfd975cda6441b9a7a01238745 +size 167 diff --git a/tasks/ropke2009/gurobi_solution_log/large_log_2.jsonl b/tasks/ropke2009/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d754d8d1eb4025f7cfb780f7fe4aa8ee0086920e --- /dev/null +++ b/tasks/ropke2009/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8573e7520d96c75a1bbdfeaf684afdf814ca6ef2610b4da151db799af6a425bf +size 1140 diff --git a/tasks/ropke2009/gurobi_solution_log/large_log_3.jsonl b/tasks/ropke2009/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..72eb5af507e94f9d7fbc72964c7816f79a0d67e1 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c7e4dbda8366d9ada358b626637d9958042b9f05a62547d155489f39c96d71a +size 744 diff --git a/tasks/ropke2009/gurobi_solution_log/large_log_4.jsonl b/tasks/ropke2009/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d23eb54ed204bc4a36c07c37998dfd767b13ee1b --- /dev/null +++ b/tasks/ropke2009/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd825011db3ac99bd0dc98132e7ffbc293026fb86d72d095368673db988e3d93 +size 1774 diff --git a/tasks/ropke2009/gurobi_solution_log/large_log_5.jsonl b/tasks/ropke2009/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..29819650ed0c30bbdff28e20add305e42de1e829 --- /dev/null +++ b/tasks/ropke2009/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9640356c1b69fd610bf5536e9429cda3e43679e055c71d27c5fe02d630d1c965 +size 3672 diff --git a/tasks/ropke2009/gurobi_solution_log/tiny_log.jsonl b/tasks/ropke2009/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5f80f8e9e962726c23fa71f0f09652591f7b929d --- /dev/null +++ b/tasks/ropke2009/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9550e27a97da7131aba914e5a22085a0faed50a66746e1eeff2402a9ee4e31b2 +size 428 diff --git a/tasks/ropke2009/instance/large_instance_1.json b/tasks/ropke2009/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..256ebb13fc26064093fe09caf45f31c7eb96717e --- /dev/null +++ b/tasks/ropke2009/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:393b84a323bcb091344804575e62bcc4912a8b2198b390f9b976daf00e8e1d9b +size 37598 diff --git a/tasks/ropke2009/instance/large_instance_2.json b/tasks/ropke2009/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ed8cd4a50df4df0722353f163fae101ab9746812 --- /dev/null +++ b/tasks/ropke2009/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ae2c0c758ec33d2f788e751bdabbbc852df4329b45c0241c73553e6140cde78 +size 37565 diff --git a/tasks/ropke2009/instance/large_instance_3.json b/tasks/ropke2009/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7b7a096abfb911c37288cf7f44d28cdfd29c13aa --- /dev/null +++ b/tasks/ropke2009/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33bbd1520628953750a853609ae27bb1729497b717f6c4d41fa4fad343c993d5 +size 25686 diff --git a/tasks/ropke2009/instance/large_instance_4.json b/tasks/ropke2009/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..82ffb576cc37531ebdc5f51f1d2eba3209d8b829 --- /dev/null +++ b/tasks/ropke2009/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58e94c344b5ed58c62022e707c40dd3909edd4a8ce849f03ea130501748a6f4e +size 37554 diff --git a/tasks/ropke2009/instance/large_instance_5.json b/tasks/ropke2009/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..65ae9f43df83b7df10a14db81fb7a1130f38ad63 --- /dev/null +++ b/tasks/ropke2009/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11e9983dd0ee6c2849dbea1b6d27c3fd4e30c1ba0980435e3c234f712bbd63cd +size 37528 diff --git a/tasks/ropke2009/instance/tiny_instance.json b/tasks/ropke2009/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..faaec195e9222bf7f0f96abb06340cfb4c0a6210 --- /dev/null +++ b/tasks/ropke2009/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4bd8766ede4d3750eb192d0e1c019e3a84c81280dbc26d887fefd9d13afb3e3 +size 9494 diff --git a/tasks/ropke2009/instance/tiny_instance_2.json b/tasks/ropke2009/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..dd4e9847e2116bdf5460b977630a46f7a4faa8db --- /dev/null +++ b/tasks/ropke2009/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffa5b603cdaed5f58ad69f4f1596c94c510568d9c704df8d67a661dfbcb5a03a +size 28040 diff --git a/tasks/ropke2009/instance_schema.json b/tasks/ropke2009/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..73e94fa7a785aa8e82f02971c6abf99b86a5f869 --- /dev/null +++ b/tasks/ropke2009/instance_schema.json @@ -0,0 +1,42 @@ +{ + "num_requests": " Total number of transportation requests to be fulfilled.", + "num_nodes": " Total number of nodes in the network, including origin depot, pickup nodes, delivery nodes, and destination depot.", + "num_vehicles": " Number of identical vehicles available in the fleet.", + "vehicle_capacity": " Maximum load that each vehicle can carry at any point along its route.", + "planning_horizon": " Latest time by which all vehicles must return to the depot.", + "fixed_cost_per_vehicle": " Fixed cost incurred each time a vehicle is dispatched from the depot.", + "objective": { + "primary": " The primary optimization goal for the fleet.", + "secondary": " The secondary optimization goal, applied among solutions tied on the primary goal." + }, + "depot": { + "x": " X-coordinate of the depot location.", + "y": " Y-coordinate of the depot location.", + "time_window": " Earliest departure and latest return times for vehicles at the depot." + }, + "requests": [ + { + "request_id": " Unique identifier for this transportation request.", + "pickup_node": " Node index where the load for this request is picked up.", + "delivery_node": " Node index where the load for this request is delivered.", + "load": " Quantity of goods to be transported for this request.", + "pickup_coord": " X and Y coordinates of the pickup location.", + "delivery_coord": " X and Y coordinates of the delivery location.", + "pickup_time_window": " Earliest and latest times at which service may begin at the pickup location.", + "delivery_time_window": " Earliest and latest times at which service may begin at the delivery location.", + "travel_time_pickup_to_delivery": " Travel time (Euclidean distance) from the pickup location to the delivery location for this request." + } + ], + "nodes": [ + { + "id": " Unique index of this node in the network.", + "type": " Role of this node: 'depot_origin', 'pickup', 'delivery', or 'depot_destination'.", + "x": " X-coordinate of this node.", + "y": " Y-coordinate of this node.", + "demand": " Change in vehicle load when visiting this node (positive for pickups, negative for deliveries, zero for depots).", + "service_time": " Time spent servicing at this node before departing.", + "time_window": " Earliest and latest times at which service may begin at this node.", + "pair": " Node index of the corresponding paired pickup or delivery node (present only for pickup and delivery nodes)." + } + ] +} diff --git a/tasks/ropke2009/mathematical_formulation.md b/tasks/ropke2009/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..8399fb64b358190afa34b677f18bdd059493ef5b --- /dev/null +++ b/tasks/ropke2009/mathematical_formulation.md @@ -0,0 +1,65 @@ +# Original Formulation: Pickup and Delivery Problem with Time Windows (PDPTW) + +*Source: “Branch and Cut and Price for the Pickup and Delivery Problem with Time Windows”, Stefan Ropke, Jean-François Cordeau, Transportation Science 43(3):267–286, 2009.* + +This is the standard three-index mixed-integer program of Section 2.2, which the paper writes first as the definition of the PDPTW and whose notation ($x^k_{ij}, B^k_i, Q^k_i$) is carried into the rest of the paper. The set partitioning formulation of Section 2.3, used as the basis of the branch-and-cut-and-price algorithm, is recorded under **Variants**. + +## Sets and Indices + +- $n$ : number of transportation requests. + +- $G=(N,A)$ : directed graph with node set $N$ and arc set $A$. + +- $N=\{0,1,\dots,2n+1\}$ : node set. Node $0$ is the origin depot and node $2n+1$ is the destination depot. + +- $P=\{1,\dots,n\}$ : set of pickup nodes. + +- $D=\{n+1,\dots,2n\}$ : set of delivery nodes. Request $i$ is associated with pickup node $i$ and delivery node $n+i$. + +- $K$ : set of (identical) vehicles. + +## Parameters + +- $q_i$ : load at node $i\in N$, with $q_0=q_{2n+1}=0$ and $q_i=-q_{n+i}$ for $i=1,\dots,n$. + +- $d_i$ : nonnegative service duration at node $i$, with $d_0=d_{2n+1}=0$. + +- $[a_i,b_i]$ : time window at node $i\in P\cup D$ ($a_i$ = earliest, $b_i$ = latest start of service); depot windows $[a_0,b_0]$ and $[a_{2n+1},b_{2n+1}]$ give earliest departure / latest return times. + +- $Q$ : vehicle capacity (vehicles are identical). + +- $c_{ij}$ : routing cost on arc $(i,j)\in A$. + +- $t_{ij}$ : travel time on arc $(i,j)\in A$; $t_{ij}$ includes the service time $d_i$ at node $i$. Both $c_{ij}$ and $t_{ij}$ satisfy the triangle inequality. + +## Decision Variables + +- $x^k_{ij}\in\{0,1\}$ for $(i,j)\in A,\ k\in K$ : $=1$ iff vehicle $k$ travels directly from node $i$ to node $j$. + +- $B^k_i\ge 0$ for $i\in N,\ k\in K$ : time at which vehicle $k$ begins service at node $i$. + +- $Q^k_i\ge 0$ for $i\in N,\ k\in K$ : load of vehicle $k$ upon leaving node $i$. + +## Objective + +$$\begin{equation} +\min \sum_{k\in K}\sum_{i\in N}\sum_{j\in N} c_{ij}\, x^k_{ij} \tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{k\in K}\sum_{j\in N} x^k_{ij} &= 1 && \forall\, i\in P \tag{2}\\[2pt] +\sum_{j\in N} x^k_{ij} - \sum_{j\in N} x^k_{n+i,\,j} &= 0 && \forall\, i\in P,\ k\in K \tag{3}\\[2pt] +\sum_{j\in N} x^k_{0j} &= 1 && \forall\, k\in K \tag{4}\\[2pt] +\sum_{j\in N} x^k_{ji} - \sum_{j\in N} x^k_{ij} &= 0 && \forall\, i\in P\cup D,\ k\in K \tag{5}\\[2pt] +\sum_{i\in N} x^k_{i,\,2n+1} &= 1 && \forall\, k\in K \tag{6} +\end{align}$$ $$\begin{align} +B^k_j &\ge (B^k_i + t_{ij})\, x^k_{ij} && \forall\, i\in N,\ j\in N,\ k\in K \tag{7} +\end{align}$$ $$\begin{align} +Q^k_j &\ge (Q^k_i + q_j)\, x^k_{ij} && \forall\, i\in N,\ j\in N,\ k\in K \tag{8}\\[2pt] +B^k_i + t_{i,\,n+i} &\le B^k_{n+i} && \forall\, i\in P,\ k\in K \tag{9}\\[2pt] +a_i \le B^k_i &\le b_i && \forall\, i\in N,\ k\in K \tag{10}\\[2pt] +\max\{0,q_i\} \le Q^k_i &\le \min\{Q,\,Q+q_i\} && \forall\, i\in N,\ k\in K \tag{11}\\[2pt] +x^k_{ij} &\in \{0,1\} && \forall\, i\in N,\ j\in N,\ k\in K \tag{12} +\end{align}$$ diff --git a/tasks/ropke2009/problem_description.txt b/tasks/ropke2009/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..3a425bcd23f22b87bbd1c9a5ca954a1f10db4609 --- /dev/null +++ b/tasks/ropke2009/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A fleet of identical vehicles operates out of a single depot to fulfill a set of transportation requests. Each request specifies that a certain load must be picked up at one location and delivered to a different location. The number of requests and the number of available vehicles are given as input. Each vehicle has the same carrying capacity. The input data for each request includes the pickup and delivery coordinates, the load to be transported (a positive quantity), the time window at the pickup location (earliest and latest times at which service may begin), and the time window at the delivery location. The depot also has a time window representing the earliest departure and latest return times for all vehicles. For every pair of locations (including the depot), the routing cost and travel time are given. Travel times include the service duration at the origin location of each trip leg, and both routing costs and travel times satisfy the triangle inequality. Service durations at the depot are zero. + +The dispatcher must assign each request to exactly one vehicle and determine the sequence in which that vehicle visits its assigned pickup and delivery locations. Every request must be served: no request may be left unassigned and no request may be split across vehicles. For each request, the same vehicle that performs the pickup must also perform the corresponding delivery, and the pickup must occur before the delivery on that vehicle's route. Each vehicle in the fleet departs from the depot and returns to the depot, including vehicles that serve no requests. + +When a vehicle arrives at a location before the earliest allowable service time, it may wait until service is permitted. Service at any location must begin no later than the latest allowable time specified by that location's time window. After a vehicle begins service and the travel time to the next location elapses (recall that travel time already incorporates the service duration at the current location), the vehicle arrives at its next stop, where the same time window rules apply. + +The load carried by each vehicle changes as pickups and deliveries are performed. When a pickup occurs, the vehicle's load increases by the request's load quantity; when the corresponding delivery occurs, the load decreases by the same amount. At no point along any vehicle's route may the carried load exceed the vehicle capacity, and at no point may it fall below zero. + +The goal is to minimize the total routing cost, defined as the sum of the routing costs on all arcs traversed by all vehicles. diff --git a/tasks/ropke2009/solution_logger.py b/tasks/ropke2009/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/ropke2009/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/ropke2009/solution_schema.json b/tasks/ropke2009/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3b008a51d9598237a822005a87ff0575c790721f --- /dev/null +++ b/tasks/ropke2009/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total routing distance traveled by all vehicles serving the requests.", + "routes": [ + { + "vehicle": " Identifier of the vehicle assigned to this route.", + "nodes": " Ordered sequence of node identifiers visited by the vehicle, starting at the origin depot, alternating pickups and deliveries while respecting pairing and precedence, and ending at the destination depot." + } + ] +} diff --git a/tasks/roshanaei2017/feasibility_check.py b/tasks/roshanaei2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f95d44d09e27795aee5f1b7e79e30b9da8d9f49e --- /dev/null +++ b/tasks/roshanaei2017/feasibility_check.py @@ -0,0 +1,909 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for CORPS (Collaborative Operating Room Planning and +Scheduling) solutions from Roshanaei et al. (2017). + +Verifies the FULL original problem (constraints 1-22) plus a Tier C +objective-consistency check (constraint 23) that recomputes the MP +objective from the solution variables and rejects values that disagree +with the reported objective_value. + +Constraint enumeration: + 0 : domain (continuous time vars >= 0, eta/pi in {0,1}) + 1 : mandatory patients scheduled exactly once + 2 : optional patients scheduled at most once + 3 : surgeon at most one hospital per day + 4 : x_pshdr <= z_shd + 5 : x_pshdr <= y_hdr + 6 : OR capacity sum_p T_ps x_pshdr <= B_hdr y_hdr + v_hdr + 7 : surgeon weighted-time availability + 8 : 0 <= v_hdr <= V_hdr + 9 : exactly one (s, r) per scheduled patient at (h, d) + 10 : f_p >= F_p + E_ps + 11 : per-OR no-overlap (also subsumes 12) + 13 : per-surgeon no-overlap (also subsumes 14) + 15 : f_p + G_p <= B_r + v_r + 16 : e_s >= f_p + 17 : i_s <= f_p - E_ps + 18 : e_s - i_s <= A_sd + 19 : c_r >= f_p + G_p + 21 : v_r >= c_r - B_r + 23 : objective consistency (Tier C: recomputed objective must match + reported objective_value within tolerance) +""" + +import argparse +import json +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', 'objective_value', 'opened_ors', 'or_sequences', 'surgeon_assignments', 'surgeon_sequences') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('or_sequences', 'surgeon_assignments', 'surgeon_sequences') +_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 + + + +# ---------------------------------------------------------------- +# Loaders +# ---------------------------------------------------------------- + +def load_instance(path): + with open(path) as f: + data = json.load(f) + + patients = {p["patient_id"]: p for p in data["patients"]} + surgeons = {s["surgeon_id"]: s for s in data["surgeons"]} + hospitals = {h["hospital_id"]: h for h in data["hospitals"]} + + or_lookup = {} # (h, r) -> or_info + for h in data["hospitals"]: + hid = h["hospital_id"] + for or_info in h["ORs"]: + or_lookup[(hid, or_info["or_id"])] = or_info + + return data, patients, surgeons, hospitals, or_lookup + + +def load_solution(path): + with open(path) as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + return _frontieror_contract_result + + # Allocation + x = {} + finish_times = {} # (p, h, d) -> f_p + surgery_start = {} # (p, h, d) -> start of surgery proper + for a in sol.get("assignments", []): + key = (a["patient_id"], a["surgeon_id"], a["hospital_id"], + a["day"], a["or_id"]) + x[key] = 1 + ph = (a["patient_id"], a["hospital_id"], a["day"]) + if "finish_time" in a: + finish_times[ph] = a["finish_time"] + if "surgery_start_time" in a: + surgery_start[ph] = a["surgery_start_time"] + + y = {} + completion = {} # (h, d, r) -> c_r + if "opened_ors" in sol: + for o in sol["opened_ors"]: + y[(o["hospital_id"], o["day"], o["or_id"])] = 1 + if "completion_time" in o: + completion[(o["hospital_id"], o["day"], o["or_id"])] = \ + o["completion_time"] + if "or_details" in sol: + for o in sol["or_details"]: + y[(o["hospital_id"], o["day"], o["or_id"])] = 1 + for (p, s, h, d, r) in x: + y[(h, d, r)] = 1 + + z = {} + surg_start = {} # (s, h, d) -> i_s + surg_end = {} # (s, h, d) -> e_s + if "surgeon_assignments" in sol: + for sa in sol["surgeon_assignments"]: + key = (sa["surgeon_id"], sa["hospital_id"], sa["day"]) + z[key] = 1 + if "start_time" in sa: + surg_start[key] = sa["start_time"] + if "end_time" in sa: + surg_end[key] = sa["end_time"] + for (p, s, h, d, r) in x: + z[(s, h, d)] = 1 + + v = {} + if "opened_ors" in sol: + for o in sol["opened_ors"]: + v[(o["hospital_id"], o["day"], o["or_id"])] = o.get("overtime", 0.0) + elif "or_details" in sol: + for o in sol["or_details"]: + v[(o["hospital_id"], o["day"], o["or_id"])] = o.get( + "mp_overtime_minutes", 0.0) + for key in y: + if key not in v: + v[key] = 0.0 + + return (x, y, z, v, finish_times, surgery_start, completion, + surg_start, surg_end) + + +# ---------------------------------------------------------------- +# Parameter accessors +# ---------------------------------------------------------------- + +def get_E(patients, p, s): + return patients[p]["surgeon_specific_times"][str(s)] + + +def get_T(patients, p, s): + pat = patients[p] + return pat["preparation_time"] + get_E(patients, p, s) + pat["cleaning_time"] + + +def get_F(patients, p): + return patients[p]["preparation_time"] + + +def get_G(patients, p): + return patients[p]["cleaning_time"] + + +def get_B(or_lookup, h, d, r): + info = or_lookup.get((h, r)) + if info and str(d) in info["daily"]: + return info["daily"][str(d)]["regular_time"] + return 480 + + +def get_V_max(or_lookup, h, d, r): + info = or_lookup.get((h, r)) + if info and str(d) in info["daily"]: + return info["daily"][str(d)]["max_overtime"] + return 120 + + +def get_K(or_lookup, h, d, r): + """Fixed cost of opening OR r at hospital h on day d. + + K_{hdr} = fixed_cost_per_hour * (regular_time_minutes / 60). + """ + info = or_lookup.get((h, r)) + if info is None: + return 0.0 + B = get_B(or_lookup, h, d, r) + return float(info.get("fixed_cost_per_hour", 0.0)) * (B / 60.0) + + +def get_C(or_lookup, h, d, r): + """Overtime cost per minute for OR r at hospital h on day d. + + C_{hdr} = overtime_cost_per_hour / 60 (since v is in minutes). + """ + info = or_lookup.get((h, r)) + if info is None: + return 0.0 + return float(info.get("overtime_cost_per_hour", 0.0)) / 60.0 + + +def get_L(hospitals, s, h, d): + """Surgeon-hospital-day fixed cost. Stored per hospital, per surgeon.""" + hosp = hospitals.get(h) + if hosp is None: + return 0.0 + return float(hosp.get("surgeon_fixed_costs_per_day", {}).get(str(s), 0.0)) + + +# ---------------------------------------------------------------- +# Main check +# ---------------------------------------------------------------- + +def check_feasibility(instance_path, solution_path, result_path): + tol = 1e-3 # SP constraints often need slightly looser tolerance + eps = 1e-5 + + data, patients, surgeons, hospitals, or_lookup = load_instance(instance_path) + + with open(solution_path) as f: + raw_sol = json.load(f) + sol_status = raw_sol.get("status") + sol_assignments = raw_sol.get("assignments", []) + if sol_status in (3, "3", "INFEASIBLE", "NO_SOLUTION_FOUND") or \ + (raw_sol.get("objective_value") is None and len(sol_assignments) == 0): + status_desc = raw_sol.get("status_name", raw_sol.get("status_description", + raw_sol.get("status", "unknown"))) + result = { + "feasible": False, + "violated_constraints": [1], + "violations": [ + f"No solution provided (solver status={status_desc}). " + f"Empty assignments cannot satisfy constraint (1)." + ], + "violation_magnitudes": [{ + "constraint": 1, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }], + } + with open(result_path, "w") as f: + json.dump(result, f, indent=2) + return result + + (x, y, z, v, finish_times, surgery_start, completion, + surg_start_d, surg_end_d) = load_solution(solution_path) + + num_days = data["num_days"] + alpha = data["alpha"] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def add_violation(constraint_idx, msg, lhs_val, rhs_val, raw_excess): + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": lhs_val, "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, "ratio": ratio, + }) + + # ================================================================ + # VARIABLE-DOMAIN CHECKS + # ---------------------------------------------------------------- + # Math model declares the continuous time variables non-negative + # (f_p, c_r, i_s, e_s >= 0) and the order indicators (eta_{pk,hdr}, + # pi_{pk,hd}) binary in {0, 1}. The binary {0,1} domain of + # x_{pshdr}, y_{hdr}, z_{shd} is enforced implicitly by how + # load_solution reads them (set membership -> value 1; absence -> 0), + # so they need no explicit numeric check here. + # Use constraint index 0 to flag any domain violation distinctly + # from the numbered model constraints (1)-(22). + # ================================================================ + + # f_p >= 0 (finish_time per assignment) + for (p, h, d), fp in finish_times.items(): + if fp < -tol: + add_violation( + 0, + f"Domain: finish_time f_p < 0 for p={p},h={h},d={d}: " + f"f_p={fp:.6f}", + fp, 0.0, abs(fp), + ) + + # c_r >= 0 (completion_time per opened OR) + for (h, d, r), cr in completion.items(): + if cr < -tol: + add_violation( + 0, + f"Domain: completion_time c_r < 0 for h={h},d={d},r={r}: " + f"c_r={cr:.6f}", + cr, 0.0, abs(cr), + ) + + # i_s >= 0 (surgeon start_time) + for (s, h, d), is_ in surg_start_d.items(): + if is_ < -tol: + add_violation( + 0, + f"Domain: surgeon start_time i_s < 0 for s={s},h={h},d={d}: " + f"i_s={is_:.6f}", + is_, 0.0, abs(is_), + ) + + # e_s >= 0 (surgeon end_time) + for (s, h, d), es in surg_end_d.items(): + if es < -tol: + add_violation( + 0, + f"Domain: surgeon end_time e_s < 0 for s={s},h={h},d={d}: " + f"e_s={es:.6f}", + es, 0.0, abs(es), + ) + + # eta in {0,1}: or_sequences[*].p_after_k + for entry in raw_sol.get("or_sequences", []) or []: + eta = entry.get("p_after_k") + if eta is None: + continue + if not (abs(eta - 0.0) <= tol or abs(eta - 1.0) <= tol): + add_violation( + 0, + f"Domain: or_sequences p_after_k not binary for " + f"h={entry.get('hospital_id')},d={entry.get('day')}," + f"r={entry.get('or_id')},p={entry.get('patient_p')}," + f"k={entry.get('patient_k')}: eta={eta}", + float(eta), 1.0, min(abs(eta - 0.0), abs(eta - 1.0)), + ) + + # pi in {0,1}: surgeon_sequences[*].p_after_k + for entry in raw_sol.get("surgeon_sequences", []) or []: + pi_v = entry.get("p_after_k") + if pi_v is None: + continue + if not (abs(pi_v - 0.0) <= tol or abs(pi_v - 1.0) <= tol): + add_violation( + 0, + f"Domain: surgeon_sequences p_after_k not binary for " + f"h={entry.get('hospital_id')},d={entry.get('day')}," + f"s={entry.get('surgeon_id')},p={entry.get('patient_p')}," + f"k={entry.get('patient_k')}: pi={pi_v}", + float(pi_v), 1.0, min(abs(pi_v - 0.0), abs(pi_v - 1.0)), + ) + + # ================================================================ + # (1) Mandatory patients scheduled exactly once + # ================================================================ + patient_count = defaultdict(int) + for (p, s, h, d, r) in x: + patient_count[p] += 1 + + for pid, pat in patients.items(): + if pat["due_date"] <= num_days: + count = patient_count.get(pid, 0) + if abs(count - 1.0) > tol: + add_violation( + 1, + f"Mandatory patient {pid} scheduled {count} time(s)", + float(count), 1.0, abs(count - 1.0), + ) + + # ================================================================ + # (2) Optional patients scheduled at most once + # ================================================================ + for pid, pat in patients.items(): + if pat["due_date"] > num_days: + count = patient_count.get(pid, 0) + if count - 1.0 > tol: + add_violation( + 2, + f"Optional patient {pid} scheduled {count} times", + float(count), 1.0, count - 1.0, + ) + + # ================================================================ + # (3) Surgeon at most one hospital per day + # ================================================================ + surgeon_hosp_per_day = defaultdict(set) + for (s, h, d) in z: + surgeon_hosp_per_day[(s, d)].add(h) + + for (s, d), hosp_set in surgeon_hosp_per_day.items(): + lhs_val = float(len(hosp_set)) + if lhs_val - 1.0 > tol: + add_violation( + 3, + f"Surgeon {s} at {len(hosp_set)} hospitals on day {d}", + lhs_val, 1.0, lhs_val - 1.0, + ) + + # ================================================================ + # (4) x_pshdr <= z_shd + # ================================================================ + for (p, s, h, d, r) in x: + z_val = 1.0 if (s, h, d) in z else 0.0 + if 1.0 - z_val > tol: + add_violation( + 4, + f"Patient {p}/surgeon {s} at hospital {h} day {d} room {r} " + f"but surgeon not present", + 1.0, z_val, 1.0 - z_val, + ) + + # ================================================================ + # (5) x_pshdr <= y_hdr + # ================================================================ + for (p, s, h, d, r) in x: + y_val = 1.0 if (h, d, r) in y else 0.0 + if 1.0 - y_val > tol: + add_violation( + 5, + f"Patient {p} at hospital {h} day {d} room {r} but OR closed", + 1.0, y_val, 1.0 - y_val, + ) + + # ================================================================ + # (6) OR capacity: sum T*x <= B*y + v + # ================================================================ + or_load = defaultdict(float) + for (p, s, h, d, r) in x: + or_load[(h, d, r)] += get_T(patients, p, s) + + for (h, d, r), total_load in or_load.items(): + B_hdr = get_B(or_lookup, h, d, r) + y_val = 1.0 if (h, d, r) in y else 0.0 + v_val = v.get((h, d, r), 0.0) + rhs_val = B_hdr * y_val + v_val + if total_load - rhs_val > tol: + add_violation( + 6, + f"OR cap exceeded h={h} d={d} r={r}: " + f"load={total_load:.2f} > B*y+v={rhs_val:.2f}", + total_load, rhs_val, total_load - rhs_val, + ) + + # ================================================================ + # (7) Surgeon weighted-time availability + # ================================================================ + surgeon_load = defaultdict(float) + for (p, s, h, d, r) in x: + E_ps = get_E(patients, p, s) + T_ps = get_T(patients, p, s) + surgeon_load[(s, h, d)] += alpha * E_ps + (1.0 - alpha) * T_ps + + for (s, h, d), weighted in surgeon_load.items(): + A_sd = surgeons[s]["availability_by_day"].get(str(d), 0) + z_val = 1.0 if (s, h, d) in z else 0.0 + rhs_val = float(A_sd) * z_val + if weighted - rhs_val > tol: + add_violation( + 7, + f"Surgeon {s} availability exceeded h={h} d={d}: " + f"load={weighted:.2f} > A*z={rhs_val:.2f}", + weighted, rhs_val, weighted - rhs_val, + ) + + # ================================================================ + # (8) Overtime bounds: 0 <= v <= V_hdr + # ================================================================ + for (h, d, r), v_val in v.items(): + V_hdr = get_V_max(or_lookup, h, d, r) + if v_val < -tol: + add_violation(8, f"Negative overtime h={h} d={d} r={r}: v={v_val}", + v_val, 0.0, abs(v_val)) + if v_val - V_hdr > tol: + add_violation(8, f"Overtime > V_max h={h} d={d} r={r}: " + f"v={v_val:.2f} > {V_hdr}", + v_val, float(V_hdr), v_val - V_hdr) + + # ================================================================ + # SEQUENCING constraints (9)-(22) + # ---------------------------------------------------------------- + patients_at_hdr = defaultdict(list) + patients_at_hds = defaultdict(list) + surgeon_for_pat_at_hd = {} # (p,h,d) -> s + or_for_pat_at_hd = {} # (p,h,d) -> r + for (p, s, h, d, r) in x: + patients_at_hdr[(h, d, r)].append(p) + patients_at_hds[(h, d, s)].append(p) + surgeon_for_pat_at_hd[(p, h, d)] = s + or_for_pat_at_hd[(p, h, d)] = r + + # ================================================================ + # (9) Each scheduled patient has exactly one (s,r) at (h,d) + # ================================================================ + pat_phd = defaultdict(list) + for (p, s, h, d, r) in x: + pat_phd[(p, h, d)].append((s, r)) + for (p, h, d), srs in pat_phd.items(): + if len(srs) != 1: + add_violation( + 9, + f"Patient {p} at h={h} d={d} has {len(srs)} (s,r) pairs", + float(len(srs)), 1.0, abs(len(srs) - 1.0), + ) + + # ================================================================ + # (10) f_p >= F_p + E_ps + # ================================================================ + for (p, s, h, d, r), _ in x.items(): + if (p, h, d) not in finish_times: + add_violation( + 10, + f"Missing finish_time for patient {p} at h={h} d={d}", + 0.0, 1.0, 1.0, + ) + continue + fp = finish_times[(p, h, d)] + Fp = get_F(patients, p) + Eps = get_E(patients, p, s) + if fp + tol < Fp + Eps: + add_violation( + 10, + f"f_p < F_p + E_ps for p={p}: f={fp:.2f} < {Fp + Eps:.2f}", + fp, Fp + Eps, (Fp + Eps) - fp, + ) + + # ================================================================ + # (11)/(12) Per-OR no-overlap + # ================================================================ + for (h, d, r), plist in patients_at_hdr.items(): + for i in range(len(plist)): + for j in range(i + 1, len(plist)): + p, k = plist[i], plist[j] + if (p, h, d) not in finish_times or (k, h, d) not in finish_times: + continue + fp = finish_times[(p, h, d)] + fk = finish_times[(k, h, d)] + sp_ = surgeon_for_pat_at_hd[(p, h, d)] + sk_ = surgeon_for_pat_at_hd[(k, h, d)] + Fp, Fk = get_F(patients, p), get_F(patients, k) + Gp, Gk = get_G(patients, p), get_G(patients, k) + Eps = get_E(patients, p, sp_) + Eks = get_E(patients, k, sk_) + p_after_k_ok = (fp + tol >= fk + Gk + Fp + Eps) + k_after_p_ok = (fk + tol >= fp + Gp + Fk + Eks) + if not (p_after_k_ok or k_after_p_ok): + short_p = (fk + Gk + Fp + Eps) - fp + short_k = (fp + Gp + Fk + Eks) - fk + add_violation( + 11, + f"OR overlap p={p}/k={k} at (h={h},d={d},r={r}): " + f"neither order feasible (p-after-k short {short_p:.2f}, " + f"k-after-p short {short_k:.2f})", + max(fp, fk), + max(fk + Gk + Fp + Eps, fp + Gp + Fk + Eks), + min(short_p, short_k), + ) + + # ================================================================ + # (13)/(14) Per-surgeon no-overlap + # ================================================================ + for (h, d, s), plist in patients_at_hds.items(): + for i in range(len(plist)): + for j in range(i + 1, len(plist)): + p, k = plist[i], plist[j] + if (p, h, d) not in finish_times or (k, h, d) not in finish_times: + continue + fp = finish_times[(p, h, d)] + fk = finish_times[(k, h, d)] + Eps = get_E(patients, p, s) + Eks = get_E(patients, k, s) + p_after_k_ok = (fp + tol >= fk + Eps) + k_after_p_ok = (fk + tol >= fp + Eks) + if not (p_after_k_ok or k_after_p_ok): + short_p = (fk + Eps) - fp + short_k = (fp + Eks) - fk + add_violation( + 13, + f"Surgeon overlap p={p}/k={k} surgeon={s} at " + f"(h={h},d={d}): neither order feasible " + f"(p-after-k short {short_p:.2f}, k-after-p short " + f"{short_k:.2f})", + max(fp, fk), max(fk + Eps, fp + Eks), + min(short_p, short_k), + ) + + # ================================================================ + # (15) f_p + G_p <= B_r + v_r + # ================================================================ + for (p, s, h, d, r), _ in x.items(): + if (p, h, d) not in finish_times: + continue + fp = finish_times[(p, h, d)] + Gp = get_G(patients, p) + Br = get_B(or_lookup, h, d, r) + vr = v.get((h, d, r), 0.0) + if fp + Gp - (Br + vr) > tol: + add_violation( + 15, + f"f_p+G_p > B_r+v_r for p={p}, r={r}, h={h}, d={d}: " + f"{fp + Gp:.2f} > {Br + vr:.2f}", + fp + Gp, Br + vr, (fp + Gp) - (Br + vr), + ) + + # ================================================================ + # (16) e_s >= f_p / (17) i_s <= f_p - E_ps + # ================================================================ + for (p, s, h, d, r), _ in x.items(): + if (p, h, d) not in finish_times: + continue + fp = finish_times[(p, h, d)] + Eps = get_E(patients, p, s) + es = surg_end_d.get((s, h, d)) + if es is not None and es + tol < fp: + add_violation( + 16, + f"e_s < f_p for s={s},p={p},h={h},d={d}: e_s={es:.2f} < " + f"f_p={fp:.2f}", + es, fp, fp - es, + ) + is_ = surg_start_d.get((s, h, d)) + if is_ is not None and is_ - (fp - Eps) > tol: + add_violation( + 17, + f"i_s > f_p - E_ps for s={s},p={p},h={h},d={d}: " + f"i_s={is_:.2f} > {fp - Eps:.2f}", + is_, fp - Eps, is_ - (fp - Eps), + ) + + # ================================================================ + # (18) e_s - i_s <= A_s + # ================================================================ + for (s, h, d), is_ in surg_start_d.items(): + es = surg_end_d.get((s, h, d)) + if es is None: + continue + A_sd = surgeons[s]["availability_by_day"].get(str(d), 0) + if (es - is_) - A_sd > tol: + add_violation( + 18, + f"surgeon-window > A_sd for s={s},h={h},d={d}: " + f"e-i={es - is_:.2f} > A={A_sd}", + es - is_, float(A_sd), (es - is_) - A_sd, + ) + + # ================================================================ + # (19) c_r >= f_p + G_p + # ================================================================ + for (p, s, h, d, r), _ in x.items(): + if (p, h, d) not in finish_times: + continue + fp = finish_times[(p, h, d)] + Gp = get_G(patients, p) + cr = completion.get((h, d, r)) + if cr is None: + add_violation( + 19, + f"Missing completion_time for OR (h={h},d={d},r={r})", + 0.0, fp + Gp, fp + Gp, + ) + continue + if cr + tol < fp + Gp: + add_violation( + 19, + f"c_r < f_p+G_p for p={p}, OR (h={h},d={d},r={r}): " + f"c={cr:.2f} < {fp + Gp:.2f}", + cr, fp + Gp, (fp + Gp) - cr, + ) + + # ================================================================ + # (20) 0 <= v_r <= V_r (covered by (8)) + # ================================================================ + + # ================================================================ + # (21) v_r >= c_r - B_r + # ================================================================ + for (h, d, r), cr in completion.items(): + Br = get_B(or_lookup, h, d, r) + vr = v.get((h, d, r), 0.0) + if (cr - Br) - vr > tol: + add_violation( + 21, + f"v_r < c_r - B_r for (h={h},d={d},r={r}): " + f"v={vr:.2f} < c-B={cr - Br:.2f}", + vr, cr - Br, (cr - Br) - vr, + ) + + # ================================================================ + # (22) Integrality of x (handled by x being read as 0/1 from solution) + # ================================================================ + + # ================================================================ + # (23) Objective consistency (Tier C defense against score-gaming) + # ---------------------------------------------------------------- + # Recompute the MP objective directly from the solution variables + # (y, z, v, x for optional patients) and reject when the reported + # objective_value disagrees beyond tolerance. This catches LLM + # exploits that return fabricated obj values (e.g. 0 or float-max) + # while submitting otherwise-feasible routes/assignments. + # + # Formula (Roshanaei et al. 2017, MP): + # obj = sum_{h,d,r} K_{hdr} y_{hdr} + # + sum_{s,h,d} L_{shd} z_{shd} + # + sum_{h,d,r} C_{hdr} v_{hdr} + # - sum_{p optional} U_p * (sum x_pshdr) + # ================================================================ + reported_obj_raw = raw_sol.get("objective_value") + if reported_obj_raw is not None: + try: + reported_obj = float(reported_obj_raw) + except (TypeError, ValueError): + reported_obj = None + if reported_obj is not None: + opened_fixed_cost = sum( + get_K(or_lookup, h, d, r) for (h, d, r) in y + ) + surgeon_fixed_cost = sum( + get_L(hospitals, s, h, d) for (s, h, d) in z + ) + overtime_cost = sum( + get_C(or_lookup, h, d, r) * v_val + for (h, d, r), v_val in v.items() + ) + optional_reward = 0.0 + for (p, s, h, d, r) in x: + pat = patients.get(p) + if pat is None: + continue + if pat["due_date"] > num_days: + optional_reward += float(pat.get("reward", 0.0)) + + true_obj = (opened_fixed_cost + surgeon_fixed_cost + + overtime_cost - optional_reward) + abs_diff = abs(reported_obj - true_obj) + # 0.1% relative tolerance with 1e-2 absolute floor (costs are + # small floats per-minute, summed across many ORs). + obj_tol = max(1e-2, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + add_violation( + 23, + f"Objective consistency violated: reported " + f"objective_value={reported_obj} differs from recomputed " + f"MP objective sum(K*y)+sum(L*z)+sum(C*v)-sum(U_p*x)=" + f"{true_obj} (K*y={opened_fixed_cost:.4f}, " + f"L*z={surgeon_fixed_cost:.4f}, " + f"C*v={overtime_cost:.4f}, " + f"-U*x=-{optional_reward:.4f}; |diff|={abs_diff:.3g}, " + f"tol={obj_tol:.3g})", + reported_obj, true_obj, abs_diff, + ) + + result = { + "feasible": len(violated_constraints) == 0, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(result_path, "w") as f: + json.dump(result, f, indent=2) + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for CORPS (Roshanaei et al. 2017)" + ) + 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() + + result = check_feasibility(args.instance_path, args.solution_path, + args.result_path) + + if result["feasible"]: + print("FEASIBLE: All constraints (1)-(23) satisfied.") + else: + print(f"INFEASIBLE: violated constraints {result['violated_constraints']}") + for msg in result["violations"]: + print(f" - {msg}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/roshanaei2017/gurobi_code.py b/tasks/roshanaei2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..fb7aeed051b2e4c6ca31f92f3143ba16013e983b --- /dev/null +++ b/tasks/roshanaei2017/gurobi_code.py @@ -0,0 +1,703 @@ +""" +CORPS (Collaborative Operating Room Planning and Scheduling) model +from Roshanaei et al. (2017), implemented as a monolithic MIP solved by Gurobi. + +_GUROBI_CODE_START_TIME = time.time() +This implements the FULL original problem: + - Allocation Master Problem (MP), constraints (1)-(8) + - Sequencing Subproblem (SP), constraints (9)-(22) +both merged into a single MIP. Sequencing decisions (finish times f_p, OR-order +binaries eta, surgeon-order binaries pi, OR completion c_{h,d,r}, surgeon +start/end i_s/e_s) are added per (hospital, day) so that the assignment +produced by MP is guaranteed to admit a feasible no-overlap schedule respecting +turnover/cleaning, surgeon availability, and OR overtime caps. +""" + +import argparse +import json +import time + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_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) -> dict: + with open(instance_path, "r") as f: + data = json.load(f) + + num_patients = data["num_patients"] + num_surgeons = data["num_surgeons"] + num_hospitals = data["num_hospitals"] + num_days = data["num_days"] + alpha = data["alpha"] + + patients = data["patients"] + surgeons = data["surgeons"] + hospitals = data["hospitals"] + + # ---------------------------------------------------------------- + # Pre-compute derived data + # ---------------------------------------------------------------- + + # Surgeon operating days (set of 0-indexed days) + surgeon_days = {} # surgeon_id -> set of day indices + surgeon_avail = {} # (s, d) -> A_sd + for surg in surgeons: + s = surg["surgeon_id"] + surgeon_days[s] = set(surg["operating_days"]) + for day_str, avail in surg["availability_by_day"].items(): + surgeon_avail[(s, int(day_str))] = avail + + # Hospital / OR data + or_data = {} # (h, r) -> OR dict + or_ids_by_hospital = {} # h -> list of or_id + for hosp in hospitals: + h = hosp["hospital_id"] + or_ids_by_hospital[h] = [] + for or_info in hosp["ORs"]: + r = or_info["or_id"] + or_ids_by_hospital[h].append(r) + or_data[(h, r)] = or_info + + # Surgeon fixed cost per day at hospital h: L_{s,h,d} (same for all days) + surgeon_hosp_cost = {} # (s, h) -> cost + for hosp in hospitals: + h = hosp["hospital_id"] + for s_str, cost in hosp["surgeon_fixed_costs_per_day"].items(): + surgeon_hosp_cost[(int(s_str), h)] = cost + + # Patient data helpers + patient_data = {} + for pat in patients: + p = pat["patient_id"] + patient_data[p] = pat + + # ---------------------------------------------------------------- + # Cost / parameter accessors + # ---------------------------------------------------------------- + + def get_K(h, d, r): + info = or_data[(h, r)] + B = info["daily"][str(d)]["regular_time"] # minutes + return info["fixed_cost_per_hour"] * (B / 60.0) + + def get_C(h, d, r): + info = or_data[(h, r)] + return info["overtime_cost_per_hour"] / 60.0 + + def get_B(h, d, r): + return or_data[(h, r)]["daily"][str(d)]["regular_time"] + + def get_V(h, d, r): + return or_data[(h, r)]["daily"][str(d)]["max_overtime"] + + def get_L(s, h, d): + return surgeon_hosp_cost.get((s, h), 0.0) + + def get_F(p): + return patient_data[p]["preparation_time"] + + def get_G(p): + return patient_data[p]["cleaning_time"] + + def get_T(p, s): + pat = patient_data[p] + E_ps = pat["surgeon_specific_times"][str(s)] + return pat["preparation_time"] + E_ps + pat["cleaning_time"] + + def get_E(p, s): + return patient_data[p]["surgeon_specific_times"][str(s)] + + # ---------------------------------------------------------------- + # Build feasible (p, s, h, d, r) tuples (allocation domain) + # ---------------------------------------------------------------- + feasible_tuples = [] + tuples_by_patient = {} + tuples_by_or_day = {} # (h,d,r) -> list of (p,s,h,d,r) + tuples_by_surgeon_day = {} # (s,d) -> list of (p,s,h,d,r) + tuples_by_pshd = {} # (p,s,h,d) -> list of r + tuples_by_shd = {} # (s,h,d) -> list of (p,s,h,d,r) + tuples_by_phd = {} # (p,h,d) -> list of (p,s,h,d,r) + tuples_by_phdr = {} # (p,h,d,r) -> list of (p,s,h,d,r) + + for pat in patients: + p = pat["patient_id"] + due_date = pat["due_date"] + tuples_by_patient[p] = [] + + for s in pat["eligible_surgeons"]: + if s not in surgeon_days: + continue + for h_str, eligible_ors in pat["eligible_ORs_by_hospital"].items(): + h = int(h_str) + for r in eligible_ors: + for d in surgeon_days[s]: + # due_date 是允许完成的最晚日(inclusive),所以仅当 d > due_date 时跳过 + # 原代码 `due_date <= d: continue` off-by-one,把 d == due_date 也错误排除 + if d > due_date: + continue + tup = (p, s, h, d, r) + feasible_tuples.append(tup) + tuples_by_patient[p].append(tup) + tuples_by_or_day.setdefault((h, d, r), []).append(tup) + tuples_by_surgeon_day.setdefault((s, d), []).append(tup) + tuples_by_pshd.setdefault((p, s, h, d), []).append(r) + tuples_by_shd.setdefault((s, h, d), []).append(tup) + tuples_by_phd.setdefault((p, h, d), []).append(tup) + tuples_by_phdr.setdefault((p, h, d, r), []).append(tup) + + # Active sets + active_hdr = set() + active_shd = set() + active_hd = set() + for (p, s, h, d, r) in feasible_tuples: + active_hdr.add((h, d, r)) + active_shd.add((s, h, d)) + active_hd.add((h, d)) + + # Patients eligible at (h,d): those with at least one tuple at (h,d,*) + patients_at_hd = {} + for (h, d) in active_hd: + plist = sorted({p for (p, s, hh, dd, r) in feasible_tuples + if hh == h and dd == d}) + patients_at_hd[(h, d)] = plist + + # Surgeons eligible at (h,d) + surgeons_at_hd = {} + for (h, d) in active_hd: + slist = sorted({s for (s, hh, dd) in active_shd if hh == h and dd == d}) + surgeons_at_hd[(h, d)] = slist + + # ORs eligible at (h,d) + ors_at_hd = {} + for (h, d) in active_hd: + rlist = sorted({r for (hh, dd, r) in active_hdr if hh == h and dd == d}) + ors_at_hd[(h, d)] = rlist + + # For each (h,d,r): list of patients that can be scheduled there + patients_at_hdr = {} + for (h, d, r) in active_hdr: + plist = sorted({p for (p, s, hh, dd, rr) in feasible_tuples + if hh == h and dd == d and rr == r}) + patients_at_hdr[(h, d, r)] = plist + + # For each (h,d,s): patients that can be scheduled with that surgeon there + patients_at_hds = {} + for (s, h, d) in active_shd: + plist = sorted({p for (p, ss, hh, dd, r) in feasible_tuples + if hh == h and dd == d and ss == s}) + patients_at_hds[(h, d, s)] = plist + + # ---------------------------------------------------------------- + # Big-M values per (h, d): max total OR time on that day + 1 + # (per math_model.txt comment 4) + # ---------------------------------------------------------------- + bigM_hd = {} + for (h, d) in active_hd: + rlist = ors_at_hd[(h, d)] + max_or_time = max(get_B(h, d, r) + get_V(h, d, r) for r in rlist) + bigM_hd[(h, d)] = max_or_time + 1.0 + + # ---------------------------------------------------------------- + # Create Gurobi model + # ---------------------------------------------------------------- + model = gp.Model("CORPS") + model.setParam("Threads", 1) + model.Params.TimeLimit = time_limit + + # ----------------- Allocation variables (MP) ----------------- + x = model.addVars(feasible_tuples, vtype=GRB.BINARY, name="x") + y = model.addVars(active_hdr, vtype=GRB.BINARY, name="y") + z = model.addVars(active_shd, vtype=GRB.BINARY, name="z") + v = model.addVars(active_hdr, lb=0.0, name="v") # overtime + for (h, d, r) in active_hdr: + v[h, d, r].ub = get_V(h, d, r) + + # ----------------- Sequencing variables (SP) ----------------- + # f[p, h, d] finishing time of patient p if scheduled at hospital h on day d + f_keys = list(tuples_by_phd.keys()) + f = model.addVars(f_keys, lb=0.0, name="f") + + # Per-OR upper bound on f_p when scheduled there + for (p, h, d) in f_keys: + f[p, h, d].ub = bigM_hd[(h, d)] + + # eta[p, k, h, d, r] : 1 if p is operated AFTER k in OR r at (h,d) + # Defined for p < k where p, k could share OR r (both have a tuple (.,.,h,d,r)) + eta_keys = [] + for (h, d, r) in active_hdr: + plist = patients_at_hdr[(h, d, r)] + for i in range(len(plist)): + for j in range(i + 1, len(plist)): + p, k = plist[i], plist[j] + eta_keys.append((p, k, h, d, r)) + eta = model.addVars(eta_keys, vtype=GRB.BINARY, name="eta") + + # pi[p, k, h, d, s] : 1 if p is operated AFTER k on surgeon s's list at (h,d) + pi_keys = [] + for (s, h, d) in active_shd: + plist = patients_at_hds[(h, d, s)] + for i in range(len(plist)): + for j in range(i + 1, len(plist)): + p, k = plist[i], plist[j] + pi_keys.append((p, k, h, d, s)) + pi = model.addVars(pi_keys, vtype=GRB.BINARY, name="pi") + + # c[h, d, r] : completion time of OR r at (h,d) + c = model.addVars(active_hdr, lb=0.0, name="c") + for (h, d, r) in active_hdr: + c[h, d, r].ub = bigM_hd[(h, d)] + + # i_s[s, h, d] : starting time of surgeon s's day at (h,d) + # e_s[s, h, d] : ending time of surgeon s's day at (h,d) + i_var = model.addVars(active_shd, lb=0.0, name="iS") + e_var = model.addVars(active_shd, lb=0.0, name="eS") + for (s, h, d) in active_shd: + i_var[s, h, d].ub = bigM_hd[(h, d)] + e_var[s, h, d].ub = bigM_hd[(h, d)] + + # ---------------------------------------------------------------- + # Objective: identical to MP + # ---------------------------------------------------------------- + obj = gp.LinExpr() + for (h, d, r) in active_hdr: + obj += get_K(h, d, r) * y[h, d, r] + for (s, h, d) in active_shd: + obj += get_L(s, h, d) * z[s, h, d] + for (h, d, r) in active_hdr: + obj += get_C(h, d, r) * v[h, d, r] + for pat in patients: + p = pat["patient_id"] + if not pat["is_mandatory"] and pat["reward"] > 0: + for tup in tuples_by_patient.get(p, []): + obj -= pat["reward"] * x[tup] + model.setObjective(obj, GRB.MINIMIZE) + + # ================================================================ + # ALLOCATION (MP) constraints (1)-(8) + # ================================================================ + + # (1) Mandatory patients scheduled exactly once + for pat in patients: + p = pat["patient_id"] + if pat["is_mandatory"]: + model.addConstr( + gp.quicksum(x[tup] for tup in tuples_by_patient.get(p, [])) == 1, + name=f"c1_mand_{p}" + ) + + # (2) Optional patients at most once + for pat in patients: + p = pat["patient_id"] + if not pat["is_mandatory"]: + model.addConstr( + gp.quicksum(x[tup] for tup in tuples_by_patient.get(p, [])) <= 1, + name=f"c2_opt_{p}" + ) + + # (3) Surgeon at most one hospital per day + surgeon_day_hospitals = {} + for (s, h, d) in active_shd: + surgeon_day_hospitals.setdefault((s, d), []).append((s, h, d)) + for (s, d), shd_list in surgeon_day_hospitals.items(): + if len(shd_list) >= 1: + model.addConstr( + gp.quicksum(z[s, h, d] for (s, h, d) in shd_list) <= 1, + name=f"c3_surg_one_hosp_{s}_{d}" + ) + + # (4) x_pshdr <= z_shd (aggregated per (p,s,h,d)) + for (p, s, h, d), r_list in tuples_by_pshd.items(): + model.addConstr( + gp.quicksum(x[p, s, h, d, r] for r in r_list) <= z[s, h, d], + name=f"c4_xz_{p}_{s}_{h}_{d}" + ) + + # (5) x_pshdr <= y_hdr + for tup in feasible_tuples: + p, s, h, d, r = tup + model.addConstr(x[tup] <= y[h, d, r], name=f"c5_xy_{p}_{s}_{h}_{d}_{r}") + + # (6) OR capacity (MP-level): sum T*x <= B*y + v + for (h, d, r), tup_list in tuples_by_or_day.items(): + model.addConstr( + gp.quicksum(get_T(p, s) * x[p, s, h, d, r] + for (p, s, _, _, _) in tup_list) + <= get_B(h, d, r) * y[h, d, r] + v[h, d, r], + name=f"c6_or_cap_{h}_{d}_{r}" + ) + + # (7) Surgeon weighted-time availability (MP-level) + for (s, h, d), tup_list in tuples_by_shd.items(): + A_sd = surgeon_avail.get((s, d), 0) + model.addConstr( + gp.quicksum( + (alpha * get_E(p, s) + (1 - alpha) * get_T(p, s)) + * x[p, s, h, d, r] + for (p, s_val, h_val, d_val, r) in tup_list + ) <= A_sd * z[s, h, d], + name=f"c7_surg_avail_{s}_{h}_{d}" + ) + + # (8) Overtime bounds 0 <= v <= V_hdr (already set via lb/ub) + # Add explicit upper bound constraint for documentation / dual visibility + for (h, d, r) in active_hdr: + model.addConstr(v[h, d, r] <= get_V(h, d, r), + name=f"c8_overtime_max_{h}_{d}_{r}") + + # ================================================================ + # SEQUENCING (SP) constraints (9)-(22) + # ================================================================ + + # (9) For every patient assigned at (h,d), exactly one (s,r) pair + # This is implied by combination of (1)/(2) plus (4)/(5), but we add + # the consistency form: sum_{s,r} x_pshdr at fixed (h,d) <= 1. + # The "= 1" form only applies if patient is at (h,d), which is captured + # by linking sequencing variables only to assigned tuples below. + # No explicit constraint needed beyond (1)/(2). + + # (10) f_p >= F_p + sum_s,r E_ps * x_pshdr [for any (p, h, d) where p is assigned] + # Linearize: f[p,h,d] >= F_p * (sum x_phdrs) + sum E_ps x_pshdr + # We tie f[p,h,d] to assignment: if patient not scheduled at (h,d), f=0 by lb. + # Actually f[p,h,d] >= F_p*assigned + sum_s,r E_ps x_pshdr is fine. + for (p, h, d), tup_list in tuples_by_phd.items(): + Fp = get_F(p) + # assigned indicator = sum_{s,r} x_pshdr (0 or 1) + assigned_expr = gp.quicksum(x[t] for t in tup_list) + E_expr = gp.quicksum(get_E(t[0], t[1]) * x[t] for t in tup_list) + model.addConstr( + f[p, h, d] >= Fp * assigned_expr + E_expr, + name=f"c10_f_min_{p}_{h}_{d}" + ) + # Also: if not assigned at (h,d), force f=0 (tightening, optional) + model.addConstr( + f[p, h, d] <= bigM_hd[(h, d)] * assigned_expr, + name=f"c10b_f_zero_{p}_{h}_{d}" + ) + + # (11)/(12) OR no-overlap: for p= f_k + G_k + F_p + E_ps + # else (k after p): f_k >= f_p + G_p + F_k + E_ks + # Linearization with M*(slack) per math_model.txt. + # x_psr (in math_model) corresponds here to sum_{s in Omega_p} x_pshdr (binary). + # We use the unique (p,h,d,r)-row sum since at most one s. + def x_at_phdr(p, h, d, r): + """Sum x_pshdr over s for fixed (p,h,d,r).""" + tlist = tuples_by_phdr.get((p, h, d, r), []) + if not tlist: + return None + return gp.quicksum(x[t] for t in tlist) + + for (h, d, r) in active_hdr: + plist = patients_at_hdr[(h, d, r)] + M = bigM_hd[(h, d)] + for i in range(len(plist)): + for j in range(i + 1, len(plist)): + p, k = plist[i], plist[j] + xp = x_at_phdr(p, h, d, r) + xk = x_at_phdr(k, h, d, r) + Fp, Fk = get_F(p), get_F(k) + Gp, Gk = get_G(p), get_G(k) + # E_ps depends on s — but since at most one s wins, we can + # use sum_s E_ps * x_pshdr (this is exactly E_ps if assigned). + E_p_expr = gp.quicksum(get_E(t[0], t[1]) * x[t] + for t in tuples_by_phdr[(p, h, d, r)]) + E_k_expr = gp.quicksum(get_E(t[0], t[1]) * x[t] + for t in tuples_by_phdr[(k, h, d, r)]) + # (11) p after k + model.addConstr( + f[p, h, d] >= f[k, h, d] + Gk * xk + Fp * xp + E_p_expr + - M * (3 - eta[p, k, h, d, r] - xp - xk), + name=f"c11_ord_pk_{p}_{k}_{h}_{d}_{r}" + ) + # (12) k after p + model.addConstr( + f[k, h, d] >= f[p, h, d] + Gp * xp + Fk * xk + E_k_expr + - M * (2 + eta[p, k, h, d, r] - xp - xk), + name=f"c12_ord_kp_{p}_{k}_{h}_{d}_{r}" + ) + + # (13)/(14) Surgeon no-overlap: for p= f_k + E_ps + # else : f_k >= f_p + E_ks + # NOTE: for surgeon ordering, paper writes E_ps without prep time -- this + # is because the surgeon only needs to be present DURING the surgery proper. + def x_at_phds(p, h, d, s): + """Sum x_pshdr over r for fixed (p,s,h,d).""" + rlist = tuples_by_pshd.get((p, s, h, d), []) + if not rlist: + return None + return gp.quicksum(x[(p, s, h, d, r)] for r in rlist) + + for (s, h, d) in active_shd: + plist = patients_at_hds[(h, d, s)] + M = bigM_hd[(h, d)] + for i in range(len(plist)): + for j in range(i + 1, len(plist)): + p, k = plist[i], plist[j] + xp = x_at_phds(p, h, d, s) + xk = x_at_phds(k, h, d, s) + E_ps = get_E(p, s) + E_ks = get_E(k, s) + # (13) p after k + model.addConstr( + f[p, h, d] >= f[k, h, d] + E_ps * xp + - M * (3 - pi[p, k, h, d, s] - xp - xk), + name=f"c13_surg_pk_{p}_{k}_{h}_{d}_{s}" + ) + # (14) k after p + model.addConstr( + f[k, h, d] >= f[p, h, d] + E_ks * xk + - M * (2 + pi[p, k, h, d, s] - xp - xk), + name=f"c14_surg_kp_{p}_{k}_{h}_{d}_{s}" + ) + + # (15) f_p + G_p <= B_r + v_r whenever p uses OR r at (h,d) + # Linearized: f_p + G_p - M*(1 - x_at_phdr) <= B_r*y_hdr + v_hdr + for (h, d, r) in active_hdr: + plist = patients_at_hdr[(h, d, r)] + M = bigM_hd[(h, d)] + Br = get_B(h, d, r) + for p in plist: + xpr = x_at_phdr(p, h, d, r) + Gp = get_G(p) + model.addConstr( + f[p, h, d] + Gp * xpr - M * (1 - xpr) + <= Br * y[h, d, r] + v[h, d, r], + name=f"c15_f_le_Bv_{p}_{h}_{d}_{r}" + ) + + # (16) e_s >= f_p whenever p assigned to s at (h,d) + # (17) i_s <= f_p - E_ps whenever p assigned to s at (h,d) + for (s, h, d) in active_shd: + plist = patients_at_hds[(h, d, s)] + M = bigM_hd[(h, d)] + for p in plist: + xps = x_at_phds(p, h, d, s) + E_ps = get_E(p, s) + # (16) + model.addConstr( + e_var[s, h, d] >= f[p, h, d] - M * (1 - xps), + name=f"c16_es_ge_fp_{s}_{p}_{h}_{d}" + ) + # (17) + model.addConstr( + i_var[s, h, d] <= f[p, h, d] - E_ps * xps + M * (1 - xps), + name=f"c17_is_le_fp_{s}_{p}_{h}_{d}" + ) + + # (18) e_s - i_s <= A_s (use A_sd; the SP uses surgeon-day availability) + for (s, h, d) in active_shd: + A_sd = surgeon_avail.get((s, d), 0) + model.addConstr( + e_var[s, h, d] - i_var[s, h, d] <= A_sd, + name=f"c18_surg_window_{s}_{h}_{d}" + ) + + # (19) c_r >= f_p + G_p whenever p uses OR r + for (h, d, r) in active_hdr: + plist = patients_at_hdr[(h, d, r)] + M = bigM_hd[(h, d)] + for p in plist: + xpr = x_at_phdr(p, h, d, r) + Gp = get_G(p) + model.addConstr( + c[h, d, r] >= f[p, h, d] + Gp * xpr - M * (1 - xpr), + name=f"c19_cr_ge_fp_{p}_{h}_{d}_{r}" + ) + + # (20) 0 <= v_r <= V_r (already enforced via bounds + (8)) + # (21) v_r >= c_r - B_r + for (h, d, r) in active_hdr: + Br = get_B(h, d, r) + model.addConstr( + v[h, d, r] >= c[h, d, r] - Br * y[h, d, r], + name=f"c21_overtime_def_{h}_{d}_{r}" + ) + + # (22) integrality (already declared via vtype=BINARY) + + # ---------------------------------------------------------------- + # Solve + # ---------------------------------------------------------------- + wall_start = time.time() + model.optimize() + wall_time = time.time() - wall_start + + # ---------------------------------------------------------------- + # Extract solution + # ---------------------------------------------------------------- + result = { + "instance_path": instance_path, + "solver": "gurobi", + "time_limit": time_limit, + "wall_time": round(wall_time, 2), + "status": model.Status, + "status_name": { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.SUBOPTIMAL: "SUBOPTIMAL", + }.get(model.Status, str(model.Status)), + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["mip_gap"] = model.MIPGap + + # --- Patient assignments + finish times --- + assignments = [] + for tup in feasible_tuples: + if x[tup].X > 0.5: + p, s, h, d, r = tup + pat = patient_data[p] + fp_val = f[p, h, d].X if (p, h, d) in f_keys else 0.0 + E_ps = get_E(p, s) + Fp = get_F(p) + Gp = get_G(p) + start_time = max(0.0, fp_val - E_ps) + room_in = max(0.0, fp_val - E_ps - Fp) + room_out = fp_val + Gp + assignments.append({ + "patient_id": p, + "surgeon_id": s, + "hospital_id": h, + "day": d, + "or_id": r, + "is_mandatory": pat["is_mandatory"], + "T_ps": get_T(p, s), + "finish_time": round(fp_val, 4), + "surgery_start_time": round(start_time, 4), + "room_entry_time": round(room_in, 4), + "room_exit_time": round(room_out, 4), + }) + + # --- Opened ORs with completion + overtime --- + opened_ors = [] + for (h, d, r) in active_hdr: + if y[h, d, r].X > 0.5: + opened_ors.append({ + "hospital_id": h, + "day": d, + "or_id": r, + "regular_time": get_B(h, d, r), + "completion_time": round(c[h, d, r].X, 4), + "overtime": round(v[h, d, r].X, 4), + }) + + # --- Surgeon assignments with start/end --- + surgeon_assignments = [] + for (s, h, d) in active_shd: + if z[s, h, d].X > 0.5: + surgeon_assignments.append({ + "surgeon_id": s, + "hospital_id": h, + "day": d, + "start_time": round(i_var[s, h, d].X, 4), + "end_time": round(e_var[s, h, d].X, 4), + }) + + # --- Sequencing (order) decisions --- + or_sequences = [] + for (p, k, h, d, r) in eta_keys: + xp_v = sum(x[t].X for t in tuples_by_phdr.get((p, h, d, r), [])) + xk_v = sum(x[t].X for t in tuples_by_phdr.get((k, h, d, r), [])) + if xp_v > 0.5 and xk_v > 0.5: + or_sequences.append({ + "hospital_id": h, + "day": d, + "or_id": r, + "patient_p": p, + "patient_k": k, + "p_after_k": int(eta[p, k, h, d, r].X > 0.5), + }) + + surgeon_sequences = [] + for (p, k, h, d, s) in pi_keys: + xp_v = sum(x[(p, s, h, d, r)].X + for r in tuples_by_pshd.get((p, s, h, d), [])) + xk_v = sum(x[(k, s, h, d, r)].X + for r in tuples_by_pshd.get((k, s, h, d), [])) + if xp_v > 0.5 and xk_v > 0.5: + surgeon_sequences.append({ + "hospital_id": h, + "day": d, + "surgeon_id": s, + "patient_p": p, + "patient_k": k, + "p_after_k": int(pi[p, k, h, d, s].X > 0.5), + }) + + result["assignments"] = assignments + result["opened_ors"] = opened_ors + result["surgeon_assignments"] = surgeon_assignments + result["or_sequences"] = or_sequences + result["surgeon_sequences"] = surgeon_sequences + result["num_patients_scheduled"] = len(assignments) + result["num_mandatory_scheduled"] = sum( + 1 for a in assignments if a["is_mandatory"]) + result["num_optional_scheduled"] = sum( + 1 for a in assignments if not a["is_mandatory"]) + else: + result["objective_value"] = None + result["best_bound"] = None + result["mip_gap"] = None + result["assignments"] = [] + result["opened_ors"] = [] + result["surgeon_assignments"] = [] + result["or_sequences"] = [] + result["surgeon_sequences"] = [] + result["num_patients_scheduled"] = 0 + result["num_mandatory_scheduled"] = 0 + result["num_optional_scheduled"] = 0 + + with open(solution_path, "w") as f_out: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f_out, indent=2) + + print(f"Status: {result['status_name']}") + print(f"Objective: {result['objective_value']}") + print(f"Wall time: {wall_time:.2f}s") + print(f"Solution written to {solution_path}") + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the CORPS model (Roshanaei et al. 2017) with Gurobi" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the instance JSON file") + parser.add_argument("--solution_path", type=str, + default="gurobi_solution_1.json", + help="Path to write the solution JSON file") + parser.add_argument("--time_limit", type=int, default=3600, + help="Gurobi time limit in seconds") + parser.add_argument("--log_path", type=str, default=None, + help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/roshanaei2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/roshanaei2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roshanaei2017/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/roshanaei2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/roshanaei2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roshanaei2017/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/roshanaei2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/roshanaei2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roshanaei2017/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/roshanaei2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/roshanaei2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roshanaei2017/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/roshanaei2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/roshanaei2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roshanaei2017/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/roshanaei2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/roshanaei2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/roshanaei2017/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/roshanaei2017/gurobi_solution/large_solution_1.json b/tasks/roshanaei2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e6ca8ff96acd79299a5c7efecfe5199010bf0f43 --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7e99110176bce10938d0b92de536c7244af53de238f91a34447be911a617959 +size 78651 diff --git a/tasks/roshanaei2017/gurobi_solution/large_solution_2.json b/tasks/roshanaei2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..23f7e58ee9c7439bab65f8d08aa797ab4d354202 --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2821bfefa123a65cfd7b0f17a5a002421bf5e4209cb694819809a74130cbee50 +size 71937 diff --git a/tasks/roshanaei2017/gurobi_solution/large_solution_3.json b/tasks/roshanaei2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..85efb2bfa6bd2d784d07932454f9d76817cebde3 --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfee606ceb463f8d19205a73f641614b407a43fee05ed4f40564f2729799a50b +size 71453 diff --git a/tasks/roshanaei2017/gurobi_solution/large_solution_4.json b/tasks/roshanaei2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..579c8c2de0c1d73443efc5164b4eefc7430427fc --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a535f06afd5d06509979ac674a97b8c0d054fdb6fe06438b433ed2e8a3af7bb +size 73857 diff --git a/tasks/roshanaei2017/gurobi_solution/large_solution_5.json b/tasks/roshanaei2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..57638047514b5d1e557026cdcd636a0b8ecad9fb --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1cf1e7e07fed369a2efe9c51d9a303ac584287f671145904ec5a7f7b1f0213e +size 81698 diff --git a/tasks/roshanaei2017/gurobi_solution/tiny_solution.json b/tasks/roshanaei2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..538ed813b083a25a8f2bc2c8008639629d805b3b --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf3aba3864fa18e76f151e787b134b3009c12556893e55f1ed931205f6bf858a +size 5103 diff --git a/tasks/roshanaei2017/gurobi_solution_log/large_log_1.jsonl b/tasks/roshanaei2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8668f77a48012f6bb413d855be0ac7e708627672 --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed7dcdb80537682a6faa3109e8799de8fe9376f8c1b92f639a9057dd9226193b +size 4358 diff --git a/tasks/roshanaei2017/gurobi_solution_log/large_log_2.jsonl b/tasks/roshanaei2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce407c30e78f9f5cbbafb33d02175f16e7724abf --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4296e6e75d216ccac5cb6afbe1e92070d1c75821cc5446b7e9c093a2d7355dea +size 3407 diff --git a/tasks/roshanaei2017/gurobi_solution_log/large_log_3.jsonl b/tasks/roshanaei2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..16b077a46ac3cca40c310cd10c27d406393689b4 --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f641b88db4548c8f7afae98f18247729368a4e3fc16a27ffcdd661f64ba4eee +size 3127 diff --git a/tasks/roshanaei2017/gurobi_solution_log/large_log_4.jsonl b/tasks/roshanaei2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..615f4b57767a221c71cc7501a2e07d10253c04f9 --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3545fa05f91c9382955323cc7fe4162624c5b8a028bdb814fec559490c4e8e42 +size 4426 diff --git a/tasks/roshanaei2017/gurobi_solution_log/large_log_5.jsonl b/tasks/roshanaei2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8b329b4cf4839243dbadb611bd986c987e41d072 --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f625bc46a799202b4d74af78f916e82a698b729936e48e77c2bf55e4d9e74b1 +size 4100 diff --git a/tasks/roshanaei2017/gurobi_solution_log/tiny_log.jsonl b/tasks/roshanaei2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bafa5ab844da68b26742d250d75d94f1275d7a2d --- /dev/null +++ b/tasks/roshanaei2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff2770aa4cdf21b5ac701b2c040b56a4753ae8d98118ce9233560db2bde138c7 +size 108 diff --git a/tasks/roshanaei2017/instance/large_instance_1.json b/tasks/roshanaei2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..82978c7660e6cfba72c89674ed0baf09e9d2911a --- /dev/null +++ b/tasks/roshanaei2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a95e2225d2ffbfe748cb6de1039dc05d716f167c587daf28f32467f67ef8f05e +size 87669 diff --git a/tasks/roshanaei2017/instance/large_instance_2.json b/tasks/roshanaei2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..19fe6ffd3c605e51b4b757900d786d8f503b223d --- /dev/null +++ b/tasks/roshanaei2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61277433c676fd7bd4953c4b5734e67f6b936dca7adb2545d1561b85f78dd90a +size 87466 diff --git a/tasks/roshanaei2017/instance/large_instance_3.json b/tasks/roshanaei2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..0f7e06310b17d302f44db16294365d0e5c8565db --- /dev/null +++ b/tasks/roshanaei2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82418aef3a1cbf261ad6a318b7e15489f1c35bf33448bde160893e7fb588a3dd +size 88130 diff --git a/tasks/roshanaei2017/instance/large_instance_4.json b/tasks/roshanaei2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..0bba81b7cd05ca2be43235b02421d70af19456c3 --- /dev/null +++ b/tasks/roshanaei2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f2310a8803957f212463583bddc9f38d0edde482449c082d9fab3eeb07c4569 +size 87695 diff --git a/tasks/roshanaei2017/instance/large_instance_5.json b/tasks/roshanaei2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..7cb115f8582b3457a888877cc1710fe7cb67d478 --- /dev/null +++ b/tasks/roshanaei2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84ed8ea731203d29890aa28c624a4e9ad2290ea62aefa296fb5483fd2a6dc424 +size 87550 diff --git a/tasks/roshanaei2017/instance/tiny_instance.json b/tasks/roshanaei2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..01305582ae1c49cfc74fe22096b65bc85de40f87 --- /dev/null +++ b/tasks/roshanaei2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e308098c70e0046c228cc609aa41fdea32751895526d8b047395f8c4358e1730 +size 12307 diff --git a/tasks/roshanaei2017/instance_schema.json b/tasks/roshanaei2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..6b43863606ab845de088ffc9a6e6056e4d82e385 --- /dev/null +++ b/tasks/roshanaei2017/instance_schema.json @@ -0,0 +1,59 @@ +{ + "num_patients": " Total number of patients requiring surgical scheduling.", + "num_surgeons": " Total number of surgeons available across all hospitals.", + "num_hospitals": " Total number of hospitals in the coalition.", + "ORs_per_hospital": " Number of operating rooms in each hospital.", + "num_days": " Number of days in the planning horizon.", + "alpha": " Schedule tightness parameter controlling how surgeon workload is measured, where 0 counts full OR-occupation time and 1 counts only surgical procedure time.", + "patients": [ + { + "patient_id": " Unique identifier for this patient.", + "due_date": " Latest day by which this patient must be scheduled, where values within the planning horizon indicate a mandatory patient and values beyond indicate an optional patient.", + "is_mandatory": " Whether this patient must be scheduled within the planning horizon.", + "preparation_time": " Pre-incision setup time in minutes required before the surgeon begins operating on this patient.", + "cleaning_time": " OR turnover time in minutes required after this patient's surgery is completed.", + "base_surgical_time": " Baseline surgical procedure duration in minutes before surgeon-specific adjustment.", + "eligible_surgeons": " Surgeons qualified to operate on this patient.", + "eligible_ORs_by_hospital": { + "{hospital_id}": " Operating rooms at this hospital where this patient can be scheduled." + }, + "surgeon_specific_times": { + "{surgeon_id}": " Surgical procedure duration in minutes when this specific surgeon operates on this patient." + }, + "reward": " Benefit earned for scheduling this optional patient within the current planning horizon, or 0 for mandatory patients." + } + ], + "surgeons": [ + { + "surgeon_id": " Unique identifier for this surgeon.", + "availability_by_day": { + "{day}": " Maximum number of minutes this surgeon is available to operate on this day." + }, + "operating_days": " Days within the planning horizon on which this surgeon is available to operate." + } + ], + "hospitals": [ + { + "hospital_id": " Unique identifier for this hospital.", + "hospital_name": " Name of this hospital.", + "ORs": [ + { + "or_id": " Unique identifier for this operating room within its hospital.", + "regular_time": " Default regular session time in minutes for this operating room.", + "max_overtime": " Default maximum allowable overtime in minutes for this operating room.", + "fixed_cost_per_hour": " Hourly cost incurred when this operating room is opened for a day.", + "overtime_cost_per_hour": " Hourly cost charged for each hour of overtime used in this operating room.", + "daily": { + "{day}": { + "regular_time": " Regular session time in minutes for this operating room on this day.", + "max_overtime": " Maximum allowable overtime in minutes for this operating room on this day." + } + } + } + ], + "surgeon_fixed_costs_per_day": { + "{surgeon_id}": " Fixed cost incurred when this surgeon is assigned to operate at this hospital on any given day." + } + } + ] +} diff --git a/tasks/roshanaei2017/mathematical_formulation.md b/tasks/roshanaei2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..1acbf6292fbb43aab8742b54d010081e23fa14e2 --- /dev/null +++ b/tasks/roshanaei2017/mathematical_formulation.md @@ -0,0 +1,153 @@ +# Original Formulation: Collaborative Operating Room Planning and Scheduling (CORPS) + +*Source: Collaborative Operating Room Planning and Scheduling, Vahid Roshanaei, Curtiss Luong, Dionne M. Aleman, David R. Urbach, INFORMS Journal on Computing 29(3):558–580, 2017.* + +## Sets and Indices + +$$\begin{align*} +& p,\, s,\, h,\, d,\, r && \text{indices for patients, surgeons, hospitals, days, ORs}\\ +& \mathcal{P} && \text{set of patients } (p=1,\dots,|\mathcal{P}|)\\ +& \mathcal{S} && \text{set of surgeons } (s=1,\dots,|\mathcal{S}|)\\ +& \mathcal{H} && \text{set of hospitals } (h=1,\dots,|\mathcal{H}|)\\ +& \mathcal{D} && \text{set of days in the planning horizon } (d=1,\dots,|\mathcal{D}|)\\ +& \mathcal{R}_h && \text{set of ORs in hospital } h \ (r=1,\dots,|\mathcal{R}_h|)\\ +& \mathcal{P}_{hdr} && \text{patients operable in room } r \text{ of hospital } h \text{ with } \theta_p \geq d\\ +& \Lambda_{s,d} && \text{patients belonging to surgeon } s \text{ with } \theta_p \geq d\\ +& \Omega_p && \text{set of preferred (qualified) surgeons for patient } p\\ +& \Delta_s && \text{set of days on which surgeon } s \text{ operates}\\ +& \mathcal{C}_{ph} && \text{set of ORs at hospital } h \text{ eligible for patient } p +\end{align*}$$ SP-specific sets (Table 2), defined over the case set of one hospital-day: $$\begin{align*} +& \mathcal{C}_p && \text{qualified ORs for patient } p\\ +& \mathcal{C}_{pk} && \text{qualified ORs shared between patients } p \text{ and } k\\ +& \Omega_p && \text{qualified surgeons for patient } p\\ +& \Omega_{pk} && \text{qualified surgeons shared between patients } p \text{ and } k\\ +& \hat{\mathcal{P}}_{hd}^{(i)},\ \hat{\mathcal{S}}_{hd}^{(i)},\ \hat{\mathcal{R}}_{hd}^{(i)} + && \text{patients, surgeons, ORs assigned by the MP to hospital } h, \text{ day } d \text{ at iteration } i +\end{align*}$$ + +## Parameters + +$$\begin{align*} +& K_{hdr},\, C_{hdr} && \text{fixed and variable (overtime) costs of OR } r \text{ in hospital } h \text{ on day } d\\ +& L_{shd} && \text{fixed cost of surgeon } s \text{ operating in hospital } h \text{ on day } d\\ +& B_{hdr}\ (\text{SP: } B_r) && \text{regular time of OR } r \text{ in hospital } h \text{ on day } d\\ +& T_{ps} && \text{total preparation + surgery + cleaning time of patient } p \text{ by surgeon } s\\ +& F_p && \text{preparation time of patient } p\\ +& G_p && \text{OR turnover (cleaning) time after patient } p\\ +& E_{ps} && \text{surgical procedure time of patient } p \text{ by surgeon } s,\ \ E_{ps}=T_{ps}-(G_p+F_p)\\ +& A_{sd}\ (\text{SP: } A_s) && \text{available time of surgeon } s \text{ on day } d\\ +& U_p && \text{reward for optional patient } p \text{ if operated on in the current horizon}\\ +& \theta_p && \text{due date of patient } p\\ +& V_{hdr}\ (\text{SP: } V_r) && \text{maximum allowable overtime of OR } r\\ +& \alpha && \text{surgeon schedule tightness coefficient, } \alpha \in [0,1]\\ +& M && \text{a large positive number (SP)} +\end{align*}$$ + +## Decision Variables + +Allocation Master Problem (MP): $$\begin{align*} +& x_{pshdr} \in \{0,1\} && 1 \text{ if patient } p \text{ is operated by surgeon } s \text{ in hospital } h \text{ on day } d \text{ in room } r\\ +& y_{hdr} \in \{0,1\} && 1 \text{ if room } r \text{ of hospital } h \text{ on day } d \text{ is opened}\\ +& z_{shd} \in \{0,1\} && 1 \text{ if surgeon } s \text{ is in hospital } h \text{ on day } d\\ +& v_{hdr} \geq 0 && \text{overtime of OR } r \text{ in hospital } h \text{ on day } d +\end{align*}$$ Sequencing Subproblem (SP), per hospital-day $hd$: $$\begin{align*} +& x_{psr} \in \{0,1\} && 1 \text{ if patient } p \text{ is operated by surgeon } s \text{ in OR } r\\ +& \eta_{pkr} \in \{0,1\} && 1 \text{ if patient } p \text{ is operated after patient } k \text{ in OR } r\\ +& \pi_{pks} \in \{0,1\} && 1 \text{ if patient } p \text{ is operated after patient } k \text{ on surgeon } s\text{'s list}\\ +& f_p \geq 0 && \text{finishing time of surgical case } p\\ +& c_r \geq 0 && \text{completion time of OR } r\\ +& v_r \geq 0 && \text{overtime of OR } r\\ +& i_s \geq 0 && \text{starting time of surgeon } s\\ +& e_s \geq 0 && \text{ending time of surgeon } s +\end{align*}$$ + +## Objective + +**Allocation Master Problem (MP).** Minimize OR-opening, surgeon, and overtime costs, less the rewards earned by scheduling optional patients: $$\begin{equation} +\min \Bigg\{ +\sum_{h \in \mathcal{H}} \sum_{d \in \mathcal{D}} \sum_{r \in \mathcal{R}_h} K_{hdr}\, y_{hdr} ++ \sum_{s \in \mathcal{S}} \sum_{h \in \mathcal{H}} \sum_{d \in \mathcal{D}} L_{shd}\, z_{shd} ++ \sum_{h \in \mathcal{H}} \sum_{d \in \mathcal{D}} \sum_{r \in \mathcal{R}_h} C_{hdr}\, v_{hdr} +- \sum_{p \in \mathcal{P} \,\mid\, \theta_p > |\mathcal{D}|} U_p + \sum_{s \in \Omega_p} \sum_{h \in \mathcal{H}} \sum_{d \in \mathcal{D}} \sum_{r \in \mathcal{C}_{ph}} x_{pshdr} +\Bigg\} \tag{MP} +\end{equation}$$ + +**Sequencing Subproblem (SP), for hospital-day $hd$.** Minimize OR overtime cost: $$\begin{equation} +\min\ \ \bar{v}_{hdr}^{(i)} = \sum_{r \in \hat{\mathcal{R}}_{hd}^{(i)}} c_r\, v_r \tag{SP} +\end{equation}$$ + +## Constraints + +#### Allocation Master Problem (MP). + +$$\begin{align} +& \sum_{s \in \Omega_p} \sum_{h \in \mathcal{H}} \sum_{d \leq \theta_p} \sum_{r \in \mathcal{C}_{ph}} x_{pshdr} = 1 + && \forall\, p \in \mathcal{P} \mid \theta_p \leq |\mathcal{D}| \tag{1}\\ +& \sum_{s \in \Omega_p} \sum_{h \in \mathcal{H}} \sum_{d \in \mathcal{D}} \sum_{r \in \mathcal{C}_{ph}} x_{pshdr} \leq 1 + && \forall\, p \in \mathcal{P} \mid \theta_p > |\mathcal{D}| \tag{2}\\ +& \sum_{h \in \mathcal{H}} z_{shd} \leq 1 + && \forall\, s \in \mathcal{S};\ d \in \Delta_s \tag{3}\\ +& x_{pshdr} \leq z_{shd} + && \forall\, p \in \mathcal{P};\ s \in \Omega_p;\ h \in \mathcal{H};\ d \in \Delta_s;\ r \in \mathcal{C}_{ph} \tag{4}\\ +& x_{pshdr} \leq y_{hdr} + && \forall\, p \in \mathcal{P};\ s \in \Omega_p;\ h \in \mathcal{H};\ d \in \Delta_s;\ r \in \mathcal{C}_{ph} \tag{5}\\ +& \sum_{p \in \mathcal{P}_{hdr}} \sum_{s \in \Omega_p} T_{ps}\, x_{pshdr} \leq B_{hdr}\, y_{hdr} + v_{hdr} + && \forall\, h \in \mathcal{H};\ d \in \Delta_s;\ r \in \mathcal{R}_h \tag{6}\\ +& \sum_{p \in \Lambda_{s,d}} \sum_{r \in \mathcal{C}_{ph}} \big(\alpha E_{ps} + (1-\alpha) T_{ps}\big) x_{pshdr} \leq A_{sd}\, z_{shd} + && \forall\, s \in \mathcal{S};\ h \in \mathcal{H};\ d \in \Delta_s \tag{7}\\ +& V_{hdr} \geq v_{hdr} \geq 0 + && \forall\, h \in \mathcal{H};\ d \in \mathcal{D};\ r \in \mathcal{R}_h \tag{8}\\ +& x_{pshdr},\, y_{hdr},\, z_{shd} \in \{0,1\} + && \forall\, p \in \mathcal{P};\ s \in \Omega_p;\ h \in \mathcal{H};\ d \in \Delta_s;\ r \in \mathcal{C}_{ph} \notag +\end{align}$$ + +#### Sequencing Subproblem (SP), for hospital-day $hd$ at iteration $i$. + +(All summation index sets are intersected with the MP-assigned sets $\hat{\mathcal{S}}_{hd}^{(i)}$, $\hat{\mathcal{R}}_{hd}^{(i)}$, $\hat{\mathcal{P}}_{hd}^{(i)}$.) $$\begin{align} +& \sum_{s \in \hat{\mathcal{S}}_{hd}^{(i)} \cap \Omega_p} + \sum_{r \in \hat{\mathcal{R}}_{hd}^{(i)} \cap \mathcal{C}_p} x_{psr} = 1 + && \forall\, p \in \hat{\mathcal{P}}_{hd}^{(i)} \tag{9}\\ +& f_p \geq F_p + \sum_{s \in \hat{\mathcal{S}}_{hd}^{(i)} \cap \Omega_p} + \sum_{r \in \hat{\mathcal{R}}_{hd}^{(i)} \cap \mathcal{C}_p} E_{ps}\, x_{psr} + && \forall\, p \in \hat{\mathcal{P}}_{hd}^{(i)} \tag{10}\\ +& f_p \geq f_k + G_k + F_p + \sum_{s \in \hat{\mathcal{S}}_{hd}^{(i)} \cap \Omega_p} E_{ps}\, x_{psr} + - M\Big(3 - \eta_{pkr} - \!\!\sum_{s \in \hat{\mathcal{S}}_{hd}^{(i)} \cap \Omega_p}\!\! x_{psr} + - \!\!\sum_{s \in \hat{\mathcal{S}}_{hd}^{(i)} \cap \Omega_k}\!\! x_{ksr}\Big) + && \forall\, p,k \in \hat{\mathcal{P}}_{hd}^{(i)} \mid p= 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/roshanaei2017/solution_schema.json b/tasks/roshanaei2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..773deda197ed035e976ca41cbe5c19bc0bbf99b2 --- /dev/null +++ b/tasks/roshanaei2017/solution_schema.json @@ -0,0 +1,57 @@ +{ + "objective_value": " Total cost equal to the sum of opened operating-room fixed costs, surgeon-hospital-day fixed costs, and overtime costs, minus the rewards earned from scheduled optional patients.", + "assignments": [ + { + "patient_id": " Identifier of the scheduled patient.", + "surgeon_id": " Identifier of the surgeon assigned to perform this patient's surgery.", + "hospital_id": " Identifier of the hospital where this patient's surgery is performed.", + "day": " Day in the planning horizon on which this patient's surgery takes place.", + "or_id": " Identifier of the operating room within the chosen hospital used for this patient.", + "is_mandatory": " Whether the scheduled patient is a mandatory case (true) or an optional case (false).", + "T_ps": " Total operating-room occupation time for this patient with the assigned surgeon, equal to preparation time plus surgeon-specific surgical procedure time plus cleaning time.", + "finish_time": " Clock time within the day at which the surgical procedure on this patient is completed.", + "surgery_start_time": " Clock time within the day at which the surgeon begins the surgical procedure on this patient.", + "room_entry_time": " Clock time within the day at which the patient enters the operating room and preparation begins.", + "room_exit_time": " Clock time within the day at which the patient leaves the operating room after cleaning is finished." + } + ], + "opened_ors": [ + { + "hospital_id": " Identifier of the hospital containing the opened operating room.", + "day": " Day in the planning horizon on which the operating room is opened.", + "or_id": " Identifier of the operating room that is opened in the given hospital on the given day.", + "regular_time": " Regular non-overtime session length available in this operating room on this day.", + "completion_time": " Clock time at which the last surgery in this operating room finishes, including its subsequent cleaning.", + "overtime": " Amount of overtime used in this operating room beyond its regular session length." + } + ], + "surgeon_assignments": [ + { + "surgeon_id": " Identifier of the surgeon deployed to a hospital on a given day.", + "hospital_id": " Identifier of the hospital to which the surgeon is deployed on this day.", + "day": " Day in the planning horizon on which the surgeon works at the assigned hospital.", + "start_time": " Clock time at which the surgeon begins working at the assigned hospital on this day.", + "end_time": " Clock time at which the surgeon finishes working at the assigned hospital on this day." + } + ], + "or_sequences": [ + { + "hospital_id": " Identifier of the hospital containing the operating room shared by the two patients.", + "day": " Day in the planning horizon on which both patients are scheduled in the same operating room.", + "or_id": " Identifier of the operating room in which both patients are scheduled on this day.", + "patient_p": " Identifier of the first patient in the ordered pair sharing this operating room on this day.", + "patient_k": " Identifier of the second patient in the ordered pair sharing this operating room on this day.", + "p_after_k": " Equals 1 if patient_p is operated on after patient_k in this operating room, and 0 if patient_k is operated on after patient_p." + } + ], + "surgeon_sequences": [ + { + "hospital_id": " Identifier of the hospital where the two patients share the same surgeon on the given day.", + "day": " Day in the planning horizon on which the surgeon operates on both patients.", + "surgeon_id": " Identifier of the surgeon who performs both patients' surgeries at this hospital on this day.", + "patient_p": " Identifier of the first patient in the ordered pair sharing this surgeon on this day.", + "patient_k": " Identifier of the second patient in the ordered pair sharing this surgeon on this day.", + "p_after_k": " Equals 1 if patient_p's surgery is performed after patient_k's by this surgeon, and 0 if patient_k's surgery is performed after patient_p's." + } + ] +} diff --git a/tasks/rostami2021/feasibility_check.py b/tasks/rostami2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..581af86d427455448389327260bdb5bbb315c33b --- /dev/null +++ b/tasks/rostami2021/feasibility_check.py @@ -0,0 +1,618 @@ +""" +Feasibility checker for the Stochastic Single-Allocation Hub Location Problem +with Variable Allocation (DEF_V). + +Checks ORIGINAL DEF_V constraints (the formulation (25)-(28) in the paper): + Constraint 1 (tag 25): sum_{k!=i} x^s_{ik} = 1 - z_i, for all i in N, s in S_w + Constraint 2 (tag 26): x^s_{ik} <= z_k, for all i,k in N (i!=k), s in S_w + Constraint 3 (tag 27): z_i in {0,1}, for all i in N + Constraint 4 (tag 28): x^s_{ik} in {0,1}, for all i,k in N, s in S_w + +Additionally checks variant-specific constraints: + Constraint 5 (tag 20): sum_k z_k >= 1 (SAHLP / CSAHLP: at least one hub) + Constraint 6 (SApHMP only): sum_k z_k = p (exactly p hubs) + Constraint 7 (CSAHLP only): sum_i O^s_i * X^s_{ik} <= Gamma_k * z_k, for all k, s + +Tier-C objective-consistency check (added to defeat LLM score-gaming exploits +that fabricate `objective_value`): + Constraint 8: the reported objective_value must equal the obj recomputed + from (z, x^s) using the DEF_V formula (Section 3.2 / page 8): + obj = sum_k f_k z_k + + sum_s p_s sum_{i,k, i!=k} c^s_{ik} x^s_{ik} + + sum_s p_s sum_{i,j} alpha w^s_{ij} + sum_{k,l in N} d_{k,l} X^s_{i,k} X^s_{j,l} + where c^s_{ik} = d_{ik}(chi O^s_i + delta D^s_i), + X^s_{i,i} := z_i, X^s_{i,k} := x^s_{i,k} for k != i. + Tolerance: max(1e-3, 1e-3 * |true_obj|) (0.1% relative, + 1e-3 absolute floor). For SApHMP, the f_k z_k term is + dropped (the fixed-cost layer is replaced by the p-hub + cardinality constraint). + +The flow variables y^s_{ikl} and flow-balance constraints (Eq 9-11) are an +Ernst-Krishnamoorthy linearization of the original quadratic inter-hub +transport terms; they are NOT part of the original DEF_V formulation +(25)-(28) and are therefore NOT checked here. LLM-evolved algorithms that +solve DEF_V without flow linearization still produce valid original- +formulation solutions, which this checker must accept. +""" + +import json +import argparse + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('allocations', 'hubs', 'objective_value', 'x_values', 'z_values') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('hubs', 'allocations') +_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="Check feasibility of a candidate solution for the stochastic SAHLP (DEF_V)." + ) + 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() + + tol = 1e-5 + eps = 1e-5 + + # ========================================================================= + # Load instance data + # ========================================================================= + with open(args.instance_path, 'r') as f: + instance = json.load(f) + + n = instance['n'] + num_scenarios = instance['num_scenarios'] + variant = instance['problem_info']['variant'] + scenarios = instance['scenarios'] + p_hubs = instance.get('p_hubs') + hub_capacities = instance.get('hub_capacities') + distances = instance['distances'] + fixed_costs = instance['fixed_costs'] + chi = instance['cost_parameters']['chi'] + alpha = instance['cost_parameters']['alpha'] + delta = instance['cost_parameters']['delta'] + + N = range(n) + S = range(num_scenarios) + + # Precompute scenario-dependent demands and outgoing flows O^s_i + w_s = [] + O_s = [] + D_s = [] + for s in S: + ws = scenarios[s]['demands'] + w_s.append(ws) + Os = [sum(ws[i][j] for j in N) for i in N] + Ds = [sum(ws[j][i] for j in N) for i in N] + O_s.append(Os) + D_s.append(Ds) + + # ========================================================================= + # Load candidate solution. Raw solver values (z_values, x_values) are + # required so the binary-integrality and multi-allocation constraints + # (Eq 25, 27, 28) are not vacuous. + # ========================================================================= + 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 + + def _reject(reason): + result = { + "feasible": False, + "violated_constraints": [], + "violations": [reason], + "violation_magnitudes": [], + } + with open(args.result_path, 'w') as fout: + json.dump(result, fout, indent=2) + print(f"Solution is INFEASIBLE. {reason}") + print(f"Result written to {args.result_path}") + + for required in ('z_values', 'x_values'): + if required not in solution: + _reject( + f"Solution missing required field '{required}' " + "(raw solver values needed for Eq 25, 27, 28)." + ) + return + + # Continuous z values straight from the solver -- do NOT cast to int, + # otherwise the binary check on Eq 27 becomes vacuous. + z = [float(solution['z_values'][k]) for k in N] + + # Raw x values: nested dict keyed by str(s) -> str(i) -> str(k). Nested + # keying lets node i map to multiple k values in the same scenario, so + # Eq 25 violations are expressible. + x_raw = solution['x_values'] + x_s = {} + for s in S: + s_dict = x_raw.get(str(s), {}) + for i in N: + i_dict = s_dict.get(str(i), {}) + for k in N: + if i != k: + x_s[(s, i, k)] = float(i_dict.get(str(k), 0.0)) + + # Rounded views used only by the capacity / flow helpers; binary + # integrality itself is verified tolerance-wise by Constraints 3 and 4. + z_int = [int(round(zv)) for zv in z] + + def X(s, i, k): + if i == k: + return z_int[i] + return int(round(x_s.get((s, i, k), 0.0))) + + # ========================================================================= + # Check constraints + # ========================================================================= + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + def record_violation(constraint_idx, msg, lhs_val, rhs_val, violation_amount): + violated_constraints.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs_val), eps) + ratio = violation_amount / normalizer + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs_val), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ------------------------------------------------------------------------- + # Constraint 1 (tag 25): sum_{k!=i} x^s_{ik} = 1 - z_i, for all i, s + # ------------------------------------------------------------------------- + for s in S: + for i in N: + lhs = sum(x_s.get((s, i, k), 0) for k in N if k != i) + rhs = 1 - z[i] + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 1, + f"Constraint 25 violated: scenario {s}, node {i}: " + f"sum_k x^s_{{i={i},k}} = {lhs}, expected 1 - z_{i} = {rhs}", + lhs, rhs, violation_amount + ) + + # ------------------------------------------------------------------------- + # Constraint 2 (tag 26): x^s_{ik} <= z_k, for all i,k (i!=k), s + # ------------------------------------------------------------------------- + for s in S: + for i in N: + for k in N: + if i != k: + x_val = x_s.get((s, i, k), 0) + z_val = z[k] + lhs = x_val + rhs = z_val + violation_amount = lhs - rhs # <= constraint: how much LHS exceeds RHS + if violation_amount > tol: + record_violation( + 2, + f"Constraint 26 violated: scenario {s}, node {i} allocated to " + f"non-hub node {k}: x^s_{{i={i},k={k}}} = {x_val}, z_{k} = {z_val}", + lhs, rhs, violation_amount + ) + + # ------------------------------------------------------------------------- + # Constraint 3 (tag 27): z_i in {0,1}, for all i + # Tolerance check on the raw solver value (Item 1 of reviewer note). + # ------------------------------------------------------------------------- + for i in N: + z_val = z[i] + dist_to_binary = abs(z_val - round(z_val)) + if dist_to_binary > tol: + record_violation( + 3, + f"Constraint 27 violated: z_{i} = {z_val} is not binary", + z_val, round(z_val), dist_to_binary + ) + + # ------------------------------------------------------------------------- + # Constraint 4 (tag 28): x^s_{ik} in {0,1}, for all i,k, s + # Tolerance check on the raw solver value (Item 1 of reviewer note). + # ------------------------------------------------------------------------- + for s in S: + for i in N: + for k in N: + if i != k: + x_val = x_s.get((s, i, k), 0.0) + dist_to_binary = abs(x_val - round(x_val)) + if dist_to_binary > tol: + record_violation( + 4, + f"Constraint 28 violated: x^s_{{s={s},i={i},k={k}}} = {x_val} " + f"is not binary", + x_val, round(x_val), dist_to_binary + ) + + # ------------------------------------------------------------------------- + # Constraint 5 (tag 20): sum_k z_k >= 1 (at least one hub) + # This applies to SAHLP and CSAHLP variants (not SApHMP which uses constraint 6) + # ------------------------------------------------------------------------- + if variant != "SApHMP": + lhs = sum(z[k] for k in N) + rhs = 1 + violation_amount = rhs - lhs # >= constraint: how much RHS exceeds LHS + if violation_amount > tol: + record_violation( + 5, + f"Constraint 20 violated: sum of z_k = {lhs}, need >= {rhs} (at least one hub)", + lhs, rhs, violation_amount + ) + + # ------------------------------------------------------------------------- + # Constraint 6 (SApHMP only): sum_k z_k = p + # ------------------------------------------------------------------------- + if variant == "SApHMP" and p_hubs is not None: + lhs = sum(z[k] for k in N) + rhs = p_hubs + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + record_violation( + 6, + f"SApHMP constraint violated: number of hubs = {lhs}, expected p = {rhs}", + lhs, rhs, violation_amount + ) + + # ------------------------------------------------------------------------- + # Constraint 7 (CSAHLP only): sum_i O^s_i * X^s_{ik} <= Gamma_k * z_k + # ------------------------------------------------------------------------- + if variant == "CSAHLP" and hub_capacities is not None: + for s in S: + for k in N: + lhs = sum(O_s[s][i] * X(s, i, k) for i in N) + rhs = hub_capacities[k] * z[k] + violation_amount = lhs - rhs # <= constraint + if violation_amount > tol: + record_violation( + 7, + f"CSAHLP capacity violated: scenario {s}, hub {k}: " + f"total flow = {lhs}, capacity = {rhs}", + lhs, rhs, violation_amount + ) + + # Variable Domain Checks (auto-generated by add_domain_checks.py) + # hubs: list[int] of node indices in [0, n) without duplicates, consistent with z_values. + hubs = solution.get("hubs", []) + seen_hubs = set() + for h in hubs: + if not isinstance(h, int) or h < 0 or h >= n: + record_violation( + 7, + f"Invalid node index in hubs: {h} (valid range 0..{n-1})", + float(h if isinstance(h, (int, float)) else -1), 0.0, 1.0, + ) + elif h in seen_hubs: + record_violation( + 7, + f"Duplicate node index in hubs: {h} (binary domain violated)", + 2.0, 1.0, 1.0, + ) + else: + seen_hubs.add(h) + + # allocations: dict[scenario_str -> dict[node_str -> hub_int]] + # Each assigned hub must be in [0, n) and must be one of the opened hubs. + allocations = solution.get("allocations", {}) + opened_hubs = set(seen_hubs) + # If hubs list was empty/invalid, fall back to z_values indicator. + if not opened_hubs: + for k_idx in range(n): + if z[k_idx] > 0.5: + opened_hubs.add(k_idx) + for s_key, alloc_dict in allocations.items(): + if not isinstance(alloc_dict, dict): + continue + for node_key, hub_val in alloc_dict.items(): + try: + nd = int(node_key) + except (TypeError, ValueError): + nd = -1 + if not (0 <= nd < n): + record_violation( + 7, + f"Invalid node key in allocations[{s_key!r}]: {node_key!r}", + float(nd), 0.0, 1.0, + ) + continue + if not isinstance(hub_val, int) or hub_val < 0 or hub_val >= n: + record_violation( + 7, + f"Invalid hub index in allocations[{s_key!r}][{node_key!r}]: {hub_val}", + float(hub_val if isinstance(hub_val, (int, float)) else -1), + 0.0, 1.0, + ) + elif opened_hubs and hub_val not in opened_hubs: + record_violation( + 7, + f"allocations[{s_key!r}][{node_key!r}] assigns to {hub_val} " + f"but that node is not an opened hub", + float(hub_val), 1.0, 1.0, + ) + + # ------------------------------------------------------------------------- + # Constraint 8 (Tier-C obj-consistency): the reported objective_value + # must match the obj recomputed from (z, x^s) using the DEF_V formula. + # All variables determining the obj are in the solution, so this is a + # full recompute (not a lower bound). Tolerance: max(1e-3, 1e-3*|true|). + # + # Quadratic inter-hub term simplification: define X^s_{i,k} = z_i if k==i + # else x^s_{i,k}. Then the four sub-sums in the DEF_V obj collapse to + # sum_{k,l in N} d_{k,l} X^s_{i,k} X^s_{j,l} + # so the inter-hub cost contribution is + # alpha * sum_{i,j} w^s_{ij} (sum_l X^s_{j,l} * h^s_i[l]) + # where h^s_i[l] = sum_k X^s_{i,k} d_{k,l}. This is O(n^3) per scenario. + # ------------------------------------------------------------------------- + reported_obj_raw = solution.get("objective_value") + if reported_obj_raw is not None: + try: + reported_obj = float(reported_obj_raw) + except (TypeError, ValueError): + reported_obj = None + + if reported_obj is not None: + # 1. fixed-cost layer (suppressed for SApHMP, per Section 10). + if variant == "SApHMP": + setup_cost = 0.0 + else: + setup_cost = sum(fixed_costs[k] * z[k] for k in N) + + true_obj = float(setup_cost) + for s in S: + ps = float(scenarios[s]['probability']) + ws = w_s[s] + Os = O_s[s] + Ds = D_s[s] + + # Build X^s[i] as a length-n vector for this scenario. + Xs = [] + for i in N: + row = [0.0] * n + row[i] = z[i] + for k in N: + if k == i: + continue + row[k] = x_s.get((s, i, k), 0.0) + Xs.append(row) + + # Collection + distribution: sum_{i,k, i!=k} c^s_{ik} x^s_{ik} + cd_term = 0.0 + for i in N: + di = distances[i] + coeff_i = chi * Os[i] + delta * Ds[i] + for k in N: + if i == k: + continue + xv = x_s.get((s, i, k), 0.0) + if xv == 0.0: + continue + cd_term += di[k] * coeff_i * xv + + # Inter-hub transfer: alpha * sum_{i,j} w^s_{ij} + # * sum_{k,l} d_{k,l} X^s_{i,k} X^s_{j,l} + ih_term = 0.0 + for i in N: + Xi = Xs[i] + h = [0.0] * n + for k in N: + xk = Xi[k] + if xk == 0.0: + continue + dk = distances[k] + for l in N: + h[l] += xk * dk[l] + wi = ws[i] + for j in N: + wij = wi[j] + if wij == 0: + continue + Xj = Xs[j] + acc = 0.0 + for l in N: + xj = Xj[l] + if xj == 0.0: + continue + acc += xj * h[l] + ih_term += wij * acc + ih_term *= alpha + + true_obj += ps * (cd_term + ih_term) + + abs_diff = abs(reported_obj - true_obj) + # 0.1% relative with 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + record_violation( + 8, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} differs from recomputed DEF_V obj=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported_obj, true_obj, abs_diff, + ) + + # ========================================================================= + # Build result + # ========================================================================= + feasible = len(violated_constraints) == 0 + + # Aggregate violations by constraint index for concise messages + constraint_msgs = {} + for mag in violation_magnitudes: + c = mag["constraint"] + if c not in constraint_msgs: + constraint_msgs[c] = [] + for v_msg in violations: + # Extract constraint index from the corresponding magnitude entry + pass + + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if feasible: + print(f"Solution is FEASIBLE. Result written to {args.result_path}") + else: + print(f"Solution is INFEASIBLE. {len(violation_magnitudes)} violation(s) found.") + print(f"Violated constraints: {sorted(violated_constraints)}") + 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/rostami2021/gurobi_code.py b/tasks/rostami2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd9dbf714fd157a1149c3afefed0fb5a8cea671 --- /dev/null +++ b/tasks/rostami2021/gurobi_code.py @@ -0,0 +1,311 @@ +""" +Gurobi implementation of DEF_V (Deterministic Equivalent Formulation with Variable Allocation) +using the flow-based mixed-integer linear reformulation of Ernst & Krishnamoorthy (1996). + +Source: Rostami, Kämmerling, Naoum-Sawaya, Buchheim, Clausen (2021) + "Stochastic single-allocation hub location" + European Journal of Operational Research + +This program solves the deterministic equivalent of SP_V (stochastic SAHLP with variable +allocation) by linearizing the quadratic inter-hub transport terms using flow variables +y^s_{ikl}, following the approach described in Section 2 (SAHLP-flow) extended per scenario. + +Supports three problem variants: + - SAHLP: Single Allocation Hub Location Problem (with fixed hub setup costs) + - SApHMP: Single Allocation p-Hub Median Problem (exactly p hubs, no setup costs) + - CSAHLP: Capacitated SAHLP (with hub capacity constraints) +""" + +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 main(): + parser = argparse.ArgumentParser( + description="Solve the stochastic SAHLP (DEF_V) using flow-based linearization 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 for the output solution JSON file.') + parser.add_argument('--time_limit', type=int, required=True, + help='Maximum solver runtime in seconds.') + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + # ========================================================================= + # Load instance data + # ========================================================================= + with open(args.instance_path, 'r') as f: + instance = json.load(f) + + n = instance['n'] + num_scenarios = instance['num_scenarios'] + chi = instance['cost_parameters']['chi'] + alpha = instance['cost_parameters']['alpha'] + delta = instance['cost_parameters']['delta'] + d = instance['distances'] + f_costs = instance['fixed_costs'] + p_hubs = instance.get('p_hubs') + hub_capacities = instance.get('hub_capacities') + variant = instance['problem_info']['variant'] + scenarios = instance['scenarios'] + + N = range(n) + S = range(num_scenarios) + + # ========================================================================= + # Precompute scenario-dependent parameters + # ========================================================================= + w_s = [] # w_s[s][i][j]: flow from i to j under scenario s + O_s = [] # O_s[s][i]: total outgoing flow from node i under scenario s + D_s = [] # D_s[s][i]: total incoming flow to node i under scenario s + p_s = [] # p_s[s]: probability of scenario s + c_s = [] # c_s[s][i][k]: collection/distribution cost coefficient + + for s in S: + ws = scenarios[s]['demands'] + w_s.append(ws) + p_s.append(scenarios[s]['probability']) + + Os = [sum(ws[i][j] for j in N) for i in N] + Ds = [sum(ws[j][i] for j in N) for i in N] + O_s.append(Os) + D_s.append(Ds) + + # c^s_{ik} = d_{ik} * (chi * O^s_i + delta * D^s_i) + cs = [[d[i][k] * (chi * Os[i] + delta * Ds[i]) for k in N] for i in N] + c_s.append(cs) + + # ========================================================================= + # Build Gurobi model: DEF_V with flow-based linearization + # ========================================================================= + model = gp.Model("DEF_V_flow") + model.setParam("TimeLimit", args.time_limit) + # Paper uses single thread for experiments + model.setParam("Threads", 1) + + # ----- First-stage decision variables ----- + # z_k in {0,1}: 1 if hub is opened at node k + z = model.addVars(n, vtype=GRB.BINARY, name="z") + + # ----- Second-stage decision variables (per scenario) ----- + # x^s_{ik} in {0,1}: allocation of node i to hub k (for i != k) + x = {} + for s in S: + for i in N: + for k in N: + if i != k: + x[s, i, k] = model.addVar(vtype=GRB.BINARY, name=f"x_{s}_{i}_{k}") + + # ----- Flow variables for linearization ----- + # y^s_{ikl} >= 0: total flow originating at node i, routed via hub k then hub l + y = {} + for s in S: + for i in N: + for k in N: + for l in N: + y[s, i, k, l] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"y_{s}_{i}_{k}_{l}" + ) + + model.update() + + # ----- Helper: X^s_{ik} = z_i if i==k, x^s_{ik} if i!=k ----- + # This captures the convention that x_{kk} = z_k (a hub is allocated to itself) + def X(s, i, k): + if i == k: + return z[i] + else: + return x[s, i, k] + + # ========================================================================= + # Objective function + # ========================================================================= + # Hub setup costs (not used for SApHMP) + if variant == "SApHMP": + hub_cost = 0 + else: + hub_cost = gp.quicksum(f_costs[k] * z[k] for k in N) + + # Collection/distribution costs: sum_s p_s sum_{i,k: i!=k} c^s_{ik} x^s_{ik} + cd_cost = gp.quicksum( + p_s[s] * c_s[s][i][k] * x[s, i, k] + for s in S for i in N for k in N if i != k + ) + + # Inter-hub transfer costs (linearized): sum_s p_s sum_{i,k,l} alpha d_{kl} y^s_{ikl} + transfer_cost = gp.quicksum( + p_s[s] * alpha * d[k][l] * y[s, i, k, l] + for s in S for i in N for k in N for l in N + ) + + model.setObjective(hub_cost + cd_cost + transfer_cost, GRB.MINIMIZE) + + # ========================================================================= + # Constraints + # ========================================================================= + + # (25) Single allocation: sum_{k!=i} x^s_{ik} = 1 - z_i, for all i, s + for s in S: + for i in N: + model.addConstr( + gp.quicksum(x[s, i, k] for k in N if k != i) == 1 - z[i], + name=f"alloc_{s}_{i}" + ) + + # (26) Linking: x^s_{ik} <= z_k, for all i, k (i!=k), s + for s in S: + for i in N: + for k in N: + if i != k: + model.addConstr( + x[s, i, k] <= z[k], + name=f"link_{s}_{i}_{k}" + ) + + # Hub count constraint depends on variant + if variant == "SApHMP" and p_hubs is not None: + # Exactly p hubs + model.addConstr( + gp.quicksum(z[k] for k in N) == p_hubs, + name="p_hubs" + ) + else: + # (20) At least one hub + model.addConstr( + gp.quicksum(z[k] for k in N) >= 1, + name="at_least_one_hub" + ) + + # CSAHLP capacity constraints (per scenario) + if variant == "CSAHLP" and hub_capacities is not None: + for s in S: + for k in N: + # sum_i O^s_i * X^s_{ik} <= Gamma_k * z_k + model.addConstr( + gp.quicksum(O_s[s][i] * X(s, i, k) for i in N) + <= hub_capacities[k] * z[k], + name=f"cap_{s}_{k}" + ) + + # ----- Flow-based linearization constraints (per scenario) ----- + # These follow the pattern of SAHLP-flow (eqs 9-11) applied per scenario + # with X^s_{ik} replacing x_{ik}. + + # Flow balance (eq 9 per scenario): + # sum_l y^s_{ikl} - sum_l y^s_{ilk} = O^s_i * X^s_{ik} - sum_j w^s_{ij} * X^s_{jk} + # for all i, k, s + for s in S: + for i in N: + for k in N: + lhs = ( + gp.quicksum(y[s, i, k, l] for l in N) + - gp.quicksum(y[s, i, l, k] for l in N) + ) + rhs = ( + O_s[s][i] * X(s, i, k) + - gp.quicksum(w_s[s][i][j] * X(s, j, k) for j in N) + ) + model.addConstr(lhs == rhs, name=f"flow_bal_{s}_{i}_{k}") + + # Flow bound (eq 10 per scenario): + # sum_l y^s_{ikl} <= O^s_i * X^s_{ik}, for all i, k, s + for s in S: + for i in N: + for k in N: + model.addConstr( + gp.quicksum(y[s, i, k, l] for l in N) + <= O_s[s][i] * X(s, i, k), + name=f"flow_bnd_{s}_{i}_{k}" + ) + + # (y >= 0 is enforced by lb=0 in variable definition) + + # ========================================================================= + # Solve + # ========================================================================= + model.optimize() + + # ========================================================================= + # Extract and save solution + # ========================================================================= + solution = {} + + if model.SolCount > 0: + solution['objective_value'] = model.ObjVal + solution['hubs'] = [k for k in N if z[k].X > 0.5] + + # Extract allocations per scenario + allocations = {} + for s in S: + alloc_s = {} + for i in N: + if z[i].X > 0.5: + # Node i is a hub, allocated to itself + alloc_s[str(i)] = i + else: + for k in N: + if k != i and x[s, i, k].X > 0.5: + alloc_s[str(i)] = k + break + allocations[str(s)] = alloc_s + solution['allocations'] = allocations + + # Raw solver values for the ORIGINAL DEF_V decision variables (z, x^s). + # Flow variables y^s_{ikl} are an internal linearization auxiliary + # (Ernst & Krishnamoorthy) and are NOT part of the original + # formulation, so they are not exported. + solution['z_values'] = [float(z[k].X) for k in N] + solution['x_values'] = { + str(s): { + str(i): { + str(k): float(x[s, i, k].X) + for k in N if k != i + } + for i in N + } + for s in S + } + + solution['status'] = model.Status + solution['mip_gap'] = model.MIPGap if hasattr(model, 'MIPGap') else None + solution['runtime'] = model.Runtime + solution['node_count'] = int(model.NodeCount) + else: + solution['objective_value'] = None + solution['status'] = model.Status + solution['runtime'] = model.Runtime + + 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"Hubs: {solution.get('hubs', [])}") + else: + print("No feasible solution found within the time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/rostami2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rostami2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rostami2021/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/rostami2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rostami2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rostami2021/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/rostami2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rostami2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rostami2021/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/rostami2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rostami2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rostami2021/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/rostami2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rostami2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rostami2021/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/rostami2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rostami2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rostami2021/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/rostami2021/gurobi_solution/large_solution_1.json b/tasks/rostami2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..25c630228019fae1c7787cb3f3d0f290b2b2c47f --- /dev/null +++ b/tasks/rostami2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4fe356f2d7e3aad13dbc6f50e3963bd067d5fc2c71bf71c173b9d0a0e808b0f2 +size 1005859 diff --git a/tasks/rostami2021/gurobi_solution/large_solution_2.json b/tasks/rostami2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..866d50e1640cd6c2c90c92ae38fa1148a79d8813 --- /dev/null +++ b/tasks/rostami2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01ee0df00b693ff75bf89165c4bed0c2bb60df1aef05ba17eed5bf5928e3168f +size 1005626 diff --git a/tasks/rostami2021/gurobi_solution/large_solution_3.json b/tasks/rostami2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3d997f8c42b64690de3e58e77da14cf93480765b --- /dev/null +++ b/tasks/rostami2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44557ae9d2318d9b58db452f37c05b8706ed22e9fea6d662b1773d4ee39c62c5 +size 1005666 diff --git a/tasks/rostami2021/gurobi_solution/large_solution_4.json b/tasks/rostami2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..c67a46f491f8d821d1f6ba1b3b7d707171610eee --- /dev/null +++ b/tasks/rostami2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f1b6339c541629cc1beddb20d9d2c0c30257352c172ca2f3d5869978050f37d +size 1005643 diff --git a/tasks/rostami2021/gurobi_solution/large_solution_5.json b/tasks/rostami2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a30d2e87de937a3bd6599c378ddbefe875c5e26e --- /dev/null +++ b/tasks/rostami2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da773aba715181ef174a2ddd3d26fe38d419d33805896072bed2fc7945a93f33 +size 1005647 diff --git a/tasks/rostami2021/gurobi_solution/tiny_solution.json b/tasks/rostami2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..b271885db781fbfab947c896bfdf360a5e7a8a99 --- /dev/null +++ b/tasks/rostami2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f610b08035b9999624ab598d0f176735a884f684db64f03ea0dac1f684b2435f +size 10619 diff --git a/tasks/rostami2021/gurobi_solution_log/large_log_1.jsonl b/tasks/rostami2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..01bde063452194d14a4c39a9076248c71dcd90b6 --- /dev/null +++ b/tasks/rostami2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cb26e506fecf1fd5e61e4f9b629dfc360946bc4794cb5c27c1aea97eb852c4a +size 56 diff --git a/tasks/rostami2021/gurobi_solution_log/large_log_2.jsonl b/tasks/rostami2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2fba2aa58661df91fd6b36096df7ec0a3d174a57 --- /dev/null +++ b/tasks/rostami2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df5fb48a26255f10a694a08e27952d27ba4e2b4b8d778f2f2aa156dd31324f6d +size 56 diff --git a/tasks/rostami2021/gurobi_solution_log/large_log_3.jsonl b/tasks/rostami2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2e3a105f301f8296f81e9643ac2f7cffa02e0c47 --- /dev/null +++ b/tasks/rostami2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f8e5e6c68038ed9848562b7e546fc5f860d00ddf53daa908f1bf09e619b7e75 +size 56 diff --git a/tasks/rostami2021/gurobi_solution_log/large_log_4.jsonl b/tasks/rostami2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f0c0dff12369a8e4fcc6f9e909acb62d7b801398 --- /dev/null +++ b/tasks/rostami2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dda73dd62814fdb3cdd282c0455e3854809c2f7a1d46c9e4f90508ad2f5d2e9b +size 56 diff --git a/tasks/rostami2021/gurobi_solution_log/large_log_5.jsonl b/tasks/rostami2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5a1b7341693f3d19263f05209424ac61ab12edfa --- /dev/null +++ b/tasks/rostami2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ef6655c0745f15ec20a8c8d146384c48512bc6ef3931b12a98eb5d390f482c8 +size 56 diff --git a/tasks/rostami2021/gurobi_solution_log/tiny_log.jsonl b/tasks/rostami2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b7464c94377109a65ca0e9205a2fe83d54ed1a3a --- /dev/null +++ b/tasks/rostami2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b73bc7d91e3c9f9aa5c242a93584011779557f3ed062ae53e7e43c8ebc73dcc +size 54 diff --git a/tasks/rostami2021/instance/large_instance_1.json b/tasks/rostami2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5c1fbf9a232660e59562e9235b613ab70039965a --- /dev/null +++ b/tasks/rostami2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69dd6b3671f8a9155a043747097a7a43334c701dcb402cd8bea6edf451d17466 +size 905815 diff --git a/tasks/rostami2021/instance/large_instance_2.json b/tasks/rostami2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..323bcaaa0ec39cca86bc7f377eeb58f9a6528617 --- /dev/null +++ b/tasks/rostami2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da79d357c50aca41585d61eca3f999e668dd52bedb533345fe467fef26fdc497 +size 905804 diff --git a/tasks/rostami2021/instance/large_instance_3.json b/tasks/rostami2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..cdb922c2657f287e15c5143788c06a964e2e0396 --- /dev/null +++ b/tasks/rostami2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:296ad31f9542b62c5fb8a31c3967b65ab517a1067901db13d286d29a5ae020e0 +size 905813 diff --git a/tasks/rostami2021/instance/large_instance_4.json b/tasks/rostami2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..f9bcd93f9f7000977efb8fb73e7a6da8ecfc2de7 --- /dev/null +++ b/tasks/rostami2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe1bf278a0e473ff44aaec212a4cdfe747888fdb9cc56e50ba57a05e588e0a35 +size 905812 diff --git a/tasks/rostami2021/instance/large_instance_5.json b/tasks/rostami2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9bf8f3900809cff1fbd75fef90617b50c3ccfcb7 --- /dev/null +++ b/tasks/rostami2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82caa9f113afaa2ce8b5fd0d836aeb2cb6138f12658b95fcae1137e67857ded6 +size 904894 diff --git a/tasks/rostami2021/instance/tiny_instance.json b/tasks/rostami2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..333ee09b7602e87fca90667680123bf5e25f5a90 --- /dev/null +++ b/tasks/rostami2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8fce78f53b1aefc4ace1e752c1cf2121f0c16379722cace045d041050027080 +size 12383 diff --git a/tasks/rostami2021/instance_schema.json b/tasks/rostami2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2098cf7e34572e02723ba1ef5e56bfe8b059b23f --- /dev/null +++ b/tasks/rostami2021/instance_schema.json @@ -0,0 +1,22 @@ +{ + "n": " Number of nodes in the transportation network, each serving as an origin, destination, and candidate hub location.", + "num_scenarios": " Number of demand scenarios representing uncertain future conditions.", + "cost_parameters": { + "chi": " Unit cost rate for shipping flow from an origin node to its assigned hub (collection leg).", + "alpha": " Unit cost rate for shipping flow between two hubs (inter-hub transfer leg).", + "delta": " Unit cost rate for shipping flow from a hub to a destination node (distribution leg)." + }, + "p_hubs": " Exact number of hubs that must be opened in the p-hub median variant, or null if not applicable.", + "node_coordinates": " Geographic x-y coordinates of each node in the network.", + "distances": " Euclidean distance between each pair of nodes.", + "base_demands": " Baseline number of shipments from each origin node to each destination node, with zero on the diagonal.", + "fixed_costs": " One-time setup cost incurred when opening each candidate node as a hub.", + "hub_capacities": " Maximum total outgoing flow that each hub can handle in the capacitated variant, or null if uncapacitated.", + "scenarios": [ + { + "probability": " Likelihood of this demand scenario occurring.", + "pi_factors": " Multiplicative scaling factor applied to each node when generating scenario-specific demands.", + "demands": " Number of shipments from each origin to each destination under this scenario, with zero on the diagonal." + } + ] +} diff --git a/tasks/rostami2021/mathematical_formulation.md b/tasks/rostami2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..e5adf455dbdeec3a9d02b52801af6aa2f8863c30 --- /dev/null +++ b/tasks/rostami2021/mathematical_formulation.md @@ -0,0 +1,47 @@ +# Original Formulation: Stochastic Single-Allocation Hub Location with Variable Allocation (DEF$_V$) + +Rostami, Kämmerling, Naoum-Sawaya, Buchheim, Clausen. “Stochastic single-allocation hub location,” *European Journal of Operational Research*, 2021. Section 3.2. + +## Sets, Indices and Parameters + +- $N = \{1,\dots,n\}$: set of nodes (possible hub locations, origins, destinations). + +- $S_w = \{s_1,\dots,s_m\}$: finite support (scenarios) of the random parameter $\xi$, with probabilities $p_s = \mathbb{P}(\xi=s)$. + +- $d_{ij}$: distance between nodes $i$ and $j$. + +- $w_{ij}^s$: flow of items from node $i$ to node $j$ under scenario $s$; $O_i^s = \sum_{j\in N} w_{ij}^s$ (outgoing), $D_i^s = \sum_{j\in N} w_{ji}^s$ (incoming). + +- $\chi$, $\alpha$, $\delta$: collection, transfer (inter-hub), and distribution costs per unit flow per unit distance. + +- $f_k$: fixed set-up cost for locating a hub at node $k$. + +- $c_{ik}^s = d_{ik}(\chi\, O_i^s + \delta\, D_i^s)$: scenario-dependent collection/distribution cost coefficient. + +## Decision Variables + +**First-stage** (location decisions): $$z_k \in \{0,1\}, \quad k\in N,\qquad z_k=1 \iff \text{a hub is opened at node }k.$$ **Second-stage** (scenario-dependent allocation of non-hub nodes): $$x_{ik}^s \in \{0,1\}, \quad i,k\in N,\ i\neq k,\ s\in S_w,$$ with $x_{ik}^s=1$ iff node $i$ is allocated to hub $k$ under scenario $s$. + +## Deterministic Equivalent Formulation DEF$_V$ (Section 3.2, eqs. 25–28) + +DEF$_V$ is the mixed-integer *quadratic* program: $$\begin{align} +\text{DEF}_V:\quad \min\ & + \sum_{k\in N} f_k\, z_k + + \sum_{s\in S_w} p_s \sum_{\substack{i,k\in N \\ i\neq k}} c_{ik}^s\, x_{ik}^s \notag\\ +& {}+ \sum_{s\in S_w} p_s \sum_{i,j\in N} \alpha\, w_{ij}^s \Biggl[ + d_{ij}\, z_i\, z_j + + \sum_{\substack{\ell\in N \\ \ell\neq j}} d_{i\ell}\, z_i\, x_{j\ell}^s \notag\\ +& \qquad\qquad\qquad\qquad + + \sum_{\substack{k\in N \\ k\neq i}} d_{kj}\, x_{ik}^s\, z_j + + \sum_{\substack{k,\ell\in N \\ k\neq i,\ \ell\neq j}} d_{k\ell}\, x_{ik}^s\, x_{j\ell}^s + \Biggr] \tag{DEF$_V$} \\ +\text{s.t.}\ & + \sum_{\substack{k\in N \\ k\neq i}} x_{ik}^s = 1 - z_i, + && i\in N,\ s\in S_w \tag{25}\\ +& x_{ik}^s \le z_k, + && i,k\in N,\ i\neq k,\ s\in S_w \tag{26}\\ +& z_i \in \{0,1\}, + && i\in N \tag{27}\\ +& x_{ik}^s \in \{0,1\}, + && i,k\in N,\ i\neq k,\ s\in S_w. \tag{28} +\end{align}$$ diff --git a/tasks/rostami2021/problem_description.txt b/tasks/rostami2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..28dc26b466a94ff0660d46900a3313aed5babad0 --- /dev/null +++ b/tasks/rostami2021/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A transportation network consists of a given number of nodes that serve simultaneously as origins, destinations, and candidate hub locations. Every pair of nodes has a known distance between them. Each node has a fixed setup cost that is incurred if that node is selected to operate as a hub. Shipments between origin-destination pairs must be routed through the hub network: every shipment travels from its origin to a first hub (collection), possibly transfers to a second hub (inter-hub transfer), and then proceeds from that hub to its destination (distribution). The cost per unit of flow for the collection leg is the collection unit rate times the distance from origin to the first hub, the cost for the inter-hub leg is the transfer unit rate times the distance between the two hubs, and the cost for the distribution leg is the distribution unit rate times the distance from the second hub to the destination. Three unit cost rates are given as input: one for collection, one for inter-hub transfer, and one for distribution. + +Demand is uncertain and is described by a finite set of scenarios, each with a known probability. In each scenario, the flow of items to be shipped from every origin to every destination is specified. The total outgoing flow from a node in a given scenario is the sum of its flows to all destinations under that scenario, and the total incoming flow to a node is the sum of flows from all origins to that node under that scenario. + +The planner must make two types of decisions. First, before any scenario is realized, the planner selects which nodes to open as hubs; at least one hub must be opened. Second, after the demand scenario is revealed, the planner assigns every non-hub node to exactly one of the open hubs. A node that is itself a hub serves as its own hub and is not assigned elsewhere. A non-hub node may only be assigned to a node that has been opened as a hub. These assignment decisions are allowed to differ across scenarios, so the spoke-to-hub mapping can adapt to the realized demand. + +The total cost has three components. The first component is the sum of fixed setup costs over all opened hubs, paid once regardless of the scenario. The second component, computed per scenario and weighted by the scenario probability, covers collection and distribution: for each non-hub node assigned to a hub, the cost is the distance from the node to its assigned hub multiplied by the sum of the collection rate times the node's total outgoing flow plus the distribution rate times the node's total incoming flow in that scenario. The third component, also computed per scenario and weighted by the scenario probability, covers inter-hub transfer: for each origin-destination pair with positive flow, the transfer cost is the transfer unit rate times the flow times the distance between the hub serving the origin and the hub serving the destination. When both the origin and its assigned hub are the same node (i.e., the origin is itself a hub), the first hub on the path is that origin node; similarly, when the destination is a hub, the second hub on the path is that destination node. For non-hub origins and destinations, the respective hubs are determined by the scenario-specific assignments. + +The goal is to minimize the total expected cost, which is the sum of the fixed hub setup costs and the probability-weighted average across all scenarios of the collection, distribution, and inter-hub transfer costs. The problem also admits two variants. In the hub median variant, the fixed setup costs are removed and replaced by the requirement that exactly a prescribed number of hubs must be opened, where that number is a given integer. In the capacitated variant, each candidate hub node has a given capacity, and in every scenario the total outgoing flow of all nodes assigned to a hub (including the hub itself if it sends flow) must not exceed that hub's capacity. diff --git a/tasks/rostami2021/solution_logger.py b/tasks/rostami2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rostami2021/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/rostami2021/solution_schema.json b/tasks/rostami2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..73e96c7fc8e50f88306fc9f95ad5fe02c6ac71f6 --- /dev/null +++ b/tasks/rostami2021/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Total expected cost combining fixed hub setup costs and the probability-weighted sum of collection, distribution, and inter-hub transfer costs across all demand scenarios.", + "hubs": " Indices of nodes chosen to operate as hubs.", + "allocations": " For each scenario, a mapping from every node to the hub it is served by under that scenario; a hub node is mapped to itself. Inner dict has key: '{node}' with integer value giving the index of the assigned hub.", + "z_values": " For each node, an indicator of whether that node is opened as a hub (1 = opened, 0 = not opened).", + "x_values": " For each scenario, the spoke-to-hub assignment pattern. Inner dict has key: '{origin_node}' mapping to a dict with key: '{candidate_hub}' (excluding the origin itself) and float value indicating whether the origin node is assigned to that candidate hub in that scenario (1 = assigned, 0 = not assigned)." +} diff --git a/tasks/rothenbacher2018/feasibility_check.py b/tasks/rothenbacher2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..72b0cf6676676181f948b7693391bcd8f70d808e --- /dev/null +++ b/tasks/rothenbacher2018/feasibility_check.py @@ -0,0 +1,1401 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Truck-and-Trailer Routing Problem with Time Windows (TTRPTW). + +Paper: Rothenbaecher, Drexl, Irnich (2018) +"Branch-and-Price-and-Cut for the Truck-and-Trailer Routing Problem with Time Windows" + +Constraints (numbered top-to-bottom from the formulation section): + Constraint 1 (1b): Partitioning - every customer is served exactly once. + Constraint 2 (1c): Fleet size - do not exceed available vehicles of each type. + Constraint 3 (1d): Variable domain - lambda^k_r >= 0, integer. + +Route feasibility conditions (implicitly defining R^k): + Constraint 4: Time feasibility - service within time windows / planning horizon. + Constraint 5: Load feasibility - truck/trailer capacity not exceeded. + Constraint 6: Accessibility - truck customers only when trailer detached, etc. + Constraint 7: Loading policy - correct loading into truck/trailer. + Constraint 8: Elementarity - each customer visited at most once per route. + Constraint 9: Structure - route starts/ends at depot, trailer recoupled before return. + Constraint 10: Objective consistency - reported objective_value must lie in the + envelope [L, U] of total cost recomputed from the solution's route + structure and instance cost coefficients. L assumes the truck travels + alone on every arc (no trailer surcharge) and U assumes the trailer + is towed on every arc; handling and fixed costs are exact. This guards + against LLM exploits that fabricate the objective (e.g. obj=0 on a + non-trivial route, or obj=sys.float_info.max). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'routes') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + if operation == "assignment_key_set": + reported_set = set(solution[target]) + expected_set = {entry[source_key] for entry in solution[source]} + if reported_set != expected_set: + violations.append( + f"{target}={sorted(reported_set)} does not match the " + f"decision-derived value {sorted(expected_set)}" + ) + continue + + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def build_location_map(instance): + """Build a map from location id to location info.""" + loc_map = {} + depot = instance['depot'] + loc_map[depot['id']] = {'x': depot['x'], 'y': depot['y'], 'type': 'depot'} + + for c in instance['truck_customers']: + loc_map[c['id']] = { + 'x': c['x'], 'y': c['y'], 'type': 'truck_customer', + 'supply': c['supply'], 'service_time': c.get('service_time', instance['parameters']['service_time']) + } + for c in instance['trailer_customers']: + loc_map[c['id']] = { + 'x': c['x'], 'y': c['y'], 'type': 'trailer_customer', + 'supply': c['supply'], 'service_time': c.get('service_time', instance['parameters']['service_time']) + } + for t in instance['transshipment_locations']: + loc_map[t['id']] = {'x': t['x'], 'y': t['y'], 'type': 'transshipment'} + + return loc_map + + +def get_vehicle_class_info(instance, vc_id): + """Get vehicle class info by class_id.""" + for vc in instance['fleet']['vehicle_classes']: + if vc['class_id'] == vc_id: + return vc + return None + + +def detect_solution_format(solution): + """Detect whether this is an efficient_algorithm or gurobi solution.""" + if 'solver' in solution and solution.get('solver') == 'Gurobi': + return 'gurobi' + if 'algorithm' in solution: + return 'efficient' + # Fallback: check route fields + if solution.get('routes'): + r0 = solution['routes'][0] + if 'route_sequence_physical' in r0: + return 'gurobi' + if 'path_vertices' in r0: + return 'efficient' + return 'unknown' + + +def extract_routes(solution, instance, fmt): + """ + Extract a unified route representation from either solution format. + + Returns a list of dicts, each with: + - vehicle_class_id: int + - customers_served: list of customer IDs (service visits only) + - route_cost: float + - physical_sequence: list of location IDs visited (physical locations) + - decouple_locations: list of location IDs where trailer is decoupled + - couple_locations: list of location IDs where trailer is recoupled + """ + routes = [] + if fmt == 'gurobi': + for r in solution.get('routes', []): + vc_id = r.get('vehicle_class', r.get('vehicle_class_id')) + routes.append({ + 'vehicle_class_id': vc_id, + 'customers_served': r.get('customers_served', []), + 'route_cost': r.get('route_cost', 0.0), + 'physical_sequence': r.get('route_sequence_physical', r.get('route_sequence', [])), + 'decouple_locations': r.get('decouple_locations', []), + 'transfer_locations': r.get('transfer_locations', []), + 'couple_locations': r.get('couple_locations', []), + }) + elif fmt == 'efficient': + for r in solution.get('routes', []): + vc_id = r.get('vehicle_class_id') + vc = get_vehicle_class_info(instance, vc_id) + has_trailer = vc['trailer_type_id'] != 0 if vc else False + + path_vertices = r.get('path_vertices', []) + customers_served = r.get('customers_served', []) + + # Reconstruct physical sequence from path_vertices using the pricing + # network vertex numbering from efficient_algorithm.py + physical_seq = reconstruct_physical_sequence( + path_vertices, vc_id, instance, has_trailer) + + dc_locs, cp_locs = extract_dc_cp_from_path( + path_vertices, vc_id, instance, has_trailer) + + routes.append({ + 'vehicle_class_id': vc_id, + 'customers_served': customers_served, + 'route_cost': r.get('route_cost', 0.0), + 'physical_sequence': physical_seq, + 'decouple_locations': dc_locs, + 'couple_locations': cp_locs, + }) + else: + for r in solution.get('routes', []): + vc_id = r.get('vehicle_class_id', r.get('vehicle_class')) + routes.append({ + 'vehicle_class_id': vc_id, + 'customers_served': r.get('customers_served', []), + 'route_cost': r.get('route_cost', 0.0), + 'physical_sequence': r.get('route_sequence_physical', + r.get('route_sequence', + r.get('path_vertices', []))), + 'decouple_locations': r.get('decouple_locations', []), + 'couple_locations': r.get('couple_locations', []), + }) + + return routes + + +def build_vertex_info_for_class(vc_id, instance, has_trailer): + """ + Reconstruct the pricing network vertex mapping for a vehicle class, + mirroring the logic in efficient_algorithm.py PricingNetwork._build_vertices. + + Returns vid_map: vid -> (type, location_id) + """ + depot_id = instance['depot']['id'] + N_L = [c['id'] for c in instance['truck_customers']] + N_H = [c['id'] for c in instance['trailer_customers']] + T_set = [t['id'] for t in instance['transshipment_locations']] + + vid_map = {} + vid_map[0] = ('D+', depot_id) + vid_map[1] = ('D-', depot_id) + + next_vid = 2 + for n in N_L: + vid_map[next_vid] = ('NL', n) + next_vid += 1 + + for n in N_H: + vid_map[next_vid] = ('NH', n) + next_vid += 1 + if has_trailer: + vid_map[next_vid] = ('DC', n) + next_vid += 1 + vid_map[next_vid] = ('TAU', n) + next_vid += 1 + vid_map[next_vid] = ('CP', n) + next_vid += 1 + + if has_trailer: + for t in T_set: + vid_map[next_vid] = ('DC', t) + next_vid += 1 + vid_map[next_vid] = ('TAU', t) + next_vid += 1 + vid_map[next_vid] = ('CP', t) + next_vid += 1 + + return vid_map + + +def reconstruct_physical_sequence(path_vertices, vc_id, instance, has_trailer): + """Convert pricing network vertex IDs to physical location IDs.""" + vid_map = build_vertex_info_for_class(vc_id, instance, has_trailer) + physical = [] + for vid in path_vertices: + if vid in vid_map: + _, loc_id = vid_map[vid] + physical.append(loc_id) + else: + physical.append(vid) + return physical + + +def extract_dc_cp_from_path(path_vertices, vc_id, instance, has_trailer): + """Extract decouple/couple locations from pricing network path.""" + vid_map = build_vertex_info_for_class(vc_id, instance, has_trailer) + dc_locs = [] + cp_locs = [] + for vid in path_vertices: + if vid in vid_map: + vtype, loc_id = vid_map[vid] + if vtype == 'DC': + dc_locs.append(loc_id) + elif vtype == 'CP': + cp_locs.append(loc_id) + return dc_locs, cp_locs + + +def _get_customer_time_window(instance, loc_id): + """Return [e_n, l_n] for a customer loc_id from the instance, or None if absent.""" + for c in instance.get('truck_customers', []): + if c.get('id') == loc_id: + return c.get('time_window') + for c in instance.get('trailer_customers', []): + if c.get('id') == loc_id: + return c.get('time_window') + return None + + +def check_feasibility(instance, solution): + """ + Check all hard constraints for the TTRPTW solution. + Returns (feasible, violated_constraints, violations, violation_magnitudes). + """ + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + fmt = detect_solution_format(solution) + routes = extract_routes(solution, instance, fmt) + + loc_map = build_location_map(instance) + params = instance['parameters'] + dist_matrix = instance['distance_matrix'] + time_matrix = instance['travel_time_matrix'] + depot_id = instance['depot']['id'] + + N_L_ids = set(c['id'] for c in instance['truck_customers']) + N_H_ids = set(c['id'] for c in instance['trailer_customers']) + N_ids = N_L_ids | N_H_ids + + planning_horizon = params['planning_horizon'] + service_time = params['service_time'] + coupling_time = params['coupling_time'] + decoupling_time = params['decoupling_time'] + transfer_time = params['transfer_time'] + + vc_map = {} + for vc in instance['fleet']['vehicle_classes']: + vc_map[vc['class_id']] = vc + + truck_type_map = {} + for tt in instance['fleet']['truck_types']: + truck_type_map[tt['id']] = tt + trailer_type_map = {} + for tt in instance['fleet']['trailer_types']: + trailer_type_map[tt['id']] = tt + + # ========================================================================= + # Constraint 1 (1b): Partitioning - every customer served exactly once + # ========================================================================= + customer_visit_count = {} + for n in N_ids: + customer_visit_count[n] = 0 + + for ri, route in enumerate(routes): + for cid in route['customers_served']: + if cid in customer_visit_count: + customer_visit_count[cid] += 1 + + for n in sorted(N_ids): + count = customer_visit_count[n] + # Constraint: sum a_{rn} lambda_r = 1, i.e., count == 1 + lhs = count + rhs = 1 + violation_amount = abs(lhs - rhs) + if violation_amount > tol: + violated_constraints.add(1) + if count == 0: + violations.append(f"Customer {n} is not served by any route") + else: + violations.append(f"Customer {n} is served {count} times (expected exactly 1)") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 1, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 2 (1c): Fleet size - do not exceed available vehicles + # ========================================================================= + # Count vehicles used per truck type and trailer type + truck_type_usage = {} + trailer_type_usage = {} + + for route in routes: + vc_id = route['vehicle_class_id'] + vc = vc_map.get(vc_id) + if vc is None: + continue + tid = vc['truck_type_id'] + truck_type_usage[tid] = truck_type_usage.get(tid, 0) + 1 + trid = vc['trailer_type_id'] + if trid != 0: + trailer_type_usage[trid] = trailer_type_usage.get(trid, 0) + 1 + + for tid, tt in truck_type_map.items(): + used = truck_type_usage.get(tid, 0) + available = tt['num_available'] + # Constraint: used <= available + lhs = used + rhs = available + violation_amount = max(0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Truck type {tid}: {used} used, but only {available} available") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 2, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + for trid, tt in trailer_type_map.items(): + used = trailer_type_usage.get(trid, 0) + available = tt['num_available'] + lhs = used + rhs = available + violation_amount = max(0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Trailer type {trid}: {used} used, but only {available} available") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 2, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 3 (1d): Variable domain - lambda >= 0, integer + # ========================================================================= + # In the solution, each route is selected (lambda=1) or not. The routes + # list represents the selected routes. We check that route selection counts + # are non-negative integers (they always are by construction in the solution + # format, but we verify). + # For the efficient solution, check if solution explicitly has lambda values. + # In practice, each route in the list is used exactly once (lambda=1). + # We verify the route costs are non-negative as a basic domain check. + for ri, route in enumerate(routes): + # lambda_r is implicitly 1 for each listed route, which is >= 0 and integer. + # Check that route_cost >= 0 as a sanity check on the cost parameter. + rc = route.get('route_cost', 0.0) + lhs = 1 # lambda value (implicitly 1) + rhs = 0 # lambda >= 0 + violation_amount = max(0, rhs - lhs) # >= constraint: violation if rhs > lhs + # This will always be 0 since lambda=1 >= 0, but we include the check. + if violation_amount > tol: + violated_constraints.add(3) + violations.append(f"Route {ri}: lambda value is negative") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 3, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # ========================================================================= + # Route feasibility conditions (Constraints 4-9) + # These are checked per route. + # ========================================================================= + for ri, route in enumerate(routes): + vc_id = route['vehicle_class_id'] + vc = vc_map.get(vc_id) + if vc is None: + violations.append(f"Route {ri}: unknown vehicle class {vc_id}") + continue + + has_trailer = vc['trailer_type_id'] != 0 + Q_L = vc['truck_capacity'] + Q_H = vc['trailer_capacity'] if has_trailer else 0 + + customers_served = route['customers_served'] + physical_seq = route['physical_sequence'] + dc_locs = route['decouple_locations'] + tau_locs = route.get('transfer_locations', []) + cp_locs = route['couple_locations'] + + # Determine the vertex types along the physical sequence + # We need to figure out trailer state (attached/detached) along the route + # to properly check constraints. + + # Build a detailed traversal with trailer state tracking + # For gurobi solutions, we have decouple_locations and couple_locations + # For efficient solutions, we extracted them from the pricing network path + + # Reconstruct detailed traversal: + # The physical_sequence includes depot and all visited locations. + # decouple/couple locations indicate where the trailer is dropped/picked up. + + # Determine trailer state at each step + # Start: trailer attached if has_trailer, else no trailer + trailer_attached = has_trailer + trailer_park_loc = None # where the trailer is parked (None if attached) + + # Build an ordered list of events (visit customer, decouple, couple, transfer) + # from the physical sequence and decouple/couple info + + # For efficient solutions, the path_vertices give us exact vertex types + # For gurobi solutions, we use route_sequence (with network vertex IDs) or + # route_sequence_physical with decouple/couple markers + + # ===================================================================== + # Constraint 4: Time feasibility + # ===================================================================== + current_time = planning_horizon[0] + time_violated = False + + # Track trailer state for time computation + trailer_on = has_trailer + dc_set = set() + cp_set = set() + + # Build the event sequence: we need to know at each step what operation happens + if fmt == 'efficient': + vid_map = build_vertex_info_for_class(vc_id, instance, has_trailer) + path_verts = route.get('path_vertices', + solution['routes'][ri].get('path_vertices', [])) + event_seq = [] + for vid in path_verts: + if vid in vid_map: + vtype, loc_id = vid_map[vid] + else: + vtype, loc_id = '?', vid + event_seq.append((vtype, loc_id)) + elif fmt == 'gurobi': + # Gurobi: use route_sequence (network vertex IDs) if available + raw_route = solution['routes'][ri] + route_seq = raw_route.get('route_sequence', []) + phys_seq = raw_route.get('route_sequence_physical', []) + + # Build event sequence from route_sequence and physical matching + # In gurobi format, route_sequence contains network vertex IDs + # and route_sequence_physical contains physical location IDs + # Decouple/couple locations tell us where operations happen + + # Reconstruct vertex types from gurobi format + event_seq = _build_gurobi_event_seq( + route_seq, phys_seq, dc_locs, cp_locs, depot_id, + N_L_ids, N_H_ids, has_trailer, instance, + tau_locs=tau_locs) + else: + # Fallback: treat physical_sequence as simple location visits + event_seq = [] + for loc in physical_seq: + if loc == depot_id: + event_seq.append(('depot', loc)) + elif loc in N_L_ids: + event_seq.append(('NL', loc)) + elif loc in N_H_ids: + event_seq.append(('NH', loc)) + else: + event_seq.append(('?', loc)) + + # Time-window verification. + # + # For Gurobi-format solutions, we read the MIP's own t[k,vi,n] decisions + # from `arrival_times` rather than re-simulating along the route — the + # network has node copies, decouple/couple, and transshipment events that + # the simulator could not reliably reorder. If `arrival_times` is missing + # (legacy gurobi solution emitted by the pre-fix code), fail loudly + # instead of silently falling back to simulation; the upstream gurobi_code + # must emit arrival_times. + # + # For efficient solutions and unknown formats, fall through to the + # simulator below. + used_arrival_times = False + if fmt == 'gurobi': + raw_route = solution['routes'][ri] + arrival_times = raw_route.get('arrival_times') + if arrival_times is None: + violated_constraints.add(4) + violations.append( + f"Route {ri}: gurobi solution missing 'arrival_times'; " + f"feasibility checker requires per-node MIP times for time-window " + f"verification (re-run with the patched gurobi_code.py).") + violation_magnitudes.append({ + 'constraint': 4, + 'lhs': 0.0, 'rhs': 0.0, + 'raw_excess': 1.0, 'normalizer': 1.0, 'ratio': 1.0, + }) + time_violated = True + else: + used_arrival_times = True + route_seq = raw_route.get('route_sequence', []) + # arrival_times keys are str (JSON serialization); accept both. + def _t_at(node): + if str(node) in arrival_times: + return float(arrival_times[str(node)]) + if node in arrival_times: + return float(arrival_times[node]) + return None + for step_idx, (vtype, loc_id) in enumerate(event_seq): + network_node = route_seq[step_idx] if step_idx < len(route_seq) else loc_id + t_val = _t_at(network_node) + if t_val is None: + violated_constraints.add(4) + violations.append( + f"Route {ri}: arrival_times missing entry for network " + f"node {network_node} at step {step_idx} (loc {loc_id})") + violation_magnitudes.append({ + 'constraint': 4, + 'lhs': 0.0, 'rhs': 0.0, + 'raw_excess': 1.0, 'normalizer': 1.0, 'ratio': 1.0, + }) + time_violated = True + continue + + if vtype in ('NL', 'NH'): + cust_tw = _get_customer_time_window(instance, loc_id) + if cust_tw is not None and len(cust_tw) == 2: + e_n, l_n = cust_tw[0], cust_tw[1] + if t_val < e_n - tol: + violated_constraints.add(4) + violations.append( + f"Route {ri}: service at customer {loc_id} starts at " + f"{t_val:.2f}, before earliest window {e_n} at step {step_idx}") + normalizer = max(abs(e_n), eps) + violation_magnitudes.append({ + 'constraint': 4, + 'lhs': float(t_val), 'rhs': float(e_n), + 'raw_excess': float(e_n - t_val), + 'normalizer': float(normalizer), + 'ratio': float((e_n - t_val) / normalizer), + }) + time_violated = True + if t_val > l_n + tol: + violated_constraints.add(4) + violations.append( + f"Route {ri}: service at customer {loc_id} starts at " + f"{t_val:.2f}, past latest window {l_n} at step {step_idx}") + normalizer = max(abs(l_n), eps) + violation_magnitudes.append({ + 'constraint': 4, + 'lhs': float(t_val), 'rhs': float(l_n), + 'raw_excess': float(t_val - l_n), + 'normalizer': float(normalizer), + 'ratio': float((t_val - l_n) / normalizer), + }) + time_violated = True + + rhs = planning_horizon[1] + if t_val > rhs + tol: + violated_constraints.add(4) + violations.append( + f"Route {ri}: time {t_val:.2f} exceeds planning horizon " + f"{rhs} at step {step_idx} (location {loc_id})") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 4, + 'lhs': float(t_val), 'rhs': float(rhs), + 'raw_excess': float(t_val - rhs), + 'normalizer': float(normalizer), + 'ratio': float((t_val - rhs) / normalizer), + }) + time_violated = True + + if not used_arrival_times: + # Simulate the route timing (efficient solutions or unknown formats). + current_time = planning_horizon[0] + prev_loc = None + + for step_idx, (vtype, loc_id) in enumerate(event_seq): + if step_idx == 0: + prev_loc = loc_id + continue + + # Travel time from prev_loc to loc_id + tt = time_matrix[prev_loc][loc_id] + + # Add handling time at previous vertex + if step_idx > 1: + prev_vtype = event_seq[step_idx - 1][0] + if prev_vtype in ('NL', 'NH'): + tt += service_time + elif prev_vtype == 'DC': + tt += decoupling_time + elif prev_vtype == 'CP': + tt += coupling_time + elif prev_vtype == 'TAU': + tt += transfer_time + + current_time = current_time + tt + + # Customer-specific time window (math_model: service starts in [e_n, l_n]) + if vtype in ('NL', 'NH'): + cust_tw = _get_customer_time_window(instance, loc_id) + if cust_tw is not None and len(cust_tw) == 2: + e_n, l_n = cust_tw[0], cust_tw[1] + if current_time < e_n: + current_time = e_n + lhs_tw = current_time + rhs_tw = l_n + viol_tw = max(0, lhs_tw - rhs_tw) + if viol_tw > tol: + violated_constraints.add(4) + violations.append( + f"Route {ri}: service at customer {loc_id} starts at " + f"{current_time:.2f}, past latest window {l_n} at step {step_idx}") + normalizer = max(abs(rhs_tw), eps) + violation_magnitudes.append({ + 'constraint': 4, + 'lhs': float(lhs_tw), + 'rhs': float(rhs_tw), + 'raw_excess': float(viol_tw), + 'normalizer': float(normalizer), + 'ratio': float(viol_tw / normalizer), + }) + time_violated = True + + # Check time window (planning horizon for all vertices) + lhs = current_time + rhs = planning_horizon[1] + violation_amount = max(0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(4) + violations.append( + f"Route {ri}: time {current_time:.2f} exceeds planning horizon " + f"{planning_horizon[1]} at step {step_idx} (location {loc_id})") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 4, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + time_violated = True + + prev_loc = loc_id + + # ===================================================================== + # Constraint 5: Load feasibility + # ===================================================================== + truck_load = 0.0 + trailer_load = 0.0 + trailer_on = has_trailer + + for step_idx, (vtype, loc_id) in enumerate(event_seq): + if vtype in ('D+', 'D-', 'depot'): + pass + elif vtype == 'NL': + # Truck customer: trailer must be detached, load goes to truck + q = loc_map.get(loc_id, {}).get('supply', 0) + truck_load += q + elif vtype == 'NH': + q = loc_map.get(loc_id, {}).get('supply', 0) + if trailer_on: + # Load goes to trailer first, overflow to truck + space_in_trailer = Q_H - trailer_load + to_trailer = min(q, space_in_trailer) + to_truck = q - to_trailer + trailer_load += to_trailer + truck_load += to_truck + else: + # Trailer detached: load goes to truck + truck_load += q + elif vtype == 'DC': + # Decoupling: trailer detached at this location + trailer_on = False + elif vtype == 'CP': + # Coupling: trailer reattached, transfer load from truck to trailer + trailer_on = True + transferable = min(truck_load, Q_H - trailer_load) + truck_load -= transferable + trailer_load += transferable + elif vtype == 'TAU': + # Transfer: transfer load from truck to trailer + transferable = min(truck_load, Q_H - trailer_load) + truck_load -= transferable + trailer_load += transferable + + # Check truck capacity + lhs_truck = truck_load + rhs_truck = Q_L + viol_truck = max(0, lhs_truck - rhs_truck) + if viol_truck > tol: + violated_constraints.add(5) + violations.append( + f"Route {ri}: truck load {truck_load:.1f} exceeds capacity " + f"{Q_L} at step {step_idx} (location {loc_id})") + normalizer = max(abs(rhs_truck), eps) + violation_magnitudes.append({ + 'constraint': 5, + 'lhs': float(lhs_truck), + 'rhs': float(rhs_truck), + 'raw_excess': float(viol_truck), + 'normalizer': float(normalizer), + 'ratio': float(viol_truck / normalizer), + }) + + # Check trailer capacity + if has_trailer: + lhs_trail = trailer_load + rhs_trail = Q_H + viol_trail = max(0, lhs_trail - rhs_trail) + if viol_trail > tol: + violated_constraints.add(5) + violations.append( + f"Route {ri}: trailer load {trailer_load:.1f} exceeds capacity " + f"{Q_H} at step {step_idx} (location {loc_id})") + normalizer = max(abs(rhs_trail), eps) + violation_magnitudes.append({ + 'constraint': 5, + 'lhs': float(lhs_trail), + 'rhs': float(rhs_trail), + 'raw_excess': float(viol_trail), + 'normalizer': float(normalizer), + 'ratio': float(viol_trail / normalizer), + }) + + # ===================================================================== + # Constraint 6: Accessibility + # ===================================================================== + trailer_on = has_trailer + trailer_park_loc = None + + for step_idx, (vtype, loc_id) in enumerate(event_seq): + if vtype == 'DC': + # Decoupling: trailer must be attached to decouple + if not trailer_on: + lhs = 0 # trailer_on = False means not attached + rhs = 1 # requires attached + violation_amount = abs(lhs - rhs) + violated_constraints.add(6) + violations.append( + f"Route {ri}: decoupling at location {loc_id} but trailer " + f"not attached at step {step_idx}") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 6, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + trailer_on = False + trailer_park_loc = loc_id + elif vtype == 'CP': + # Coupling: trailer must be detached AND parked at this exact location. + if trailer_on or trailer_park_loc is None or trailer_park_loc != loc_id: + lhs = 0 # trailer not parked here + rhs = 1 # trailer must be parked at loc_id + violation_amount = abs(lhs - rhs) + violated_constraints.add(6) + if trailer_on: + detail = "trailer still attached" + elif trailer_park_loc is None: + detail = "trailer was never decoupled" + else: + detail = f"trailer parked at {trailer_park_loc}" + violations.append( + f"Route {ri}: coupling at location {loc_id} but {detail} " + f"at step {step_idx}") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 6, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + trailer_on = True + trailer_park_loc = None + elif vtype == 'TAU': + # Transfer: trailer must be parked at this location + pass # trailer_on state doesn't change + elif vtype == 'NL': + # Truck customer: trailer must be detached + if trailer_on and has_trailer: + lhs = 1 # trailer attached + rhs = 0 # requires detached + violation_amount = abs(lhs - rhs) + violated_constraints.add(6) + violations.append( + f"Route {ri}: truck customer {loc_id} visited with trailer " + f"attached at step {step_idx}") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 6, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # ===================================================================== + # Constraint 7: Loading policy + # (Checked implicitly in Constraint 5 load simulation above. + # The loading policy dictates HOW load is distributed between truck + # and trailer. We re-verify: at trailer customers with trailer + # attached, supply should go to trailer first, overflow to truck. + # At truck customers or when trailer detached, supply goes to truck. + # At coupling/transfer, load transferred from truck to trailer.) + # ===================================================================== + # We re-simulate with strict policy checking + truck_load_c7 = 0.0 + trailer_load_c7 = 0.0 + trailer_on_c7 = has_trailer + + for step_idx, (vtype, loc_id) in enumerate(event_seq): + if vtype in ('D+', 'D-', 'depot'): + pass + elif vtype == 'NL': + q = loc_map.get(loc_id, {}).get('supply', 0) + # Must load into truck (trailer detached or truck customer) + truck_load_c7 += q + elif vtype == 'NH': + q = loc_map.get(loc_id, {}).get('supply', 0) + if trailer_on_c7: + space_in_trailer = Q_H - trailer_load_c7 + to_trailer = min(q, space_in_trailer) + to_truck = q - to_trailer + trailer_load_c7 += to_trailer + truck_load_c7 += to_truck + else: + truck_load_c7 += q + elif vtype == 'DC': + # No load transfer at decoupling + trailer_on_c7 = False + elif vtype == 'CP': + # Transfer as much as possible from truck to trailer + trailer_on_c7 = True + transferable = min(truck_load_c7, Q_H - trailer_load_c7) + truck_load_c7 -= transferable + trailer_load_c7 += transferable + elif vtype == 'TAU': + # Transfer as much as possible from truck to trailer + transferable = min(truck_load_c7, Q_H - trailer_load_c7) + truck_load_c7 -= transferable + trailer_load_c7 += transferable + + # Check total load doesn't exceed combined capacity at any point + total_load = truck_load_c7 + trailer_load_c7 + total_cap = Q_L + Q_H + lhs = total_load + rhs = total_cap + violation_amount = max(0, lhs - rhs) + if violation_amount > tol: + violated_constraints.add(7) + violations.append( + f"Route {ri}: total load {total_load:.1f} exceeds combined " + f"capacity {total_cap} at step {step_idx} (location {loc_id})") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 7, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # ===================================================================== + # Constraint 8: Elementarity - each customer visited at most once per route + # ===================================================================== + cust_counts = {} + for cid in customers_served: + cust_counts[cid] = cust_counts.get(cid, 0) + 1 + + for cid, cnt in cust_counts.items(): + if cnt > 1: + lhs = cnt + rhs = 1 + violation_amount = abs(lhs - rhs) + violated_constraints.add(8) + violations.append( + f"Route {ri}: customer {cid} visited {cnt} times in same route") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 8, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # ===================================================================== + # Constraint 9: Structure - route starts/ends at depot, trailer recoupled + # ===================================================================== + # Check depot start + if event_seq: + first_vtype, first_loc = event_seq[0] + if first_loc != depot_id: + lhs = first_loc + rhs = depot_id + violation_amount = abs(lhs - rhs) + violated_constraints.add(9) + violations.append( + f"Route {ri}: does not start at depot (starts at location {first_loc})") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 9, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # Check depot end + last_vtype, last_loc = event_seq[-1] + if last_loc != depot_id: + lhs = last_loc + rhs = depot_id + violation_amount = abs(lhs - rhs) + violated_constraints.add(9) + violations.append( + f"Route {ri}: does not end at depot (ends at location {last_loc})") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 9, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # Check trailer recoupled before depot return (for complete vehicles) + if has_trailer: + # After processing all events, trailer should be attached at end + trailer_final = has_trailer # start attached + for (vtype, loc_id) in event_seq: + if vtype == 'DC': + trailer_final = False + elif vtype == 'CP': + trailer_final = True + + if not trailer_final: + lhs = 0 # trailer not attached + rhs = 1 # requires attached + violation_amount = abs(lhs - rhs) + violated_constraints.add(9) + violations.append( + f"Route {ri}: trailer not recoupled before returning to depot") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + 'constraint': 9, + 'lhs': float(lhs), + 'rhs': float(rhs), + 'raw_excess': float(violation_amount), + 'normalizer': float(normalizer), + 'ratio': float(violation_amount / normalizer), + }) + + # ========================================================================= + # Constraint 10: exact objective consistency + # ========================================================================= + # Recompute the true objective from the route structure using the cost rule: + # per-route cost = truck_fixed_cost + travel_cost + handling_cost + # where travel_cost = sum over arcs of dist[i][j] * (cf [+ tw if towing]). + # In the published Gurobi format, route_sequence contains the expanded + # decouple/couple node identifiers. Those identifiers determine exactly + # whether each arc is traversed with the trailer, using the same rule as + # gurobi_code.py. The previous all-detached/all-attached envelope admitted + # fabricated objectives throughout a wide interval. + reported_obj = solution.get("objective_value") + if reported_obj is not None and routes: + try: + reported = float(reported_obj) + reported_ok = math.isfinite(reported) + except (TypeError, ValueError): + reported = None + reported_ok = False + if reported_ok: + decoupling_cost_val = params.get('decoupling_cost', 0.0) + coupling_cost_val = params.get('coupling_cost', 0.0) + transfer_cost_val = params.get('transfer_cost', 0.0) + + n_orig = len(dist_matrix) + parking_locations = sorted( + N_H_ids + | {item['id'] for item in instance['transshipment_locations']} + ) + dp_nodes = { + n_orig + idx for idx in range(len(parking_locations)) + } + cp_nodes = { + n_orig + len(parking_locations) + idx + for idx in range(len(parking_locations)) + } + + def physical_node(node): + if not isinstance(node, int): + raise ValueError(f"non-integer expanded node id {node!r}") + if 0 <= node < n_orig: + return node + offset = node - n_orig + if 0 <= offset < 2 * len(parking_locations): + return parking_locations[offset % len(parking_locations)] + raise ValueError(f"expanded node id {node} is out of range") + + exact_total = 0.0 + raw_routes = solution.get('routes', []) + for route_index, r in enumerate(routes): + vc_id = r.get('vehicle_class_id') + vc = vc_map.get(vc_id) + if vc is None: + raise ValueError(f"route {route_index} has unknown vehicle class {vc_id}") + has_trailer = vc.get('trailer_type_id', 0) != 0 + cf = float(vc.get('truck_cost_factor', 0.0)) + tw = float(vc.get('trailer_towing_cost_multiplier', 0.0)) if has_trailer else 0.0 + fixed = float(vc.get('truck_fixed_cost', 0.0)) + + if fmt != 'gurobi' or route_index >= len(raw_routes): + raise ValueError( + "exact objective validation requires route_sequence and " + "route_sequence_physical in the published solution format" + ) + network_sequence = raw_routes[route_index].get('route_sequence') + physical_sequence = raw_routes[route_index].get( + 'route_sequence_physical' + ) + if (not isinstance(network_sequence, list) + or not isinstance(physical_sequence, list) + or len(network_sequence) != len(physical_sequence) + or len(network_sequence) < 2): + raise ValueError( + f"route {route_index} has incomplete or misaligned sequences" + ) + mapped_physical = [physical_node(node) + for node in network_sequence] + if mapped_physical != physical_sequence: + raise ValueError( + f"route {route_index} route_sequence_physical does not " + f"match its expanded route_sequence" + ) + + travel = 0.0 + for source, target in zip(network_sequence, + network_sequence[1:]): + source_physical = physical_node(source) + target_physical = physical_node(target) + towing = ( + has_trailer + and (source == depot_id + or source in N_H_ids + or source in cp_nodes) + and (target == depot_id + or target in N_H_ids + or target in dp_nodes) + ) + factor = cf + (tw if towing else 0.0) + travel += factor * float( + dist_matrix[source_physical][target_physical] + ) + + n_dc = len(r.get('decouple_locations', []) or []) + n_cp = len(r.get('couple_locations', []) or []) + n_tau = len(r.get('transfer_locations', []) or []) + handling = (n_dc * decoupling_cost_val + + n_cp * coupling_cost_val + + n_tau * transfer_cost_val) + + exact_total += fixed + travel + handling + + tol_obj = max(1e-3, 1e-8 * max(abs(exact_total), 1.0)) + difference = abs(reported - exact_total) + if difference > tol_obj: + violated_constraints.add(10) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from exactly recomputed route cost " + f"{exact_total:.6f} (difference={difference:.6g}, " + f"tol={tol_obj:.4g})") + normalizer = max(abs(exact_total), eps) + violation_magnitudes.append({ + 'constraint': 10, + 'lhs': float(reported), + 'rhs': float(exact_total), + 'raw_excess': float(difference), + 'normalizer': float(normalizer), + 'ratio': float(difference / normalizer), + }) + + feasible = len(violated_constraints) == 0 + return feasible, sorted(violated_constraints), violations, violation_magnitudes + + +def _build_gurobi_event_seq(route_seq, phys_seq, dc_locs, cp_locs, + depot_id, N_L_ids, N_H_ids, has_trailer, instance, + tau_locs=None): + """ + Build event sequence from gurobi solution format. + + In gurobi format: + - route_sequence contains network vertex IDs + - route_sequence_physical contains physical location IDs + - When a physical location appears in decouple_locations, transfer_locations, + or couple_locations, the vertex at that physical location in the + route_sequence may be a DC/TAU/CP vertex rather than a customer vertex. + + We use route_sequence_physical and match against DC/TAU/CP locations. + """ + if tau_locs is None: + tau_locs = [] + T_set = set(t['id'] for t in instance['transshipment_locations']) + + events = [] + # Track which decouple/transfer/couple locations we've encountered + dc_remaining = list(dc_locs) + cp_remaining = list(cp_locs) + + if len(route_seq) == len(phys_seq): + # Use the difference between route_seq and phys_seq to detect DC/TAU/CP + dc_used = 0 + tau_used = 0 + cp_used = 0 + + for i in range(len(phys_seq)): + loc = phys_seq[i] + net_vid = route_seq[i] + + if i == 0: + events.append(('D+', depot_id)) + elif i == len(phys_seq) - 1: + events.append(('D-', depot_id)) + elif loc == depot_id: + events.append(('depot', loc)) + elif net_vid != loc: + # Special vertex (DC, TAU, or CP) + # Check in expected order: DC first, then TAU, then CP + if dc_used < len(dc_locs) and loc == dc_locs[dc_used]: + events.append(('DC', loc)) + dc_used += 1 + elif tau_used < len(tau_locs) and loc == tau_locs[tau_used]: + events.append(('TAU', loc)) + tau_used += 1 + elif cp_used < len(cp_locs) and loc == cp_locs[cp_used]: + events.append(('CP', loc)) + cp_used += 1 + else: + # Could be TAU or another special vertex + events.append(('TAU', loc)) + elif loc in N_L_ids: + events.append(('NL', loc)) + elif loc in N_H_ids: + events.append(('NH', loc)) + elif loc in T_set: + # Transshipment visited as customer? + events.append(('TAU', loc)) + else: + events.append(('?', loc)) + else: + # Fallback: just use phys_seq with simple type detection + for i, loc in enumerate(phys_seq): + if i == 0: + events.append(('D+', depot_id)) + elif i == len(phys_seq) - 1: + events.append(('D-', depot_id)) + elif loc in N_L_ids: + events.append(('NL', loc)) + elif loc in N_H_ids: + events.append(('NH', loc)) + else: + events.append(('?', loc)) + + return events + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for TTRPTW solutions") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + 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 + + feasible, violated_constraints, violations_list, violation_magnitudes = \ + check_feasibility(instance, solution) + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violations_list, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if feasible: + print(f"FEASIBLE: Solution passes all constraint checks.") + else: + print(f"INFEASIBLE: Violated constraints: {violated_constraints}") + for v in violations_list: + 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/rothenbacher2018/gurobi_code.py b/tasks/rothenbacher2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..3f95f5ffe32ed64dc7a2fdd8c85457be8ecb70b4 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_code.py @@ -0,0 +1,1109 @@ +""" +Compact Arc-Flow MIP Formulation for the Truck-and-Trailer Routing Problem +with Time Windows (TTRPTW) + +IMPORTANT NOTES: + 1. The paper "Branch-and-Price-and-Cut for the Truck-and-Trailer Routing + Problem with Time Windows" (Rothenbaecher, Drexl, Irnich, 2018, + Transportation Science) ONLY provides a set-partitioning model + (formulation (1a)-(1d)) that requires a branch-and-price-and-cut + framework with column generation. The paper does NOT provide a compact + MIP formulation. + + 2. This file implements a compact arc-flow MIP formulation as a reasonable + implementation choice so that Gurobi can solve it directly without + column generation. This formulation is NOT from the paper -- it is an + engineering decision to capture the same problem structure in a form + amenable to a general-purpose MIP solver. + + 3. KEY MODELING DECISIONS: + - Following the paper's pricing network (Section 3, Table 2), each + parking location p has three copies: d(p) for decoupling, tau(p) + for load transfer, and c(p) for coupling. This allows the vehicle + to "visit" the same physical location multiple times with different + operations. + - For complete vehicles, the route goes: + depot -> (trailer customers on x-arcs) -> d(p) [decouple] -> + (truck customers and trailer customers on y-arcs) -> c(p) [couple] + -> (trailer customers on x-arcs) -> depot + - Solo trucks: simple TSP-like routing through customers. + - At most one decouple/recouple cycle per complete vehicle. + - MTZ subtour elimination. + - A greedy heuristic provides a warm-start MIP solution. + - Since customer_time_windows=false, we use [0, max_route_duration]. + +Author: Generated as a compact MIP alternative to the paper's BPC approach +""" + +import argparse +import json +import os +import sys +import time as time_module +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("ERROR: gurobipy is not installed. " + "Please install Gurobi and its Python interface.") + sys.exit(1) + + +def load_instance(path): + """Load a TTRPTW instance from a JSON file.""" + with open(path, "r") as f: + data = json.load(f) + return data + + +def solve_ttrptw(instance_path, solution_path, time_limit): + """Build and solve a compact arc-flow MIP for the TTRPTW.""" + data = load_instance(instance_path) + + params = data["parameters"] + fleet = data["fleet"] + depot = data["depot"] + truck_custs = data["truck_customers"] + trailer_custs = data["trailer_customers"] + trans_locs = data["transshipment_locations"] + dist_orig = data["distance_matrix"] + ttime_orig = data["travel_time_matrix"] + + horizon_end = params["planning_horizon"][1] + coupling_time_val = params["coupling_time"] + decoupling_time_val = params["decoupling_time"] + transfer_time_val = params["transfer_time"] + coupling_cost_val = params["coupling_cost"] + decoupling_cost_val = params["decoupling_cost"] + transfer_cost_val = params["transfer_cost"] + service_time_val = params["service_time"] + + depot_id = depot["id"] # 0 + N_L = [c["id"] for c in truck_custs] + N_H = [c["id"] for c in trailer_custs] + T_locs = [t["id"] for t in trans_locs] + P_orig = sorted(set(N_H) | set(T_locs)) # parking locations (original IDs) + N_cust = sorted(N_L + N_H) + n_orig = len(dist_orig) + + supply = {} + svc = {} + cust_tw = {} # customer id -> (earliest, latest); only populated when set + for c in truck_custs + trailer_custs: + supply[c["id"]] = c["supply"] + svc[c["id"]] = c.get("service_time", service_time_val) + tw = c.get("time_window") + if tw is not None: + cust_tw[c["id"]] = (float(tw[0]), float(tw[1])) + for nid in [depot_id] + T_locs: + supply[nid] = 0 + svc[nid] = 0.0 + + vehicle_classes = fleet["vehicle_classes"] + truck_types = {tt["id"]: tt for tt in fleet["truck_types"]} + trailer_types = {tt["id"]: tt for tt in fleet["trailer_types"]} + vc_info = {vc["class_id"]: vc for vc in vehicle_classes} + + def is_complete(cid): + return vc_info[cid]["trailer_type_id"] != 0 + + # ========================================================================= + # EXPANDED NODE SET + # For complete vehicles, each parking location p gets two extra copies: + # d(p) = decouple node (arrive with trailer, leave without) + # c(p) = couple node (arrive without trailer, leave with) + # These are virtual nodes at the same physical location. + # + # For solo trucks, only depot + customers are needed. + # ========================================================================= + # Assign IDs to expanded nodes: + # Original nodes: 0..n_orig-1 + # d(p) for p in P_orig: n_orig, n_orig+1, ... + # c(p) for p in P_orig: after all d(p) nodes + + dp_node = {} # decouple copy: dp_node[p] = new_id + cp_node = {} # couple copy: cp_node[p] = new_id + next_id = n_orig + for p in P_orig: + dp_node[p] = next_id + next_id += 1 + for p in P_orig: + cp_node[p] = next_id + next_id += 1 + + total_nodes = next_id + + # Expanded distance and travel time: dp/cp nodes inherit from original p + def edist(i, j): + """Distance between expanded nodes.""" + ri = i if i < n_orig else ( + P_orig[(i - n_orig) % len(P_orig)] if i < n_orig + len(P_orig) + else P_orig[(i - n_orig - len(P_orig)) % len(P_orig)]) + rj = j if j < n_orig else ( + P_orig[(j - n_orig) % len(P_orig)] if j < n_orig + len(P_orig) + else P_orig[(j - n_orig - len(P_orig)) % len(P_orig)]) + return dist_orig[ri][rj] + + def ettime(i, j): + """Travel time between expanded nodes.""" + ri = i if i < n_orig else ( + P_orig[(i - n_orig) % len(P_orig)] if i < n_orig + len(P_orig) + else P_orig[(i - n_orig - len(P_orig)) % len(P_orig)]) + rj = j if j < n_orig else ( + P_orig[(j - n_orig) % len(P_orig)] if j < n_orig + len(P_orig) + else P_orig[(j - n_orig - len(P_orig)) % len(P_orig)]) + return ttime_orig[ri][rj] + + # Helper to get the "real" (physical) node for any expanded node + def real_node(i): + if i < n_orig: + return i + idx = (i - n_orig) % len(P_orig) + return P_orig[idx] + + # ========================================================================= + # NODE SETS for each vehicle type + # ========================================================================= + # Solo truck nodes: depot + all customers (no trans, no dp/cp) + solo_nodes = [depot_id] + N_cust + + # Complete vehicle nodes: depot + customers + dp + cp copies + # Note: Transshipment locations are only useful as parking locations, + # which is handled by dp_node/cp_node copies. They serve no customer + # supply, so we exclude the original T_locs nodes from the CV node set + # to reduce the number of arcs. + cv_nodes = [depot_id] + N_cust + cv_dp_nodes = [dp_node[p] for p in P_orig] + cv_cp_nodes = [cp_node[p] for p in P_orig] + cv_all_nodes = cv_nodes + cv_dp_nodes + cv_cp_nodes + + N_L_s = set(N_L) + N_H_s = set(N_H) + T_locs_s = set(T_locs) + N_cust_s = set(N_cust) + dp_nodes_s = set(cv_dp_nodes) + cp_nodes_s = set(cv_cp_nodes) + + M = horizon_end # Big-M for time + + # ========================================================================= + # BUILD MODEL + # ========================================================================= + model = gp.Model("TTRPTW") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + model.setParam("MIPGap", 1e-4) + model.setParam("MIPFocus", 1) + + vehicles = [] + for vc in vehicle_classes: + for vi in range(vc["num_available"]): + vehicles.append((vc["class_id"], vi)) + + # ========================================================================= + # VARIABLES + # ========================================================================= + u = {} # vehicle used + arc_v = {} # arc traversed + sv = {} # customer served + tm = {} # time at node + ld = {} # total load at node + ps = {} # MTZ position + + for (k, vi) in vehicles: + vc_d = vc_info[k] + is_cv = is_complete(k) + Q_L = vc_d["truck_capacity"] + Q_H = vc_d["trailer_capacity"] if is_cv else 0 + Q_total = Q_L + Q_H + + u[k, vi] = model.addVar(vtype=GRB.BINARY, name=f"u_{k}_{vi}") + + nodes = cv_all_nodes if is_cv else solo_nodes + n_v = len(nodes) + + for n in N_cust: + sv[k, vi, n] = model.addVar(vtype=GRB.BINARY, + name=f"sv_{k}_{vi}_{n}") + + # Arc variables + # For solo trucks: arcs between solo_nodes + # For CVs: structured arcs based on paper's Table 2 + for i in nodes: + for j in nodes: + if i == j: + continue + + # For solo trucks: all arcs allowed + if not is_cv: + arc_v[k, vi, i, j] = model.addVar( + vtype=GRB.BINARY, name=f"a_{k}_{vi}_{i}_{j}") + continue + + # For complete vehicles: restrict arcs based on Table 2 + # x-arcs (with trailer): depot <-> N_H, depot <-> dp, N_H <-> N_H, N_H <-> dp + # y-arcs (truck alone): dp -> N_L, dp -> N_H, N_L -> N_L, + # N_L -> N_H, N_H -> N_L, N_L -> cp, N_H -> cp + # dp -> cp (direct return without serving anyone) + # cp -> N_H, cp -> dp (another cycle), cp -> depot + # Note: T_locs original nodes are excluded from CV nodes; + # T_locs are only available as parking via dp/cp copies. + + create_arc = False + + # Categorize nodes + i_is_depot = (i == depot_id) + j_is_depot = (j == depot_id) + i_is_NL = (i in N_L_s) + j_is_NL = (j in N_L_s) + i_is_NH = (i in N_H_s) + j_is_NH = (j in N_H_s) + i_is_dp = (i in dp_nodes_s) + j_is_dp = (j in dp_nodes_s) + i_is_cp = (i in cp_nodes_s) + j_is_cp = (j in cp_nodes_s) + + # x-arcs (with trailer attached): + # depot -> NH, depot -> dp + if i_is_depot and (j_is_NH or j_is_dp): + create_arc = True + # NH -> depot + if i_is_NH and j_is_depot: + create_arc = True + # NH <-> NH + if i_is_NH and j_is_NH: + create_arc = True + # NH -> dp (going to decouple) + if i_is_NH and j_is_dp: + create_arc = True + # cp -> depot (return after coupling) + if i_is_cp and j_is_depot: + create_arc = True + # cp -> NH (visit more trailer custs after coupling) + if i_is_cp and j_is_NH: + create_arc = True + # cp -> dp (another decouple cycle -- not used since we limit + # to 1 cycle, but included for completeness) + if i_is_cp and j_is_dp: + create_arc = True + + # y-arcs (truck alone): + # dp -> NL, dp -> NH (leaving parking, truck alone) + if i_is_dp and (j_is_NL or j_is_NH): + create_arc = True + # dp -> cp (direct: decouple then couple without visiting anyone) + if i_is_dp and j_is_cp: + create_arc = True + # NL -> NL, NL -> NH, NL -> cp (truck alone) + if i_is_NL and (j_is_NL or j_is_NH or j_is_cp): + create_arc = True + # NH -> NL, NH -> cp (truck alone in decouple phase) + if i_is_NH and (j_is_NL or j_is_cp): + create_arc = True + + if create_arc: + arc_v[k, vi, i, j] = model.addVar( + vtype=GRB.BINARY, name=f"a_{k}_{vi}_{i}_{j}") + + # Time, load, position. Customer time windows (when present in the + # instance) are enforced as variable bounds on tm[k,vi,i] for the + # node copy whose physical node is a customer with a tw entry. + for i in nodes: + rn = real_node(i) + if rn in cust_tw: + tw_lo, tw_hi = cust_tw[rn] + else: + tw_lo, tw_hi = 0.0, horizon_end + tm[k, vi, i] = model.addVar(lb=tw_lo, ub=tw_hi, + vtype=GRB.CONTINUOUS, + name=f"tm_{k}_{vi}_{i}") + ld[k, vi, i] = model.addVar(lb=0, ub=Q_total, + vtype=GRB.CONTINUOUS, + name=f"ld_{k}_{vi}_{i}") + ps[k, vi, i] = model.addVar(lb=0, ub=n_v, + vtype=GRB.CONTINUOUS, + name=f"ps_{k}_{vi}_{i}") + + model.update() + + # ========================================================================= + # OBJECTIVE + # ========================================================================= + obj = gp.LinExpr() + for (k, vi) in vehicles: + vc_d = vc_info[k] + is_cv = is_complete(k) + cf = vc_d["truck_cost_factor"] + tw = vc_d["trailer_towing_cost_multiplier"] + nodes = cv_all_nodes if is_cv else solo_nodes + + obj += vc_d["truck_fixed_cost"] * u[k, vi] + + for i in nodes: + for j in nodes: + if (k, vi, i, j) not in arc_v: + continue + d = edist(i, j) + + if not is_cv: + # Solo truck: truck cost only + obj += cf * d * arc_v[k, vi, i, j] + else: + # Determine if this is a with-trailer or truck-alone arc + # by checking node types. + # With-trailer arcs: involve depot, NH, T, dp(arriving), cp(leaving) + # Truck-alone arcs: involve dp(leaving), NL, cp(arriving) + is_x_arc = False + # x-arc if source is depot/NH/cp AND dest is depot/NH/dp + i_trailer = (i == depot_id or i in N_H_s + or i in cp_nodes_s) + j_trailer = (j == depot_id or j in N_H_s + or j in dp_nodes_s) + if i_trailer and j_trailer: + is_x_arc = True + + if is_x_arc: + obj += (cf + tw) * d * arc_v[k, vi, i, j] + else: + obj += cf * d * arc_v[k, vi, i, j] + + # Handling costs for CV + if is_cv: + for p in P_orig: + dp = dp_node[p] + cp_n = cp_node[p] + # Decouple cost: paid if dp node is visited + dp_in = gp.quicksum( + arc_v[k, vi, j, dp] for j in nodes + if (k, vi, j, dp) in arc_v) + obj += decoupling_cost_val * dp_in + # Couple cost: paid if cp node is visited + cp_in = gp.quicksum( + arc_v[k, vi, j, cp_n] for j in nodes + if (k, vi, j, cp_n) in arc_v) + obj += coupling_cost_val * cp_in + + model.setObjective(obj, GRB.MINIMIZE) + + # ========================================================================= + # CONSTRAINTS + # ========================================================================= + + # (C1) Each customer served exactly once + for n in N_cust: + model.addConstr( + gp.quicksum(sv[k, vi, n] for (k, vi) in vehicles) == 1, + name=f"once_{n}") + + # (C2) Fleet + for tt_id, tt in truck_types.items(): + rel = [(k, vi) for (k, vi) in vehicles + if vc_info[k]["truck_type_id"] == tt_id] + if rel: + model.addConstr( + gp.quicksum(u[k, vi] for (k, vi) in rel) + <= tt["num_available"], name=f"ft_{tt_id}") + for tt_id, tt in trailer_types.items(): + rel = [(k, vi) for (k, vi) in vehicles + if vc_info[k]["trailer_type_id"] == tt_id] + if rel: + model.addConstr( + gp.quicksum(u[k, vi] for (k, vi) in rel) + <= tt["num_available"], name=f"fh_{tt_id}") + + # Symmetry breaking + for vc in vehicle_classes: + k = vc["class_id"] + for vi in range(vc["num_available"] - 1): + model.addConstr(u[k, vi] >= u[k, vi + 1], + name=f"sym_{k}_{vi}") + + # Per-vehicle + for (k, vi) in vehicles: + vc_d = vc_info[k] + is_cv = is_complete(k) + Q_L = vc_d["truck_capacity"] + Q_H = vc_d["trailer_capacity"] if is_cv else 0 + Q_total = Q_L + Q_H + nodes = cv_all_nodes if is_cv else solo_nodes + n_v = len(nodes) + + def out_f(i): + return gp.quicksum(arc_v[k, vi, i, j] for j in nodes + if (k, vi, i, j) in arc_v) + def in_f(i): + return gp.quicksum(arc_v[k, vi, j, i] for j in nodes + if (k, vi, j, i) in arc_v) + + # Depot + model.addConstr(out_f(depot_id) == u[k, vi], name=f"do_{k}_{vi}") + model.addConstr(in_f(depot_id) == u[k, vi], name=f"di_{k}_{vi}") + + # Flow conservation at all non-depot nodes + for i in nodes: + if i == depot_id: + continue + model.addConstr(in_f(i) == out_f(i), name=f"fc_{k}_{vi}_{i}") + + # Served = inflow for customers + for n in N_cust: + model.addConstr(in_f(n) == sv[k, vi, n], + name=f"svl_{k}_{vi}_{n}") + model.addConstr(sv[k, vi, n] <= u[k, vi], + name=f"svu_{k}_{vi}_{n}") + + # At most one visit per node + for i in nodes: + if i == depot_id: + continue + model.addConstr(in_f(i) <= 1, name=f"v1_{k}_{vi}_{i}") + + # Depot load = 0 + model.addConstr(ld[k, vi, depot_id] == 0, name=f"dl_{k}_{vi}") + + # MTZ + time + load along arcs + for i in nodes: + for j in nodes: + if (k, vi, i, j) not in arc_v: + continue + + # MTZ + if i != depot_id and j != depot_id: + model.addConstr( + ps[k, vi, j] >= ps[k, vi, i] + 1 + - n_v * (1 - arc_v[k, vi, i, j]), + name=f"mtz_{k}_{vi}_{i}_{j}") + + # Time propagation (skip j=depot: depot time=0 is departure, + # return time is not tracked at depot since it's a single node) + if j != depot_id: + st_i = svc.get(real_node(i), 0.0) + handling_i = 0.0 + if i in dp_nodes_s: + handling_i = decoupling_time_val + elif i in cp_nodes_s: + handling_i = coupling_time_val + + model.addConstr( + tm[k, vi, j] >= tm[k, vi, i] + st_i + handling_i + + ettime(i, j) - M * (1 - arc_v[k, vi, i, j]), + name=f"tm_{k}_{vi}_{i}_{j}") + + # Load propagation (both lower and upper bounds for tightness) + rj = real_node(j) + if rj in N_cust_s and j not in dp_nodes_s and j not in cp_nodes_s: + # Visiting a customer: load increases by supply[rj] + model.addConstr( + ld[k, vi, j] >= ld[k, vi, i] + supply[rj] + - Q_total * (1 - arc_v[k, vi, i, j]), + name=f"ld_{k}_{vi}_{i}_{j}") + model.addConstr( + ld[k, vi, j] <= ld[k, vi, i] + supply[rj] + + Q_total * (1 - arc_v[k, vi, i, j]), + name=f"ldup_{k}_{vi}_{i}_{j}") + elif j != depot_id: + # Non-customer (dp, cp): load preserved + model.addConstr( + ld[k, vi, j] >= ld[k, vi, i] + - Q_total * (1 - arc_v[k, vi, i, j]), + name=f"ldu_{k}_{vi}_{i}_{j}") + model.addConstr( + ld[k, vi, j] <= ld[k, vi, i] + + Q_total * (1 - arc_v[k, vi, i, j]), + name=f"ldl_{k}_{vi}_{i}_{j}") + + # Route duration: for any arc (i, depot), the departure from i + # must leave enough time to return: + # tm[i] + svc[i] + handling + ttime[i][depot] <= horizon_end + for i in nodes: + if i == depot_id: + continue + if (k, vi, i, depot_id) not in arc_v: + continue + st_i = svc.get(real_node(i), 0.0) + handling_i = 0.0 + if i in dp_nodes_s: + handling_i = decoupling_time_val + elif i in cp_nodes_s: + handling_i = coupling_time_val + model.addConstr( + tm[k, vi, i] + st_i + handling_i + ettime(i, depot_id) + <= horizon_end + M * (1 - arc_v[k, vi, i, depot_id]), + name=f"dur_{k}_{vi}_{i}") + + # ---- COMPLETE VEHICLE specific constraints ---- + if is_cv: + # (CV1) At most one decouple location used (at most one dp visited) + model.addConstr( + gp.quicksum(in_f(dp_node[p]) for p in P_orig) <= 1, + name=f"mdc_{k}_{vi}") + + # (CV2) At most one couple location used + model.addConstr( + gp.quicksum(in_f(cp_node[p]) for p in P_orig) <= 1, + name=f"mcp_{k}_{vi}") + + # (CV3) Number of decouples = number of couples + model.addConstr( + gp.quicksum(in_f(dp_node[p]) for p in P_orig) == + gp.quicksum(in_f(cp_node[p]) for p in P_orig), + name=f"dcp_{k}_{vi}") + + # (CV4) Couple must be at same physical location as decouple + for p in P_orig: + model.addConstr( + in_f(cp_node[p]) <= in_f(dp_node[p]), + name=f"cpdc_{k}_{vi}_{p}") + + # (CV5) Truck customers can only be served if decouple happens + for n in N_L: + model.addConstr( + sv[k, vi, n] <= + gp.quicksum(in_f(dp_node[p]) for p in P_orig), + name=f"tcdc_{k}_{vi}_{n}") + + # (CV5b) Ordering: NL customers must come between dp and cp + # in the MTZ position. This enforces that the trailer is + # detached before serving truck customers. + for n in N_L: + for p in P_orig: + dp_n = dp_node[p] + cp_n = cp_node[p] + # ps[n] >= ps[dp] + 1 if both n and dp are visited + model.addConstr( + ps[k, vi, n] >= ps[k, vi, dp_n] + 1 + - n_v * (1 - sv[k, vi, n]) + - n_v * (1 - in_f(dp_n)), + name=f"odp_{k}_{vi}_{n}_{p}") + # ps[cp] >= ps[n] + 1 if both n and cp are visited + model.addConstr( + ps[k, vi, cp_n] >= ps[k, vi, n] + 1 + - n_v * (1 - sv[k, vi, n]) + - n_v * (1 - in_f(cp_n)), + name=f"ocp_{k}_{vi}_{n}_{p}") + + # (CV6) Capacity during truck-alone phase: + # When the truck is alone (between dp and cp), the supply + # picked up must fit in the truck. The load at dp includes + # supply from the with-trailer phase, and the load increase + # from dp to cp must be <= Q_L (truck capacity). + # ld[cp] - ld[dp] <= Q_L for each parking location p. + for p in P_orig: + dp_n = dp_node[p] + cp_n = cp_node[p] + model.addConstr( + ld[k, vi, cp_n] - ld[k, vi, dp_n] <= Q_L, + name=f"capalone_{k}_{vi}_{p}") + + # ---- CAPACITY CUTS ---- + # Total served supply <= vehicle total capacity + model.addConstr( + gp.quicksum(supply[n] * sv[k, vi, n] for n in N_cust) <= Q_total, + name=f"capcut_{k}_{vi}") + + # ========================================================================= + # WARM START: Greedy heuristic + # ========================================================================= + print("Building heuristic warm-start solution...") + heur_routes = _greedy_heuristic(data, P_orig, dp_node, cp_node, vc_info) + heur_served = set() + for r in heur_routes: + heur_served.update(r["customers"]) + print(f"Heuristic: {len(heur_served)}/{len(N_cust)} customers, " + f"{len(heur_routes)} vehicles") + + # Apply warm start + for (k, vi) in vehicles: + u[k, vi].Start = 0 + for n in N_cust: + sv[k, vi, n].Start = 0 + nodes = cv_all_nodes if is_complete(k) else solo_nodes + for i in nodes: + for j in nodes: + if (k, vi, i, j) in arc_v: + arc_v[k, vi, i, j].Start = 0 + + for r in heur_routes: + k = r["class_id"] + vi = r["vehicle_index"] + is_cv = is_complete(k) + vc_d = vc_info[k] + Q_total = vc_d["truck_capacity"] + (vc_d["trailer_capacity"] if is_cv else 0) + + u[k, vi].Start = 1 + for n in r["customers"]: + sv[k, vi, n].Start = 1 + + seq = r["sequence"] + for idx in range(len(seq) - 1): + i, j = seq[idx], seq[idx + 1] + if (k, vi, i, j) in arc_v: + arc_v[k, vi, i, j].Start = 1 + + # Time and load + cur_time = 0.0 + cur_load = 0.0 + for idx, node in enumerate(seq): + if (k, vi, node) in tm: + tm[k, vi, node].Start = cur_time + if (k, vi, node) in ld: + ld[k, vi, node].Start = min(cur_load, Q_total) + if (k, vi, node) in ps: + ps[k, vi, node].Start = idx + + if idx < len(seq) - 1: + nxt = seq[idx + 1] + rn = real_node(node) + st_node = svc.get(rn, 0.0) + handling = 0.0 + if node in dp_nodes_s: + handling = decoupling_time_val + elif node in cp_nodes_s: + handling = coupling_time_val + cur_time += st_node + handling + ettime(node, nxt) + rnxt = real_node(nxt) + if rnxt in N_cust_s and nxt not in dp_nodes_s and nxt not in cp_nodes_s: + cur_load += supply[rnxt] + + # Depot load must be 0 (override end-of-route accumulation) + if (k, vi, depot_id) in ld: + ld[k, vi, depot_id].Start = 0 + if (k, vi, depot_id) in tm: + tm[k, vi, depot_id].Start = 0 + if (k, vi, depot_id) in ps: + ps[k, vi, depot_id].Start = 0 + + # ========================================================================= + # SOLVE + # ========================================================================= + model.update() + print(f"\nModel: {model.NumVars} vars, {model.NumConstrs} constrs") + print(f"Time limit: {time_limit}s") + + solve_start = time_module.time() + model.optimize() + solve_time = time_module.time() - solve_start + + # ========================================================================= + # EXTRACT SOLUTION + # ========================================================================= + solution = { + "instance_path": instance_path, + "solver": "Gurobi", + "formulation": "compact_arc_flow_MIP_with_node_copies", + "note": ( + "The paper only provides a set-partitioning model (1a)-(1d) " + "requiring branch-and-price-and-cut. This compact arc-flow MIP " + "with decouple/couple node copies is an implementation choice." + ), + "solve_time_seconds": round(solve_time, 2), + "time_limit_seconds": time_limit, + } + + if model.Status == GRB.OPTIMAL: + solution["status"] = "optimal" + solution["objective_value"] = round(model.ObjVal, 6) + solution["mip_gap"] = model.MIPGap + elif model.Status == GRB.TIME_LIMIT: + if model.SolCount > 0: + solution["status"] = "time_limit_with_solution" + solution["objective_value"] = round(model.ObjVal, 6) + solution["mip_gap"] = model.MIPGap + solution["best_bound"] = round(model.ObjBound, 6) + else: + solution["status"] = "time_limit_no_solution" + solution["objective_value"] = None + try: + solution["best_bound"] = round(model.ObjBound, 6) + except Exception: + solution["best_bound"] = None + elif model.Status == GRB.INFEASIBLE: + solution["status"] = "infeasible" + solution["objective_value"] = None + print("WARNING: Model is infeasible.") + try: + model.computeIIS() + iis_c = [c.ConstrName for c in model.getConstrs() if c.IISConstr] + solution["iis_constraints"] = iis_c[:30] + print(f"IIS (first 30): {iis_c[:30]}") + except Exception: + pass + elif model.Status == GRB.UNBOUNDED: + solution["status"] = "unbounded" + solution["objective_value"] = None + else: + solution["status"] = f"gurobi_status_{model.Status}" + solution["objective_value"] = None + if model.SolCount > 0: + solution["objective_value"] = round(model.ObjVal, 6) + + # ---- Route extraction ---- + routes = [] + if model.SolCount > 0: + for (k_v, vi_v) in vehicles: + vc_d = vc_info[k_v] + is_cv = is_complete(k_v) + if u[k_v, vi_v].X < 0.5: + continue + + route_info = { + "vehicle_class": k_v, + "vehicle_index": vi_v, + "vehicle_description": vc_d["description"], + "is_complete_vehicle": is_cv, + "fixed_cost": vc_d["truck_fixed_cost"], + "customers_served": [], + "route_sequence": [], + "route_sequence_physical": [], + "decouple_locations": [], + "couple_locations": [], + } + + for n in N_cust: + if sv[k_v, vi_v, n].X > 0.5: + route_info["customers_served"].append(n) + + nodes = cv_all_nodes if is_cv else solo_nodes + adj = {} + for i in nodes: + for j in nodes: + if (k_v, vi_v, i, j) in arc_v and arc_v[k_v, vi_v, i, j].X > 0.5: + adj[i] = j + + seq = [depot_id] + cur = depot_id + for _ in range(len(nodes) + 2): + nxt = adj.get(cur) + if nxt is None: + break + seq.append(nxt) + if nxt == depot_id: + break + cur = nxt + if seq[-1] != depot_id: + seq.append(depot_id) + + route_info["route_sequence"] = seq + route_info["route_sequence_physical"] = [real_node(n) for n in seq] + + # Persist the model's time decisions so the feasibility checker + # can verify time windows / planning horizon directly from the + # MIP's t[k,vi,n] schedule, rather than re-simulating timing + # (which mis-handles node copies / decouple / couple / transfer + # events on this TTRPTW network). + arrival_times = {} + for n in seq: + if (k_v, vi_v, n) in tm: + arrival_times[str(n)] = round(float(tm[k_v, vi_v, n].X), 6) + route_info["arrival_times"] = arrival_times + + if is_cv: + for p in P_orig: + dp = dp_node[p] + cp_n = cp_node[p] + dp_in_val = sum( + arc_v[k_v, vi_v, j, dp].X + for j in nodes if (k_v, vi_v, j, dp) in arc_v) + if dp_in_val > 0.5: + route_info["decouple_locations"].append(p) + cp_in_val = sum( + arc_v[k_v, vi_v, j, cp_n].X + for j in nodes if (k_v, vi_v, j, cp_n) in arc_v) + if cp_in_val > 0.5: + route_info["couple_locations"].append(p) + + # Costs + cf = vc_d["truck_cost_factor"] + tw = vc_d["trailer_towing_cost_multiplier"] + travel = 0.0 + for i in nodes: + for j in nodes: + if (k_v, vi_v, i, j) in arc_v and arc_v[k_v, vi_v, i, j].X > 0.5: + d = edist(i, j) + if not is_cv: + travel += cf * d + else: + i_trailer = (i == depot_id or i in N_H_s + or i in cp_nodes_s) + j_trailer = (j == depot_id or j in N_H_s + or j in dp_nodes_s) + if i_trailer and j_trailer: + travel += (cf + tw) * d + else: + travel += cf * d + + handling = (len(route_info["decouple_locations"]) * decoupling_cost_val + + len(route_info["couple_locations"]) * coupling_cost_val) + + route_info["travel_cost"] = round(travel, 4) + route_info["handling_cost"] = round(handling, 4) + route_info["route_cost"] = round( + vc_d["truck_fixed_cost"] + travel + handling, 4) + routes.append(route_info) + + solution["routes"] = routes + + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"\nStatus: {solution['status']}") + print(f"Objective: {solution['objective_value']}") + print(f"Solve time: {solve_time:.2f}s") + if routes: + print(f"Vehicles: {len(routes)}") + for r in routes: + print(f" Class {r['vehicle_class']} idx {r['vehicle_index']}: " + f"custs={r['customers_served']}, cost={r['route_cost']}") + print(f" Route (physical): {r['route_sequence_physical']}") + if r['decouple_locations']: + print(f" Decouple at: {r['decouple_locations']}") + if r['couple_locations']: + print(f" Couple at: {r['couple_locations']}") + print(f"\nSolution written to: {solution_path}") + return solution + + +def _greedy_heuristic(data, P_orig, dp_node, cp_node, vc_info): + """ + Build a feasible heuristic solution using expanded node copies. + Returns list of routes with sequences using expanded node IDs. + """ + params = data["parameters"] + fleet = data["fleet"] + dist_orig = data["distance_matrix"] + ttime_orig = data["travel_time_matrix"] + + depot_id = data["depot"]["id"] + N_L = [c["id"] for c in data["truck_customers"]] + N_H = [c["id"] for c in data["trailer_customers"]] + T_locs = [t["id"] for t in data["transshipment_locations"]] + + supply = {} + svc = {} + for c in data["truck_customers"] + data["trailer_customers"]: + supply[c["id"]] = c["supply"] + svc[c["id"]] = c.get("service_time", params["service_time"]) + for nid in [depot_id] + T_locs: + supply[nid] = 0 + svc[nid] = 0.0 + + horizon_end = params["planning_horizon"][1] + decoupling_t = params["decoupling_time"] + coupling_t = params["coupling_time"] + + n_orig = len(dist_orig) + + def real_node(i): + if i < n_orig: + return i + idx = (i - n_orig) % len(P_orig) + return P_orig[idx] + + def edist(i, j): + return dist_orig[real_node(i)][real_node(j)] + + def ettime(i, j): + return ttime_orig[real_node(i)][real_node(j)] + + unserved_L = set(N_L) + unserved_H = set(N_H) + used_count = {vc["class_id"]: 0 for vc in fleet["vehicle_classes"]} + routes = [] + + # Strategy 1: Complete vehicles for trailer customers + truck customers + for vc in sorted(fleet["vehicle_classes"], + key=lambda v: v["total_capacity"], reverse=True): + k = vc["class_id"] + if vc["trailer_type_id"] == 0: + continue + Q_L = vc["truck_capacity"] + Q_H = vc["trailer_capacity"] + Q_total = Q_L + Q_H + cf = vc["truck_cost_factor"] + tw = vc["trailer_towing_cost_multiplier"] + + while used_count[k] < vc["num_available"] and unserved_H: + # Phase 1: serve trailer customers with trailer + seq_phase1 = [depot_id] + load = 0 + t = 0.0 + served_H = [] + + cands = sorted(unserved_H, key=lambda n: dist_orig[seq_phase1[-1]][n]) + for n in cands: + new_load = load + supply[n] + extra = svc[seq_phase1[-1]] + ttime_orig[seq_phase1[-1]][n] + back = svc[n] + ttime_orig[n][depot_id] + if new_load <= Q_total and t + extra + back <= horizon_end: + seq_phase1.append(n) + load += supply[n] + t += svc[seq_phase1[-2]] + ttime_orig[seq_phase1[-2]][n] + served_H.append(n) + + if not served_H: + break + + # Phase 2: try to decouple and serve truck customers + best_park = None + best_L = [] + best_cost = float("inf") + + if unserved_L: + for p in P_orig: + # Time to go to dp(p), decouple, serve truck custs, return, couple + dp = dp_node[p] + cp_n = cp_node[p] + t_to_p = t + svc[seq_phase1[-1]] + ttime_orig[seq_phase1[-1]][p] + t_after_dc = t_to_p + decoupling_t + truck_load = 0 + truck_seq = [] + t_truck = t_after_dc + cur = p + + remaining_L = sorted(unserved_L, key=lambda n: dist_orig[cur][n]) + for n in remaining_L: + nl = truck_load + supply[n] + extra = svc[cur] + ttime_orig[cur][n] + back = svc[n] + ttime_orig[n][p] + coupling_t + ttime_orig[p][depot_id] + if nl <= Q_L and t_truck + extra + back <= horizon_end: + truck_seq.append(n) + truck_load += supply[n] + t_truck += svc[cur] + ttime_orig[cur][n] + cur = n + + if truck_seq: + # cost = dist to p + decouple + truck route + return + couple + to depot + cost = (dist_orig[seq_phase1[-1]][p] * (cf + tw) + + sum(dist_orig[truck_seq[i]][truck_seq[i+1]] * cf + for i in range(len(truck_seq)-1)) if len(truck_seq) > 1 else 0) + cost += dist_orig[p][truck_seq[0]] * cf if truck_seq else 0 + cost += dist_orig[truck_seq[-1]][p] * cf if truck_seq else 0 + cost += dist_orig[p][depot_id] * (cf + tw) + + if cost < best_cost: + best_cost = cost + best_park = p + best_L = truck_seq[:] + + # Build full expanded sequence + if best_park is not None and best_L: + dp = dp_node[best_park] + cp_n = cp_node[best_park] + full_seq = seq_phase1 + [dp] + best_L + [cp_n, depot_id] + served_all = served_H + best_L + else: + full_seq = seq_phase1 + [depot_id] + served_all = served_H + + routes.append({ + "class_id": k, + "vehicle_index": used_count[k], + "sequence": full_seq, + "customers": served_all, + }) + used_count[k] += 1 + for n in served_H: + unserved_H.discard(n) + for n in best_L: + unserved_L.discard(n) + + # Strategy 2: Solo trucks for remaining customers + all_unserved = sorted(unserved_L | unserved_H) + for vc in sorted(fleet["vehicle_classes"], + key=lambda v: v["truck_capacity"], reverse=True): + k = vc["class_id"] + if vc["trailer_type_id"] != 0: + continue + Q_L = vc["truck_capacity"] + + while used_count[k] < vc["num_available"] and all_unserved: + seq = [depot_id] + load = 0 + t = 0.0 + served = [] + + remaining = list(all_unserved) + while remaining: + best_n = None + best_d = float("inf") + for n in remaining: + nl = load + supply[n] + extra = svc[seq[-1]] + ttime_orig[seq[-1]][n] + back = svc[n] + ttime_orig[n][depot_id] + if nl <= Q_L and t + extra + back <= horizon_end: + d = dist_orig[seq[-1]][n] + if d < best_d: + best_d = d + best_n = n + if best_n is None: + break + seq.append(best_n) + load += supply[best_n] + t += svc[seq[-2]] + ttime_orig[seq[-2]][best_n] + served.append(best_n) + remaining.remove(best_n) + + if not served: + break + + seq.append(depot_id) + routes.append({ + "class_id": k, + "vehicle_index": used_count[k], + "sequence": seq, + "customers": served, + }) + used_count[k] += 1 + for n in served: + all_unserved.remove(n) + + if all_unserved: + print(f"WARNING: Heuristic failed to serve: {all_unserved}") + + return routes + + +def main(): + parser = argparse.ArgumentParser( + description=( + "Solve the TTRPTW using a compact arc-flow MIP in 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="Output solution JSON path.") + parser.add_argument("--time_limit", type=int, default=3600, + help="Gurobi time limit in seconds (default: 3600).") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + if not os.path.isfile(args.instance_path): + print(f"ERROR: Instance file not found: {args.instance_path}") + sys.exit(1) + + solve_ttrptw(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/rothenbacher2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rothenbacher2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2018/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/rothenbacher2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rothenbacher2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2018/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/rothenbacher2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rothenbacher2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2018/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/rothenbacher2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rothenbacher2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2018/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/rothenbacher2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rothenbacher2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2018/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/rothenbacher2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rothenbacher2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2018/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/rothenbacher2018/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/rothenbacher2018/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/rothenbacher2018/gurobi_solution/large_solution_1.json b/tasks/rothenbacher2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..ddfd03085484ead8e0b26884fb327e0e66f949d2 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a450ca8741e8d992dd609c80b0dceea673f114ca561a85103cca2e2bc4d582b +size 9623 diff --git a/tasks/rothenbacher2018/gurobi_solution/large_solution_2.json b/tasks/rothenbacher2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..eda78109d4fef245961bd5fa24fa5cdcb28c15e2 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:232644c1e2143db84232d79098652f92656a6a2640081a34b90facf803db9d29 +size 11104 diff --git a/tasks/rothenbacher2018/gurobi_solution/large_solution_3.json b/tasks/rothenbacher2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..94e2ffb0467d06a495eae4ee81e87b068cbcdb85 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:996dd42478f9eb277e2c849576c57cade636daaa758c342de4d0ca02c419dee9 +size 10423 diff --git a/tasks/rothenbacher2018/gurobi_solution/large_solution_4.json b/tasks/rothenbacher2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4a36dadd282fc538b0c284c120e1878768e4f93e --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0eaf38b790b1f980858ae65b0b22c502d8e375b9e35a6500bb5d2406b2a71124 +size 13099 diff --git a/tasks/rothenbacher2018/gurobi_solution/large_solution_5.json b/tasks/rothenbacher2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d4b74e7bcc40cad08da798c445465c07c4c52c66 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74d62dce582c811a850bb18d043d4b3ecd566e59fb41ab40f2a16f6d00c7fa54 +size 10575 diff --git a/tasks/rothenbacher2018/gurobi_solution/tiny_solution.json b/tasks/rothenbacher2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..be9bfded235cdad017cdcc504a8027134e739105 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c553c652c2ffc853d195150231fcb244ae72779276d3348253ed044518678da +size 1559 diff --git a/tasks/rothenbacher2018/gurobi_solution/tiny_solution_2.json b/tasks/rothenbacher2018/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1a03f19bf81b25d6714b611e5bf4602a8349cc81 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5568a2854554ce47613b2812012002ecb1d988aa2b054987b41a15a432570ae3 +size 2488 diff --git a/tasks/rothenbacher2018/gurobi_solution_log/large_log_1.jsonl b/tasks/rothenbacher2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5b7388b871a1a0f83f3b324152e626a6054ab404 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:257611ba3d7c979df4b9d20577bef76f6eb7bb203bf2ad9ce035203caa457107 +size 2043 diff --git a/tasks/rothenbacher2018/gurobi_solution_log/large_log_2.jsonl b/tasks/rothenbacher2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b98464cccea34fa8a3d4f25c27b65eab4d5339b7 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:687d7ab61cd0106b41c55994b9da6f87c1064198b7d4071717ada8092dc320bb +size 2081 diff --git a/tasks/rothenbacher2018/gurobi_solution_log/large_log_3.jsonl b/tasks/rothenbacher2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e2e7121a4ae005ff19625325ffe98052af5e5da9 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c67f2f441bc0e101b6aa68cd13d9afc8afbb627f438c6fe37d7f96744545ed6 +size 1143 diff --git a/tasks/rothenbacher2018/gurobi_solution_log/large_log_4.jsonl b/tasks/rothenbacher2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e59374c1ddf503d674d8225df39320dfc9d09781 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9508f9ef65d777926c22777f003554ccf4ccf81b21a8949bdec2e313c8e6a013 +size 722 diff --git a/tasks/rothenbacher2018/gurobi_solution_log/large_log_5.jsonl b/tasks/rothenbacher2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..69d86acf8369f822a9874dd84c84469d6199cdb9 --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f11d6c5cb72b04c3294de439b2e6c04e8a6b1c8d54b60b47329ab808dc51a3ad +size 1981 diff --git a/tasks/rothenbacher2018/gurobi_solution_log/tiny_log.jsonl b/tasks/rothenbacher2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b34851d608f31d71b09287b8813d9d2c5e56a31d --- /dev/null +++ b/tasks/rothenbacher2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ce5f03b6b04a1a62fd24d9cf921b3f58dee1c5eb9b2a114ab033a424b551844 +size 131 diff --git a/tasks/rothenbacher2018/instance/large_instance_1.json b/tasks/rothenbacher2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..cba9828a39f4ccaa7f83cab4779b5fdf66e28d64 --- /dev/null +++ b/tasks/rothenbacher2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64c3c223a764d07388beb2d83a1054f6dcb8d3275f6b08782bddf53525f7b21f +size 173032 diff --git a/tasks/rothenbacher2018/instance/large_instance_2.json b/tasks/rothenbacher2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e7d70e1c947c4e88fa0c19fafa5c6bce4edb8bf3 --- /dev/null +++ b/tasks/rothenbacher2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d45fba13d410b5ddda49721ab7c088ed7f01430f1773ccaa5ff776140949f3b +size 163950 diff --git a/tasks/rothenbacher2018/instance/large_instance_3.json b/tasks/rothenbacher2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..4e11dd1c69d489f0465855bc0bd5b66eb325d3a6 --- /dev/null +++ b/tasks/rothenbacher2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f1ae480ad6726435e20a35ff4a94708e0c6d37756c978736d3eb46e95d09473 +size 163125 diff --git a/tasks/rothenbacher2018/instance/large_instance_4.json b/tasks/rothenbacher2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..349c4e11cd06becc17cbc0e0fc0dd7123ddac21d --- /dev/null +++ b/tasks/rothenbacher2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a63589d9720decae99ae029ec0cc0bbb365fd144a79027c506a4b4f9a8c73a89 +size 163767 diff --git a/tasks/rothenbacher2018/instance/large_instance_5.json b/tasks/rothenbacher2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..561b7fa5bfd47a26840b7def78f4cee9f2e912e1 --- /dev/null +++ b/tasks/rothenbacher2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f5516c4cd3b697b678fd89991cbaaa484b7f48fd13681038d9e08dce01daf29 +size 163306 diff --git a/tasks/rothenbacher2018/instance/tiny_instance.json b/tasks/rothenbacher2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..2173502a3c6cd489b94568fe8fce8f95ffcfe893 --- /dev/null +++ b/tasks/rothenbacher2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af7b0ab2c6f823b0a15d3f06c789655ae9df25e31683ae5255d31a69be42a6b8 +size 6806 diff --git a/tasks/rothenbacher2018/instance/tiny_instance_2.json b/tasks/rothenbacher2018/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d4a9163cef263cd79812456b98933a8015faab64 --- /dev/null +++ b/tasks/rothenbacher2018/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c9d53eaf009184a3950f658d68a30e01978dda6e2ca2112fdd8f5e652eaff31 +size 15625 diff --git a/tasks/rothenbacher2018/instance_schema.json b/tasks/rothenbacher2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..673ad21ed1797dc83b8ec92eb00664fb4008e08a --- /dev/null +++ b/tasks/rothenbacher2018/instance_schema.json @@ -0,0 +1,79 @@ +{ + "parameters": { + "max_route_duration": " Maximum allowed duration for any single route, including all travel, service, and handling times.", + "service_time": " Time spent at each customer location to perform the collection service.", + "coupling_time": " Time required to reattach a trailer to the truck at a parking location.", + "decoupling_time": " Time required to detach the trailer from the truck at a parking location.", + "transfer_time": " Time required to transfer load from the truck to the parked trailer at a parking location.", + "coupling_cost": " Cost incurred each time a trailer is reattached to the truck.", + "decoupling_cost": " Cost incurred each time a trailer is detached from the truck.", + "transfer_cost": " Cost incurred each time load is transferred from the truck to the trailer at a parking location.", + "planning_horizon": " Earliest and latest times defining the time window within which all routes must start and finish." + }, + "fleet": { + "truck_types": [ + { + "id": " Unique identifier for this truck type.", + "capacity": " Maximum load the truck can carry.", + "fixed_cost": " Cost incurred whenever a truck of this type is deployed on a route.", + "cost_factor": " Multiplier applied to travel distance to compute the truck's distance-based travel cost.", + "num_available": " Number of trucks of this type available in the fleet." + } + ], + "trailer_types": [ + { + "id": " Unique identifier for this trailer type.", + "capacity": " Maximum load the trailer can carry.", + "towing_cost_multiplier": " Additional multiplier applied to travel distance when this trailer is attached to a truck.", + "num_available": " Number of trailers of this type available in the fleet." + } + ], + "vehicle_classes": [ + { + "class_id": " Unique identifier for this vehicle class.", + "truck_type_id": " Identifier of the truck type used in this class.", + "trailer_type_id": " Identifier of the trailer type paired with the truck, or 0 if the truck operates solo.", + "truck_capacity": " Load capacity of the truck in this class.", + "trailer_capacity": " Load capacity of the trailer in this class, or 0 if no trailer.", + "total_capacity": " Combined load capacity of the truck and trailer in this class.", + "truck_fixed_cost": " Fixed cost for deploying the truck in this class.", + "truck_cost_factor": " Distance-based cost multiplier for the truck in this class.", + "trailer_towing_cost_multiplier": " Additional distance-based cost multiplier when the trailer is attached, or 0 if no trailer.", + "num_available": " Number of vehicles of this class available for deployment.", + "description": " Human-readable label describing the truck and trailer pairing." + } + ] + }, + "depot": { + "id": " Location identifier for the depot.", + "x": " Horizontal coordinate of the depot.", + "y": " Vertical coordinate of the depot." + }, + "truck_customers": [ + { + "id": " Unique identifier for this truck customer.", + "x": " Horizontal coordinate of this customer.", + "y": " Vertical coordinate of this customer.", + "supply": " Quantity of goods to be collected from this customer.", + "service_time": " Time spent at this customer to perform collection." + } + ], + "trailer_customers": [ + { + "id": " Unique identifier for this trailer customer.", + "x": " Horizontal coordinate of this customer.", + "y": " Vertical coordinate of this customer.", + "supply": " Quantity of goods to be collected from this customer.", + "service_time": " Time spent at this customer to perform collection." + } + ], + "transshipment_locations": [ + { + "id": " Unique identifier for this transshipment location.", + "x": " Horizontal coordinate of this transshipment location.", + "y": " Vertical coordinate of this transshipment location." + } + ], + "distance_matrix": " Travel distance between each pair of locations, indexed by location identifier.", + "travel_time_matrix": " Travel time between each pair of locations, indexed by location identifier." +} diff --git a/tasks/rothenbacher2018/mathematical_formulation.md b/tasks/rothenbacher2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..68e25e7be6cd6bfc888c5ee48e9ccef1edfeed4f --- /dev/null +++ b/tasks/rothenbacher2018/mathematical_formulation.md @@ -0,0 +1,56 @@ +# Original Formulation: Truck-and-Trailer Routing Problem with Time Windows (TTRPTW) + +*Source: Branch-and-Price-and-Cut for the Truck-and-Trailer Routing Problem with Time Windows, Rothenbächer, Drexl, and Irnich, 2018 (Transportation Science).* + +This is the path-based (set-partitioning) model presented in Section 3.1, the formulation whose notation is carried through every subsequent section of the paper. + +## Sets and Indices + +$$\begin{align*} +N &: \text{set of customers} \\ +N^L &\subset N: \text{set of truck customers (accessible only by a truck without its trailer)} \\ +N^H &\subset N: \text{set of trailer customers (accessible by a single truck or a complete vehicle)} \\ +L &: \text{set of truck types} \\ +H &: \text{set of trailer types} \\ +K &\subseteq L \times (H \cup \{0\}): \text{set of vehicle classes;}\\ + &\quad k=(l,0)\ \text{is a single truck of type }l,\quad k=(l,h),\,h\neq 0,\ \text{is a complete vehicle} \\ +f &\in L \cup H: \text{a vehicle type index} \\ +R^k &: \text{set of all valid routes for vehicle class } k \in K +\end{align*}$$ + +## Parameters + +$$\begin{align*} +c_r &: \text{cost of route } r \text{ (variable travel costs, depending on distance and on}\\ + &\quad \text{whether the truck tows the trailer, plus coupling/decoupling/load-transfer handling costs)} \\ +a_{rn} &: \text{number of times route } r \text{ serves customer } n \text{ (visits used only for parking,}\\ + &\quad \text{coupling, or load transfer are not counted)} \\ +b^k_f &\in\{0,1\}: \text{vehicle indicator, } 1 \text{ if vehicle class } k \in K \text{ uses vehicle type } f \in L\cup H \\ +n_f &: \text{number of available vehicles of type } f \in L \cup H +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +\lambda^k_r \in \mathbb{Z}_{\geq 0} + &: \text{number of times route } r \text{ of vehicle class } k \text{ is chosen,}\\ + &\quad \forall\, k \in K,\; r \in R^k. +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad & \sum_{k \in K} \sum_{r \in R^k} c_r \, \lambda^k_r \tag{1a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.}\quad +& \sum_{k \in K} \sum_{r \in R^k} a_{rn}\, \lambda^k_r = 1 + && (\pi_n) && \forall\, n \in N, \tag{1b}\\[2pt] +& \sum_{k \in K} \sum_{r \in R^k} b^k_f\, \lambda^k_r \leq n_f + && (\mu_f) && \forall\, f \in L \cup H, \tag{1c}\\[2pt] +& \lambda^k_r \geq 0,\ \text{integer} + && && \forall\, k \in K,\; r \in R^k. \tag{1d} +\end{align}$$ diff --git a/tasks/rothenbacher2018/problem_description.txt b/tasks/rothenbacher2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..9094d64b59d11d5fd3d90d0c69aa6dea2b01edda --- /dev/null +++ b/tasks/rothenbacher2018/problem_description.txt @@ -0,0 +1,17 @@ +# Problem Description + +A fleet of vehicles based at a central depot must collect supply from a set of geographically dispersed customers and return to the depot. The fleet is heterogeneous, consisting of multiple truck types and multiple trailer types. Each truck type has a load capacity, a fixed cost, a distance-based cost factor, and a limited number of available units. Each trailer type has its own load capacity, a towing cost multiplier that adds to the truck's travel cost whenever the trailer is attached, and a limited number of available units. A vehicle class is defined by pairing a specific truck type either with nothing (a solo truck) or with a specific trailer type (a complete vehicle). The total number of vehicles of any given truck type or trailer type used across all selected routes must not exceed the number available of that type. + +Customers are partitioned into two groups: truck customers and trailer customers. Truck customers have restricted access (small yards or narrow roads) and can only be visited by a truck traveling without its trailer attached. Trailer customers can be visited by either a solo truck or a complete vehicle with the trailer attached. Every customer has a known positive supply quantity that must be collected, a service time, and a location given by coordinates in a two-dimensional plane. Distances and travel times between all pairs of locations (depot, customers, and transshipment locations) are provided. + +In addition to the depot and customers, there is a set of dedicated transshipment locations. At any trailer customer location or transshipment location, the driver of a complete vehicle may decouple the trailer and park it. The truck then performs a subtour without the trailer, visiting truck customers and possibly trailer customers, before returning to the parking location to recouple the trailer. At trailer customer locations and transshipment locations where the trailer is parked, load may be transferred from the truck to the trailer. Any number of subtours may be performed from a single parking location, and multiple trailers may be parked at the same location simultaneously. + +Each route begins and ends at the depot. For a complete vehicle, the truck must return to the location where its trailer is parked and recouple before returning to the depot. Each customer must be served exactly once across all routes in the solution, and each customer is visited at most once within any single route. + +When the trailer is attached, collected supply is loaded into the trailer up to its remaining capacity, and any excess is loaded into the truck. When the truck is operating without its trailer, all collected supply is loaded into the truck. During coupling and transfer operations at parking locations, as much load as possible is moved from the truck to the trailer, keeping the truck as free as possible. No load transfer occurs at decoupling operations. At no point along a route may the truck carry more than its capacity or the trailer carry more than its capacity. + +Each customer has a time window specifying the earliest and latest times at which service may begin. The planning horizon defines the time window of the depot, meaning every route must be completed within this horizon. Service at each customer must start within that customer's time window. Service, coupling, decoupling, and transfer operations each consume a fixed amount of time. Travel between locations consumes time equal to the travel time for that pair of locations, which is independent of the vehicle class. The total duration of each route, including all travel, service, and handling times, must fit within the planning horizon. + +The cost of traversing an arc between two locations depends on the truck type's cost factor multiplied by the distance, plus, if the trailer is attached during that traversal, the trailer type's towing cost multiplier multiplied by the distance. In addition, coupling operations incur a fixed coupling cost, decoupling operations incur a fixed decoupling cost, and transfer operations may incur a fixed transfer cost. Each truck type also has a fixed cost incurred whenever that truck is used. + +The goal is to select a set of routes, one per deployed vehicle, that collectively serve every customer exactly once, respect all capacity, time window, accessibility, and fleet availability restrictions, and minimize the total cost, which is the sum of all fixed vehicle costs, all distance-dependent travel costs (with the trailer towing surcharge where applicable), and all handling costs for coupling, decoupling, and transfer operations. diff --git a/tasks/rothenbacher2018/solution_logger.py b/tasks/rothenbacher2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rothenbacher2018/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/rothenbacher2018/solution_schema.json b/tasks/rothenbacher2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a21698222409ea155f67d5bc514faabf87a6ed22 --- /dev/null +++ b/tasks/rothenbacher2018/solution_schema.json @@ -0,0 +1,15 @@ +{ + "objective_value": " Total cost of the solution, including all fixed vehicle costs, distance-based travel costs with the trailer towing surcharge where applicable, and handling costs for coupling and decoupling operations.", + "routes": [ + { + "vehicle_class": " Identifier of the vehicle class deployed on this route, specifying the truck type and whether a trailer is attached.", + "vehicle_index": " Index distinguishing this deployed vehicle from other vehicles of the same class.", + "customers_served": " Identifiers of all customers visited and served on this route.", + "route_sequence": " Ordered sequence of stop identifiers traversed on this route, in which each separate decoupling or coupling operation at a parking location is represented by its own distinct identifier so that repeated visits to the same parking location are distinguishable.", + "route_sequence_physical": " Ordered sequence of physical location identifiers visited on this route, where the depot, customers, and parking locations are each referred to by their original location identifier.", + "decouple_locations": " Physical location identifiers at which the trailer is detached from the truck on this route.", + "couple_locations": " Physical location identifiers at which the trailer is reattached to the truck on this route.", + "arrival_times": " Time at which the vehicle arrives at each stop along the route, where the key is the stop identifier from route_sequence and the value is the arrival time measured from the start of the planning horizon." + } + ] +} diff --git a/tasks/rothenbacher2019/feasibility_check.py b/tasks/rothenbacher2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7164378cfb5354197dd608acc531a7a94252afa3 --- /dev/null +++ b/tasks/rothenbacher2019/feasibility_check.py @@ -0,0 +1,664 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Periodic Vehicle Routing Problem with Time Windows +(PVRPTW) with Flexible Schedule Structures. + +Based on: Rothenbaecher (2019), Transportation Science. +Mathematical formulation: Route-based Extended Set-Partitioning (Eq. 1a-1f). + +Constraints are numbered top-to-bottom from the formulation section in +math_model.txt: + Constraint 1 (1b): Schedule selection — exactly one schedule per customer + Constraint 2 (1c): Linking — route schedule parts match selected schedules + Constraint 3 (1d): Fleet — at most m routes per day + Constraint 4 (1e): Binary integrality of schedule variables z_n^s + Constraint 5 (1f): Binary integrality of route variables lambda_r^p + +Route feasibility conditions (implicit in set R^p): + Constraint 6: Vehicle capacity + Constraint 7: Max route duration + Constraint 8: Customer time windows + Constraint 9: Depot time window + Constraint 10: Schedule compatibility (visit day/delivery fits offered schedule) + Constraint 11: Elementary routes (each customer at most once per route) + Constraint 12: Objective consistency (reported objective_value must equal + the sum over all routes of the Euclidean depot-to-customer-...- + to-depot tour length; recomputed independently from the + reported per-route 'cost' field to defend against fabricated + objective values). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'routes', 'schedules') +_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 euclidean_distance(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violations = [] + violation_magnitudes = [] + violated_set = set() + + # ------------------------------------------------------------------------- + # An empty solution (solver returned infeasible / no incumbent) does NOT + # satisfy constraint 1 (each customer must receive a schedule). Earlier + # versions returned feasible=True for an empty solution under a + # "vacuously true" reading; that is wrong — feasibility_check should + # strictly verify the constraints against the original solution + # structure (per the workflow guideline). + # ------------------------------------------------------------------------- + if solution.get("status") in ("infeasible", "no_solution"): + return { + "feasible": False, + "violated_constraints": [1], + "violations": [ + "Solver reported infeasible/no_solution — no candidate solution " + "to verify; constraint 1 (every customer must have a schedule) " + "cannot be satisfied." + ], + "violation_magnitudes": [{ + "constraint": 1, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }], + } + if solution.get("objective_value") is None and not solution.get("routes"): + return { + "feasible": False, + "violated_constraints": [1], + "violations": [ + "Empty solution (no objective_value and no routes) — constraint " + "1 (every customer must have a schedule) cannot be satisfied." + ], + "violation_magnitudes": [{ + "constraint": 1, "lhs": 0.0, "rhs": 1.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }], + } + + # ------------------------------------------------------------------------- + # Preprocessing: build data structures + # ------------------------------------------------------------------------- + depot = instance["depot"] + customers = instance["customers"] + num_days = instance["num_days"] + num_vehicles = instance["num_vehicles"] + capacity = instance["vehicle_capacity"] + max_duration = instance["max_route_duration"] + + cust_by_id = {c["id"]: c for c in customers} + + # Build location list and distance / travel-time functions + all_locs = [depot] + customers + loc_by_id = {loc["id"]: loc for loc in all_locs} + + def dist(id1, id2): + l1, l2 = loc_by_id[id1], loc_by_id[id2] + return euclidean_distance(l1["x"], l1["y"], l2["x"], l2["y"]) + + def travel_time(id1, id2): + """t_{o1,o2} = distance + service_time at o1.""" + return dist(id1, id2) + loc_by_id[id1]["service_time"] + + depot_id = depot["id"] + depot_tw = depot["time_window"] + + sol_routes = solution.get("routes", {}) + sol_schedules = solution.get("schedules", {}) + + def record(constraint_idx, msg, lhs_val, rhs_val, violation_amount): + violated_set.add(constraint_idx) + violations.append(msg) + normalizer = max(abs(rhs_val), eps) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs_val), + "rhs": float(rhs_val), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ===================================================================== + # Constraint 1 (1b): Schedule selection — exactly one schedule per customer + # Σ_{s ∈ S_n} z_n^s = 1 ∀ n ∈ N + # ===================================================================== + for cust in customers: + cid = cust["id"] + cid_str = str(cid) + if cid_str in sol_schedules: + count = 1 # one schedule entry per customer in solution + else: + count = 0 + rhs = 1.0 + violation_amount = abs(count - rhs) + if violation_amount > tol: + record(1, + f"Customer {cid}: {count} schedule(s) selected, expected exactly 1", + count, rhs, violation_amount) + + # If schedules present, validate schedule_index is within range + for cid_str, sched_info in sol_schedules.items(): + cid = int(cid_str) + if cid not in cust_by_id: + record(1, + f"Schedule assigned to unknown customer {cid}", + 1, 0, 1.0) + continue + cust = cust_by_id[cid] + s_idx = sched_info.get("schedule_index", -1) + if s_idx < 0 or s_idx >= len(cust["schedules"]): + record(1, + f"Customer {cid}: schedule_index {s_idx} out of range [0, {len(cust['schedules'])-1}]", + s_idx, len(cust["schedules"]) - 1, 1.0) + + # ===================================================================== + # Constraint 4 (1e): Binary integrality of z_n^s + # z_n^s ∈ {0, 1} + # ===================================================================== + # In the JSON solution, schedules are represented by a single chosen index + # per customer, so they are inherently binary. No check needed beyond + # Constraint 1. + + # ===================================================================== + # Constraint 5 (1f): Binary integrality of λ_r^p + # λ_r^p ∈ {0, 1} + # In the JSON solution, each route is either listed or not, so inherently + # binary. No additional check needed. + # ===================================================================== + + # ===================================================================== + # Constraint 3 (1d): Fleet — at most m routes per day + # Σ_{r ∈ R^p} λ_r^p ≤ m ∀ p ∈ P + # ===================================================================== + for day in range(num_days): + day_str = str(day) + day_routes = sol_routes.get(day_str, []) + num_routes = len(day_routes) + rhs = float(num_vehicles) + violation_amount = max(0.0, num_routes - rhs) + if violation_amount > tol: + record(3, + f"Day {day}: {num_routes} routes used, maximum allowed is {num_vehicles}", + num_routes, rhs, violation_amount) + + # ===================================================================== + # Route-level feasibility checks (Constraints 6-11) + # These define which routes belong to R^p. + # ===================================================================== + for day_str, day_routes in sol_routes.items(): + day = int(day_str) + for ri, route in enumerate(day_routes): + route_custs = route.get("customers", []) + + # ----------------------------------------------------------------- + # Constraint 11: Elementary routes — each customer at most once + # ----------------------------------------------------------------- + cid_counts = {} + for cid in route_custs: + cid_counts[cid] = cid_counts.get(cid, 0) + 1 + for cid, cnt in cid_counts.items(): + if cnt > 1: + violation_amount = float(cnt - 1) + record(11, + f"Day {day}, route {ri}: customer {cid} visited {cnt} times (must be at most 1)", + cnt, 1.0, violation_amount) + + # ----------------------------------------------------------------- + # Constraint 6: Vehicle capacity + # Total delivered demand ≤ Q + # ----------------------------------------------------------------- + # Demand comes from the route's parts or the schedule assignment + total_demand = 0 + route_parts = route.get("parts", {}) + if route_parts: + for cid_key, part_info in route_parts.items(): + total_demand += part_info.get("demand_per_visit", 0) + else: + # Fall back: compute from schedule assignments + for cid in route_custs: + cid_s = str(cid) + if cid_s in sol_schedules: + sched_info = sol_schedules[cid_s] + cust = cust_by_id.get(cid) + if cust: + s_idx = sched_info.get("schedule_index", 0) + if 0 <= s_idx < len(cust["schedules"]): + sched = cust["schedules"][s_idx] + for part in sched["parts"]: + if part["visit_day"] == day: + total_demand += part["demand_per_visit"] + + rhs = float(capacity) + violation_amount = max(0.0, total_demand - rhs) + if violation_amount > tol: + record(6, + f"Day {day}, route {ri}: total demand {total_demand} exceeds capacity {capacity}", + total_demand, rhs, violation_amount) + + # ----------------------------------------------------------------- + # Constraints 7, 8, 9: Duration, customer TW, depot TW + # Using Tilk & Irnich (2017) duration resources: + # E_time = max(a_j, E_time_prev + t_ij) + # E_dur = max(E_dur_prev + t_ij, E_help_prev + a_j) + # E_help = max(E_dur_prev + t_ij - b_j, E_help_prev) + # ----------------------------------------------------------------- + E_time = depot_tw[0] + E_dur = 0.0 + E_help = -depot_tw[1] + prev_id = depot_id + + for cid in route_custs: + if cid not in cust_by_id: + record(8, + f"Day {day}, route {ri}: customer {cid} not found in instance", + 0, 0, 1.0) + continue + cust = cust_by_id[cid] + tw = cust["time_window"] + t_ij = travel_time(prev_id, cid) + + E_time_new = max(tw[0], E_time + t_ij) + E_dur_new = max(E_dur + t_ij, E_help + tw[0]) + E_help_new = max(E_dur + t_ij - tw[1], E_help) + + # Constraint 8: Customer time window + if E_time_new > tw[1] + tol: + violation_amount = E_time_new - tw[1] + record(8, + f"Day {day}, route {ri}: arrival at customer {cid} at {E_time_new:.4f} exceeds time window [{tw[0]}, {tw[1]}]", + E_time_new, tw[1], violation_amount) + + # Constraint 7: Duration check at intermediate step + if E_dur_new > max_duration + tol: + violation_amount = E_dur_new - max_duration + record(7, + f"Day {day}, route {ri}: route duration {E_dur_new:.4f} exceeds max {max_duration} at customer {cid}", + E_dur_new, float(max_duration), violation_amount) + + E_time = E_time_new + E_dur = E_dur_new + E_help = E_help_new + prev_id = cid + + # Return to depot + if route_custs: + t_back = travel_time(prev_id, depot_id) + E_time_final = E_time + t_back + E_dur_final = max(E_dur + t_back, E_help + depot_tw[0]) + + # Constraint 9: Depot time window on return + if E_time_final > depot_tw[1] + tol: + violation_amount = E_time_final - depot_tw[1] + record(9, + f"Day {day}, route {ri}: return to depot at {E_time_final:.4f} exceeds depot window [{depot_tw[0]}, {depot_tw[1]}]", + E_time_final, float(depot_tw[1]), violation_amount) + + # Constraint 7: Final duration + if E_dur_final > max_duration + tol: + violation_amount = E_dur_final - max_duration + record(7, + f"Day {day}, route {ri}: final route duration {E_dur_final:.4f} exceeds max {max_duration}", + E_dur_final, float(max_duration), violation_amount) + + # ----------------------------------------------------------------- + # Constraint 10: Schedule compatibility + # Visit day and delivery amount must fit at least one offered schedule + # ----------------------------------------------------------------- + for cid in route_custs: + if cid not in cust_by_id: + continue + cust = cust_by_id[cid] + + # Determine what this route delivers for this customer + cid_str_parts = str(cid) + route_part = route_parts.get(cid_str_parts) or route_parts.get(cid) + if route_part: + visit_day = route_part.get("visit_day", day) + days_covered = route_part.get("days_covered") + demand_visit = route_part.get("demand_per_visit") + else: + visit_day = day + days_covered = None + demand_visit = None + + # Check if any schedule of this customer has a matching part + found_match = False + for sched in cust["schedules"]: + for part in sched["parts"]: + if part["visit_day"] != day: + continue + # If the route specifies days_covered and demand, check them + if days_covered is not None and part["days_covered"] != days_covered: + continue + if demand_visit is not None and abs(part["demand_per_visit"] - demand_visit) > tol: + continue + found_match = True + break + if found_match: + break + + if not found_match: + record(10, + f"Day {day}, route {ri}: visit to customer {cid} " + f"(days_covered={days_covered}, demand={demand_visit}) " + f"does not match any offered schedule part for this day", + 1, 0, 1.0) + + # ===================================================================== + # Constraint 2 (1c): Linking constraints + # For each customer n, day p, length l where S_n^{p:l} ≠ ∅: + # Σ_{r ∈ R^p} a_{rn}^{p:l} λ_r^p = Σ_{s ∈ S_n} b_s^{p:l} z_n^s + # + # LHS: number of times routes on day p visit customer n with part length l + # RHS: 1 if the selected schedule induces part (p, l), else 0 + # ===================================================================== + for cust in customers: + cid = cust["id"] + cid_str = str(cid) + + # Get the selected schedule + sched_info = sol_schedules.get(cid_str) + if sched_info is None: + # Already flagged in Constraint 1 + continue + s_idx = sched_info.get("schedule_index", 0) + if s_idx < 0 or s_idx >= len(cust["schedules"]): + continue + selected_sched = cust["schedules"][s_idx] + + # For each day p and length l where S_n^{p:l} ≠ ∅ + for day in range(num_days): + # Gather all (day, l) pairs from any schedule + lengths_set = set() + for sched in cust["schedules"]: + for part in sched["parts"]: + if part["visit_day"] == day: + lengths_set.add(part["days_covered"]) + + for l in lengths_set: + # RHS: b_s^{p:l} for selected schedule + rhs_val = 0 + for part in selected_sched["parts"]: + if part["visit_day"] == day and part["days_covered"] == l: + rhs_val = 1 + break + + # LHS: count how many routes on day p include schedule part n^{p:l}. + # A visit only counts toward a_{rn}^{p:l} when the route's parts + # info explicitly records days_covered == l for this customer; + # routes that list the customer without an explicit matching + # part cannot be assumed to cover part (p:l). + lhs_val = 0 + day_str = str(day) + for route in sol_routes.get(day_str, []): + route_parts = route.get("parts", {}) + rp = route_parts.get(str(cid)) or route_parts.get(cid) + if rp is not None and rp.get("days_covered") == l: + lhs_val += 1 + + violation_amount = abs(lhs_val - rhs_val) + if violation_amount > tol: + record(2, + f"Customer {cid}, day {day}, length {l}: " + f"routes cover {lhs_val} time(s) but selected schedule requires {rhs_val}", + lhs_val, rhs_val, violation_amount) + + # ===================================================================== + # Constraint 12: Objective consistency (Tier C defense) + # The reported objective_value must equal Σ_{p,r} c_r λ_r^p, where c_r is + # the Euclidean route cost (depot → c_1 → ... → c_k → depot). Per the + # math model (eq. 1a) and instance fields (distance_matrix_type= + # 'euclidean', cost_type='euclidean_distance'), this is exactly the sum + # of pairwise Euclidean distances along each route. We deliberately + # recompute from the raw (depot, customer) coordinates rather than + # trusting route['cost'], because a score-gaming candidate could + # fabricate per-route cost values consistent with a fake total. + # ===================================================================== + 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 day_str, day_routes in sol_routes.items(): + for route in day_routes: + route_custs = route.get("customers", []) + if not route_custs: + continue + prev = depot_id + seg = 0.0 + for cid in route_custs: + if cid not in loc_by_id: + # Unknown customer is already flagged elsewhere; do + # not let it short-circuit obj recomputation. + continue + seg += dist(prev, cid) + prev = cid + seg += dist(prev, depot_id) + true_obj += seg + + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor; the Gurobi + # reference matches the recompute to ~1e-12, so this is loose + # enough for floating-point but tight enough to catch any + # exploit larger than a fractional currency unit. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + record(12, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed Σ c_r λ_r^p =" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})", + reported, true_obj, abs_diff) + + # ===================================================================== + # Build result + # ===================================================================== + violated_list = sorted(violated_set) + feasible = len(violated_list) == 0 + + return { + "feasible": feasible, + "violated_constraints": violated_list, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for PVRPTW (Rothenbaecher 2019)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + status = "FEASIBLE" if result["feasible"] else "INFEASIBLE" + n_violations = len(result["violated_constraints"]) + print(f"Result: {status} ({n_violations} violated constraint type(s))") + if not result["feasible"]: + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/rothenbacher2019/gurobi_code.py b/tasks/rothenbacher2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..376c2a6632472cd60c26a756aafe74c867adf416 --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_code.py @@ -0,0 +1,427 @@ +#!/usr/bin/env python3 +""" +Gurobi MIP implementation of the PVRPTW (Periodic Vehicle Routing Problem +with Time Windows) with Flexible Schedule Structures. + +Based on: Rothenbächer (2019), "Branch-and-Price-and-Cut for the Periodic +Vehicle Routing Problem with Flexible Schedule Structures", +Transportation Science. + +Model: Route-based Extended Set-Partitioning Formulation (Equations 1a-1f). + +Since the model uses route-based variables (exponentially many), this +implementation enumerates all feasible elementary routes for the given +instance and then solves the MIP directly with Gurobi. + +For small instances this is exact; for larger instances the enumeration +may be intractable within the time limit. +""" + +import argparse +import json +import math +import time +import itertools +from typing import List, Dict, Tuple, Any, Optional + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass +def load_instance(path: str) -> dict: + """Load a PVRPTW instance from JSON.""" + with open(path, "r") as f: + return json.load(f) + + +def euclidean_distance(x1, y1, x2, y2) -> float: + """Compute Euclidean distance between two points. + + INFERRED ASSUMPTION: Euclidean distance as cost/distance metric, + consistent with Cordeau et al. (2001) benchmark instances. + NOT EXPLICITLY SPECIFIED IN PAPER (Comment 8 in math_model.txt). + """ + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def build_distance_and_time_matrices(instance: dict): + """ + Build distance/cost matrix and travel time matrix. + + Travel time t_{o1,o2} = Euclidean distance + service time at o1, + as stated in the paper (Section 3): "t_{o1,o2} includes service time at o1". + """ + depot = instance["depot"] + customers = instance["customers"] + all_locations = [depot] + customers + n = len(all_locations) + + dist = {} + travel_time = {} + + for i in range(n): + loc_i = all_locations[i] + for j in range(n): + loc_j = all_locations[j] + d = euclidean_distance(loc_i["x"], loc_i["y"], + loc_j["x"], loc_j["y"]) + dist[(loc_i["id"], loc_j["id"])] = d + # Travel time includes service time at origin (paper Section 3) + travel_time[(loc_i["id"], loc_j["id"])] = d + loc_i["service_time"] + + return dist, travel_time + + +def enumerate_feasible_routes(instance: dict, dist: dict, travel_time: dict, + day: int, time_budget: float = float('inf') + ) -> List[dict]: + """ + Enumerate all feasible elementary routes for a given day. + + Route feasibility (paper Section 3, Route Feasibility Conditions): + 1. Total delivered demand <= Q (vehicle capacity) + 2. Minimum route duration <= D (maximal route duration) - uses Tilk & Irnich (2017) resources + 3. Each customer visited within its time window [a_n, b_n] + 4. Route starts/ends at depot within [a_d, b_d] + 5. Visit day and delivery amount fit at least one offered schedule + 6. Each customer visited at most once per route (elementary) + """ + start_enum = time.time() + depot = instance["depot"] + customers = instance["customers"] + Q = instance["vehicle_capacity"] + D = instance["max_route_duration"] + num_days = instance["num_days"] + depot_id = depot["id"] + depot_tw = depot["time_window"] + + # Determine which customers can be visited on this day + visitable = [] + for cust in customers: + parts_for_day = [] + for sched in cust["schedules"]: + for part in sched["parts"]: + if part["visit_day"] == day: + parts_for_day.append(part) + # Remove duplicate parts + unique_parts = [] + seen = set() + for p in parts_for_day: + key = (p["visit_day"], p["days_covered"]) + if key not in seen: + seen.add(key) + unique_parts.append(p) + if unique_parts: + visitable.append((cust, unique_parts)) + + routes = [] + + def try_route(sequence: List[Tuple[dict, dict]]): + """ + Check if a given sequence of (customer, schedule_part) is feasible. + + Uses the labeling resources from Tilk & Irnich (2017) as described + in the paper (Section 4.1) for proper minimum route duration computation: + E_j^time = max(a_{o(j)}, E_i^time + t_ij) + E_j^dur = max(E_i^dur + t_ij, E_i^help + a_{o(j)}) + E_j^help = max(E_i^dur + t_ij - b_{o(j)}, E_i^help) + where t_ij = dist(o(i),o(j)) + service_time(o(i)) + """ + total_demand = sum(part["demand_per_visit"] for _, part in sequence) + if total_demand > Q: + return None + + # Forward labeling with duration resources (Tilk & Irnich 2017) + E_time = depot_tw[0] # a_d + E_dur = 0.0 + E_help = -depot_tw[1] # -b_d + cost = 0.0 + prev_id = depot_id + + for cust, part in sequence: + t_ij = travel_time[(prev_id, cust["id"])] + E_time_new = max(cust["time_window"][0], E_time + t_ij) + E_dur_new = max(E_dur + t_ij, E_help + cust["time_window"][0]) + E_help_new = max(E_dur + t_ij - cust["time_window"][1], E_help) + + if E_time_new > cust["time_window"][1]: + return None + if E_dur_new > D: + return None + + cost += dist[(prev_id, cust["id"])] + E_time, E_dur, E_help = E_time_new, E_dur_new, E_help_new + prev_id = cust["id"] + + # Return to depot + t_back = travel_time[(prev_id, depot_id)] + E_time_final = E_time + t_back + E_dur_final = max(E_dur + t_back, E_help + depot_tw[0]) + cost += dist[(prev_id, depot_id)] + + if E_time_final > depot_tw[1]: + return None + if E_dur_final > D: + return None + + parts_info = {} + for cust, part in sequence: + parts_info[cust["id"]] = { + "visit_day": part["visit_day"], + "days_covered": part["days_covered"], + "demand_per_visit": part["demand_per_visit"] + } + + return { + "cost": cost, + "customers": [cust["id"] for cust, _ in sequence], + "demand": total_demand, + "duration": E_dur_final, + "parts": parts_info + } + + # Enumerate all subsets of visitable customers + for size in range(1, len(visitable) + 1): + if time.time() - start_enum > time_budget: + break + for subset in itertools.combinations(range(len(visitable)), size): + if time.time() - start_enum > time_budget: + break + part_options = [] + for idx in subset: + cust, parts = visitable[idx] + part_options.append([(cust, p) for p in parts]) + + for part_combo in itertools.product(*part_options): + total_demand = sum(p["demand_per_visit"] for _, p in part_combo) + if total_demand > Q: + continue + + # Enumerate all feasible orderings (each yields a distinct route in R^p) + for perm in itertools.permutations(part_combo): + route = try_route(list(perm)) + if route is not None: + route["day"] = day + routes.append(route) + + return routes + + +def solve_pvrptw(instance: dict, time_limit: int) -> dict: + """Solve the PVRPTW using the route-based MIP formulation (Model 1).""" + start_time = time.time() + + depot = instance["depot"] + customers = instance["customers"] + num_days = instance["num_days"] + num_vehicles = instance["num_vehicles"] + + dist, travel_time = build_distance_and_time_matrices(instance) + + # Enumerate all feasible routes for each day + print("Enumerating feasible routes...") + all_routes = {} + for day in range(num_days): + elapsed = time.time() - start_time + budget = max(1, (time_limit * 0.4) / num_days) + routes = enumerate_feasible_routes(instance, dist, travel_time, day, budget) + all_routes[day] = routes + print(f" Day {day}: {len(routes)} feasible routes") + + total_routes = sum(len(r) for r in all_routes.values()) + print(f"Total routes enumerated: {total_routes}") + + # Build the MIP model (Equations 1a-1f) + model = gp.Model("PVRPTW") + model.setParam("Threads", 1) + remaining_time = max(1, time_limit - (time.time() - start_time)) + model.setParam("TimeLimit", remaining_time) + model.setParam("OutputFlag", 1) + + # Decision variables + # λ_r^p ∈ {0,1}: route r performed on day p (Eq. 1f) + lam = {} + for day in range(num_days): + for r_idx, route in enumerate(all_routes[day]): + lam[(day, r_idx)] = model.addVar( + vtype=GRB.BINARY, obj=route["cost"], + name=f"lam_{day}_{r_idx}" + ) + + # z_n^s ∈ {0,1}: schedule s chosen for customer n (Eq. 1e) + z = {} + for cust in customers: + for s_idx in range(len(cust["schedules"])): + z[(cust["id"], s_idx)] = model.addVar( + vtype=GRB.BINARY, obj=0, + name=f"z_{cust['id']}_{s_idx}" + ) + + model.update() + model.setAttr("ModelSense", GRB.MINIMIZE) # (1a) + + # Constraint (1b): Exactly one schedule per customer + for cust in customers: + model.addConstr( + gp.quicksum(z[(cust["id"], s_idx)] + for s_idx in range(len(cust["schedules"]))) == 1, + name=f"schedule_select_{cust['id']}" + ) + + # Constraint (1c): Linking constraints + # For each customer n, day p, length l where S_n^{p:l} ≠ ∅: + # Σ_{r∈R^p} a_{rn}^{p:l} λ_r^p = Σ_{s∈S_n} b_s^{p:l} z_n^s + for cust in customers: + n_id = cust["id"] + for day in range(num_days): + lengths_set = set() + for sched in cust["schedules"]: + for part in sched["parts"]: + if part["visit_day"] == day: + lengths_set.add(part["days_covered"]) + + for l in lengths_set: + lhs_terms = [] + for r_idx, route in enumerate(all_routes[day]): + if n_id in route["parts"]: + rp = route["parts"][n_id] + if rp["visit_day"] == day and rp["days_covered"] == l: + lhs_terms.append(lam[(day, r_idx)]) + + rhs_terms = [] + for s_idx, sched in enumerate(cust["schedules"]): + for part in sched["parts"]: + if part["visit_day"] == day and part["days_covered"] == l: + rhs_terms.append(z[(n_id, s_idx)]) + break + + if lhs_terms or rhs_terms: + lhs = gp.quicksum(lhs_terms) if lhs_terms else 0 + rhs = gp.quicksum(rhs_terms) if rhs_terms else 0 + model.addConstr(lhs == rhs, + name=f"link_{n_id}_{day}_{l}") + + # Constraint (1d): Fleet constraint — at most m routes per day + for day in range(num_days): + model.addConstr( + gp.quicksum(lam[(day, r_idx)] + for r_idx in range(len(all_routes[day])) + ) <= num_vehicles, + name=f"fleet_{day}" + ) + + model.update() + print(f"\nModel has {model.NumVars} variables and {model.NumConstrs} constraints") + print("Solving...") + + model.optimize() + + # Extract solution + solution = { + "instance_id": instance.get("instance_id", 1), + "problem_type": "PVRPTW", + "solver": "Gurobi", + "model": "Route-based Extended Set-Partitioning (Eq. 1a-1f)", + "status": None, + "objective_value": None, + "solve_time": time.time() - start_time, + "routes": {}, + "schedules": {} + } + + if model.Status == GRB.OPTIMAL: + solution["status"] = "optimal" + solution["objective_value"] = model.ObjVal + elif model.Status == GRB.TIME_LIMIT and model.SolCount > 0: + solution["status"] = "time_limit_with_solution" + solution["objective_value"] = model.ObjVal + elif model.SolCount > 0: + solution["status"] = "feasible" + solution["objective_value"] = model.ObjVal + elif model.Status == GRB.INFEASIBLE: + solution["status"] = "infeasible" + solution["objective_value"] = None + print("\nModel is infeasible. The instance cannot be solved with the " + "given number of vehicles and constraints.") + return solution + else: + solution["status"] = "no_solution" + solution["objective_value"] = None + return solution + + # Extract chosen routes + for day in range(num_days): + day_routes = [] + for r_idx, route in enumerate(all_routes[day]): + if lam[(day, r_idx)].X > 0.5: + day_routes.append({ + "customers": route["customers"], + "cost": route["cost"], + "demand": route["demand"], + "parts": {str(k): v for k, v in route["parts"].items()} + }) + if day_routes: + solution["routes"][str(day)] = day_routes + + # Extract chosen schedules + for cust in customers: + for s_idx, sched in enumerate(cust["schedules"]): + if z[(cust["id"], s_idx)].X > 0.5: + solution["schedules"][str(cust["id"])] = { + "schedule_index": s_idx, + "days": sched["days"], + "visit_frequency": sched["visit_frequency"] + } + break + + return solution + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi MIP solver for PVRPTW with Flexible Schedule Structures" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, + default="gurobi_solution_1.json", + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print(f"Loading instance from: {args.instance_path}") + instance = load_instance(args.instance_path) + + print(f"Instance: {instance.get('num_customers', '?')} customers, " + f"{instance.get('num_days', '?')} days, " + f"{instance.get('num_vehicles', '?')} vehicles") + print(f"Time limit: {args.time_limit}s") + + solution = solve_pvrptw(instance, args.time_limit) + + print(f"\nStatus: {solution['status']}") + print(f"Objective value: {solution['objective_value']}") + print(f"Solve time: {solution['solve_time']:.2f}s") + + with open(args.solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + print(f"Solution saved to: {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/rothenbacher2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/rothenbacher2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2019/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/rothenbacher2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/rothenbacher2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2019/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/rothenbacher2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/rothenbacher2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2019/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/rothenbacher2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/rothenbacher2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2019/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/rothenbacher2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/rothenbacher2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2019/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/rothenbacher2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/rothenbacher2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/rothenbacher2019/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/rothenbacher2019/gurobi_solution/large_solution_1.json b/tasks/rothenbacher2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..d4f06f651f1bc2f8d330b0c96e0489f1aa62fafd --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4504ece94bf770b093faaf5c862320c6899c7f9b65751dfe28577fb02206640 +size 22472 diff --git a/tasks/rothenbacher2019/gurobi_solution/large_solution_2.json b/tasks/rothenbacher2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e8d7720ea1201e2c69423f473a802bf0701ba33e --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0781d62ad6eac55e975228e4c88f2de94e7e7d75fa388231529a3fddf2be0acf +size 21934 diff --git a/tasks/rothenbacher2019/gurobi_solution/large_solution_3.json b/tasks/rothenbacher2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..131f80b93fed5c6a0ea1ad8c7f07f04f865c8d84 --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a7b7ba482198d775860e1e6947ae94328c831e13529f1d67c960d2941f09619 +size 22618 diff --git a/tasks/rothenbacher2019/gurobi_solution/large_solution_4.json b/tasks/rothenbacher2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4c3e272f9f12ff65715cb1d491035488b94863ef --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18349827bc32d7f826623e0ff53144f3024d07ebafec174dccc3e41f3f6fa1f8 +size 22344 diff --git a/tasks/rothenbacher2019/gurobi_solution/large_solution_5.json b/tasks/rothenbacher2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..0a399c0a67df2e573244e692d40da68cc27a57c3 --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96619c1668c1445689df022abfcfa18225089b8241bf9464c02de94348580f33 +size 22469 diff --git a/tasks/rothenbacher2019/gurobi_solution/tiny_solution.json b/tasks/rothenbacher2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..7e89aad106bad6cdfaf3b4f0c74b1fbe5ae366f4 --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab3464b68310428da26f7500ee32989b1912e669c3f970f80378239edb7cfa30 +size 5657 diff --git a/tasks/rothenbacher2019/gurobi_solution_log/large_log_1.jsonl b/tasks/rothenbacher2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c18e4beffff79627378a804d6b551a66987caac --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d55f3118d96ca9f561a02ce9b0ebdaea57d55ca5208a8902ea7d699786b1e678 +size 631 diff --git a/tasks/rothenbacher2019/gurobi_solution_log/large_log_2.jsonl b/tasks/rothenbacher2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..064aa216286b8a0ed5dd66aa613758bdd72ee5c2 --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ed3807620dee31967933b40565297831730a713bd854dc587ad94c17b637779 +size 516 diff --git a/tasks/rothenbacher2019/gurobi_solution_log/large_log_3.jsonl b/tasks/rothenbacher2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..82fbd187750ee0fc832f69a259ec9cc759377fca --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa5cead32226ec32482b3517fef1432ae1d04e3e0d6df3b50827d4755354feae +size 228 diff --git a/tasks/rothenbacher2019/gurobi_solution_log/large_log_4.jsonl b/tasks/rothenbacher2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..24895801f04e7d5b2881e055149e5a4bf715590f --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11d57f54ddfa5d9a8c6ddd58a8017019ff033eefcb457895f9a35af7b0059618 +size 400 diff --git a/tasks/rothenbacher2019/gurobi_solution_log/large_log_5.jsonl b/tasks/rothenbacher2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..455f7bf94d0c8634d011fdb894cc66fb099381c8 --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3444e50489557d58646a73d58d9e075d7a1eeb16ad0c716cc36a522bc701b477 +size 287 diff --git a/tasks/rothenbacher2019/gurobi_solution_log/tiny_log.jsonl b/tasks/rothenbacher2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5849762718917034252b6b9356aefdecc00bb314 --- /dev/null +++ b/tasks/rothenbacher2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:801a7f08cf1943140937782f3daeae78a3c8c6df8d8c9b447728a423079d9bbd +size 55 diff --git a/tasks/rothenbacher2019/instance/large_instance_1.json b/tasks/rothenbacher2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..794ce14f11cbe2170ecf58ec2e12eaf178db5c01 --- /dev/null +++ b/tasks/rothenbacher2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d78aea8ce93e3b42cf235b4ea23273282a8f694eaf15393af0e49fc508b98c3 +size 22093 diff --git a/tasks/rothenbacher2019/instance/large_instance_2.json b/tasks/rothenbacher2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..6896b38ead85129f7a28292c135de55bc2330bc3 --- /dev/null +++ b/tasks/rothenbacher2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d07f60f4f12501c2d4e3d53ab1564b16faaaff0542362af0260ab6b27ad2724 +size 22081 diff --git a/tasks/rothenbacher2019/instance/large_instance_3.json b/tasks/rothenbacher2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..5b5393ac01a3688191091ba60d7c160529c087c2 --- /dev/null +++ b/tasks/rothenbacher2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a89d7b525bea75ad2a22a67a8e10829b8545ee1d891f6a6d4acc78127b67bd2 +size 35333 diff --git a/tasks/rothenbacher2019/instance/large_instance_4.json b/tasks/rothenbacher2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2390dc4ef275d6330630312090e6c05c877dc668 --- /dev/null +++ b/tasks/rothenbacher2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdfd41b43d4b415e4bffd83dc31bbb5afdec3a64c0341bb139c432053467aeb1 +size 31775 diff --git a/tasks/rothenbacher2019/instance/large_instance_5.json b/tasks/rothenbacher2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..3b7dde6bdf2b5bbce52159c6d3e67ab3f530684b --- /dev/null +++ b/tasks/rothenbacher2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a409ce26e0046eb7aee7ee576d6524acf4ce60d0f320319d4a38bd65feef14d7 +size 35352 diff --git a/tasks/rothenbacher2019/instance/tiny_instance.json b/tasks/rothenbacher2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a328888dd21547b22b03336dbecd1ef6d5374539 --- /dev/null +++ b/tasks/rothenbacher2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed67708d32bf330ec0c1e235beddb1c2b93e622c833a774eb19aa3b1ff41ee65 +size 11618 diff --git a/tasks/rothenbacher2019/instance_schema.json b/tasks/rothenbacher2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9c54a8ff1b09e685f97129976c5b4f77de8ac9ca --- /dev/null +++ b/tasks/rothenbacher2019/instance_schema.json @@ -0,0 +1,41 @@ +{ + "num_customers": " Total number of customers to be served over the planning horizon.", + "num_days": " Number of days in the cyclic planning horizon.", + "num_vehicles": " Number of identical vehicles available for dispatching each day.", + "vehicle_capacity": " Maximum total delivery quantity that a single vehicle can carry on one route.", + "max_route_duration": " Maximum allowable duration for any single vehicle route.", + "depot": { + "id": " Unique identifier for the depot location.", + "x": " Horizontal coordinate of the depot.", + "y": " Vertical coordinate of the depot.", + "time_window": " Earliest departure and latest return time for vehicles at the depot.", + "service_time": " Duration of service at the depot (always zero)." + }, + "customers": [ + { + "id": " Unique identifier for the customer.", + "x": " Horizontal coordinate of the customer location.", + "y": " Vertical coordinate of the customer location.", + "demand_per_day": " Quantity of goods the customer requires each day.", + "time_window": " Earliest and latest time at which service may begin at this customer.", + "service_time": " Duration of the service stop at this customer.", + "visit_frequency_original": " Number of visits this customer requires per planning horizon.", + "schedules": [ + { + "days": " Days within the planning horizon on which the customer is visited under this schedule.", + "visit_frequency": " Number of visits in this schedule over the planning horizon.", + "parts": [ + { + "visit_day": " Day on which this delivery visit occurs.", + "days_covered": " Number of consecutive demand-days supplied by this single delivery.", + "demand_per_visit": " Total quantity to be delivered on this visit." + } + ] + } + ] + } + ], + "distance_matrix_type": " Method used to compute distances between all location pairs.", + "cost_type": " Method used to compute the travel cost between locations.", + "planning_horizon_cyclic": " Whether the last day of the planning horizon wraps around to the first day." +} diff --git a/tasks/rothenbacher2019/mathematical_formulation.md b/tasks/rothenbacher2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3e5f7ed6014b47815db0df6899864a6fb8ffa623 --- /dev/null +++ b/tasks/rothenbacher2019/mathematical_formulation.md @@ -0,0 +1,63 @@ +# Original Formulation: Periodic Vehicle Routing Problem with Time Windows and Flexible Schedule Structures (PVRPTW) + +*Source: A Branch-and-Price-and-Cut Algorithm for the Periodic Vehicle Routing Problem with Flexible Schedule Structures, Florian Rothenbächer, Transportation Science, 2019.* + +## Sets and Indices + +$$\begin{align*} +P &= \{0, \ldots, |P|-1\} && \text{Planning horizon (days); cyclic: day $|P|-1$ is followed by day $0$.}\\ +N &&& \text{Set of customers.}\\ +d &&& \text{Single depot.}\\ +O &= N \cup \{d\} && \text{Set of all locations.}\\ +S_n &\subseteq \mathcal{P}(P) && \text{Set of offered schedules for customer $n \in N$ ($\mathcal{P}(P)$ = power set of $P$).}\\ +L &= \{1, \ldots, |P|\} && \text{Set of possible schedule-part lengths.}\\ +S_n^{p:l} &&& \text{Subset of $S_n$ whose schedules include the schedule part $n^{p:l}$.}\\ +R &&& \text{Set of all feasible routes.}\\ +R^p &\subset R && \text{Subset of routes feasible for day $p \in P$.} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +m &&& \text{Number of homogeneous vehicles available each day.}\\ +Q &&& \text{Vehicle capacity.}\\ +D &&& \text{Maximal route duration.}\\ +[a_d, b_d] &&& \text{Time window of the depot.}\\ +q_n &&& \text{Demand per day for customer $n \in N$.}\\ +[a_n, b_n] &&& \text{Time window for customer $n \in N$.}\\ +c_r &&& \text{Cost of route $r$ (depends exclusively on traveled distance).}\\ +t_{o_1,o_2} &&& \text{Travel time from $o_1$ to $o_2$ (including service time at $o_1$).}\\ +c_{o_1,o_2} &&& \text{Travel cost from $o_1$ to $o_2$.}\\ +a_{rn}^{p:l} &&& \text{How often route $r$ includes schedule part $n^{p:l}$ (a visit to $n$ on day $p$}\\ +&&& \text{delivering $l$ days of demand); $0$ or $1$ for elementary routes.}\\ +b_s^{p:l} &&& \text{Binary: whether schedule $s$ induces the schedule part $(p:l)$.} +\end{align*}$$ A schedule part $n^{p:l}$ represents a visit to customer $n$ on day $p$ delivering the demand for $l$ consecutive days; the delivered amount is $q_n \cdot l$. + +## Decision Variables + +$$\begin{align*} +\lambda_r^p &\in \{0,1\} && \text{$1$ if route $r \in R^p$ is performed on day $p \in P$, $0$ otherwise.}\\ +z_n^s &\in \{0,1\} && \text{$1$ if schedule $s \in S_n$ is chosen for customer $n \in N$, $0$ otherwise.} +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad & \sum_{p \in P} \sum_{r \in R^p} c_r\, \lambda_r^p \tag{1a} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.}\quad +& \sum_{s \in S_n} z_n^s = 1 + && (\pi_n) && \forall\, n \in N \tag{1b}\\ +& \sum_{r \in R^p} a_{rn}^{p:l}\, \lambda_r^p = \sum_{s \in S_n} b_s^{p:l}\, z_n^s + && (\rho_n^{p:l}) && \forall\, n \in N,\; p \in P,\; l \in L : S_n^{p:l} \neq \emptyset \tag{1c}\\ +& \sum_{r \in R^p} \lambda_r^p \leq m + && (\mu_p) && \forall\, p \in P \tag{1d}\\ +& z_n^s \in \{0,1\} + && && \forall\, n \in N,\; s \in S_n \tag{1e}\\ +& \lambda_r^p \in \{0,1\} + && && \forall\, p \in P,\; r \in R^p \tag{1f} +\end{align}$$ diff --git a/tasks/rothenbacher2019/problem_description.txt b/tasks/rothenbacher2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..04d648d0746ff4e3974f24c5449f2e2e35d8e46c --- /dev/null +++ b/tasks/rothenbacher2019/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A distribution company operates a fleet of homogeneous vehicles from a single depot to serve a set of customers over a cyclic planning horizon. The planning horizon consists of a given number of days (num_days), where the last day is followed by the first day in a repeating cycle (planning_horizon_cyclic). A fixed number of identical vehicles (num_vehicles) is available each day, each with a common carrying capacity (vehicle_capacity) and a maximum allowable route duration (max_route_duration). The depot has a location specified by coordinates (x, y under depot), a time window during which vehicles must depart and return (time_window under depot), and a service time (service_time under depot). Each of the customers (num_customers in total) has a unique identifier (id), a location given by coordinates (x, y under customers), a daily demand quantity (demand_per_day), a time window within which service must begin (time_window under customers, indexed by [customer]), and a service time representing the duration of the stop (service_time under customers, indexed by [customer]). Each customer also has an original visit frequency indicating how many times per planning horizon the customer requires service (visit_frequency_original, indexed by [customer]). + +Every customer offers a set of visiting patterns called schedules (schedules, indexed by [customer][schedule]). Each schedule specifies the days on which visits occur (days, indexed by [customer][schedule]) and the number of visits in the horizon (visit_frequency, indexed by [customer][schedule]). Each visit within a schedule is associated with a specific day (visit_day) and a number of consecutive demand-days that the visit covers (days_covered); the quantity delivered on that visit equals the customer's daily demand multiplied by the number of days covered (demand_per_visit). Distances and costs between all pairs of locations are computed as Euclidean distances based on the coordinates (distance_matrix_type, cost_type). Travel time between two locations equals the Euclidean distance plus the service time at the origin location. + +The company must make two interrelated sets of decisions. First, for each customer, exactly one of the customer's offered schedules must be selected to determine on which days that customer will be visited and how much will be delivered at each visit. Second, for each day in the planning horizon, the company must design a set of vehicle routes, where each route is a sequence of customer visits starting and ending at the depot, determining which customers are served by which vehicle and in what order. The routes performed on each day must carry out exactly the visits prescribed by each customer's selected schedule: every visit (with its day and days-covered amount) required by a chosen schedule must be realized by exactly one route, and routes may not include visits that are not required by any chosen schedule. + +On each day, the number of routes performed must not exceed the number of available vehicles. Each route must satisfy the following operational requirements: the total quantity delivered across all customers on the route must not exceed the vehicle capacity; the route duration must not exceed the maximum allowable route duration; service at each customer must begin within that customer's time window; the vehicle must depart from and return to the depot within the depot's time window; each visit included in the route must be compatible with at least one of that customer's offered schedules, meaning the combination of the visiting day and the number of demand-days covered must appear in at least one schedule offered by the customer; and each customer may appear at most once on any single route. A route's cost equals the total Euclidean distance traveled along its path, including the legs from the depot to the first customer, between consecutive customers, and from the last customer back to the depot. + +The goal is to minimize the total routing cost, defined as the sum of the costs of all routes performed across all days of the planning horizon. diff --git a/tasks/rothenbacher2019/solution_logger.py b/tasks/rothenbacher2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/rothenbacher2019/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/rothenbacher2019/solution_schema.json b/tasks/rothenbacher2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..102222354210865381b4c0a32fabb3c42e8b1219 --- /dev/null +++ b/tasks/rothenbacher2019/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total routing cost summed over all routes performed across all days of the planning horizon.", + "routes": " For each day in the planning horizon, the ordered list of vehicle routes performed on that day, where each route entry has 'customers' (the sequence of customer ids visited between depot departure and return), 'cost' (the Euclidean travel cost of the route), 'demand' (the total quantity delivered on the route), and 'parts' (a dict keyed by '{customer}' giving the visit's 'visit_day', 'days_covered', and 'demand_per_visit' delivered to that customer on this route).", + "schedules": " For each customer, the chosen visiting pattern, giving the index of the selected schedule ('schedule_index'), the days on which that customer is visited ('days'), and the number of visits performed in the horizon ('visit_frequency')." +} diff --git a/tasks/ruiz2007/feasibility_check.py b/tasks/ruiz2007/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f04881d16a5cae049cc86673f4ef1942ab190210 --- /dev/null +++ b/tasks/ruiz2007/feasibility_check.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Mixed No-Idle Permutation Flowshop Scheduling +Problem (MNPFSP) from Pan & Ruiz (2014). + +Checks all hard constraints from the MILP formulation against a candidate solution. + +Constraints: + 1: each job occupies exactly one position + 2: each position is occupied by exactly one job (permutation length = n) + 3: C_{1,k} >= sum_j X_{j,k} * p_{1,j} + 4: C_{i,k} >= C_{i-1,k} + sum_j X_{j,k} * p_{i,j} + 5: no-idle equality / regular >= sequence-precedence + 6: non-negativity C_{i,k} >= 0 + 7: valid job indices (X binary) + 8: objective consistency -- reported objective_value matches makespan + C_{m-1, n-1} computed from solution's completion_times (Tier C + defense against LLM score-gaming exploits). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('completion_times', 'objective_value', 'sequence') +_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 compute_completion_times(perm, p, no_idle, n_seq, m): + """ + Compute minimum feasible completion times for a given permutation in MNPFSP. + + For no-idle machines, the start time is chosen so that the no-idle equality + and machine-precedence constraints are both satisfied. + """ + C = [[0.0] * n_seq for _ in range(m)] + + # Machine 0: no predecessor machine, so C[0][k] = cumulative processing + C[0][0] = p[0][perm[0]] + for k in range(1, n_seq): + C[0][k] = C[0][k - 1] + p[0][perm[k]] + + # Machines 1..m-1 + for i in range(1, m): + if no_idle[i]: + # No-idle: C[i][k] = S_i + cumP[k], need S_i >= C[i-1][k] - cumP[k-1] for all k + # where cumP[k] = sum_{l=0}^{k} p[i][perm[l]] + cumsum = 0.0 # tracks cumP[k-1] + S_i = C[i - 1][0] # k=0: S_i >= C[i-1][0] + for k in range(1, n_seq): + cumsum += p[i][perm[k - 1]] + needed = C[i - 1][k] - cumsum + if needed > S_i: + S_i = needed + C[i][0] = S_i + p[i][perm[0]] + for k in range(1, n_seq): + C[i][k] = C[i][k - 1] + p[i][perm[k]] + else: + # Regular machine + C[i][0] = C[i - 1][0] + p[i][perm[0]] + for k in range(1, n_seq): + C[i][k] = max(C[i - 1][k], C[i][k - 1]) + p[i][perm[k]] + + return C + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["n_jobs"] + m = instance["n_machines"] + no_idle = instance["no_idle_flags"] + pt = instance["processing_times"] # pt[j][i] + + # p[i][j] = processing time of job j on machine i + p = [[pt[j][i] for j in range(n)] for i in range(m)] + + # Extract permutation + if "permutation" in solution: + perm = solution["permutation"] + elif "sequence" in solution: + perm = solution["sequence"] + else: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["No permutation or sequence found in solution"], + "violation_magnitudes": [], + } + + # Validate job indices before using them as array indices + for k, j in enumerate(perm): + if not isinstance(j, int) or j < 0 or j >= n: + return { + "feasible": False, + "violated_constraints": [7], + "violations": [ + f"Constraint 7 violated: invalid job index {j} at position {k}" + ], + "violation_magnitudes": [], + } + + # Completion times are required in the solution + if "completion_times" not in solution: + return { + "feasible": False, + "violated_constraints": [], + "violations": ["No completion_times found in solution"], + "violation_magnitudes": [], + } + C = [] + for i in range(m): + C.append(solution["completion_times"][f"machine_{i}"]) + + violations = [] + violation_magnitudes = [] + violated_set = set() + n_seq = len(perm) + + # ------------------------------------------------------------------ + # Constraint 1: Each job occupies exactly one position + # sum_{k} X_{j,k} = 1 for all j + # ------------------------------------------------------------------ + job_counts = {} + for j in perm: + job_counts[j] = job_counts.get(j, 0) + 1 + + for j in range(n): + count = job_counts.get(j, 0) + if count != 1: + lhs = float(count) + rhs = 1.0 + va = abs(lhs - rhs) + if va > tol: + violated_set.add(1) + normalizer = max(abs(rhs), eps) + if count == 0: + violations.append(f"Job {j} not assigned to any position") + else: + violations.append( + f"Job {j} assigned to {count} positions instead of 1" + ) + violation_magnitudes.append( + { + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + } + ) + + # ------------------------------------------------------------------ + # Constraint 2: Each position occupied by exactly one job + # sum_{j} X_{j,k} = 1 for all k + # ------------------------------------------------------------------ + if n_seq != n: + lhs = float(n_seq) + rhs = float(n) + va = abs(lhs - rhs) + if va > tol: + violated_set.add(2) + normalizer = max(abs(rhs), eps) + violations.append( + f"Permutation length {n_seq} does not match number of jobs {n}" + ) + violation_magnitudes.append( + { + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + } + ) + + # ------------------------------------------------------------------ + # Constraint 3: C_{1,k} >= sum_j X_{j,k} * p_{1,j} for k=1..n + # i.e. C[0][k] >= p[0][perm[k]] + # ------------------------------------------------------------------ + for k in range(n_seq): + job_k = perm[k] + lhs_val = C[0][k] + rhs_val = float(p[0][job_k]) + va = rhs_val - lhs_val # >= constraint + if va > tol: + violated_set.add(3) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Constraint 3 violated at position {k}: " + f"C[0][{k}]={lhs_val:.4f} < p[0][job {job_k}]={rhs_val:.4f}" + ) + violation_magnitudes.append( + { + "constraint": 3, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + } + ) + + # ------------------------------------------------------------------ + # Constraint 4: C_{i,k} >= C_{i-1,k} + sum_j X_{j,k} * p_{i,j} + # for i=2..m, k=1..n (0-indexed: i=1..m-1, k=0..n-1) + # ------------------------------------------------------------------ + for i in range(1, m): + for k in range(n_seq): + job_k = perm[k] + lhs_val = C[i][k] + rhs_val = C[i - 1][k] + p[i][job_k] + va = rhs_val - lhs_val + if va > tol: + violated_set.add(4) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Constraint 4 violated at machine {i}, position {k}: " + f"C[{i}][{k}]={lhs_val:.4f} < " + f"C[{i-1}][{k}]+p[{i}][job {job_k}]={rhs_val:.4f}" + ) + violation_magnitudes.append( + { + "constraint": 4, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + } + ) + + # ------------------------------------------------------------------ + # Constraint 5: Sequence precedence for k=2..n, i=1..m + # (0-indexed: k=1..n-1, i=0..m-1) + # No-idle (i in M'): C[i][k] = C[i][k-1] + p[i][perm[k]] + # Regular (i not in M'): C[i][k] >= C[i][k-1] + p[i][perm[k]] + # ------------------------------------------------------------------ + for i in range(m): + for k in range(1, n_seq): + job_k = perm[k] + lhs_val = C[i][k] + rhs_val = C[i][k - 1] + p[i][job_k] + if no_idle[i]: + # Equality constraint + va = abs(lhs_val - rhs_val) + if va > tol: + violated_set.add(5) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Constraint 5 (no-idle =) violated at machine {i}, " + f"position {k}: C[{i}][{k}]={lhs_val:.4f} != " + f"C[{i}][{k-1}]+p[{i}][job {job_k}]={rhs_val:.4f}" + ) + violation_magnitudes.append( + { + "constraint": 5, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + } + ) + else: + # >= inequality + va = rhs_val - lhs_val + if va > tol: + violated_set.add(5) + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Constraint 5 (regular >=) violated at machine {i}, " + f"position {k}: C[{i}][{k}]={lhs_val:.4f} < " + f"C[{i}][{k-1}]+p[{i}][job {job_k}]={rhs_val:.4f}" + ) + violation_magnitudes.append( + { + "constraint": 5, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + } + ) + + # ------------------------------------------------------------------ + # Constraint 6: Non-negativity C_{i,k} >= 0 + # ------------------------------------------------------------------ + for i in range(m): + for k in range(n_seq): + lhs_val = C[i][k] + rhs_val = 0.0 + va = rhs_val - lhs_val + if va > tol: + violated_set.add(6) + normalizer = eps # |RHS| = 0 + violations.append( + f"Constraint 6 violated: C[{i}][{k}]={lhs_val:.4f} < 0" + ) + violation_magnitudes.append( + { + "constraint": 6, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": va, + "normalizer": normalizer, + "ratio": va / normalizer, + } + ) + + # ------------------------------------------------------------------ + # Constraint 7: Binary / valid job indices X_{j,k} in {0,1} + # ------------------------------------------------------------------ + for k, j in enumerate(perm): + if not isinstance(j, int) or j < 0 or j >= n: + violated_set.add(7) + violations.append( + f"Constraint 7 violated: invalid job index {j} at position {k}" + ) + violation_magnitudes.append( + { + "constraint": 7, + "lhs": float(j) if isinstance(j, (int, float)) else 0.0, + "rhs": float(n - 1), + "raw_excess": 1.0, + "normalizer": max(float(n - 1), eps), + "ratio": 1.0 / max(float(n - 1), eps), + } + ) + + # ------------------------------------------------------------------ + # Constraint 8: Objective consistency -- reported objective_value must + # match the makespan C_{m,n} = C[m-1][n_seq-1] derived from the + # solution's own completion_times. This is the Tier C defense + # against LLM exploits that fabricate objective_value (e.g. + # obj=0 on a minimization problem) while keeping the schedule + # itself nominally feasible. + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value") + if reported_obj is not None and m > 0 and n_seq > 0: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + try: + true_obj = float(C[m - 1][n_seq - 1]) + except (IndexError, TypeError, ValueError): + true_obj = None + if true_obj is not None: + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_set.add(8) + normalizer = max(abs(true_obj), eps) + violations.append( + f"Constraint 8 violated: reported objective_value=" + f"{reported} differs from makespan C[{m-1}][{n_seq-1}]=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + violation_magnitudes.append( + { + "constraint": 8, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + } + ) + + feasible = len(violated_set) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MNPFSP 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" + ) + args = parser.parse_args() + + with open(args.instance_path) as f: + instance = json.load(f) + with open(args.solution_path) as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/ruiz2007/gurobi_code.py b/tasks/ruiz2007/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..dcb5b4380e31636fb3099c2c371bd61c05eb4003 --- /dev/null +++ b/tasks/ruiz2007/gurobi_code.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the MNPFSP (Mixed No-Idle Permutation Flowshop Scheduling Problem). + +Based on: Ruiz et al. (2007), "The Mixed No-Idle Permutation Flowshop Scheduling Problem". + +This implements the MILP formulation for minimizing makespan in a permutation flowshop +where some machines are designated as "no-idle" (no idle time between consecutive jobs). + +Decision variables: + - X[j,k] binary: 1 if job j is assigned to position k in the sequence + - C[i,k] >= 0: completion time of the job in position k on machine i + - Cmax: makespan (= C[m-1, n-1]) + +Constraints: + (1) Each job assigned to exactly one position + (2) Each position assigned to exactly one job + (3) Completion time base: C[0,k] >= sum_j X[j,k]*p[0,j] + (4) Machine precedence: C[i,k] >= C[i-1,k] + sum_j X[j,k]*p[i,j] + (5) Sequence precedence (no-idle machines use equality, regular use inequality): + C[i,k] (>=|=) C[i,k-1] + sum_j X[j,k]*p[i,j] +""" + +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# ============================================================================= +# DATA LOADING +# ============================================================================= + +def load_instance(path): + """Load an MNPFSP instance from JSON.""" + with open(path, 'r') as f: + data = json.load(f) + return data + + +# ============================================================================= +# MAIN MODEL +# ============================================================================= + +def solve_mnpfsp(instance_path, solution_path, time_limit): + """Build and solve the MNPFSP MILP model using Gurobi.""" + data = load_instance(instance_path) + + n = data['n_jobs'] + m = data['n_machines'] + no_idle = data['no_idle_flags'] # length m, True if machine i is no-idle + pt = data['processing_times'] # pt[j][i] = processing time of job j on machine i + + # p[i][j] = processing time on machine i of job j + p = [[pt[j][i] for j in range(n)] for i in range(m)] + + print(f"MNPFSP Instance: n={n} jobs, m={m} machines") + print(f"No-idle machines: {[i for i in range(m) if no_idle[i]]}") + print(f"Time limit: {time_limit} seconds") + + model = gp.Model("MNPFSP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ------------------------------------------------------------------------- + # Decision variables + # ------------------------------------------------------------------------- + + # X[j,k]: binary, 1 if job j is assigned to position k + X = {} + for j in range(n): + for k in range(n): + X[j, k] = model.addVar(vtype=GRB.BINARY, name=f"X_{j}_{k}") + + # C[i,k]: completion time of job in position k on machine i + C = {} + for i in range(m): + for k in range(n): + C[i, k] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"C_{i}_{k}") + + model.update() + + # ------------------------------------------------------------------------- + # Objective: minimize makespan = C[m-1, n-1] + # ------------------------------------------------------------------------- + model.setObjective(C[m - 1, n - 1], GRB.MINIMIZE) + + # ------------------------------------------------------------------------- + # Constraint (1): Each job occupies exactly one position + # ------------------------------------------------------------------------- + for j in range(n): + model.addConstr( + gp.quicksum(X[j, k] for k in range(n)) == 1, + name=f"job_{j}_one_pos" + ) + + # ------------------------------------------------------------------------- + # Constraint (2): Each position has exactly one job + # ------------------------------------------------------------------------- + for k in range(n): + model.addConstr( + gp.quicksum(X[j, k] for j in range(n)) == 1, + name=f"pos_{k}_one_job" + ) + + # ------------------------------------------------------------------------- + # Constraint (3): Base completion time on first machine + # C[0,k] >= sum_j X[j,k]*p[0][j] for all k + # ------------------------------------------------------------------------- + for k in range(n): + model.addConstr( + C[0, k] >= gp.quicksum(X[j, k] * p[0][j] for j in range(n)), + name=f"base_m0_k{k}" + ) + + # ------------------------------------------------------------------------- + # Constraint (4): Machine precedence + # C[i,k] >= C[i-1,k] + sum_j X[j,k]*p[i][j] for i=1..m-1, k=0..n-1 + # ------------------------------------------------------------------------- + for i in range(1, m): + for k in range(n): + model.addConstr( + C[i, k] >= C[i - 1, k] + gp.quicksum(X[j, k] * p[i][j] for j in range(n)), + name=f"mach_prec_i{i}_k{k}" + ) + + # ------------------------------------------------------------------------- + # Constraint (5): Sequence precedence + # For k=1..n-1, i=0..m-1: + # If no-idle: C[i,k] = C[i,k-1] + sum_j X[j,k]*p[i][j] (equality) + # If regular: C[i,k] >= C[i,k-1] + sum_j X[j,k]*p[i][j] (inequality) + # ------------------------------------------------------------------------- + for i in range(m): + for k in range(1, n): + proc_sum = gp.quicksum(X[j, k] * p[i][j] for j in range(n)) + if no_idle[i]: + model.addConstr( + C[i, k] == C[i, k - 1] + proc_sum, + name=f"seq_noidle_i{i}_k{k}" + ) + else: + model.addConstr( + C[i, k] >= C[i, k - 1] + proc_sum, + name=f"seq_regular_i{i}_k{k}" + ) + + model.update() + + # ------------------------------------------------------------------------- + # Solve + # ------------------------------------------------------------------------- + model.optimize() + + # ------------------------------------------------------------------------- + # Extract solution + # ------------------------------------------------------------------------- + result = {"problem": "MNPFSP", "instance": instance_path} + + if model.SolCount > 0: + obj_val = model.ObjVal + result["objective_value"] = obj_val + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + result["gap"] = model.MIPGap if hasattr(model, 'MIPGap') else 0.0 + + # Extract job sequence from X variables + sequence = [None] * n + for k in range(n): + for j in range(n): + if X[j, k].X > 0.5: + sequence[k] = j + break + + result["sequence"] = sequence + + # Extract completion times for verification + completion_times = {} + for i in range(m): + completion_times[f"machine_{i}"] = [C[i, k].X for k in range(n)] + result["completion_times"] = completion_times + else: + result["objective_value"] = None + result["status"] = "infeasible_or_no_solution" + + result["solve_time"] = model.Runtime + + # Write solution + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"\nSolution written to {solution_path}") + if model.SolCount > 0: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status']}") + print(f"Sequence: {result['sequence']}") + + return result + + +# ============================================================================= +# MAIN +# ============================================================================= + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Solve MNPFSP using Gurobi MILP") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, default="gurobi_solution_1.json", + help="Path for the output solution JSON file") + parser.add_argument("--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_mnpfsp(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/ruiz2007/gurobi_feasi_result/large_feasi_result_1.json b/tasks/ruiz2007/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ruiz2007/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/ruiz2007/gurobi_feasi_result/large_feasi_result_2.json b/tasks/ruiz2007/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ruiz2007/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/ruiz2007/gurobi_feasi_result/large_feasi_result_3.json b/tasks/ruiz2007/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ruiz2007/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/ruiz2007/gurobi_feasi_result/large_feasi_result_4.json b/tasks/ruiz2007/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ruiz2007/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/ruiz2007/gurobi_feasi_result/large_feasi_result_5.json b/tasks/ruiz2007/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ruiz2007/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/ruiz2007/gurobi_feasi_result/tiny_feasi_result.json b/tasks/ruiz2007/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ruiz2007/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/ruiz2007/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/ruiz2007/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/ruiz2007/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/ruiz2007/gurobi_solution/large_solution_1.json b/tasks/ruiz2007/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..2c8999e0e9438c46e2ac1a1b31e831cdd08946f0 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb9fb5e210d48b7140d6d0c34a712e93a3e36e12e68ba583fc8fd1be03146fb6 +size 18733 diff --git a/tasks/ruiz2007/gurobi_solution/large_solution_2.json b/tasks/ruiz2007/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..bbc54bc536521f8d17a9706d50c952d8556769d5 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a151aeec108bfba53d8aca2ba234040d52df7e3774e1f5410743d77bb7366a6 +size 18755 diff --git a/tasks/ruiz2007/gurobi_solution/large_solution_3.json b/tasks/ruiz2007/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8750ecb66674f03f03abd231d03f1646bcb76e11 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55dbd3b1a3d2d1bd8ef594dd169bd7885c4344310f66d1939741f86060b1b8c4 +size 10743 diff --git a/tasks/ruiz2007/gurobi_solution/large_solution_4.json b/tasks/ruiz2007/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ae590e60437ef266e5c7d80e34da841d0510ea90 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d500d9197a9eea8d34c6c2b18a3c1d3fa375e80f91ae27ee1900955664bdf447 +size 26342 diff --git a/tasks/ruiz2007/gurobi_solution/large_solution_5.json b/tasks/ruiz2007/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..08987b7afb9586a63deaa87e1bce804fc81effd9 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:772c25e4828d76fd3a3e2e07e7c68e334845336a4acc4fbc30ab82b7025229e1 +size 10727 diff --git a/tasks/ruiz2007/gurobi_solution/tiny_solution.json b/tasks/ruiz2007/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..482d33b0d54350ff7e63d386af36b6b129e1317a --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a15d01ab02b9dccbf2f233f1ecdebfab064711f1094b391e2342828a35a19f8 +size 1359 diff --git a/tasks/ruiz2007/gurobi_solution/tiny_solution_2.json b/tasks/ruiz2007/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4a2132f9b07386ca6da9ffb9870180fb291e70ee --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab592b9205cda007ac9fa263544050f45693012f102774f572711466c4ff2623 +size 7896 diff --git a/tasks/ruiz2007/gurobi_solution_log/large_log_1.jsonl b/tasks/ruiz2007/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c792e9d21c02033b4bf27659882ca64f5a28ece1 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:647c850d7eefe8885443c6ea7410f83390e885d1fbe633302397e13b35d647a2 +size 1889 diff --git a/tasks/ruiz2007/gurobi_solution_log/large_log_2.jsonl b/tasks/ruiz2007/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..800512f540ed2507aa2d8d27593bf5721c1572d2 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e352151971ae5574db88f5b139f4f04d3d569ed7c683add74027779a4289b6a1 +size 1083 diff --git a/tasks/ruiz2007/gurobi_solution_log/large_log_3.jsonl b/tasks/ruiz2007/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8c1ee7c498c18951f2dc894bd60947c7ef12e974 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:081680fe942e9636378f92fa4eaadde136faf77980db070a9621ee3a898cce96 +size 1172 diff --git a/tasks/ruiz2007/gurobi_solution_log/large_log_4.jsonl b/tasks/ruiz2007/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8f9d0a0d469e67f418a56f63190d8705130f4c22 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab196ed68b4cf25333b4d22757aac989bd12b93a913749899d6191b5d0f362b6 +size 1300 diff --git a/tasks/ruiz2007/gurobi_solution_log/large_log_5.jsonl b/tasks/ruiz2007/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7720804078d64557c59d0e7e48d0775d8831ddbc --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c7c003cb7b7237e5391f8af230e71f334173c5fad911de2b3bd636d89c00835 +size 966 diff --git a/tasks/ruiz2007/gurobi_solution_log/tiny_log.jsonl b/tasks/ruiz2007/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..643a8e2cc5920b40a7212b098aae4bf0458b1335 --- /dev/null +++ b/tasks/ruiz2007/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01bc2aa155d9cad1052963134ca84e9b963af96298fa8898565bd09db2f17c6f +size 43 diff --git a/tasks/ruiz2007/instance/large_instance_1.json b/tasks/ruiz2007/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4afb21aa63d0fccc4066d510e081051147fefa --- /dev/null +++ b/tasks/ruiz2007/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5339af2edc0a08b59e59309c4215381ba840fc27364bed3d4244249652a1e64 +size 99518 diff --git a/tasks/ruiz2007/instance/large_instance_2.json b/tasks/ruiz2007/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..fb3c57d66bf14d002a4a663f2e0668e2da2bed1b --- /dev/null +++ b/tasks/ruiz2007/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:510b5d253e711ea0b4b16b511cd41f0f240cdd0efca888d795cd0148b18e36df +size 99496 diff --git a/tasks/ruiz2007/instance/large_instance_3.json b/tasks/ruiz2007/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c3b73d3d79ed3caee81ff6aeeb26b70114c66547 --- /dev/null +++ b/tasks/ruiz2007/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0499b184331768ee26f1cc8184944e936e099457994b5777c8aa044603b082a3 +size 56119 diff --git a/tasks/ruiz2007/instance/large_instance_4.json b/tasks/ruiz2007/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2a65f41e2ee361cc678a9a1d2cf8cc1a64ef84c4 --- /dev/null +++ b/tasks/ruiz2007/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d453c611ba621b4e305bf8ca388913cdf63d5df9c75330edf4d6297555d1f88 +size 99424 diff --git a/tasks/ruiz2007/instance/large_instance_5.json b/tasks/ruiz2007/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..03d696ae9cfc5b9466b8d678767972294a39bac7 --- /dev/null +++ b/tasks/ruiz2007/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0e8d73abece021d175f1a3eed1fb4a96b54840fe33f694d53f26d3a825a5804 +size 56203 diff --git a/tasks/ruiz2007/instance/tiny_instance.json b/tasks/ruiz2007/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..8b11c2c696bdd40ae93eab29393cff49f5829ef1 --- /dev/null +++ b/tasks/ruiz2007/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e09f8b88b9ca13fbe4a7854449a4842aa5bc5d2ab20f0d86676367d336d71a10 +size 1261 diff --git a/tasks/ruiz2007/instance/tiny_instance_2.json b/tasks/ruiz2007/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b9eae5911d34574b4f85f03dc00c59c55ef4455f --- /dev/null +++ b/tasks/ruiz2007/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10056b56bd3fd59372af2e7c1fa4687976e9bb73a506a974ececf39e01f22275 +size 6065 diff --git a/tasks/ruiz2007/instance_schema.json b/tasks/ruiz2007/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..46e6238fa0ce05972372919e367dfa8430bb5083 --- /dev/null +++ b/tasks/ruiz2007/instance_schema.json @@ -0,0 +1,7 @@ +{ + "n_jobs": " Number of jobs to be processed through the production line.", + "n_machines": " Number of machines arranged sequentially in the production line.", + "no_idle_machines": " Machines (1-indexed) designated as no-idle, where processing must be continuous with no gaps between consecutive jobs.", + "no_idle_flags": " Whether each machine (0-indexed) is designated as no-idle, requiring continuous processing with no gaps between consecutive jobs.", + "processing_times": " Time required for each job to be processed on each machine." +} diff --git a/tasks/ruiz2007/mathematical_formulation.md b/tasks/ruiz2007/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3e8e91f70ca90163f55cf346673d4514ac1419ab --- /dev/null +++ b/tasks/ruiz2007/mathematical_formulation.md @@ -0,0 +1,48 @@ +# Original Formulation: Mixed No-Idle Permutation Flowshop Scheduling Problem (MNPFSP) + +*Source: An effective iterated greedy algorithm for the mixed no-idle permutation flowshop scheduling problem, Quan-Ke Pan and Rubén Ruiz, 2014 (Omega 44:41–50; preprint submitted to OMEGA, October 2013).* + +## Sets and Parameters + +$$\begin{align*} +N &= \{1,\ldots,n\} && \text{set of } n \text{ jobs; } j \in N \text{ is a job index}\\ +M &= \{1,\ldots,m\} && \text{set of } m \text{ machines; } i \in M \text{ is a machine index}\\ +M' &\subseteq M && \text{subset of no-idle machines, } |M'| = m'\\ +&&& \text{(machines not in } M' \text{ are regular idle machines)}\\ +k &\in \{1,\ldots,n\} && \text{position index in the permutation sequence}\\ +p_{i,j} &\geq 0 && \text{known, deterministic processing time of job } j \text{ on machine } i +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +X_{j,k} &= +\begin{cases} +1, & \text{if job } j \text{ occupies position } k \text{ of the sequence}\\ +0, & \text{otherwise} +\end{cases}\\[4pt] +C_{i,k} &= \text{completion time of the job in position } k \text{ on machine } i\\ +C_{\max} &= \text{maximum completion time (makespan)} +\end{align*}$$ + +## Objective + +The objective is the minimization of the makespan, equal to the time at which the job occupying the last position of the permutation finishes at the last machine: $$\begin{equation*} +\min \; C_{\max} = C_{m,n} +\end{equation*}$$ + +## Constraints + +Subject to the following constraints: $$\begin{align} +&\sum_{k=1}^{n} X_{j,k} = 1, && j = 1,\ldots,n \tag{1}\\[4pt] +&\sum_{j=1}^{n} X_{j,k} = 1, && k = 1,\ldots,n \tag{2}\\[4pt] +&C_{1,k} \geq \sum_{j=1}^{n} X_{j,1}\cdot p_{1,j}, && k = 1,\ldots,n \tag{3}\\[4pt] +&C_{i,k} \geq C_{i-1,k} + \sum_{j=1}^{n} X_{j,k}\cdot p_{i,j}, && k = 1,\ldots,n,\; i = 2,\ldots,m \tag{4}\\[4pt] +&\begin{cases} +C_{i,k} = C_{i,k-1} + \displaystyle\sum_{j=1}^{n} X_{j,k}\cdot p_{i,j}, & \text{if } i \in M'\\[10pt] +C_{i,k} \geq C_{i,k-1} + \displaystyle\sum_{j=1}^{n} X_{j,k}\cdot p_{i,j}, & \text{otherwise} +\end{cases} +&& k = 2,\ldots,n,\; i = 1,\ldots,m \tag{5}\\[4pt] +&C_{i,k} \geq 0, && k = 1,\ldots,n,\; i = 1,\ldots,m \tag{6}\\[4pt] +&X_{i,k} \in \{0,1\}, && k = 1,\ldots,n,\; i = 1,\ldots,m \tag{7} +\end{align}$$ diff --git a/tasks/ruiz2007/problem_description.txt b/tasks/ruiz2007/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..333a1418d9e5bd1671f760ac29956a4e1d1d786d --- /dev/null +++ b/tasks/ruiz2007/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A production facility must process a set of n jobs through a series of m machines arranged in a strict sequential line, so that every job visits machine one first, then machine two, and so on through machine m. The facility must determine a single ordering (permutation) of all jobs that will be used identically on every machine; that is, the sequence in which jobs enter the first machine is the same sequence used on all subsequent machines. Each job has a known, deterministic processing time on each machine, and the input data consists of one processing time for every combination of job and machine. All jobs are independent and available for processing at time zero. Every machine is continuously available and processes exactly one job at a time, and every job can be on at most one machine at a time. Once a job begins processing on a machine it runs to completion without interruption. Setup times are included in the processing times. There is unlimited buffer storage between machines. + +The machines are partitioned into two groups. A designated subset of machines are classified as no-idle machines, and the remaining machines are regular machines. Which machines belong to the no-idle subset is specified as part of the input data. On a no-idle machine, processing must be continuous once the first job in the sequence begins: the completion time of the job in each position must equal exactly the completion time of the job in the immediately preceding position plus the processing time of the current job on that machine, leaving zero gap between consecutive jobs. On a regular machine, the completion time of a job at a given position must be at least as large as the completion time of the preceding job on that same machine plus the current job's processing time, but idle gaps between consecutive jobs are permitted. + +Regardless of machine type, the completion time of a job at any position on any machine from the second onward must be at least as large as the completion time of that same job on the preceding machine plus the job's processing time on the current machine, ensuring that a job cannot start on a machine until it has finished on the prior one. On the first machine, the completion time at each position must be at least the processing time of the job assigned to that position. All completion times must be zero or greater. + +Each job must be placed in exactly one position of the sequence, and each position must contain exactly one job. The goal is to find the permutation of jobs that minimizes the makespan, defined as the completion time of the job occupying the last position in the sequence on the last machine. diff --git a/tasks/ruiz2007/solution_logger.py b/tasks/ruiz2007/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/ruiz2007/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/ruiz2007/solution_schema.json b/tasks/ruiz2007/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..2f364f946ab63bc6c3fe78b237fa76863b8ed288 --- /dev/null +++ b/tasks/ruiz2007/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Makespan, the completion time of the job in the last sequence position on the last machine.", + "sequence": " Permutation of jobs giving the order in which jobs enter every machine, where the k-th entry is the job placed in position k.", + "completion_times": " Completion time of the job in each sequence position on the given machine, given as a list of length n_jobs ordered by position." +} diff --git a/tasks/sadykov2013/feasibility_check.py b/tasks/sadykov2013/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..340dfb0747ceeb6bad2f736199b2862e9e1c3b47 --- /dev/null +++ b/tasks/sadykov2013/feasibility_check.py @@ -0,0 +1,417 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Bin Packing Problem with Conflicts (BPPC). + +Checks all hard constraints from the compact formulation (1) in Sadykov & Vanderbeck (2013): + Constraint 1 (1b): Each item assigned to at least one bin. + Constraint 2 (1c): Bin capacity constraint. + Constraint 3 (1d): Conflict constraint -- two conflicting items cannot share a bin. + Constraint 4 (1e): y_k in {0, 1}. + Constraint 5 (1f): x_{ik} in {0, 1}. + Constraint 6: Objective consistency -- reported objective_value must equal + the recomputed number of used bins sum_k y_k. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('bins', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_instance(path): + with open(path, "r") as f: + return json.load(f) + + +def load_solution(path): + with open(path, "r") as f: + return json.load(f) + + +def parse_bins(solution): + """Parse bins from either efficient or gurobi solution format. + + Returns list of (bin_id, list_of_item_ids). + """ + bins_data = solution.get("bins", {}) + + # Efficient format: list of {"bin_id": ..., "items": [...]} + if isinstance(bins_data, list): + return [(b["bin_id"], b["items"]) for b in bins_data] + + # Gurobi format: dict of {"k": {"items": [...], ...}} + if isinstance(bins_data, dict): + result = [] + for k, v in bins_data.items(): + result.append((int(k), v["items"])) + return result + + return [] + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["num_items"] + W = instance["bin_capacity"] + items_data = instance["items"] + conflict_edges = instance["conflict_edges"] + + weights = {it["id"]: it["weight"] for it in items_data} + item_ids = set(it["id"] for it in items_data) + + bins = parse_bins(solution) + # Number of bins K = total bins in solution + K = len(bins) + + # Reconstruct assignments: which items are in which bin + # bin_items[k] = set of items in bin k + bin_items = {} + for bin_id, items in bins: + bin_items[bin_id] = set(items) + + # Build item-to-bins mapping + item_to_bins = {} + for bin_id, items_in_bin in bin_items.items(): + for i in items_in_bin: + item_to_bins.setdefault(i, set()).add(bin_id) + + # y_k = 1 if bin k is used (has items), 0 otherwise + # Since all bins in the solution are listed as used, y_k = 1 for all listed bins + y = {bin_id: 1 for bin_id in bin_items} + + violations = [] + violation_magnitudes = [] + violated_constraints = set() + + # --- Constraint 1 (1b): sum_k x_{ik} >= 1 for all i --- + for i in item_ids: + count = len(item_to_bins.get(i, set())) + lhs = float(count) + rhs = 1.0 + violation_amount = rhs - lhs # >= constraint: how much RHS exceeds LHS + if violation_amount > tol: + violated_constraints.add(1) + violations.append(f"Item {i} is not assigned to any bin (assigned {count} times)") + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 2 (1c): sum_i w_i * x_{ik} <= W * y_k for all k --- + for bin_id, items_in_bin in bin_items.items(): + total_weight = sum(weights.get(i, 0) for i in items_in_bin) + y_k = y.get(bin_id, 0) + lhs = float(total_weight) + rhs = float(W * y_k) + violation_amount = lhs - rhs # <= constraint: how much LHS exceeds RHS + if violation_amount > tol: + violated_constraints.add(2) + violations.append( + f"Capacity exceeded on bin {bin_id}: total weight {total_weight} > {W}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 3 (1d): x_{ik} + x_{jk} <= y_k for all (i,j) in E, all k --- + conflict_set = set() + for edge in conflict_edges: + i, j = edge[0], edge[1] + conflict_set.add((min(i, j), max(i, j))) + + for bin_id, items_in_bin in bin_items.items(): + items_list = sorted(items_in_bin) + items_set = set(items_list) + y_k = y.get(bin_id, 0) + for idx_a in range(len(items_list)): + for idx_b in range(idx_a + 1, len(items_list)): + a, b = items_list[idx_a], items_list[idx_b] + pair = (min(a, b), max(a, b)) + if pair in conflict_set: + lhs = 2.0 # x_{ik} + x_{jk} = 1 + 1 = 2 + rhs = float(y_k) # y_k = 1 + violation_amount = lhs - rhs + if violation_amount > tol: + violated_constraints.add(3) + violations.append( + f"Conflict violated: items {a} and {b} both in bin {bin_id}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 4 (1e): y_k in {0, 1} --- + for bin_id, y_val in y.items(): + val = float(y_val) + if abs(val - round(val)) > tol or round(val) not in (0, 1): + violated_constraints.add(4) + lhs = val + rhs_nearest = round(val) + violation_amount = abs(val - rhs_nearest) + rhs = rhs_nearest + normalizer = max(abs(rhs), eps) + violations.append(f"y_{bin_id} = {val} is not binary") + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 5 (1f): x_{ik} in {0, 1} --- + # In the solution representation, items are either in a bin or not, + # so x values are implicitly 0 or 1. Check for duplicates (item in same bin twice) + # and non-integer assignments. + for bin_id, items_in_bin in bin_items.items(): + for i in items_in_bin: + x_val = 1.0 # item is assigned + if abs(x_val - round(x_val)) > tol or round(x_val) not in (0, 1): + violated_constraints.add(5) + violation_amount = abs(x_val - round(x_val)) + rhs = round(x_val) + normalizer = max(abs(rhs), eps) + violations.append(f"x_{i},{bin_id} = {x_val} is not binary") + violation_magnitudes.append({ + "constraint": 5, + "lhs": x_val, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 6: Objective consistency (Tier C defense against obj fabrication) --- + # Objective (1a) is min sum_k y_k = number of used bins. Every bin listed in the + # solution has y_k = 1 (consistent with the original checker's y dict). Full + # recompute: true_obj = len(bins). Integer-valued, so a 0.5 tolerance catches + # any off-by-one mismatch. + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(sum(y.values())) # = len(bin_items) = number of used bins + abs_diff = abs(reported - true_obj) + obj_tol = 0.5 # integer-valued objective + if abs_diff > obj_tol: + violated_constraints.add(6) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum_k y_k=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 6, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + feasible = len(violated_constraints) == 0 + + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for BPPC (Sadykov & Vanderbeck 2013)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_instance(args.instance_path) + solution = load_solution(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasible: {result['feasible']}") + if not result["feasible"]: + print(f"Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/sadykov2013/gurobi_code.py b/tasks/sadykov2013/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..31e0c6de9a3c5278c3b56b3cf6bc9ba4161f877b --- /dev/null +++ b/tasks/sadykov2013/gurobi_code.py @@ -0,0 +1,159 @@ +""" +Bin Packing Problem with Conflicts (BPPC) - Compact Formulation 1. + +Solves the BPPC using a standard compact MIP formulation with Gurobi. + +Reference: Sadykov & Vanderbeck (2013) +""" + +import argparse +import json +import time + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def solve_bppc(instance_path: str, solution_path: str, time_limit: float) -> None: + # Load instance + with open(instance_path, "r") as f: + data = json.load(f) + + n = data["num_items"] + W = data["bin_capacity"] + items = data["items"] + conflict_edges = data["conflict_edges"] + + weights = {item["id"]: item["weight"] for item in items} + K = n # upper bound on number of bins + + # Create model + model = gp.Model("BPPC") + model.setParam("Threads", 1) + model.Params.TimeLimit = time_limit + + # Decision variables + # y[k]: 1 if bin k is used + y = model.addVars(K, vtype=GRB.BINARY, name="y") + # x[i,k]: 1 if item i is assigned to bin k + x = model.addVars(n, K, vtype=GRB.BINARY, name="x") + + # Objective: minimize number of bins used + model.setObjective(gp.quicksum(y[k] for k in range(K)), GRB.MINIMIZE) + + # Constraints + + # 1. Each item must be assigned to at least one bin + for i in range(n): + model.addConstr( + gp.quicksum(x[i, k] for k in range(K)) >= 1, + name=f"assign_{i}", + ) + + # 2. Bin capacity constraints + for k in range(K): + model.addConstr( + gp.quicksum(weights[i] * x[i, k] for i in range(n)) <= W * y[k], + name=f"capacity_{k}", + ) + + # 3. Conflict constraints + for i, j in conflict_edges: + for k in range(K): + model.addConstr( + x[i, k] + x[j, k] <= y[k], + name=f"conflict_{i}_{j}_{k}", + ) + + # 4. Symmetry breaking: y[k] >= y[k+1] + for k in range(K - 1): + model.addConstr(y[k] >= y[k + 1], name=f"symmetry_{k}") + + # Solve + start_time = time.time() + model.optimize() + solve_time = time.time() - start_time + + # Build solution + solution = { + "instance_path": instance_path, + "solver": "gurobi", + "formulation": "compact_1", + "solve_time_seconds": solve_time, + "time_limit": time_limit, + } + + if model.SolCount > 0: + obj_val = round(model.ObjVal) + solution["objective_value"] = obj_val + solution["best_bound"] = model.ObjBound + solution["mip_gap"] = model.MIPGap + solution["status"] = model.Status + + # Extract bin assignments + bins = {} + for k in range(K): + if y[k].X > 0.5: + bin_items = [i for i in range(n) if x[i, k].X > 0.5] + if bin_items: + bins[str(k)] = { + "items": bin_items, + "total_weight": sum(weights[i] for i in bin_items), + } + solution["bins"] = bins + solution["num_bins_used"] = len(bins) + else: + solution["objective_value"] = None + solution["status"] = model.Status + solution["bins"] = {} + + # 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"Solution written to {solution_path}") + if model.SolCount > 0: + print(f"Objective value (bins used): {obj_val}") + print(f"MIP gap: {model.MIPGap:.4f}") + else: + print(f"No feasible solution found. Status: {model.Status}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Solve BPPC using compact MIP 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 file.", + ) + parser.add_argument( + "--time_limit", + type=int, + required=True, + help="Time limit in seconds for Gurobi.", + ) + 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_bppc(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/sadykov2013/gurobi_feasi_result/large_feasi_result_1.json b/tasks/sadykov2013/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sadykov2013/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/sadykov2013/gurobi_feasi_result/large_feasi_result_2.json b/tasks/sadykov2013/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sadykov2013/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/sadykov2013/gurobi_feasi_result/large_feasi_result_3.json b/tasks/sadykov2013/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sadykov2013/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/sadykov2013/gurobi_feasi_result/large_feasi_result_4.json b/tasks/sadykov2013/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sadykov2013/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/sadykov2013/gurobi_feasi_result/large_feasi_result_5.json b/tasks/sadykov2013/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sadykov2013/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/sadykov2013/gurobi_feasi_result/tiny_feasi_result.json b/tasks/sadykov2013/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sadykov2013/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/sadykov2013/gurobi_solution/large_solution_1.json b/tasks/sadykov2013/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..b78780d88f8206b6a79316e02f4bf2a47d6c0655 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1085170f2c0c0ccdb1950e367c336014c385f6be176105324a6863f3eb3c151f +size 4999 diff --git a/tasks/sadykov2013/gurobi_solution/large_solution_2.json b/tasks/sadykov2013/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..9ae1b207782c4ee354a3fe69959fb805980bcda3 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf6dd303cda54ae0d1edd43398db6c333ef788738020ecb6481eddf7b3453610 +size 4794 diff --git a/tasks/sadykov2013/gurobi_solution/large_solution_3.json b/tasks/sadykov2013/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6e7f90a59a12746249530e572e34b8e4b522f004 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8a3fcd59b7afa53a70fdb1b80fb97b3c6f409c88c3cff7b17fe096cbd9a4c0a +size 4934 diff --git a/tasks/sadykov2013/gurobi_solution/large_solution_4.json b/tasks/sadykov2013/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a5a08bfebf9b7b40b9b0db7e9e018f12d804059e --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a5c418fa24dbeed418da4ad2068a608d65ed78eff30fb86017b77c85118ded4 +size 4793 diff --git a/tasks/sadykov2013/gurobi_solution/large_solution_5.json b/tasks/sadykov2013/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..2da34e88d1279efb6d97ab6553240788173da053 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60d1f30ecb3784298f79e1b9a0e6c95cad54299940563ab8b7b47294ad6a7ca0 +size 5196 diff --git a/tasks/sadykov2013/gurobi_solution/tiny_solution.json b/tasks/sadykov2013/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..304b93815c9dfa21b14acee1163e5f5a36029b58 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca0f3927524ddf5f7b79404765ab6b7ff8df83f74587a69eded5cb12c47116a1 +size 2700 diff --git a/tasks/sadykov2013/gurobi_solution_log/large_log_1.jsonl b/tasks/sadykov2013/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff551a53383c3e2701a7f0d7f2857b0c2963e2bf --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c334950df38626d23e90bdaab8c28e8134b1bc59e59d01d60a3c61f324e161df +size 169 diff --git a/tasks/sadykov2013/gurobi_solution_log/large_log_2.jsonl b/tasks/sadykov2013/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..94c7f7161ac9c606de8d93724cd9765ccdeb1217 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8024bde6e3ad381dd8b39e0d1ad36469b53fa0499aac6260fa42cc0bc32c7b7b +size 83 diff --git a/tasks/sadykov2013/gurobi_solution_log/large_log_3.jsonl b/tasks/sadykov2013/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6314e8b1eb6f9eea29e7471119473ec8cc70936a --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6b105b5877e0bd6c4c596a3c01bf4b4029d4c3012ab0e55400cb15cdfbda4e3 +size 167 diff --git a/tasks/sadykov2013/gurobi_solution_log/large_log_4.jsonl b/tasks/sadykov2013/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..852b0d60aed51afb328cd1dac61d8040f8f46ed4 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd9b6721e268e4a0f43a77b8cf2dd6535697eb772289e9708193003d5f960ffa +size 168 diff --git a/tasks/sadykov2013/gurobi_solution_log/large_log_5.jsonl b/tasks/sadykov2013/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..892ad527b986a0f2675587e1d0296bfd4d542884 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9bde842cda922974351ebc7fb444e3218e9823ff8045c7685c6d937d9ef3d43 +size 424 diff --git a/tasks/sadykov2013/gurobi_solution_log/tiny_log.jsonl b/tasks/sadykov2013/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ba84d5939d4f2c6ab7e036e5f10f6efb382c2fa8 --- /dev/null +++ b/tasks/sadykov2013/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26ca9a3345110e2866b0061895427740eec8b13694534700d681364089670486 +size 80 diff --git a/tasks/sadykov2013/instance/large_instance_1.json b/tasks/sadykov2013/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0870d624c38d33ab87cc5eaa1f700f31e75c090d --- /dev/null +++ b/tasks/sadykov2013/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14eb5b3bc678b5c9bda7e9e5533c8e6fc59ab6ff5f404c303827c7d41011c5d7 +size 139937 diff --git a/tasks/sadykov2013/instance/large_instance_2.json b/tasks/sadykov2013/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d48ee7bf422218a42348c858c34a43367a05a341 --- /dev/null +++ b/tasks/sadykov2013/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17e8b52fb9e2eb0c0afda36409535a39efe479434cba1d61377f05be4e6b080b +size 24880 diff --git a/tasks/sadykov2013/instance/large_instance_3.json b/tasks/sadykov2013/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..10ff0c02dcfe65b0a3f7e296b948f72560e398bd --- /dev/null +++ b/tasks/sadykov2013/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8e8783228da95a136743dd1157442394f2c4ccdcc1713d62a599c2c696e6ab7 +size 63234 diff --git a/tasks/sadykov2013/instance/large_instance_4.json b/tasks/sadykov2013/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..2eebf0716d4bb0b9cbd654d8f1b2d08777470425 --- /dev/null +++ b/tasks/sadykov2013/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93fa992001014b4ebc7b175726811ccb548eff47bf58c9d9fd83cbd64524392f +size 101597 diff --git a/tasks/sadykov2013/instance/large_instance_5.json b/tasks/sadykov2013/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f7d2070113c71cd7e95cf1bf02757011df2657ce --- /dev/null +++ b/tasks/sadykov2013/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08c898c5d502925a683a1c634f651661ed8bea13ff1ec7fd1c49d4901708617d +size 178336 diff --git a/tasks/sadykov2013/instance/tiny_instance.json b/tasks/sadykov2013/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a9594ecb8cb48a290e74946fc79f68378b9b4383 --- /dev/null +++ b/tasks/sadykov2013/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf341bb97b1186481c6206acf12f9e013c1bbce7a143e3d56b0ba15ddff69ea8 +size 19127 diff --git a/tasks/sadykov2013/instance_schema.json b/tasks/sadykov2013/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1459368fba57afa348a44a7f9366fb7d60aa899c --- /dev/null +++ b/tasks/sadykov2013/instance_schema.json @@ -0,0 +1,11 @@ +{ + "num_items": " Total number of items to be packed into bins.", + "bin_capacity": " Maximum total weight that each bin can hold.", + "items": [ + { + "id": " Unique identifier for the item.", + "weight": " Weight of the item." + } + ], + "conflict_edges": " Pairs of items that must not be placed in the same bin." +} \ No newline at end of file diff --git a/tasks/sadykov2013/mathematical_formulation.md b/tasks/sadykov2013/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3e4e622bfbc6f0f10ead63f430cee10bea412abf --- /dev/null +++ b/tasks/sadykov2013/mathematical_formulation.md @@ -0,0 +1,40 @@ +# Original Formulation: Bin Packing with Conflicts + +Sadykov & Vanderbeck. “Bin Packing with Conflicts: a Generic Branch-and-Price Algorithm.” Compact formulation (1a)–(1f). + +## Sets, Indices and Parameters + +- $V = \{1,\dots,n\}$: set of items. + +- $G = (V,E)$: conflict graph where $(i,j)\in E$ indicates items $i$ and $j$ cannot share a bin. + +- $K\le n$: upper bound on the number of identical bins. + +- $W\in\mathbb{Z}_+$: capacity of each bin. + +- $w_i \in \mathbb{Z}_+$: weight of item $i$, with $w_i\le W$. + +## Decision Variables + +$$\begin{align*} + x_{ik} &\in \{0,1\}, \quad i=1,\dots,n,\ k=1,\dots,K \quad + \text{($=1$ iff item $i$ is placed in bin $k$)} \\ + y_k &\in \{0,1\}, \quad k=1,\dots,K \quad + \text{($=1$ iff bin $k$ is used).} +\end{align*}$$ + +## Compact Formulation (1) + +$$\begin{align} +\min\ & \sum_{k=1}^{K} y_k \tag{1a} \\ +\text{s.t.}\ & \sum_{k=1}^{K} x_{ik} \ge 1, + && i = 1,\dots,n, \tag{1b} \\ +& \sum_{i=1}^{n} w_i\, x_{ik} \le W\, y_k, + && k = 1,\dots,K, \tag{1c} \\ +& x_{ik} + x_{jk} \le y_k, + && (i,j)\in E,\ k = 1,\dots,K, \tag{1d} \\ +& y_k \in \{0,1\}, + && k = 1,\dots,K, \tag{1e} \\ +& x_{ik} \in \{0,1\}, + && i = 1,\dots,n,\ k = 1,\dots,K. \tag{1f} +\end{align}$$ diff --git a/tasks/sadykov2013/problem_description.txt b/tasks/sadykov2013/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..26c0a12afef0bf691488aa9a926aadf44e1e146e --- /dev/null +++ b/tasks/sadykov2013/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +A collection of items must be packed into identical bins. Each item has a known non-negative integer weight, and every bin has the same integer capacity. In addition to the items and bins, a conflict graph is given: certain pairs of items are declared to be in conflict, meaning they must never be placed in the same bin. The input specifies the number of items, the capacity shared by all bins, the weight of each item (which does not exceed the bin capacity), and the list of conflicting item pairs. + +The task is to assign every item to at least one bin so that two rules are respected simultaneously. First, the total weight of all items assigned to any single bin must not exceed that bin's capacity. Second, no two items that form a conflicting pair may be assigned to the same bin. A bin is considered used if at least one item is assigned to it, and the number of available bins may be assumed large enough that a feasible packing always exists. The goal is to minimize the total number of bins used. diff --git a/tasks/sadykov2013/solution_logger.py b/tasks/sadykov2013/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/sadykov2013/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/sadykov2013/solution_schema.json b/tasks/sadykov2013/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..52753105e4a8466c974d4ab3e54ce1b86fe90fd3 --- /dev/null +++ b/tasks/sadykov2013/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total number of bins used to pack all items.", + "bins": { + "": { + "items": " Identifiers of the items packed into this bin.", + "total_weight": " Sum of the weights of the items packed into this bin." + } + } +} diff --git a/tasks/salemi2022/feasibility_check.py b/tasks/salemi2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa57cf16d117e8de927e09f940885a1da195c1b --- /dev/null +++ b/tasks/salemi2022/feasibility_check.py @@ -0,0 +1,596 @@ +""" +Feasibility checker for the two-stage stochastic Unit Commitment Problem (UCP) +from Salemi and Davarnia (2022). + +Constraints (numbered top-to-bottom from the formulation): + 1 (1b) Start-up cost linearisation + 2 (1c) Logical relation y - ybar = x_j - x_{j-1} + 3 (1d) Minimum up-time + 4 (1e) Minimum down-time + 5 (1f) Ramp-up + 6 (1g) Ramp-down + 7 (1h) Generation capacity bounds m*x <= p <= pbar <= M*x + 8 (1i) Demand satisfaction + 9 (1j) Spinning reserve + 10 (1k) Binary variable domains + 11 (1l) Non-negativity of q, p, pbar + 12 (Tier C obj recompute) Objective consistency: + reported objective_value must equal + sum_{i,j}(c_f^i x_j^i + q_j^i) + (1/S) sum_{i,j,s} c_g^i p_j^{i,s} +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'p', 'p_bar', 'q', 'x', 'y', 'y_bar') +_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 + + +# Bumped from 1e-5 to 1e-3 to absorb Gurobi numerical noise on large +# instances. 1e-5 was rejecting valid OPT solutions; 1e-3 keeps catch +# for genuine infeasibilities. +TOL = 1e-3 +EPS = 1e-3 + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def normalizer(rhs): + return max(abs(rhs), EPS) + + +def record(violations_list, magnitudes_list, constraint_idx, msg, lhs, rhs, viol_amount): + norm = normalizer(rhs) + violations_list.append((constraint_idx, msg)) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": lhs, + "rhs": rhs, + "raw_excess": viol_amount, + "normalizer": norm, + "ratio": viol_amount / norm, + }) + + +def check_feasibility(instance, solution): + """Return (feasible, violated_constraints, violations, violation_magnitudes).""" + + violations = [] # list of (constraint_idx, message) + magnitudes = [] # list of dicts + + # --- Unpack instance --- + n_gen = instance["n_generators"] + n_scen = instance["n_scenarios"] + T = instance["T"] + gens = instance["generators"] + demand = instance["demand_scenarios"] # [s][j] + reserve = instance["reserve_scenarios"] # [s][j] + + # --- Unpack solution --- + x = solution.get("x") + y = solution.get("y") + y_bar = solution.get("y_bar") + q = solution.get("q") + p = solution.get("p") # p[i][s][j] (gurobi format) + p_bar = solution.get("p_bar") # p_bar[i][s][j] + + # If the solution is empty / null (e.g. INFEASIBLE solver status), nothing to check + if x is None: + return True, [], [], [] # No solution to check; vacuously feasible + + # Derive y, y_bar from x if not provided (using constraint 1c definition) + if y is None: + y = [] + for i in range(n_gen): + yi = [] + for j in range(T): + x_prev = x[i][j - 1] if j > 0 else 0 + diff = x[i][j] - x_prev + yi.append(max(diff, 0)) + y.append(yi) + if y_bar is None: + y_bar = [] + for i in range(n_gen): + ybi = [] + for j in range(T): + x_prev = x[i][j - 1] if j > 0 else 0 + diff = x[i][j] - x_prev + ybi.append(max(-diff, 0)) + y_bar.append(ybi) + + # Derive q from x if not provided (set to minimum feasible value for checking) + if q is None: + q = [] + for i in range(n_gen): + K = gens[i]["startup_costs_K"] + qi = [] + for j in range(T): + max_q = 0.0 + # Paper (1b): k in {1,...,j-1} for 1-indexed j; with 0-indexed + # j the constraint set is k in {1,...,j} and is empty at j=0. + max_k = min(j, len(K)) + for k in range(1, max_k + 1): + past_sum = sum(x[i][j - h] for h in range(1, k + 1) if j - h >= 0) + val = K[k - 1] * (x[i][j] - past_sum) + if val > max_q: + max_q = val + qi.append(max(max_q, 0.0)) + q.append(qi) + + # ===================================================================== + # Constraint 1 (1b): Start-up cost linearisation + # q_j^i >= K_k^i * (x_j^i - sum_{h=1}^{k} x_{j-h}^i) + # for k in {1,...,j-1} (paper, 1-indexed). With 0-indexed j (j' = j-1) + # that becomes k in {1,...,j'} and is empty at j'=0 (paper's first + # period). gurobi_code.py:88 uses the same convention. + # ===================================================================== + for i in range(n_gen): + K = gens[i]["startup_costs_K"] + for j in range(T): + max_k = min(j, len(K)) + for k in range(1, max_k + 1): + past_sum = sum(x[i][j - h] for h in range(1, k + 1) if j - h >= 0) + rhs_val = K[k - 1] * (x[i][j] - past_sum) + lhs_val = q[i][j] + # Constraint: lhs >= rhs => violation if rhs - lhs > tol + viol = rhs_val - lhs_val + if viol > TOL: + record(violations, magnitudes, 1, + f"Startup cost violated: gen {i+1}, period {j+1}, k={k}: " + f"q={lhs_val:.4f} < K*(...) = {rhs_val:.4f}", + lhs_val, rhs_val, viol) + + # ===================================================================== + # Constraint 2 (1c): Logical relation + # y_j^i - ybar_j^i = x_j^i - x_{j-1}^i + # ===================================================================== + for i in range(n_gen): + for j in range(T): + x_prev = x[i][j - 1] if j > 0 else 0 + lhs_val = y[i][j] - y_bar[i][j] + rhs_val = x[i][j] - x_prev + viol = abs(lhs_val - rhs_val) + if viol > TOL: + record(violations, magnitudes, 2, + f"Logical relation violated: gen {i+1}, period {j+1}: " + f"y-ybar={lhs_val} != x_j-x_{{j-1}}={rhs_val}", + lhs_val, rhs_val, viol) + + # ===================================================================== + # Constraint 3 (1d): Minimum up-time + # sum_{j'=j-L+1}^{j} y_{j'}^i <= x_j^i + # for j in {L^i,...,T} (1-indexed) => j in {L-1,...,T-1} (0-indexed) + # ===================================================================== + for i in range(n_gen): + L = gens[i]["L"] + for j in range(L - 1, T): + lhs_val = sum(y[i][jp] for jp in range(j - L + 1, j + 1)) + rhs_val = x[i][j] + viol = lhs_val - rhs_val + if viol > TOL: + record(violations, magnitudes, 3, + f"Min up-time violated: gen {i+1}, period {j+1}: " + f"sum(y)={lhs_val} > x={rhs_val}", + lhs_val, rhs_val, viol) + + # ===================================================================== + # Constraint 4 (1e): Minimum down-time + # sum_{j'=j-ell+1}^{j} ybar_{j'}^i <= 1 - x_j^i + # for j in {ell^i,...,T} (1-indexed) => j in {ell-1,...,T-1} (0-indexed) + # ===================================================================== + for i in range(n_gen): + ell = gens[i]["ell"] + for j in range(ell - 1, T): + lhs_val = sum(y_bar[i][jp] for jp in range(j - ell + 1, j + 1)) + rhs_val = 1 - x[i][j] + viol = lhs_val - rhs_val + if viol > TOL: + record(violations, magnitudes, 4, + f"Min down-time violated: gen {i+1}, period {j+1}: " + f"sum(ybar)={lhs_val} > 1-x={rhs_val}", + lhs_val, rhs_val, viol) + + # ===================================================================== + # Constraints 5-9 require p, p_bar (per scenario) + # ===================================================================== + if p is not None and p_bar is not None: + for s in range(n_scen): + for i in range(n_gen): + RU = gens[i]["RU"] + SU = gens[i]["SU"] + RD = gens[i]["RD"] + SD = gens[i]["SD"] + m_cap = gens[i]["m"] + M_cap = gens[i]["M"] + + for j in range(T): + x_prev = x[i][j - 1] if j > 0 else 0 + p_ij = p[i][s][j] + p_prev = p[i][s][j - 1] if j > 0 else 0.0 + pbar_ij = p_bar[i][s][j] + + # ================================================= + # Constraint 5 (1f): Ramp-up + # p_j - p_{j-1} <= RU * x_{j-1} + SU * y_j + # ================================================= + lhs_val = p_ij - p_prev + rhs_val = RU * x_prev + SU * y[i][j] + viol = lhs_val - rhs_val + if viol > TOL: + record(violations, magnitudes, 5, + f"Ramp-up violated: gen {i+1}, period {j+1}, " + f"scenario {s+1}: LHS={lhs_val:.4f} > RHS={rhs_val:.4f}", + lhs_val, rhs_val, viol) + + # ================================================= + # Constraint 6 (1g): Ramp-down + # p_{j-1} - p_j <= RD * x_j + SD * ybar_j + # ================================================= + lhs_val = p_prev - p_ij + rhs_val = RD * x[i][j] + SD * y_bar[i][j] + viol = lhs_val - rhs_val + if viol > TOL: + record(violations, magnitudes, 6, + f"Ramp-down violated: gen {i+1}, period {j+1}, " + f"scenario {s+1}: LHS={lhs_val:.4f} > RHS={rhs_val:.4f}", + lhs_val, rhs_val, viol) + + # ================================================= + # Constraint 7 (1h): Capacity bounds + # m*x <= p <= pbar <= M*x + # ================================================= + # 7a: m*x <= p (p >= m*x) + lhs_val_7a = m_cap * x[i][j] + viol_7a = lhs_val_7a - p_ij + if viol_7a > TOL: + record(violations, magnitudes, 7, + f"Capacity lower bound violated: gen {i+1}, " + f"period {j+1}, scenario {s+1}: " + f"m*x={lhs_val_7a:.4f} > p={p_ij:.4f}", + p_ij, lhs_val_7a, viol_7a) + + # 7b: p <= pbar + viol_7b = p_ij - pbar_ij + if viol_7b > TOL: + record(violations, magnitudes, 7, + f"p > pbar violated: gen {i+1}, period {j+1}, " + f"scenario {s+1}: p={p_ij:.4f} > pbar={pbar_ij:.4f}", + p_ij, pbar_ij, viol_7b) + + # 7c: pbar <= M*x + rhs_val_7c = M_cap * x[i][j] + viol_7c = pbar_ij - rhs_val_7c + if viol_7c > TOL: + record(violations, magnitudes, 7, + f"Capacity upper bound violated: gen {i+1}, " + f"period {j+1}, scenario {s+1}: " + f"pbar={pbar_ij:.4f} > M*x={rhs_val_7c:.4f}", + pbar_ij, rhs_val_7c, viol_7c) + + # ================================================= + # Constraint 8 (1i): Demand satisfaction + # sum_i p_j^i >= D_j + # ================================================= + for j in range(T): + lhs_val = sum(p[i][s][j] for i in range(n_gen)) + rhs_val = demand[s][j] + viol = rhs_val - lhs_val # >= constraint: violation if rhs > lhs + if viol > TOL: + record(violations, magnitudes, 8, + f"Demand not met: period {j+1}, scenario {s+1}: " + f"sum(p)={lhs_val:.4f} < D={rhs_val:.4f}", + lhs_val, rhs_val, viol) + + # ================================================= + # Constraint 9 (1j): Spinning reserve + # sum_i pbar_j^i >= D_j + R_j + # ================================================= + for j in range(T): + lhs_val = sum(p_bar[i][s][j] for i in range(n_gen)) + rhs_val = demand[s][j] + reserve[s][j] + viol = rhs_val - lhs_val + if viol > TOL: + record(violations, magnitudes, 9, + f"Spinning reserve not met: period {j+1}, scenario {s+1}: " + f"sum(pbar)={lhs_val:.4f} < D+R={rhs_val:.4f}", + lhs_val, rhs_val, viol) + + # ===================================================================== + # Constraint 10 (1k): Binary variable domains + # x, y, ybar in {0, 1} + # ===================================================================== + for i in range(n_gen): + for j in range(T): + for var_name, var_val in [("x", x[i][j]), ("y", y[i][j]), + ("ybar", y_bar[i][j])]: + dist = min(abs(var_val - 0), abs(var_val - 1)) + if dist > TOL: + record(violations, magnitudes, 10, + f"Binary domain violated: gen {i+1}, period {j+1}: " + f"{var_name}={var_val}", + var_val, round(var_val), dist) + + # ===================================================================== + # Constraint 11 (1l): Non-negativity q, p, pbar >= 0 + # ===================================================================== + for i in range(n_gen): + for j in range(T): + if q[i][j] < -TOL: + record(violations, magnitudes, 11, + f"Non-negativity violated: gen {i+1}, period {j+1}: " + f"q={q[i][j]:.6f} < 0", + q[i][j], 0.0, -q[i][j]) + + if p is not None and p_bar is not None: + for i in range(n_gen): + for s in range(n_scen): + for j in range(T): + if p[i][s][j] < -TOL: + record(violations, magnitudes, 11, + f"Non-negativity violated: gen {i+1}, " + f"scenario {s+1}, period {j+1}: " + f"p={p[i][s][j]:.6f} < 0", + p[i][s][j], 0.0, -p[i][s][j]) + if p_bar[i][s][j] < -TOL: + record(violations, magnitudes, 11, + f"Non-negativity violated: gen {i+1}, " + f"scenario {s+1}, period {j+1}: " + f"pbar={p_bar[i][s][j]:.6f} < 0", + p_bar[i][s][j], 0.0, -p_bar[i][s][j]) + + # ===================================================================== + # Constraint 12 (Tier C): Objective consistency + # Recompute the expected total cost from the solution variables + # (formula 1a; second-stage component averaged across scenarios) + # and reject solutions whose reported objective_value disagrees. + # Defends against LLM exploits that lie about objective_value + # (e.g. obj=0 or obj=sys.float_info.max on otherwise feasible + # commitment+dispatch decisions). + # ===================================================================== + reported_obj = solution.get("objective_value") + if reported_obj is not None and p is not None: + try: + reported = float(reported_obj) + if not math.isfinite(reported): + raise ValueError("non-finite") + ok = True + except (TypeError, ValueError): + ok = False + if ok: + # First-stage cost: sum_{i,j} (c_f^i * x_j^i + q_j^i) + first_stage = 0.0 + for i in range(n_gen): + cf = gens[i]["c_f"] + for j in range(T): + first_stage += cf * x[i][j] + q[i][j] + # Expected second-stage production cost: + # (1/n_scen) * sum_{i,j,s} c_g^i * p[i][s][j] + second_stage = 0.0 + if n_scen > 0: + acc = 0.0 + for i in range(n_gen): + cg = gens[i]["c_g"] + for s in range(n_scen): + for j in range(T): + acc += cg * p[i][s][j] + second_stage = acc / n_scen + true_obj = first_stage + second_stage + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with a 1e-3 absolute floor. + tol_obj = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + record(violations, magnitudes, 12, + f"Objective consistency violated: reported " + f"objective_value={reported} differs from recomputed " + f"sum_{{i,j}}(c_f*x+q) + (1/S)*sum_{{i,j,s}}(c_g*p)=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={tol_obj:.3g})", + reported, true_obj, abs_diff) + + # --- Aggregate results --- + violated_indices = sorted(set(v[0] for v in violations)) + violation_msgs = [] + for idx in violated_indices: + msgs = [v[1] for v in violations if v[0] == idx] + # Aggregate: take first message and count + if len(msgs) == 1: + violation_msgs.append(msgs[0]) + else: + violation_msgs.append(f"{msgs[0]} (and {len(msgs)-1} more)") + + feasible = len(violated_indices) == 0 + return feasible, violated_indices, violation_msgs, magnitudes + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the stochastic UCP (Salemi & Davarnia 2022)." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + feasible, violated_constraints, violation_msgs, magnitudes = \ + check_feasibility(instance, solution) + + result = { + "feasible": feasible, + "violated_constraints": violated_constraints, + "violations": violation_msgs, + "violation_magnitudes": magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasible: {feasible}") + if violated_constraints: + print(f"Violated constraints: {violated_constraints}") + for msg in violation_msgs: + print(f" - {msg}") + 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/salemi2022/gurobi_code.py b/tasks/salemi2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..3cc7a2a4aedaaaa5ec763a5916c864fd0070a82c --- /dev/null +++ b/tasks/salemi2022/gurobi_code.py @@ -0,0 +1,308 @@ +""" +Stochastic Unit Commitment Problem (UCP) from Salemi and Davarnia (2022). + +Two-stage stochastic program: + First stage: commitment (x, y, y_bar binary) + startup cost (q continuous) + Second stage: production (p, p_bar continuous) per demand scenario + +Minimises first-stage costs plus expected second-stage production costs. +""" + +import argparse +import json +import time + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def build_model(instance): + n_gen = instance["n_generators"] + n_scen = instance["n_scenarios"] + T = instance["T"] + gens = instance["generators"] + demand = instance["demand_scenarios"] # [s][j] + reserve = instance["reserve_scenarios"] # [s][j] + + model = gp.Model("StochasticUCP") + model.setParam("Threads", 1) + + # Index ranges + periods = range(T) # 0-indexed: period j corresponds to j+1 in paper + generators = range(n_gen) + scenarios = range(n_scen) + + # ---- First-stage variables ---- + # x[i,j]: commitment status of generator i in period j + x = model.addVars(generators, periods, vtype=GRB.BINARY, name="x") + # y[i,j]: start-up indicator + y = model.addVars(generators, periods, vtype=GRB.BINARY, name="y") + # y_bar[i,j]: shut-down indicator + y_bar = model.addVars(generators, periods, vtype=GRB.BINARY, name="ybar") + # q[i,j]: start-up cost + q = model.addVars(generators, periods, lb=0.0, name="q") + + # ---- Second-stage variables ---- + # p[i,j,s]: production of generator i in period j under scenario s + p = model.addVars(generators, periods, scenarios, lb=0.0, name="p") + # p_bar[i,j,s]: available capacity + p_bar = model.addVars(generators, periods, scenarios, lb=0.0, name="pbar") + + # Initial conditions: x_0^i = 0 for all i (all generators start OFF) + # We handle this inline when j-1 or j-h references period 0 or earlier. + + # ---- Objective (1a) ---- + first_stage = gp.quicksum( + gens[i]["c_f"] * x[i, j] + q[i, j] + for i in generators + for j in periods + ) + second_stage = (1.0 / n_scen) * gp.quicksum( + gens[i]["c_g"] * p[i, j, s] + for i in generators + for j in periods + for s in scenarios + ) + model.setObjective(first_stage + second_stage, GRB.MINIMIZE) + + # ---- Constraint (1b): Start-up cost linearization ---- + # q_j^i >= K_k^i * (x_j^i - sum_{h=1}^{k} x_{j-h}^i) + # for k in {1, ..., j} (paper says k in {1,...,j-1} but j is 1-indexed; + # here j is 0-indexed so k in {1, ..., j+1-1} = {1,...,j} when j>=1, + # and for j=0 (first period), k can be 1 only with x_{-1}=0). + # Actually: paper j in {1,...,T}, k in {1,...,j-1}. With 0-indexing: + # j in {0,...,T-1}, k in {1,...,j} (since paper's j-1 maps to our j). + # For j=0 in paper (j=1), k in {1,...,0} is empty. But we also need k + # up to T for the full startup cost schedule. + # Corrected: paper says k in {1,...,j-1} for period j (1-indexed). + # 0-indexed: for period j, k in {1,...,j}. (paper j -> our j+1, so k <= j+1-1 = j) + # Also k is bounded by len(startup_costs_K) = T. + for i in generators: + K = gens[i]["startup_costs_K"] # K[k-1] = cost after k inactive periods + for j in periods: + # k ranges from 1 to j (0-indexed j corresponds to 1-indexed j+1) + # In paper: k in {1,...,j-1} for 1-indexed j, i.e. k in {1,...,j} for 0-indexed j + max_k = j # since paper's j-1 = our j when converting + # Also k <= T (length of K array) + max_k = min(max_k, len(K)) + for k in range(1, max_k + 1): + # sum_{h=1}^{k} x_{j-h}^i, where x for negative index = 0 + past_sum = gp.quicksum( + x[i, j - h] for h in range(1, k + 1) if j - h >= 0 + ) + model.addConstr( + q[i, j] >= K[k - 1] * (x[i, j] - past_sum), + name=f"startup_{i}_{j}_{k}" + ) + + # ---- Constraint (1c): Logical relation ---- + # y_j^i - y_bar_j^i = x_j^i - x_{j-1}^i, x_0^i = 0 + for i in generators: + for j in periods: + x_prev = x[i, j - 1] if j >= 1 else 0 + model.addConstr( + y[i, j] - y_bar[i, j] == x[i, j] - x_prev, + name=f"logical_{i}_{j}" + ) + + # ---- Constraint (1d): Minimum up-time ---- + # sum_{j'=j-L+1}^{j} y_{j'}^i <= x_j^i, for j >= L-1 (0-indexed) + for i in generators: + L = gens[i]["L"] + for j in range(L - 1, T): + model.addConstr( + gp.quicksum(y[i, jp] for jp in range(j - L + 1, j + 1)) <= x[i, j], + name=f"minup_{i}_{j}" + ) + + # ---- Constraint (1e): Minimum down-time ---- + # sum_{j'=j-ell+1}^{j} y_bar_{j'}^i <= 1 - x_j^i, for j >= ell-1 (0-indexed) + for i in generators: + ell = gens[i]["ell"] + for j in range(ell - 1, T): + model.addConstr( + gp.quicksum(y_bar[i, jp] for jp in range(j - ell + 1, j + 1)) + <= 1 - x[i, j], + name=f"mindown_{i}_{j}" + ) + + # ---- Per-scenario constraints ---- + for s in scenarios: + for i in generators: + RU = gens[i]["RU"] + SU = gens[i]["SU"] + RD = gens[i]["RD"] + SD = gens[i]["SD"] + m_cap = gens[i]["m"] + M_cap = gens[i]["M"] + + for j in periods: + x_prev = x[i, j - 1] if j >= 1 else 0 + p_prev = p[i, j - 1, s] if j >= 1 else 0 + + # (1f) Ramp-up + model.addConstr( + p[i, j, s] - p_prev <= RU * x_prev + SU * y[i, j], + name=f"rampup_{i}_{j}_{s}" + ) + + # (1g) Ramp-down + model.addConstr( + p_prev - p[i, j, s] <= RD * x[i, j] + SD * y_bar[i, j], + name=f"rampdown_{i}_{j}_{s}" + ) + + # (1h) Generation capacity bounds + model.addConstr( + p[i, j, s] >= m_cap * x[i, j], + name=f"pmin_{i}_{j}_{s}" + ) + model.addConstr( + p[i, j, s] <= p_bar[i, j, s], + name=f"p_le_pbar_{i}_{j}_{s}" + ) + model.addConstr( + p_bar[i, j, s] <= M_cap * x[i, j], + name=f"pbarmax_{i}_{j}_{s}" + ) + + # (1i) Demand satisfaction + for j in periods: + model.addConstr( + gp.quicksum(p[i, j, s] for i in generators) >= demand[s][j], + name=f"demand_{j}_{s}" + ) + + # (1j) Spinning reserve + for j in periods: + model.addConstr( + gp.quicksum(p_bar[i, j, s] for i in generators) + >= demand[s][j] + reserve[s][j], + name=f"reserve_{j}_{s}" + ) + + model.update() + return model, x, y, y_bar, q, p, p_bar + + +def solve_and_save(model, instance, x, y, y_bar, q, p, p_bar, solution_path): + n_gen = instance["n_generators"] + n_scen = instance["n_scenarios"] + T = instance["T"] + + model.optimize() + + result = { + "status": model.Status, + "status_name": { + GRB.OPTIMAL: "OPTIMAL", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + GRB.TIME_LIMIT: "TIME_LIMIT", + }.get(model.Status, str(model.Status)), + "objective_value": None, + "best_bound": None, + "mip_gap": None, + "solve_time": model.Runtime, + "x": None, + "y": None, + "y_bar": None, + "q": None, + "p": None, + "p_bar": None, + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["mip_gap"] = model.MIPGap + + # Extract first-stage solution + result["x"] = [ + [int(round(x[i, j].X)) for j in range(T)] + for i in range(n_gen) + ] + result["y"] = [ + [int(round(y[i, j].X)) for j in range(T)] + for i in range(n_gen) + ] + result["y_bar"] = [ + [int(round(y_bar[i, j].X)) for j in range(T)] + for i in range(n_gen) + ] + result["q"] = [ + [q[i, j].X for j in range(T)] + for i in range(n_gen) + ] + + # Extract second-stage solution + result["p"] = [ + [ + [p[i, j, s].X for j in range(T)] + for s in range(n_scen) + ] + for i in range(n_gen) + ] + result["p_bar"] = [ + [ + [p_bar[i, j, s].X for j in range(T)] + for s in range(n_scen) + ] + for i in range(n_gen) + ] + + with open(solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the stochastic UCP (Salemi & Davarnia 2022) with Gurobi." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to instance JSON file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the solution JSON file.") + parser.add_argument("--time_limit", type=float, default=3600, + help="Gurobi time limit in seconds (default: 3600).") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + with open(args.instance_path, "r") as f: + instance = json.load(f) + + model, x, y, y_bar, q, p, p_bar = build_model(instance) + model.setParam("TimeLimit", args.time_limit) + + result = solve_and_save(model, instance, x, y, y_bar, q, p, p_bar, + args.solution_path) + + print(f"Status: {result['status_name']}") + if result["objective_value"] is not None: + print(f"Objective: {result['objective_value']:.4f}") + print(f"Best bound: {result['best_bound']:.4f}") + print(f"MIP gap: {result['mip_gap']:.6f}") + print(f"Solve time: {result['solve_time']:.2f}s") + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/salemi2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/salemi2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/salemi2022/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/salemi2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/salemi2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/salemi2022/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/salemi2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/salemi2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/salemi2022/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/salemi2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/salemi2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/salemi2022/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/salemi2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/salemi2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/salemi2022/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/salemi2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/salemi2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/salemi2022/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/salemi2022/gurobi_solution/large_solution_1.json b/tasks/salemi2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0ea5399093aff3df490dd8a9ab1a5bc522cc8c3b --- /dev/null +++ b/tasks/salemi2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b157e422ae6d6af82bf854752ea1199dc1ab143664dcd27167b584adcaa8eb5 +size 7001295 diff --git a/tasks/salemi2022/gurobi_solution/large_solution_2.json b/tasks/salemi2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..f03dd330ca9dd0f754de10290b97cdb81fd34fd8 --- /dev/null +++ b/tasks/salemi2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b938bbd4677822d24a2bcb4628f23910884038bab79fe11dbf6e92c99ef1bc3 +size 7028876 diff --git a/tasks/salemi2022/gurobi_solution/large_solution_3.json b/tasks/salemi2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1c871f571ee79751063c2571ddda209f2bf93693 --- /dev/null +++ b/tasks/salemi2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53225deb9f391eccab9551dfc825839a3a892c3886b094c515e43f0396e3c901 +size 7035933 diff --git a/tasks/salemi2022/gurobi_solution/large_solution_4.json b/tasks/salemi2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..760396b16d4e0c1732264224f7ae97dcc0a395e8 --- /dev/null +++ b/tasks/salemi2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29d3a12ab7a5c19c984573c443af0fe8e81f5ed7a75c7ec3d2dadcea837da57b +size 7048037 diff --git a/tasks/salemi2022/gurobi_solution/large_solution_5.json b/tasks/salemi2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f2b94340be64244a491822a7913fc6ee8f51d8b3 --- /dev/null +++ b/tasks/salemi2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf6444161363576974d15d8b3ecbd767cb2e0c7605832b0b171cc39193fe1688 +size 7041635 diff --git a/tasks/salemi2022/gurobi_solution/tiny_solution.json b/tasks/salemi2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..18116ff2268610019f0c72b4fd5aa36a4cc06110 --- /dev/null +++ b/tasks/salemi2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47b397c2b45a43d928d4d2e67579e1ef2fa02b385de230bac1777d6cd7ee3507 +size 365843 diff --git a/tasks/salemi2022/gurobi_solution_log/large_log_1.jsonl b/tasks/salemi2022/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..00e0417dceddb1f2b6b1613e862b6f60380d1154 --- /dev/null +++ b/tasks/salemi2022/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf2609b9868a533dd0b5212af43f58d272a8aee372c988af7d7fc70177e66582 +size 681 diff --git a/tasks/salemi2022/gurobi_solution_log/large_log_2.jsonl b/tasks/salemi2022/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..71c8cffd8fc44996750cf50625873a3b3987a2fd --- /dev/null +++ b/tasks/salemi2022/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79e0a02bc6c540297e28d44052b2b666706cfaf7b2dcf94d55f97c651778e509 +size 683 diff --git a/tasks/salemi2022/gurobi_solution_log/large_log_3.jsonl b/tasks/salemi2022/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6d37268f45d14ab468cc2335d9dbab059d29678b --- /dev/null +++ b/tasks/salemi2022/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c2ae2733c8a2a001f4c272f76245dfc6a3e45fc412b83e5eec97d529c2f071d +size 682 diff --git a/tasks/salemi2022/gurobi_solution_log/large_log_4.jsonl b/tasks/salemi2022/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dbb4cc1cc04248addaac7823971be9a337f269ea --- /dev/null +++ b/tasks/salemi2022/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea1efc13a896abfe906da4b9295406c5f09a50215695cdfd1ad90f46a2c12e29 +size 568 diff --git a/tasks/salemi2022/gurobi_solution_log/large_log_5.jsonl b/tasks/salemi2022/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a2a0193f758c3109b885653a1aad2659ab64c59d --- /dev/null +++ b/tasks/salemi2022/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ef5fe72a283e701df109df905fdebab5222b2734140eb2d0da15ffca6e7aa9e +size 967 diff --git a/tasks/salemi2022/gurobi_solution_log/tiny_log.jsonl b/tasks/salemi2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9bb6c3340c33b3291e710b4120ef95c52e29b42b --- /dev/null +++ b/tasks/salemi2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:328f42aaf2018833ff72cba4e1b8ad72bdcdd541f50d71a3122ad563c3b6e69f +size 216 diff --git a/tasks/salemi2022/instance/large_instance_1.json b/tasks/salemi2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..8a10a86afd5cb580385a4adeea23fe10936e425b --- /dev/null +++ b/tasks/salemi2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9694f24eb79a35ece5ab9130ca4b90883b327a99cf246f689c784bd9e34d5379 +size 85486 diff --git a/tasks/salemi2022/instance/large_instance_2.json b/tasks/salemi2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..3857ca2dde59c9464144332fc4624e0340a5b06a --- /dev/null +++ b/tasks/salemi2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4874fe815a046be2b925f1852b088677edac2e465cf7d80da0f5ce1d3587930c +size 77228 diff --git a/tasks/salemi2022/instance/large_instance_3.json b/tasks/salemi2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..aab36ba062d85c03f785b0e4e312a635330a9503 --- /dev/null +++ b/tasks/salemi2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac85de69f2c47305625641772c404bbf39b070046bd4efcee2074fc902307efa +size 86113 diff --git a/tasks/salemi2022/instance/large_instance_4.json b/tasks/salemi2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..015f27b814553fad4148ff2bff2a3a4387e647e1 --- /dev/null +++ b/tasks/salemi2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ce7509ee340b5f09c72e1eac103792fd83ab342e5d8b4d056506284c5d9ea20 +size 104646 diff --git a/tasks/salemi2022/instance/large_instance_5.json b/tasks/salemi2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9b23a26bc2c36dea4351b0f22d7f51887c68b461 --- /dev/null +++ b/tasks/salemi2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:941673fc483e2ad2a81530ecd86b7e2f08b08d1e3d46e9e46dbdbf2d04774088 +size 76026 diff --git a/tasks/salemi2022/instance/tiny_instance.json b/tasks/salemi2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b35697d4e3f110858a6db9e4c4bd9b68b508118c --- /dev/null +++ b/tasks/salemi2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b516b751b7a35bbd58a118a8d9da2f31184dc8e293822c4dbfdfbbacd5c015c1 +size 40809 diff --git a/tasks/salemi2022/instance_schema.json b/tasks/salemi2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..33505d36d8063ef4730084deaa5d37ba721412d3 --- /dev/null +++ b/tasks/salemi2022/instance_schema.json @@ -0,0 +1,22 @@ +{ + "n_generators": " Number of thermal generators in the fleet.", + "n_scenarios": " Number of equally likely demand scenarios.", + "T": " Number of time periods in the planning horizon.", + "generators": [ + { + "M": " Maximum power output of the generator when running (MW).", + "m": " Minimum power output of the generator when running (MW).", + "L": " Minimum number of consecutive periods the generator must remain on once started.", + "ell": " Minimum number of consecutive periods the generator must remain off once shut down.", + "RU": " Maximum increase in production allowed between consecutive periods while the generator stays on (MW).", + "SU": " Maximum production allowed in the period the generator first turns on (MW).", + "RD": " Maximum decrease in production allowed between consecutive periods while the generator stays on (MW).", + "SD": " Maximum production allowed in the last period before the generator turns off (MW).", + "c_g": " Per-unit cost of power produced by the generator ($/MWh).", + "c_f": " Fixed operating cost paid in every period the generator is running ($).", + "startup_costs_K": " Cost of starting the generator after exactly k consecutive inactive periods, for k = 1 to T ($)." + } + ], + "demand_scenarios": " Power demand for each scenario in each time period (MW).", + "reserve_scenarios": " Spinning reserve requirement for each scenario in each time period (MW)." +} diff --git a/tasks/salemi2022/mathematical_formulation.md b/tasks/salemi2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..7c3a8a269146445d84ea76f80ff0acda6ffb680c --- /dev/null +++ b/tasks/salemi2022/mathematical_formulation.md @@ -0,0 +1,56 @@ +# Original Formulation: Unit Commitment Problem (UCP) + +Salemi & Davarnia. “On the Structure of Decision Diagram-Representable Mixed Integer Programs with Application to Unit Commitment.” Formulation (1a)–(1l). + +## Sets and Indices + +$N = \{1,\dots,n\}$: set of generators, indexed by $i$. +$\mathcal{T} = \{1,\dots,T\}$: set of time periods, indexed by $j$. + +## Parameters + +$c_f^i$: fixed operating (no-load) cost of generator $i$; $c_g^i$: variable production cost; $K_k^i$: start-up cost after $k$ consecutive inactive periods (linearization of a logarithmic start-up cost); $L^i \ge 1$: minimum up-time; $\ell^i \ge 1$: minimum down-time; $m^i$, $M^i$: minimum/maximum production capacity; $SU^i$, $SD^i$: start-up / shut-down ramp rates; $RU^i$, $RD^i$: ramp-up / ramp-down rates (assumed $SU^i\le RU^i$, $SD^i\le RD^i$); $D_j$: total demand at time $j$; $R_j$: spinning reserve requirement at time $j$. + +## Decision Variables + +$$\begin{align*} + x_j^i &\in \{0,1\}\quad + \text{commitment: $=1$ iff unit $i$ is up at time $j$;} \\ + y_j^i &\in \{0,1\}\quad + \text{start-up: $=1$ iff unit $i$ starts up at time $j$;} \\ + \bar{y}_j^i &\in \{0,1\}\quad + \text{shut-down: $=1$ iff unit $i$ shuts down at time $j$;} \\ + p_j^i &\ge 0\ \ \text{production of unit $i$ at time $j$;} \\ + \bar{p}_j^i &\ge 0\ \ \text{maximum available power of unit $i$ at time $j$;} \\ + q_j^i &\ge 0\ \ \text{start-up cost variable of unit $i$ at time $j$.} +\end{align*}$$ + +## Formulation (1) + +$$\begin{align} +\min\quad + & \sum_{i=1}^{n}\sum_{j=1}^{T} \bigl(c_f^i\, x_j^i + c_g^i\, p_j^i + q_j^i\bigr) \tag{1a}\\ +\text{s.t.}\quad + & q_j^i \ge K_k^i\!\left(x_j^i - \sum_{h=1}^{k} x_{j-h}^i\right), + && \!\!\!\!\!\!\!\!\forall k\in\{1,\dots,j-1\},\, j\in\mathcal{T},\, i\in N \tag{1b}\\ + & y_j^i - \bar{y}_j^i = x_j^i - x_{j-1}^i, + && \forall j\in\{1,\dots,T\},\, i\in N \tag{1c}\\ + & \sum_{j'=j-L^i+1}^{j} y_{j'}^i \le x_j^i, + && \forall j\in\{L^i,\dots,T\},\, i\in N \tag{1d}\\ + & \sum_{j'=j-\ell^i+1}^{j} \bar{y}_{j'}^i \le 1 - x_j^i, + && \forall j\in\{\ell^i,\dots,T\},\, i\in N \tag{1e}\\ + & p_j^i - p_{j-1}^i \le RU^i\, x_{j-1}^i + SU^i\, y_j^i, + && \forall j\in\mathcal{T},\, i\in N \tag{1f}\\ + & p_{j-1}^i - p_j^i \le RD^i\, x_j^i + SD^i\, \bar{y}_j^i, + && \forall j\in\mathcal{T},\, i\in N \tag{1g}\\ + & m^i\, x_j^i \le p_j^i \le \bar{p}_j^i \le M^i\, x_j^i, + && \forall j\in\mathcal{T},\, i\in N \tag{1h}\\ + & \sum_{i=1}^{n} p_j^i \ge D_j, + && \forall j\in\mathcal{T} \tag{1i}\\ + & \sum_{i=1}^{n} \bar{p}_j^i \ge D_j + R_j, + && \forall j\in\mathcal{T} \tag{1j}\\ + & x_j^i,\ y_j^i,\ \bar{y}_j^i \in \{0,1\}, + && \forall j\in\mathcal{T},\, i\in N \tag{1k}\\ + & q_j^i,\ p_j^i,\ \bar{p}_j^i \ge 0, + && \forall j\in\mathcal{T},\, i\in N. \tag{1l} +\end{align}$$ diff --git a/tasks/salemi2022/problem_description.txt b/tasks/salemi2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..6669fa86ca8d2718794bbd8dc39589d657ebdb7e --- /dev/null +++ b/tasks/salemi2022/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A power system operator manages a fleet of thermal generators over a discrete planning horizon consisting of a given number of time periods under demand uncertainty represented by a finite set of scenarios. Each generator has a fixed operating cost paid in every period the unit is running, a per-unit production cost applied to the power it generates, and a start-up cost that depends on how long the generator has been consecutively offline before restarting. The start-up cost is determined by a precomputed schedule that gives the cost of starting a generator after any given number of consecutive inactive periods; this schedule is nondecreasing, reflecting the physical principle that a unit that has been idle longer requires more energy to restart. Each generator also has a minimum and maximum power output when it is running, a minimum number of consecutive periods it must remain on once started, and a minimum number of consecutive periods it must remain off once shut down. Four ramping parameters govern how quickly each generator can change its output between consecutive periods: a ramp-up rate limiting the increase in production while the unit stays on, a start-up ramp rate limiting production in the period a unit first turns on, a ramp-down rate limiting the decrease in production while the unit stays on, and a shut-down ramp rate limiting production in the last period before a unit turns off. It is assumed that each generator's start-up ramp rate does not exceed its ramp-up rate, and its shut-down ramp rate does not exceed its ramp-down rate. All generators are assumed to be offline at the start of the planning horizon. + +The operator must make two kinds of decisions. First, for each generator and each time period, the operator decides whether to have the unit running, whether the unit is starting up, and whether it is shutting down; these on/off, start-up, and shut-down choices are made before uncertainty is revealed and must be the same across all scenarios. Second, given a particular demand scenario, the operator decides how much power each running generator produces and how much capacity each running generator makes available in each period; these production and availability decisions are made separately for each scenario. + +The start-up, shut-down, and commitment status of each generator are linked by the requirement that the difference between the start-up indicator and the shut-down indicator in any period equals the change in commitment status from the previous period to the current one. Once a generator starts up, it must remain on for at least as many consecutive periods as its minimum up-time requires; specifically, the total number of start-ups occurring within any window of consecutive periods equal in length to the minimum up-time and ending at a period where the unit is considered may not exceed the commitment status at that period. Symmetrically, once a generator shuts down, it must remain off for at least as many consecutive periods as its minimum down-time requires; the total number of shut-downs within any window equal in length to the minimum down-time and ending at a given period may not exceed one minus the commitment status at that period. + +The start-up cost incurred by a generator in a given period is at least as large as the precomputed start-up cost corresponding to a certain number of consecutive inactive periods, multiplied by the quantity obtained by subtracting from the current-period commitment status the sum of the commitment statuses over that same number of preceding periods, and this must hold for every such count of consecutive inactive periods from one up to the number of periods that have elapsed before the current one. When a generator is off, its production and available capacity are both zero. When a generator is on, its production is at least its minimum output and at most its available capacity, which is itself at most the generator's maximum output. The increase in a generator's production from one period to the next may not exceed the ramp-up rate multiplied by the previous-period commitment status, plus the start-up ramp rate multiplied by the current-period start-up indicator. The decrease in a generator's production from one period to the next may not exceed the ramp-down rate multiplied by the current-period commitment status, plus the shut-down ramp rate multiplied by the current-period shut-down indicator. + +In each scenario and each time period, the total production across all generators must meet or exceed the scenario's demand for that period. Additionally, the total available capacity across all generators must meet or exceed the sum of the scenario's demand and its spinning reserve requirement for that period. + +The goal is to minimize the total expected cost, computed as the sum of all generators' fixed operating costs and start-up costs over all periods (these are scenario-independent) plus the average across all scenarios of the total production costs for all generators over all periods. diff --git a/tasks/salemi2022/solution_logger.py b/tasks/salemi2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/salemi2022/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/salemi2022/solution_schema.json b/tasks/salemi2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f69dd6907d7fce606fed79c02e726e9361029f51 --- /dev/null +++ b/tasks/salemi2022/solution_schema.json @@ -0,0 +1,9 @@ +{ + "objective_value": " Total expected cost, combining the fixed operating and start-up costs of all generators across all periods with the average production cost across scenarios.", + "x": " Whether each generator is running in each period (1 = running, 0 = off).", + "y": " Whether each generator is starting up in each period (1 = starting up, 0 = not).", + "y_bar": " Whether each generator is shutting down in each period (1 = shutting down, 0 = not).", + "q": " Start-up cost charged to each generator in each period.", + "p": " Power produced by each generator in each period under each demand scenario.", + "p_bar": " Available power capacity of each generator in each period under each demand scenario." +} diff --git a/tasks/samarghandi2017/feasibility_check.py b/tasks/samarghandi2017/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1d0937b00d4668a266488b1034439e8de3da4a0 --- /dev/null +++ b/tasks/samarghandi2017/feasibility_check.py @@ -0,0 +1,545 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for F|nwt, d_j|C_max (No-Wait Flow Shop with Due Dates). + +Checks all hard constraints from Models I-V as listed in math_model.txt, +numbered sequentially from top to bottom: + + Model I : Constraints 1-11 (Eqs. 5-15) + Model II : Constraints 12-23 (Eqs. 18-29) + Model III: Constraints 24-31 (Eqs. 32-39) + Model IV : Constraints 32-34 (Eqs. 42-44) + Model V : Constraints 35-40 (Eqs. 46-51) + Constraint 41 (obj consistency): reported objective_value must equal the + makespan recomputed from the sequence (Tier C defense). + +This is the obj-recompute variant (feasibility_check_new.py); the original +feasibility_check.py is kept untouched. The makespan C_max is fully +determined by the sequence (the no-wait property fixes every start time +S_{ij}), so a *full recompute* applies: true_obj = max_j(S_{mj} + p_{mj}). +Constraint 41 rejects a solution whose self-reported objective_value +disagrees with that recomputed value. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'sequence') +_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 + + + +# --------------------------------------------------------------------------- +# Contribution matrix (Samarghandi algorithm, Section 3) +# --------------------------------------------------------------------------- + +def _compute_cjk(pj_orig, pk, m): + """Compute c_{j,k} for a pair of jobs using Samarghandi's algorithm.""" + pj = list(pj_orig) + t, w = 1, 0 + while True: + if t >= m: + return pk[m - 1] + if pj[t] >= pk[w]: + t += 1 + w += 1 + if t >= m: + return pk[m - 1] + else: + cum, z = 0, None + for h in range(t, m): + cum += pj[h] + if cum - pk[w] >= 0: + z = h + break + if z is None: + return max(0, sum(pk[w:]) - sum(pj[t:])) + pj[z] = sum(pj[t:z + 1]) - pk[w] + w += 1 + t = z + if t >= m: + return pk[m - 1] + + +def build_contribution_matrix(n, m, p): + """Build (n+1) x (n+1) contribution matrix C (1-indexed).""" + C = [[0] * (n + 1) for _ in range(n + 1)] + for k in range(1, n + 1): + C[0][k] = sum(p[i][k - 1] for i in range(m)) + for j in range(1, n + 1): + pj = [p[i][j - 1] for i in range(m)] + for k in range(1, n + 1): + if j != k: + pk = [p[i][k - 1] for i in range(m)] + C[j][k] = _compute_cjk(pj, pk, m) + return C + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for F|nwt, d_j|C_max" + ) + parser.add_argument("--instance_path", required=True, + help="Path to instance JSON file.") + parser.add_argument("--solution_path", required=True, + help="Path to candidate solution JSON file.") + parser.add_argument("--result_path", required=True, + help="Path to write feasibility result JSON file.") + args = parser.parse_args() + + with open(args.instance_path) as f: + 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 + + tol = 1e-5 + eps = 1e-5 + + n = inst["n_jobs"] + m = inst["n_machines"] + p = inst["processing_times"] # p[i][j] 0-indexed (machine i, job j) + dd = inst["due_dates"] # dd[j] 0-indexed + + seq = sol["sequence"] # 1-indexed job numbers + obj_val = sol.get("objective_value") + + violations = [] + violation_magnitudes = [] + violated_set = set() + + def record(idx, msg, lhs, rhs, raw_excess): + violated_set.add(idx) + violations.append(msg) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(raw_excess), + "normalizer": float(normalizer), + "ratio": float(raw_excess / normalizer), + }) + + # Handle null / empty sequence + if seq is None or len(seq) == 0: + result = { + "feasible": False, + "violated_constraints": [], + "violations": ["Solution has no sequence (infeasible or no solution found)"], + "violation_magnitudes": [], + } + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + return + + seq0 = [j - 1 for j in seq] # 0-indexed + + # ====================================================================== + # Derive Model I decision variables from sequence + # ====================================================================== + # Binary x_I[j][k] = 1 iff job k+1 immediately follows job j+1 + x_I = [[0] * n for _ in range(n)] + for pos in range(len(seq0) - 1): + x_I[seq0[pos]][seq0[pos + 1]] = 1 + + # Start times S[i][j] via no-wait property + S = [[0.0] * n for _ in range(m)] + first = seq0[0] + S[0][first] = 0.0 + for i in range(1, m): + S[i][first] = S[i - 1][first] + p[i - 1][first] + + for pos in range(1, len(seq0)): + prev_j = seq0[pos - 1] + curr_j = seq0[pos] + max_s0 = 0.0 + for i in range(m): + # S[i][curr] >= S[i][prev] + p[i][prev] (sequencing) + # S[i][curr] = S[0][curr] + sum_{l=0..i-1} p[l][curr] (no-wait) + offset_curr = sum(p[l][curr_j] for l in range(i)) + needed = S[i][prev_j] + p[i][prev_j] - offset_curr + if needed > max_s0: + max_s0 = needed + S[0][curr_j] = max_s0 + for i in range(1, m): + S[i][curr_j] = S[i - 1][curr_j] + p[i - 1][curr_j] + + # Big-M value (sum of all processing times) + M_val = sum(p[i][j] for i in range(m) for j in range(n)) + + # ====================================================================== + # Build contribution matrix C (1-indexed, size (n+1) x (n+1)) + # ====================================================================== + C = build_contribution_matrix(n, m, p) + + # ====================================================================== + # Derive Model II variables (with dummy jobs 0 and n+1) + # ====================================================================== + N2 = n + 2 + x_II = [[0] * N2 for _ in range(N2)] + x_II[0][seq[0]] = 1 + for pos in range(len(seq) - 1): + x_II[seq[pos]][seq[pos + 1]] = 1 + x_II[seq[-1]][n + 1] = 1 + + # u variables (MTZ subtour elimination) + u = [0] * N2 + u[0] = 1 + for pos in range(len(seq)): + u[seq[pos]] = pos + 2 + u[n + 1] = len(seq) + 2 + + # F variables (finish times via contribution matrix) + F = [0.0] * N2 + cum_c = 0.0 + for pos in range(len(seq)): + job_1 = seq[pos] + if pos == 0: + cum_c += C[0][job_1] + else: + cum_c += C[seq[pos - 1]][job_1] + F[job_1] = cum_c + F[n + 1] = cum_c + + # Extended contribution matrix C' for Model II (c'_{j,n+1}=0, c'_{n+1,k}=0) + Cp = [[0] * N2 for _ in range(N2)] + for j in range(n + 1): + for k in range(1, n + 1): + Cp[j][k] = C[j][k] + + # ====================================================================== + # Derive Model III variables (position-assignment) + # ====================================================================== + x_III = [[0] * n for _ in range(n)] + for l in range(min(n, len(seq0))): + if 0 <= seq0[l] < n: + x_III[l][seq0[l]] = 1 + + # L[l] = cumulative finish time at position l+1 (0-indexed) + L = [0.0] * n + L[0] = C[0][seq[0]] + for l in range(1, min(n, len(seq))): + L[l] = L[l - 1] + C[seq[l - 1]][seq[l]] + + # ###################################################################### + # CHECK ALL HARD CONSTRAINTS (numbered 1-40, top to bottom) + # ###################################################################### + + # ==== MODEL I ==== + + # Constraint 1 (Eq.5): C_max >= S_{mj} + p_{mj} for j=1..n [>=] + if obj_val is not None: + for j in range(n): + comp_j = S[m - 1][j] + p[m - 1][j] + va = comp_j - obj_val + if va > tol: + record(1, + f"Constraint 1 (Eq.5): C_max={obj_val} < completion " + f"of job {j+1}={comp_j}", + obj_val, comp_j, va) + + # Constraint 2 (Eq.6): S_{ik} + M(1-x_{jk}) >= S_{ij} + p_{ij} [>=] + for i in range(m): + for j in range(n): + for k in range(n): + lhs_v = S[i][k] + M_val * (1 - x_I[j][k]) + rhs_v = S[i][j] + p[i][j] + va = rhs_v - lhs_v + if va > tol: + record(2, + f"Constraint 2 (Eq.6): Sequencing violated " + f"i={i+1},j={j+1},k={k+1}: LHS={lhs_v} < RHS={rhs_v}", + lhs_v, rhs_v, va) + + # Constraint 3 (Eq.7): S_{(i+1)j} = S_{ij} + p_{ij} [=] + for i in range(m - 1): + for j in range(n): + lhs_v = S[i + 1][j] + rhs_v = S[i][j] + p[i][j] + va = abs(lhs_v - rhs_v) + if va > tol: + record(3, + f"Constraint 3 (Eq.7): No-wait violated " + f"i={i+1},j={j+1}: S={lhs_v} != {rhs_v}", + lhs_v, rhs_v, va) + + # Constraint 4 (Eq.8): S_{mj} + p_{mj} <= d_j [<=] + for j in range(n): + comp_j = S[m - 1][j] + p[m - 1][j] + va = comp_j - dd[j] + if va > tol: + record(4, + f"Constraint 4 (Eq.8): Due date violated job {j+1}: " + f"completion={comp_j} > d={dd[j]}", + comp_j, dd[j], va) + + # Constraint 5 (Eq.9): sum_j x_{jk} <= 1 for k=1..n [<=] + for k in range(n): + s = sum(x_I[j][k] for j in range(n)) + va = s - 1 + if va > tol: + record(5, + f"Constraint 5 (Eq.9): Job {k+1} has {s} predecessors (> 1)", + s, 1, va) + + # Constraint 6 (Eq.10): sum_k x_{jk} <= 1 for j=1..n [<=] + for j in range(n): + s = sum(x_I[j][k] for k in range(n)) + va = s - 1 + if va > tol: + record(6, + f"Constraint 6 (Eq.10): Job {j+1} has {s} successors (> 1)", + s, 1, va) + + # Constraint 7 (Eq.11): x_{jk} + x_{kj} <= 1 [<=] + for j in range(n): + for k in range(n): + if j != k: + s = x_I[j][k] + x_I[k][j] + va = s - 1 + if va > tol: + record(7, + f"Constraint 7 (Eq.11): Bidirectional link " + f"jobs {j+1} and {k+1}", + s, 1, va) + + # Constraint 8 (Eq.12): sum_{j,k} x_{jk} = n-1 [=] + total_x = sum(x_I[j][k] for j in range(n) for k in range(n)) + va = abs(total_x - (n - 1)) + if va > tol: + record(8, + f"Constraint 8 (Eq.12): Total links={total_x} != {n-1}", + total_x, n - 1, va) + + # Constraint 9 (Eq.13): x_{jj} = 0 [=] + for j in range(n): + va = abs(x_I[j][j]) + if va > tol: + record(9, + f"Constraint 9 (Eq.13): Self-loop job {j+1}", + x_I[j][j], 0, va) + + # Constraint 10 (Eq.14): S_{ij} >= 0 [>=] + for i in range(m): + for j in range(n): + if S[i][j] < -tol: + record(10, + f"Constraint 10 (Eq.14): S[{i+1}][{j+1}]={S[i][j]:.6f} < 0", + S[i][j], 0, -S[i][j]) + + # Constraint 11 (Eq.15): x_{jk} in {0,1} + for j in range(n): + for k in range(n): + v = x_I[j][k] + if v not in (0, 1): + va = min(abs(v), abs(v - 1)) + record(11, + f"Constraint 11 (Eq.15): x[{j+1}][{k+1}]={v} not binary", + v, round(v), va) + + # ==== MODELS II, III, IV, V SKIPPED ==== + # These are reformulation models (contribution matrix + MTZ / position- + # assignment / CP disjunctive) that operate on auxiliary variables + # (u, F, x_II, x_III, L) derived from the sequence. A generated algorithm + # operating on the F|nwt,d_j|Cmax problem description need produce only the + # sequence; Model I checks already cover the business feasibility, and + # Models II-V are equivalent restatements that add no constraint power. + + # ==== OBJECTIVE CONSISTENCY (Tier C defense) ==== + # Constraint 41: the reported objective_value must equal the makespan + # recomputed from the sequence. The objective of Model I is + # min C_max (Eq.4); for any fixed sequence the no-wait property fixes + # every start time S_{ij}, so the makespan is fully determined: + # true_obj = max_j ( S_{mj} + p_{mj} ). + # This is a *full recompute* -- every variable the objective depends on + # is implied by the sequence. The original checker's constraint 1 + # (Eq.5) already rejects an under-reported C_max (C_max >= each + # completion); constraint 41 additionally rejects an over-reported or + # otherwise inconsistent C_max, closing the obj=MAX_FLOAT score-gaming + # gap and making the objective check exact. + if obj_val is not None: + try: + reported_obj = float(obj_val) + except (TypeError, ValueError): + reported_obj = None + if reported_obj is not None: + true_obj = max(S[m - 1][j] + p[m - 1][j] for j in range(n)) + abs_diff = abs(reported_obj - 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(41, + f"Constraint 41 (objective consistency): reported " + f"objective_value={reported_obj} differs from " + f"recomputed makespan max_j(S_mj+p_mj)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={obj_tol:.6g})", + reported_obj, true_obj, abs_diff) + + # ====================================================================== + # Output result + # ====================================================================== + feasible = len(violated_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + print(f"Feasible: {feasible}") + if not feasible: + print(f"Violated constraints: {sorted(violated_set)}") + 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/samarghandi2017/gurobi_code.py b/tasks/samarghandi2017/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..9e87ce8290eee6d92aba5615560fcc6b3a3718eb --- /dev/null +++ b/tasks/samarghandi2017/gurobi_code.py @@ -0,0 +1,371 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of Model I for F|nwt, d_j|C_max +(No-Wait Flow Shop Scheduling with Due Date Constraints) + +Source: Samarghandi & Behroozi (2017), Computers and Operations Research 81, pp. 141-159 + +Model I is a Mixed Integer Programming formulation that works directly with +processing times (does not require pre-computation of the contribution matrix). + +Decision variables: + x_{jk} in {0,1}: 1 if job J_k is placed immediately after job J_j in the sequence + S_{ij} >= 0 : starting time of i-th operation of job J_j (continuous) + C_max >= 0 : makespan (continuous) + +Objective: minimize C_max + +Constraints (equations reference paper numbering): + (5) C_max >= S_{mj} + p_{mj} for all j + (6) S_{ik} + M*(1-x_{jk}) >= S_{ij} + p_{ij} for all i,j,k [big-M sequencing] + (7) S_{(i+1)j} = S_{ij} + p_{ij} for all i= 0 + (15) x_{jk} in {0,1} + +NOTE on big-M (Eq. 6): The paper warns that choosing M too large causes CPLEX to +eliminate it in pre-solve. The paper recommends indicator constraints as an alternative +but notes the original big-M formulation performs better overall (Section 6.1). +INFERRED ASSUMPTION: M is set to the sum of all processing times, which is a safe +upper bound on any start time S_{ij} + p_{ij} in a feasible schedule. + +NOTE on sub-tour elimination: The time-indexed variables S_{ij} with positive +processing times implicitly prevent sub-tours, so no MTZ-style constraints are needed. +""" + +import argparse +import json +import sys +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("ERROR: gurobipy not found. Install Gurobi and its Python API.") + sys.exit(1) + + +def load_instance(path): + """Load problem instance from JSON file. + + Returns: + n : number of jobs + m : number of machines + p : processing_times[i][j] = p_{i+1, j+1} (0-indexed; machine i+1, job j+1) + d : due_dates[j] = d_{j+1} (0-indexed) + """ + with open(path, "r") as f: + data = json.load(f) + n = data["n_jobs"] + m = data["n_machines"] + p = data["processing_times"] # p[i][j] 0-indexed + d = data["due_dates"] # d[j] 0-indexed + return n, m, p, d + + +def compute_makespan(seq_0indexed, n, m, p): + """Recompute the no-wait flow shop makespan C_max from a job permutation. + + Mirrors the start-time recursion in feasibility_check.py so that the + reported objective_value equals evaluate(sequence) exactly, eliminating + MIPGap-induced drift between model.ObjVal (continuous) and the true + integer-feasible makespan. + """ + if not seq_0indexed: + return None + S = [[0.0] * n for _ in range(m)] + first = seq_0indexed[0] + S[0][first] = 0.0 + for i in range(1, m): + S[i][first] = S[i - 1][first] + p[i - 1][first] + for pos in range(1, len(seq_0indexed)): + prev_j = seq_0indexed[pos - 1] + curr_j = seq_0indexed[pos] + max_s0 = 0.0 + for i in range(m): + offset_curr = sum(p[l][curr_j] for l in range(i)) + needed = S[i][prev_j] + p[i][prev_j] - offset_curr + if needed > max_s0: + max_s0 = needed + S[0][curr_j] = max_s0 + for i in range(1, m): + S[i][curr_j] = S[i - 1][curr_j] + p[i - 1][curr_j] + return max(S[m - 1][j] + p[m - 1][j] for j in seq_0indexed) + + +def extract_sequence(x_vals, n): + """Reconstruct the job permutation from the x variable values. + + Builds a successor map then walks from the unique first job + (the job with no predecessor) to produce an ordered sequence. + Returns a 0-indexed list of jobs. + """ + successor = {} + for j in range(n): + for k in range(n): + if j != k and x_vals.get((j, k), 0) > 0.5: + successor[j] = k + + # First job = job with no predecessor among those that appear as a successor + all_jobs = set(range(n)) + jobs_with_predecessor = set(successor.values()) + first_candidates = all_jobs - jobs_with_predecessor + + if not first_candidates: + # Fallback: arbitrary order (should not happen in a valid solution) + return list(range(n)) + + first = next(iter(first_candidates)) + seq = [first] + visited = {first} + cur = first + while cur in successor: + nxt = successor[cur] + if nxt in visited: + break + seq.append(nxt) + visited.add(nxt) + cur = nxt + + # Append any jobs not reached (safety fallback) + for j in range(n): + if j not in visited: + seq.append(j) + + return seq + + +def solve(n, m, p, d, time_limit): + """Build and solve Model I using Gurobi. + + Args: + n : number of jobs + m : number of machines + p[i][j] : processing time (0-indexed: machine i+1, job j+1) + d[j] : due date (0-indexed: job j+1) + time_limit : maximum solver runtime in seconds (int) + + Returns: + dict with keys: status, objective_value, sequence + """ + # ---------------------------------------------------------------- + # Big-M: upper bound on any possible S_{ij} + p_{ij}. + # Sum of ALL processing times is a safe (if loose) upper bound. + # INFERRED ASSUMPTION: paper only states "M is a sufficiently large + # number" without giving an exact value (math_model.txt note 10). + # ---------------------------------------------------------------- + M = sum(p[i][j] for i in range(m) for j in range(n)) + + model = gp.Model("NoWaitFlowShop_ModelI") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # ------------------------------------------------------------------ + # Decision variables + # ------------------------------------------------------------------ + # Binary assignment: x[j,k] = 1 <=> J_{k+1} immediately follows J_{j+1} + x = {} + for j in range(n): + for k in range(n): + x[j, k] = model.addVar(vtype=GRB.BINARY, name=f"x_{j+1}_{k+1}") + + # Starting times: S[i,j] = starting time of (i+1)-th operation of J_{j+1} + S = {} + for i in range(m): + for j in range(n): + S[i, j] = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, + name=f"S_{i+1}_{j+1}") + + # Makespan + C_max = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, name="C_max") + + model.update() + + # ------------------------------------------------------------------ + # Objective: minimize C_max (Eq. 4) + # ------------------------------------------------------------------ + model.setObjective(C_max, GRB.MINIMIZE) + + # ------------------------------------------------------------------ + # Constraint (5): C_max >= S_{mj} + p_{mj} for j = 1,...,n + # ------------------------------------------------------------------ + for j in range(n): + model.addConstr( + C_max >= S[m - 1, j] + p[m - 1][j], + name=f"Cmax_lb_{j+1}" + ) + + # ------------------------------------------------------------------ + # Constraint (6): S_{ik} + M*(1-x_{jk}) >= S_{ij} + p_{ij} + # for i=1,...,m; j,k=1,...,n (j != k, since x_{jj}=0) + # ------------------------------------------------------------------ + for i in range(m): + for j in range(n): + for k in range(n): + if j != k: + model.addConstr( + S[i, k] + M * (1 - x[j, k]) >= S[i, j] + p[i][j], + name=f"Seq_{i+1}_{j+1}_{k+1}" + ) + + # ------------------------------------------------------------------ + # Constraint (7): S_{(i+1)j} = S_{ij} + p_{ij} (no-wait) + # for i=1,...,m-1; j=1,...,n + # ------------------------------------------------------------------ + for i in range(m - 1): + for j in range(n): + model.addConstr( + S[i + 1, j] == S[i, j] + p[i][j], + name=f"NoWait_{i+1}_{j+1}" + ) + + # ------------------------------------------------------------------ + # Constraint (8): S_{mj} + p_{mj} <= d_j (due date) + # for j = 1,...,n + # ------------------------------------------------------------------ + for j in range(n): + model.addConstr( + S[m - 1, j] + p[m - 1][j] <= d[j], + name=f"DueDate_{j+1}" + ) + + # ------------------------------------------------------------------ + # Constraint (9): sum_j x_{jk} <= 1 for k = 1,...,n + # ------------------------------------------------------------------ + for k in range(n): + model.addConstr( + gp.quicksum(x[j, k] for j in range(n)) <= 1, + name=f"InDeg_{k+1}" + ) + + # ------------------------------------------------------------------ + # Constraint (10): sum_k x_{jk} <= 1 for j = 1,...,n + # ------------------------------------------------------------------ + for j in range(n): + model.addConstr( + gp.quicksum(x[j, k] for k in range(n)) <= 1, + name=f"OutDeg_{j+1}" + ) + + # ------------------------------------------------------------------ + # Constraint (11): x_{jk} + x_{kj} <= 1 for j,k = 1,...,n + # ------------------------------------------------------------------ + for j in range(n): + for k in range(j + 1, n): + model.addConstr( + x[j, k] + x[k, j] <= 1, + name=f"Antipar_{j+1}_{k+1}" + ) + + # ------------------------------------------------------------------ + # Constraint (12): sum_{j,k} x_{jk} = n-1 + # ------------------------------------------------------------------ + model.addConstr( + gp.quicksum(x[j, k] for j in range(n) for k in range(n)) == n - 1, + name="TotalLinks" + ) + + # ------------------------------------------------------------------ + # Constraint (13): x_{jj} = 0 for j = 1,...,n + # ------------------------------------------------------------------ + for j in range(n): + model.addConstr(x[j, j] == 0, name=f"NoDiag_{j+1}") + + # ------------------------------------------------------------------ + # Solve + # ------------------------------------------------------------------ + model.optimize() + + # ------------------------------------------------------------------ + # Extract and return result + # ------------------------------------------------------------------ + result = {} + status = model.Status + + if status == GRB.INFEASIBLE: + result["status"] = "INFEASIBLE" + result["objective_value"] = None + result["sequence"] = None + + elif model.SolCount > 0: + # Read x variable values and reconstruct the permutation first + x_vals = {(j, k): x[j, k].X for j in range(n) for k in range(n) if j != k} + seq_0indexed = extract_sequence(x_vals, n) + result["sequence"] = [j + 1 for j in seq_0indexed] # 1-indexed output + + # Report objective_value = evaluate(sequence). Saves Gurobi's bound-driven + # value separately for diagnostics; it can drift below the true makespan + # by up to MIPGap. + result["objective_value"] = compute_makespan(seq_0indexed, n, m, p) + result["solver_obj_val"] = float(model.ObjVal) + try: + result["mip_gap"] = float(model.MIPGap) + except Exception: + result["mip_gap"] = None + + if status == GRB.OPTIMAL: + result["status"] = "OPTIMAL" + else: + result["status"] = "TIME_LIMIT_FEASIBLE" + + else: + result["status"] = "NO_SOLUTION_FOUND" + result["objective_value"] = None + result["sequence"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi Model I for F|nwt, d_j|C_max (Samarghandi & Behroozi 2017)" + ) + 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 where the solution JSON will be written.") + parser.add_argument("--time_limit", type=int, default=3600, + help="Maximum solver runtime in seconds (default: 3600).") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + n, m, p, d = load_instance(args.instance_path) + print(f"Loaded instance: {n} jobs, {m} machines") + print(f"Time limit: {args.time_limit} s") + + result = solve(n, m, p, d, 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"Objective value : {result['objective_value']}") + if result.get("sequence"): + print(f"Sequence : {result['sequence']}") + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/samarghandi2017/gurobi_feasi_result/large_feasi_result_1.json b/tasks/samarghandi2017/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/samarghandi2017/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/samarghandi2017/gurobi_feasi_result/large_feasi_result_2.json b/tasks/samarghandi2017/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/samarghandi2017/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/samarghandi2017/gurobi_feasi_result/large_feasi_result_3.json b/tasks/samarghandi2017/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/samarghandi2017/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/samarghandi2017/gurobi_feasi_result/large_feasi_result_4.json b/tasks/samarghandi2017/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/samarghandi2017/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/samarghandi2017/gurobi_feasi_result/large_feasi_result_5.json b/tasks/samarghandi2017/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/samarghandi2017/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/samarghandi2017/gurobi_feasi_result/tiny_feasi_result.json b/tasks/samarghandi2017/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/samarghandi2017/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/samarghandi2017/gurobi_solution/large_solution_1.json b/tasks/samarghandi2017/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..99c1928dc90aa1b40ed00f5d00fb63186c0ab386 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df9d465e3e1d7e5a2ed9755928c10b12ba9493ca00ceee3fca984de78b2770c6 +size 331 diff --git a/tasks/samarghandi2017/gurobi_solution/large_solution_2.json b/tasks/samarghandi2017/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a901f9a21fa859eb3943d61596b5badf7230f6de --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:552e94072475021c3c5b463dc6778a867c4f8ea773d81f35890536d31d4567de +size 321 diff --git a/tasks/samarghandi2017/gurobi_solution/large_solution_3.json b/tasks/samarghandi2017/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..5bcd6239afa2e58094a0c642ecff615d5e439df6 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:826fb1587923ed6f45294d589f6f7b1d7f9d42a2514c6d7b36dd859a508e7f81 +size 320 diff --git a/tasks/samarghandi2017/gurobi_solution/large_solution_4.json b/tasks/samarghandi2017/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..51db5b047ef9ab07b3cc5a50adb5a5d464f7376b --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6e25546e7fda0c7c953cbaca06797c81a65375b0e88b0ee5d30eae32ae7cd6d +size 321 diff --git a/tasks/samarghandi2017/gurobi_solution/large_solution_5.json b/tasks/samarghandi2017/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..b07dda68324010cc967081c343786519d5ca8aa1 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fd2705c03915306750c9bc214dae6668bd0845eb272f2eb962037689aaadd46 +size 333 diff --git a/tasks/samarghandi2017/gurobi_solution/tiny_solution.json b/tasks/samarghandi2017/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..8600755095ab1e3e9aa0239b9c8bf6dae90dc6f7 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab17e9815899013cd19bac7ebe536ff59a66cf653d5e094358dc3fae44b7a994 +size 186 diff --git a/tasks/samarghandi2017/gurobi_solution_log/large_log_1.jsonl b/tasks/samarghandi2017/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b6dc2dc5b59d9dbade8463409c8b74f29d535a93 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:442fefef6db7753317f3dbdb20887173dd218fea99f57982bb9f47fc519ed80f +size 1625 diff --git a/tasks/samarghandi2017/gurobi_solution_log/large_log_2.jsonl b/tasks/samarghandi2017/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..da74b47d7cf1cda7c904b5c04eb2ec2e89c6d6c3 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4c5f40780b0c41a3475d5d16efe57c4d99f63b6ca23ff5e9cf045b0f88d2754 +size 1123 diff --git a/tasks/samarghandi2017/gurobi_solution_log/large_log_3.jsonl b/tasks/samarghandi2017/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..578733ea1df30904eae35ec2064c966145057929 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71881676ffc066c5ecb4ffb2f0a000b6c78abcab7d68de562ada56a623ba63b8 +size 588 diff --git a/tasks/samarghandi2017/gurobi_solution_log/large_log_4.jsonl b/tasks/samarghandi2017/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6afafbf59e26fec8689c403c8173e81400d54096 --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:269c73ac0b3cf475880db5b7b502175a0b2581301c2b8def5738fef85ed4f14c +size 1169 diff --git a/tasks/samarghandi2017/gurobi_solution_log/large_log_5.jsonl b/tasks/samarghandi2017/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..51c6b861be7e77d64c83ab2aefd892c7987f81ce --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62cb2cf2c92394da523086f42e4128035e48fe6b3b91e34d14cb186c331262e2 +size 779 diff --git a/tasks/samarghandi2017/gurobi_solution_log/tiny_log.jsonl b/tasks/samarghandi2017/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..16fb2f8c21176bc7b5d6b7a5270797917b9c834f --- /dev/null +++ b/tasks/samarghandi2017/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52f0c314976a4a9d80a68e70a077b278a2c9276f25d973c2d699e7363acd0692 +size 84 diff --git a/tasks/samarghandi2017/instance/large_instance_1.json b/tasks/samarghandi2017/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c94dd293a9eb589fe6cd16d905cf3ecc986cd612 --- /dev/null +++ b/tasks/samarghandi2017/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d225f74f2f155b3e2f30d0a6850bd21b6534bd880a14bd1e64936e69bef4f43 +size 2691 diff --git a/tasks/samarghandi2017/instance/large_instance_2.json b/tasks/samarghandi2017/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..145393a1d12f89ef7da1e8599d9c55828f520fc2 --- /dev/null +++ b/tasks/samarghandi2017/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2dc06a9fe9e119dfc192974432bd9adc1082f044ba3cde71b612e74383e0a829 +size 2771 diff --git a/tasks/samarghandi2017/instance/large_instance_3.json b/tasks/samarghandi2017/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b55649b03ab3b3e9fb6668638249a37c12c1119c --- /dev/null +++ b/tasks/samarghandi2017/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5dbbf599d61df731414c79b50a9eeb5f26508941c6b86c11d4c75ef48699bebc +size 2770 diff --git a/tasks/samarghandi2017/instance/large_instance_4.json b/tasks/samarghandi2017/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..faee05958207db15da4e4d49132918214db326ba --- /dev/null +++ b/tasks/samarghandi2017/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8266155bec41c756e4b51c0ba6ad8aaa36e739267c2db870091592fde74a9e87 +size 2866 diff --git a/tasks/samarghandi2017/instance/large_instance_5.json b/tasks/samarghandi2017/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..fcd26272297f594abf3bc443ef3247ba5e718d20 --- /dev/null +++ b/tasks/samarghandi2017/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0ef7b23fd9e78fbc79fdc5a74fca6c61fea160cbe5f7b7eb7ff3f98e220cf64 +size 2864 diff --git a/tasks/samarghandi2017/instance/tiny_instance.json b/tasks/samarghandi2017/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..a4af75705ffe434504d652b87eff615961714c91 --- /dev/null +++ b/tasks/samarghandi2017/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a432a7e3d0265ee3aa6be2aa6dbd92863823e713144b62a54ce3913935df1b89 +size 781 diff --git a/tasks/samarghandi2017/instance_schema.json b/tasks/samarghandi2017/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..af020aa3aebbba9f71d882e06fa07b2b5db3292a --- /dev/null +++ b/tasks/samarghandi2017/instance_schema.json @@ -0,0 +1,6 @@ +{ + "n_jobs": " Number of jobs to be processed through the flow shop.", + "n_machines": " Number of machines arranged in series that every job must visit.", + "processing_times": " Time required for each machine to process each job.", + "due_dates": " Latest allowable completion time on the last machine for each job." +} \ No newline at end of file diff --git a/tasks/samarghandi2017/mathematical_formulation.md b/tasks/samarghandi2017/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f0b395b303b68aacf5bdef9135fb26d1686c238f --- /dev/null +++ b/tasks/samarghandi2017/mathematical_formulation.md @@ -0,0 +1,40 @@ +# Sets and Parameters + +- $m$: number of machines; index $i = 1,\ldots,m$. + +- $n$: number of jobs; index $j,k = 1,\ldots,n$. Job $j$ is denoted $J_j$. + +- $p_{ij}$: processing time of the $i$-th operation of $J_j$. + +- $d_j$: due date of $J_j$. + +- $M$: a sufficiently large constant (big-$M$). + +# Decision Variables + +$$\begin{equation} +x_{jk} = \begin{cases} 1 & \text{if } J_k \text{ is placed immediately after } J_j \text{ in the sequence}, \\ 0 & \text{otherwise}, \end{cases} +\quad j,k = 1,2,\ldots,n \tag{3} +\end{equation}$$ Continuous variables: $S_{ij} \geq 0$ (starting time of the $i$-th operation of $J_j$); $C_{\max} \geq 0$. + +# Objective + +$$\begin{equation} +\text{minimize} \quad C_{\max} \tag{4} +\end{equation}$$ + +# Constraints + +$$\begin{align} +C_{\max} &\geq S_{mj} + p_{mj} && j = 1,2,\ldots,n \tag{5} \\ +S_{ik} + M\bigl(1 - x_{jk}\bigr) &\geq S_{ij} + p_{ij} && i = 1,\ldots,m;\; j,k = 1,\ldots,n \tag{6} \\ +S_{(i+1)j} &= S_{ij} + p_{ij} && i = 1,\ldots,m-1;\; j = 1,\ldots,n \tag{7} \\ +S_{mj} + p_{mj} &\leq d_j && j = 1,2,\ldots,n \tag{8} \\ +\sum_{j=1}^{n} x_{jk} &\leq 1 && k = 1,2,\ldots,n \tag{9} \\ +\sum_{k=1}^{n} x_{jk} &\leq 1 && j = 1,2,\ldots,n \tag{10} \\ +x_{jk} + x_{kj} &\leq 1 && j,k = 1,2,\ldots,n \tag{11} \\ +\sum_{j=1}^{n}\sum_{k=1}^{n} x_{jk} &= n-1 \tag{12} \\ +x_{jj} &= 0 && j = 1,2,\ldots,n \tag{13} \\ +S_{ij} &\geq 0 && i = 1,\ldots,m;\; j = 1,\ldots,n \tag{14} \\ +x_{jk} &\in \{0,1\} && j,k = 1,2,\ldots,n \tag{15} +\end{align}$$ diff --git a/tasks/samarghandi2017/problem_description.txt b/tasks/samarghandi2017/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..f1a5f1a7cd50f821bcd649c889502a5265805ce5 --- /dev/null +++ b/tasks/samarghandi2017/problem_description.txt @@ -0,0 +1,9 @@ +# Problem Description + +A manufacturing facility processes a set of jobs on machines arranged in series, forming a flow shop. Every job must visit all machines in the same fixed order, from the first machine through the last machine, and every job has a known processing time on each machine. All jobs are available for processing at time zero, no preemption or interruption of any operation is permitted, each machine can handle only one job at a time, and no job can be on more than one machine simultaneously. Crucially, no waiting is allowed between consecutive operations of the same job: once a job finishes on one machine, it must start immediately on the next machine with zero delay. Each job also has a given due date by which its last operation must be completed; this is a hard requirement that cannot be violated. + +Because of the no-wait restriction, the schedule is fully determined by a single permutation of the jobs, since the order in which jobs visit the machines is identical across all machines. The planner must therefore determine the sequence in which all jobs are processed. For each job, a start time on each machine is implicitly determined by the sequence and the no-wait rule: the start time of a job's operation on the next machine equals the start time on the current machine plus the processing time on the current machine. Operations of different jobs must not overlap on any machine: if one job is sequenced immediately after another, the successor's operation on every machine must not begin before the predecessor's operation on that same machine has finished. Every job's completion time on the last machine must not exceed that job's due date. + +The goal is to find the job sequence that minimizes the makespan, defined as the latest completion time among all jobs on the last machine. The makespan equals the maximum, over all jobs, of the sum of that job's start time on the last machine and its processing time on the last machine. The input data consists of the number of jobs, the number of machines, a processing time for each combination of job and machine, and a due date for each job. + +The sequencing requirement is that the total number of immediate-successor links among the jobs equals one fewer than the total number of jobs, each job has at most one immediate predecessor and at most one immediate successor in the sequence, no job can be its own successor, and for any pair of jobs at most one of the two possible predecessor-successor relationships holds. Together these rules ensure the jobs form a single chain covering every job exactly once. When a job is sequenced immediately after another, the start time of every operation of the successor on each machine must be at least as large as the start time of the corresponding operation of the predecessor plus the predecessor's processing time on that machine; when the two jobs are not adjacent this ordering requirement is relaxed via a sufficiently large constant. The no-wait rule is enforced as a strict equality: for every job and every machine except the last, the start time on the next machine equals the start time on the current machine plus the current processing time. The due-date rule requires that, for every job, the start time on the last machine plus the processing time on the last machine does not exceed the job's due date. diff --git a/tasks/samarghandi2017/solution_logger.py b/tasks/samarghandi2017/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/samarghandi2017/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/samarghandi2017/solution_schema.json b/tasks/samarghandi2017/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9387bc0f77e1a2120d77a38cb3207deba1108066 --- /dev/null +++ b/tasks/samarghandi2017/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Makespan, the latest completion time among all jobs on the last machine.", + "sequence": " Order in which jobs are processed through all machines, using 1-based job indices." +} \ No newline at end of file diff --git a/tasks/sansegundo2016/feasibility_check.py b/tasks/sansegundo2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..4f24e309d6166b45d39bdfce2077c0b9762c232c --- /dev/null +++ b/tasks/sansegundo2016/feasibility_check.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Maximum Clique Problem (MCP). + +Mathematical formulation: + max sum_{i in V} x_i + s.t. + (C1) x_i + x_j <= 1, for all (i,j) not in E, i < j + (C2) x_i in {0, 1}, for all i in V + +Constraints enforced by this checker: + 1 (C1) Clique constraint: every pair of selected vertices must be adjacent. + 2 (C2) Binary domain: clique vertices must be distinct valid indices in [0, n). + 3 (Tier C obj-consistency) Reported objective_value must equal the recomputed + clique size sum_i x_i (= number of distinct valid vertices in clique_vertices). + This blocks LLM exploits that pass constraints but lie about the objective + (e.g. reporting sys.float_info.max or 0 on a valid clique). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('clique_vertices', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_instance(path): + with open(path, 'r') as f: + data = json.load(f) + graph = data['graph'] + n = graph['num_vertices'] + adj = [set() for _ in range(n)] + for u_str, neighbors in graph['adjacency_list'].items(): + u = int(u_str) + for v in neighbors: + if u != v: + adj[u].add(v) + adj[v].add(u) + return n, adj + + +def load_solution(path): + with open(path, 'r') as f: + sol = json.load(f) + return sol['clique_vertices'] + + +def check_feasibility(instance_path, solution_path, result_path): + n, adj = load_instance(instance_path) + with open(solution_path, 'r') as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return _frontieror_contract_result + clique_vertices = sol.get('clique_vertices', []) or [] + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # --- Constraint (C1): x_i + x_j <= 1 for all (i,j) not in E, i < j --- + # If both i and j are in the clique, then x_i + x_j = 2. + # For this to be feasible, (i,j) must be in E. If not, C1 is violated. + clique_set = set(clique_vertices) + sorted_clique = sorted(clique_vertices) + c1_violations = [] + for idx_a in range(len(sorted_clique)): + i = sorted_clique[idx_a] + for idx_b in range(idx_a + 1, len(sorted_clique)): + j = sorted_clique[idx_b] + if not isinstance(i, int) or not isinstance(j, int): + continue + if i < 0 or i >= n or j < 0 or j >= n: + continue + if j not in adj[i]: + # LHS = x_i + x_j = 2, RHS = 1 + lhs = 2.0 + rhs = 1.0 + violation_amount = lhs - rhs # 1.0 + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + c1_violations.append((i, j, lhs, rhs, violation_amount, normalizer, ratio)) + + if c1_violations: + violated_constraints.add(1) + if len(c1_violations) <= 10: + for i, j, *_ in c1_violations: + violations.append( + f"C1 violated: vertices {i} and {j} are both in the clique but are not adjacent" + ) + else: + violations.append( + f"C1 violated: {len(c1_violations)} pairs of clique vertices are not adjacent" + ) + for i, j, lhs, rhs, raw_excess, normalizer, ratio in c1_violations: + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + }) + + # --- Constraint (C2): x_i in {0, 1} for all i in V --- + # Check that all clique vertices are valid vertex indices in [0, n). + c2_violations = [] + for v in clique_vertices: + if not isinstance(v, int) or v < 0 or v >= n: + lhs = float(v) if isinstance(v, (int, float)) else 0.0 + # For domain violation, treat as |x - round(x)| or out-of-range + rhs = 0.0 # nearest valid boundary + violation_amount = 1.0 # binary domain violation + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + c2_violations.append((v, lhs, rhs, violation_amount, normalizer, ratio)) + + if c2_violations: + violated_constraints.add(2) + for v, *_ in c2_violations: + violations.append(f"C2 violated: vertex {v} is not a valid vertex in V = {{0, ..., {n-1}}}") + for v, lhs, rhs, raw_excess, normalizer, ratio in c2_violations: + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + }) + + # Also check for duplicates (a vertex selected more than once violates binary domain) + seen = set() + for v in clique_vertices: + if v in seen: + if 2 not in violated_constraints: + violated_constraints.add(2) + violations.append(f"C2 violated: vertex {v} appears more than once in the clique") + violation_magnitudes.append({ + "constraint": 2, + "lhs": 2.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + seen.add(v) + + # --- Constraint (C3): obj-consistency (Tier C) --- + # True objective = sum_i x_i = number of distinct valid vertices selected. + # Reject when the reported objective_value disagrees by more than 0.5 + # (objective is integer-valued, so a half-unit tolerance fires on any + # integer-magnitude mismatch while remaining robust to harmless float noise). + reported_obj = sol.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + valid_distinct = set( + v for v in clique_vertices + if isinstance(v, int) and 0 <= v < n + ) + true_obj = float(len(valid_distinct)) + abs_diff = abs(reported - true_obj) + tol = 0.5 # objective is integer-valued + if abs_diff > tol: + violated_constraints.add(3) + violations.append( + f"C3 violated: reported objective_value={reported} differs " + f"from recomputed sum_i x_i={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={tol:.3g})" + ) + normalizer = max(abs(true_obj), EPS) + violation_magnitudes.append({ + "constraint": 3, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + feasible = len(violated_constraints) == 0 + + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(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[:10]: + print(f" - {v}") + print(f"Result written to {result_path}") + + +def main(): + parser = argparse.ArgumentParser(description="Feasibility checker for Maximum Clique Problem") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + check_feasibility(args.instance_path, args.solution_path, args.result_path) + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/sansegundo2016/gurobi_code.py b/tasks/sansegundo2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2c737952c56801a59a57aa479dbae6e25e5615 --- /dev/null +++ b/tasks/sansegundo2016/gurobi_code.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +""" +Gurobi ILP formulation for the Maximum Clique Problem (MCP). + +Paper: "A new exact maximum clique algorithm for large and massive sparse graphs" +Authors: Pablo San Segundo, Alvaro Lopez, Panos M. Pardalos (2016) + +The paper does NOT present an ILP formulation; it uses a combinatorial branch-and-bound +algorithm (BBMCSP). The standard ILP formulation below is the canonical textbook +formulation of MCP: + + max sum_{i in V} x_i + s.t. x_i + x_j <= 1, for all (i,j) not in E, i < j + x_i in {0, 1}, for all i in V +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, 'r') as f: + data = json.load(f) + graph = data['graph'] + n = graph['num_vertices'] + edges = set() + # Instance uses adjacency_list (dict: vertex_str -> [neighbor, ...]) + adj_list = graph['adjacency_list'] + for u_str, neighbors in adj_list.items(): + u = int(u_str) + for v in neighbors: + if u != v: + edges.add((min(u, v), max(u, v))) + return n, edges + + +def solve_max_clique(instance_path, solution_path, time_limit): + n, edges = load_instance(instance_path) + + # Build adjacency set for fast lookup + adj = set(edges) + + model = gp.Model("MaxClique") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x_i = 1 if vertex i is in the clique + x = model.addVars(n, vtype=GRB.BINARY, name="x") + + # Objective: maximize clique size + model.setObjective(gp.quicksum(x[i] for i in range(n)), GRB.MAXIMIZE) + + # Constraint (C1): for every pair of non-adjacent vertices, at most one can be in clique + # x_i + x_j <= 1 for all (i,j) not in E, i < j + # For efficiency, build neighbor sets first + neighbors = [set() for _ in range(n)] + for u, v in edges: + neighbors[u].add(v) + neighbors[v].add(u) + + for i in range(n): + for j in range(i + 1, n): + if j not in neighbors[i]: + model.addConstr(x[i] + x[j] <= 1) + + model.optimize() + + # Extract solution + objective_value = 0 + clique_vertices = [] + + if model.SolCount > 0: + objective_value = round(model.ObjVal) + clique_vertices = [i for i in range(n) if x[i].X > 0.5] + + solution = { + "objective_value": objective_value, + "clique_size": objective_value, + "clique_vertices": clique_vertices, + "status": model.Status, + "solver": "gurobi", + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + } + + with open(solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Objective value: {objective_value}") + print(f"Clique vertices: {clique_vertices}") + print(f"Solution written to {solution_path}") + + +def main(): + parser = argparse.ArgumentParser(description="Gurobi solver for Maximum Clique Problem") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_max_clique(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/sansegundo2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/sansegundo2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2016/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/sansegundo2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/sansegundo2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2016/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/sansegundo2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/sansegundo2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2016/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/sansegundo2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/sansegundo2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2016/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/sansegundo2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/sansegundo2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2016/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/sansegundo2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/sansegundo2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2016/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/sansegundo2016/gurobi_solution/large_solution_1.json b/tasks/sansegundo2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..608bbda5974ee622f43cb85570172882d86fd61a --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84c94eeb680c55a7686a998ccb8f51ab67810e12413728ab103ed3371569c386 +size 169 diff --git a/tasks/sansegundo2016/gurobi_solution/large_solution_2.json b/tasks/sansegundo2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8a88c162a3954af4191db732362751052aa4c46f --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67ffb0d3cc17d898e1f894e457166bde838f8d235f5da7244d4687a18dbc5dce +size 171 diff --git a/tasks/sansegundo2016/gurobi_solution/large_solution_3.json b/tasks/sansegundo2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..a13bd7ba7e71ac6ee762423c07d50bb67e78d6af --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9553ac9b6320e78b75eee2d8e5946dcfcf6318a3a556c152c695eb30d7638b3 +size 209 diff --git a/tasks/sansegundo2016/gurobi_solution/large_solution_4.json b/tasks/sansegundo2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..8586223c50e086c82f5b566f5c2c28acac4b6b1a --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:242c39cd7c3903b131560710a103b3e93ca2f15552a0a426e513f06c7fe52e89 +size 250 diff --git a/tasks/sansegundo2016/gurobi_solution/large_solution_5.json b/tasks/sansegundo2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..dda8deb86298651a477376560374b4a0c663586f --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:024b10e3d9a57923be734c434eef336adf0089b1120e96676f22e1870e5b0b6b +size 183 diff --git a/tasks/sansegundo2016/gurobi_solution/tiny_solution.json b/tasks/sansegundo2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..291112f4e1d3b8d121da1cd8ad2e7a15147ef5bd --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fccd286a339e9b495be5ef339980ebc8283fe56c3b3ed9b442c375b51b2cea18 +size 183 diff --git a/tasks/sansegundo2016/gurobi_solution_log/large_log_1.jsonl b/tasks/sansegundo2016/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6736c39873b07ba0e9d7e360c3319959d9e04aa4 --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08dca0f91589a80debd7cf8c17c9b02693ee26b4d7709a8973a13f74b8fda56f +size 83 diff --git a/tasks/sansegundo2016/gurobi_solution_log/large_log_2.jsonl b/tasks/sansegundo2016/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fad9abb9273ecdf669877b446583c1834955b018 --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:121add89e9b96f85b91de04de7da31491ce78d922acda9a0bf611b84281c8d9b +size 83 diff --git a/tasks/sansegundo2016/gurobi_solution_log/large_log_3.jsonl b/tasks/sansegundo2016/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f0b2a5a4078b7d1a079fc54ff879343270baabdd --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d04c096ccfb42fb8c026fb7f0ad09a7c354e488b28921fb019f2839285d46448 +size 83 diff --git a/tasks/sansegundo2016/gurobi_solution_log/large_log_4.jsonl b/tasks/sansegundo2016/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..82b918d2aac01b2e7486ccb59323ef35772f59db --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d72541e373a2351297bed9a39e053d119eca08d324fd9dc0aca4392b99a50900 +size 41 diff --git a/tasks/sansegundo2016/gurobi_solution_log/large_log_5.jsonl b/tasks/sansegundo2016/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a0e93032fd842b255d170200ad834040cd9eb03e --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3470313c7fa1826058cfa5cf0bdf613ef8c9a80b30d060b30b0a1559f7204b1 +size 40 diff --git a/tasks/sansegundo2016/gurobi_solution_log/tiny_log.jsonl b/tasks/sansegundo2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..78012df0c3c4ee86324aa5e1491035fa3ba38134 --- /dev/null +++ b/tasks/sansegundo2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a2b22e78de8dd0567717c3c0e9ac54eb4f19642b9df18ab01ac1ea12f7ed91f +size 40 diff --git a/tasks/sansegundo2016/instance/large_instance_1.json b/tasks/sansegundo2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6e1c271e5e3d78fecf188f636481588749ace907 --- /dev/null +++ b/tasks/sansegundo2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e70b9c9df24f06ec5c60900a9bf8683203f5e51fb5443a28c009ca00302e7ce0 +size 36639 diff --git a/tasks/sansegundo2016/instance/large_instance_2.json b/tasks/sansegundo2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..39b4b6db7812847a40bb8e2f8699ac590675b955 --- /dev/null +++ b/tasks/sansegundo2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:259a9c125d9263a638eb0cc8304edc55ef8fb6d038123c61a7032c6164c6376c +size 270380 diff --git a/tasks/sansegundo2016/instance/large_instance_3.json b/tasks/sansegundo2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e4377807abc3cc3327780b8ca3c832c0cc1cdca9 --- /dev/null +++ b/tasks/sansegundo2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54af3bb709d1ace1204a446cbdcfeceb1c7cbf7b5329962fca3a784519128b75 +size 14492 diff --git a/tasks/sansegundo2016/instance/large_instance_4.json b/tasks/sansegundo2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..58a89d75372f864cad451cc765fbb6711e763ddf --- /dev/null +++ b/tasks/sansegundo2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72ceab02e8c2cf808e908157f4ab4447ce5556f1f56230ce6ec3fa2da5016e8c +size 241055 diff --git a/tasks/sansegundo2016/instance/large_instance_5.json b/tasks/sansegundo2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..826dafd1068d7bc77ec250653c1d0c5ee8bd9c9d --- /dev/null +++ b/tasks/sansegundo2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a028d3bb76d243eaf2f30b6306d7b49089b2d296cbf77e083e1b3bec81a76b7 +size 37100 diff --git a/tasks/sansegundo2016/instance/tiny_instance.json b/tasks/sansegundo2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..2560d3389f9d44b951c0f651044522d027559f37 --- /dev/null +++ b/tasks/sansegundo2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77fa135b3f42fa3db907a6d949f1f09d8e50bc0c5b589ef637ee63de05efc36d +size 6030 diff --git a/tasks/sansegundo2016/instance_schema.json b/tasks/sansegundo2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..19d648bf9f81b9e87fb299a51d2a952af5572049 --- /dev/null +++ b/tasks/sansegundo2016/instance_schema.json @@ -0,0 +1,9 @@ +{ + "graph": { + "num_vertices": " Total number of vertices in the graph.", + "num_edges": " Total number of undirected edges in the graph.", + "max_degree": " Highest number of neighbors any single vertex has.", + "avg_degree": " Average number of neighbors per vertex across the entire graph.", + "adjacency_list": " For each vertex, the sorted list of vertices it is directly connected to by an edge." + } +} \ No newline at end of file diff --git a/tasks/sansegundo2016/mathematical_formulation.md b/tasks/sansegundo2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..37768d06b4061bccb8503820fb88ce0a2bc9a293 --- /dev/null +++ b/tasks/sansegundo2016/mathematical_formulation.md @@ -0,0 +1,34 @@ +# Original Formulation: Maximum Clique Problem (MCP) + +*Source: A new exact maximum clique algorithm for large and massive sparse graphs, Pablo San Segundo, Alvaro Lopez, Panos M. Pardalos, 2016.* + +## Sets and Parameters + +- $G=(V,E)$: a simple undirected graph (paper, Section 1). + +- $V=\{v_1,v_2,\dots,v_n\}$: finite set of vertices, $|V|=n$. + +- $E\subseteq V\times V$: set of edges, made up of pairs of distinct vertices. + +- Two vertices are *adjacent* (neighbors) iff they are connected by an edge. + +- $N(v)$ (or $N_G(v)$): the neighbor set of vertex $v$ in $G$, i.e. $\{u\in V:(u,v)\in E\}$. + +- $\omega(G)$: the clique number, the size of the maximum clique (= optimal objective value). + +## Decision Variables + +- $x_i\in\{0,1\}$, $\forall i\in V$: $x_i=1$ if vertex $v_i$ is selected into the clique, $0$ otherwise. + +## Objective + +$$\begin{align} +\max \quad \omega \;=\; \sum_{i\in V} x_i \tag{OBJ} +\end{align}$$ + +## Constraints + +$$\begin{align} +x_i + x_j &\;\le\; 1, & \forall\,(i,j)\notin E,\ i= self.best_obj: + return + if self.sense == "maximize" and objective_value <= self.best_obj: + return + + elapsed = time.time() - self.start_time + + # Throttle writes + if self.best_obj is not None and elapsed - self._last_log_time < self.min_interval: + self.best_obj = objective_value + return + + self.best_obj = objective_value + self._last_log_time = elapsed + + with open(self.log_path, "a") as f: + f.write(json.dumps({"time": round(elapsed, 3), + "objective_value": objective_value}) + "\n") diff --git a/tasks/sansegundo2016/solution_schema.json b/tasks/sansegundo2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a2e2a7605c4c282f12b015f170faaa63a8375491 --- /dev/null +++ b/tasks/sansegundo2016/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Number of vertices in the selected clique.", + "clique_vertices": " Vertices chosen to form the clique, where every pair of selected vertices is directly connected by an edge in the graph." +} diff --git a/tasks/sansegundo2023/feasibility_check.py b/tasks/sansegundo2023/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc513ada773fa62ace83d45ab209acb9b4940f7 --- /dev/null +++ b/tasks/sansegundo2023/feasibility_check.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Maximum Clique Problem (MCP). + +Paper: San Segundo et al. (2023), "CliSAT: A new exact algorithm for hard + maximum clique problems", EJOR 307, 1008-1025. + +Constraints (numbered top-to-bottom from the formulation): + Constraint 1 (9b): x_u + x_v <= 1, for all {u,v} in bar{E}(G) + Constraint 2 (9c): x_u in {0, 1}, for all u in V(G) + Constraint 3 (Tier-C obj recompute): reported objective_value must equal + the recomputed value of sum_{u in V} x_u (size of the reported clique + restricted to valid, distinct vertices in V). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('clique_vertices', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + violations = [] + violation_magnitudes = [] + violated_set = set() + + # --- Extract instance data --- + n = instance["num_vertices"] + vertices = instance["vertices"] + vertex_set = set(vertices) + + # Build adjacency sets + if "adjacency_list" in instance: + adj = {int(k): set(v) for k, v in instance["adjacency_list"].items()} + else: + adj = {v: set() for v in vertices} + for u, w in instance["edges"]: + adj[u].add(w) + adj[w].add(u) + for v in vertices: + if v not in adj: + adj[v] = set() + + # --- Extract solution clique --- + if "clique" in solution: + clique = solution["clique"] + elif "clique_vertices" in solution: + clique = solution["clique_vertices"] + else: + clique = [] + + # Build x values: x_u = 1 if u in clique, else 0 + x = {v: 0 for v in vertices} + for v in clique: + x[v] = 1 + + # --- Constraint 2 (9c): x_u in {0, 1}, for all u in V --- + # Check that all clique vertices are valid vertices in the graph + for v in clique: + if v not in vertex_set: + lhs = 1.0 # x_v = 1 but v not in V + rhs = 0.0 # should not be selected + violation_amount = 1.0 + violated_set.add(2) + violations.append( + f"Vertex {v} in clique is not a valid vertex in V (domain violation)" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # Check for duplicates in clique + if len(clique) != len(set(clique)): + from collections import Counter + counts = Counter(clique) + for v, cnt in counts.items(): + if cnt > 1: + lhs = float(cnt) + rhs = 1.0 + violation_amount = lhs - rhs + violated_set.add(2) + violations.append( + f"Vertex {v} appears {cnt} times in clique (must be binary)" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 1 (9b): x_u + x_v <= 1, for all {u,v} in bar{E}(G) --- + # For every pair of vertices in the clique, they must be adjacent in G. + # If they are non-adjacent, then {u,v} in bar{E}(G) and x_u + x_v = 2 > 1. + clique_valid = [v for v in clique if v in vertex_set] + clique_sorted = sorted(set(clique_valid)) + for i in range(len(clique_sorted)): + u = clique_sorted[i] + for j in range(i + 1, len(clique_sorted)): + v = clique_sorted[j] + if v not in adj.get(u, set()): + # Non-adjacent pair both selected: x_u + x_v = 2, limit is 1 + lhs = 2.0 + rhs = 1.0 + violation_amount = lhs - rhs # 1.0 + violated_set.add(1) + violations.append( + f"Non-adjacent vertices {u} and {v} both in clique " + f"(x_{u} + x_{v} = 2 > 1)" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # --- Constraint 3 (Tier-C obj recompute): reported objective_value must + # match the recomputed sum_{u in V} x_u. The MCP objective (9a) is fully + # determined by the clique indicator x, which is itself derived from the + # solution's clique_vertices list. Full recompute applies. Tolerance is + # 0.5 (the objective is integer-valued, so any mismatch of >=1 fires). + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(sum(x[v] for v in vertices)) + abs_diff = abs(reported - true_obj) + tol = 0.5 + if abs_diff > tol: + lhs = reported + rhs = true_obj + violation_amount = abs_diff + violated_set.add(3) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum_v(x_v)={true_obj} " + f"(|diff|={abs_diff:.3g}, tol={tol:.3g})" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + feasible = len(violated_set) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Maximum Clique Problem (MCP)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the instance JSON file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the solution JSON file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the feasibility result JSON file") + args = parser.parse_args() + + 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 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/sansegundo2023/gurobi_code.py b/tasks/sansegundo2023/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..b8ab59c55bf01aab1ddfa739222b59085f9e1122 --- /dev/null +++ b/tasks/sansegundo2023/gurobi_code.py @@ -0,0 +1,252 @@ +#!/usr/bin/env python3 +""" +Gurobi ILP implementation of the Maximum Clique Problem (MCP). + +Paper: San Segundo et al. (2023), "CliSAT: A new exact algorithm for hard + maximum clique problems", EJOR 307, 1008-1025. + +Formulation (Section 3.6): + max sum_{u in V} x_u (9a) + s.t. sum_{u in I} x_u <= 1, for all I in C (10) + x_u in {0, 1}, for all u in V (9c) + +where C is a collection of independent sets of G covering all non-adjacent +pairs {u,v} in the complement edge set bar{E}(G). + +The collection C is generated using the heuristic from Bettinelli, Cacchiani, +& Malaguti (2017), which is **NOT EXPLICITLY SPECIFIED IN THIS PAPER**. + +INFERRED ASSUMPTION: We approximate the Bettinelli et al. heuristic with a +greedy independent set cover: for each non-adjacent pair not yet covered by +an existing independent set, grow a maximal independent set containing that +pair using greedy first-fit expansion. +""" + +import argparse +import json +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load an MCP instance from JSON.""" + with open(instance_path, 'r') as f: + data = json.load(f) + + vertices = data["vertices"] + n = data["num_vertices"] + edges = data["edges"] + adjacency_list = {int(k): set(v) for k, v in data["adjacency_list"].items()} + + # Build adjacency set of frozensets for quick edge lookup + adj_set = set() + for u, v in edges: + adj_set.add((min(u, v), max(u, v))) + + return vertices, n, adj_set, adjacency_list, data + + +def generate_independent_set_cover(vertices, n, adj_set, adjacency_list): + """ + Generate a collection of independent sets covering all non-adjacent pairs. + + For each non-adjacent pair {u,v}, if not already covered by an existing + independent set, grow a maximal independent set containing {u,v} using + greedy first-fit expansion. + + **NOT EXPLICITLY SPECIFIED IN PAPER**: The exact heuristic from + Bettinelli et al. (2017) is cited but not detailed. This greedy approach + is an INFERRED ASSUMPTION that approximates the spirit of the method. + """ + independent_sets = [] + + # Track which non-adjacent pairs are covered + # For efficiency, we check coverage on the fly rather than storing all pairs + # Build a mapping: for each pair -> list of independent set indices containing both + # We use a set of covered pairs for quick lookup + covered_pairs = set() + + # Iterate over all non-adjacent pairs + for i in range(n): + u = vertices[i] + neighbors_u = adjacency_list.get(u, set()) + for j in range(i + 1, n): + v = vertices[j] + # Check if u and v are non-adjacent (complement edge) + if v in neighbors_u: + continue # u and v are adjacent in G, skip + + pair = (u, v) + if pair in covered_pairs: + continue + + # Grow a maximal independent set containing {u, v} + indep_set = {u, v} + # Neighbors of the independent set in G (vertices adjacent to any + # member) — these cannot be added + excluded = neighbors_u | adjacency_list.get(v, set()) + + # Greedily add more vertices + for k in range(n): + w = vertices[k] + if w in indep_set or w in excluded: + continue + # w is non-adjacent to all current members of indep_set + # (since w not in excluded means w is not a neighbor of any member) + indep_set.add(w) + excluded |= adjacency_list.get(w, set()) + + indep_set_list = sorted(indep_set) + independent_sets.append(indep_set_list) + + # Mark all non-adjacent pairs within this independent set as covered + for a_idx in range(len(indep_set_list)): + for b_idx in range(a_idx + 1, len(indep_set_list)): + a, b = indep_set_list[a_idx], indep_set_list[b_idx] + covered_pairs.add((a, b)) + + return independent_sets + + +def solve_mcp_gurobi(vertices, n, adj_set, adjacency_list, time_limit): + """ + Solve MCP using Gurobi ILP with strengthened independent set inequalities. + + Formulation: (9a) + (10) + (9c) from the paper. + """ + if n == 0: + return 0.0, [] + if n == 1: + return 1.0, [vertices[0]] + + # Skip IS-cover heuristic — at n=3333 the greedy alone takes 60-90s + # AND has been shown to produce incomplete coverage (2026-05-17 1h + # rerun: clique_size=2632 with 2.77M non-adjacent pair violations). + # We use pairwise non-edge constraints below for correctness. + independent_sets = [] + + model = gp.Model("MCP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x_u in {0,1} for all u in V (9c) + x = {} + for u in vertices: + x[u] = model.addVar(vtype=GRB.BINARY, name=f"x_{u}") + + model.update() + + # Objective: maximize sum of x_u (9a) + model.setObjective( + gp.quicksum(x[u] for u in vertices), + GRB.MAXIMIZE + ) + + # Constraints: edge formulation (9c). For every non-edge {u,v} in + # complement(G), x_u + x_v <= 1. This is correctness-guaranteed but + # at O(|complement E|) ≈ O(n²) constraints (~4.4M for n=3333). + # + # NOTE: The IS-cover heuristic (independent_sets) is computed above + # for potential strengthening, but at n=3333 the greedy heuristic + # alone took 60-90s without covering all complement edges — the + # 2026-05-17 1h rerun produced clique_size=2632 with 2.77M + # non-adjacent pairs both selected. Using pairwise constraints + # directly (skipping the strengthened IS-cover variant) is slower + # in LP relaxation but correctness-guaranteed; gurobi's cut + # generator + clique inequalities at presolve will recover much of + # the IS strengthening automatically. + nonedge_count = 0 + for i in range(n): + u = vertices[i] + neighbors_u = adjacency_list.get(u, set()) + for j in range(i + 1, n): + v = vertices[j] + if v in neighbors_u: + continue # adjacent in G — no exclusion needed + model.addConstr(x[u] + x[v] <= 1, name=f"nonedge_{u}_{v}") + nonedge_count += 1 + print(f"[gurobi_code] added {nonedge_count} pairwise non-edge constraints " + f"(skipping the IS-cover strengthening — heuristic was incomplete " + f"on this scale and let gurobi's cut generator handle clique lifting)") + + # Solve + model.optimize() + + # Extract solution + obj_val = None + clique_vertices = [] + + if model.SolCount > 0: + obj_val = model.ObjVal + for u in vertices: + if x[u].X > 0.5: + clique_vertices.append(u) + else: + obj_val = None + + return obj_val, clique_vertices + + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi ILP solver for Maximum Clique Problem (MCP)" + ) + 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 + vertices, n, adj_set, adjacency_list, instance_data = \ + load_instance(args.instance_path) + + # Solve + obj_val, clique_vertices = solve_mcp_gurobi( + vertices, n, adj_set, adjacency_list, args.time_limit + ) + + # Build solution output + solution = { + "problem": "Maximum Clique Problem (MCP)", + "instance_path": args.instance_path, + "solver": "Gurobi", + "objective_value": obj_val if obj_val is not None else None, + "clique_vertices": clique_vertices, + "clique_size": len(clique_vertices), + } + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + if obj_val is not None: + print(f"Optimal objective value (clique size): {obj_val}") + print(f"Clique vertices: {clique_vertices}") + else: + print("No feasible solution found within time limit.") + + +if __name__ == "__main__": + main() diff --git a/tasks/sansegundo2023/gurobi_feasi_result/large_feasi_result_1.json b/tasks/sansegundo2023/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2023/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/sansegundo2023/gurobi_feasi_result/large_feasi_result_2.json b/tasks/sansegundo2023/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2023/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/sansegundo2023/gurobi_feasi_result/large_feasi_result_3.json b/tasks/sansegundo2023/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2023/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/sansegundo2023/gurobi_feasi_result/large_feasi_result_4.json b/tasks/sansegundo2023/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2023/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/sansegundo2023/gurobi_feasi_result/large_feasi_result_5.json b/tasks/sansegundo2023/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2023/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/sansegundo2023/gurobi_feasi_result/tiny_feasi_result.json b/tasks/sansegundo2023/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/sansegundo2023/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/sansegundo2023/gurobi_solution/large_solution_1.json b/tasks/sansegundo2023/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f40813ad277190765f5bf82320b64340d3d688c0 --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36b7ced737ee1918f19d286cfaa1478e6ceff4554df85382a2a879340f656fa3 +size 356 diff --git a/tasks/sansegundo2023/gurobi_solution/large_solution_2.json b/tasks/sansegundo2023/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..71cf228bd20da8843fe35abedf314c6ac234025e --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4389fe1188a943eabcafb6565e4a542f8c380b50f68082df2c4c7690de74cc5 +size 338 diff --git a/tasks/sansegundo2023/gurobi_solution/large_solution_3.json b/tasks/sansegundo2023/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6af9a7dc8f9a65e82a57a661c27cf6d0c48142a9 --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40d702aa584f938c768e4be2926e0fcccc9afb960b16f4090953bf993d6076ee +size 687 diff --git a/tasks/sansegundo2023/gurobi_solution/large_solution_4.json b/tasks/sansegundo2023/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a0d3407131e8f3aabb5ded25559442904fc84837 --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:781adc9d77ee36c7b18d7ed5502084a4b233ae35c7e5a4162274ad69ede7858e +size 610 diff --git a/tasks/sansegundo2023/gurobi_solution/large_solution_5.json b/tasks/sansegundo2023/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..f6934cf6f35e8e2d651d01855a9753ffd8505c0e --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9184376ce152b928ab4a1ecd2c91e6bfdd721d42d8e4a7b3567cf5263573ccd3 +size 1097 diff --git a/tasks/sansegundo2023/gurobi_solution/tiny_solution.json b/tasks/sansegundo2023/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..80de775d6514b7ff1bf53c3648482fc6b64bfe82 --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f85e46acdcdd5203d15efa37a2ca205edd447d92779513ac14307b5e86623c6 +size 433 diff --git a/tasks/sansegundo2023/gurobi_solution_log/large_log_1.jsonl b/tasks/sansegundo2023/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..49baa3004fdebe98ea01bb53c7908db1ef72f5d6 --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bb622cbd622128418bc52292d0f950a937aa2cdb6fcd030ee41427c9e9cfb92 +size 40 diff --git a/tasks/sansegundo2023/gurobi_solution_log/large_log_2.jsonl b/tasks/sansegundo2023/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2131d33626db7ffaaeddf8bef34ed78ccfc10a3f --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a79539c88e87783bbe4f170b7e99fc5bda6a4facf0b383d88fac6269da62ead0 +size 40 diff --git a/tasks/sansegundo2023/gurobi_solution_log/large_log_3.jsonl b/tasks/sansegundo2023/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b85e3443055a5d3a15e401300901f116690db37d --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f807bb5e1a98c9ce48a2f5750bcc881007f0be552ee84914322b085427bbcf4 +size 41 diff --git a/tasks/sansegundo2023/gurobi_solution_log/large_log_4.jsonl b/tasks/sansegundo2023/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..57c5178d4294e9677b99c4d29d936dfb0a9234cb --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5633e594ed43d6a9e1b8262c5c85c9e2d895c26ba20b1242aeb297ec6739a48d +size 41 diff --git a/tasks/sansegundo2023/gurobi_solution_log/large_log_5.jsonl b/tasks/sansegundo2023/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fe5cf6812b41648cb9d0998a24d3ea4d2003a73a --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b84b1a2a6c1e5488408cd10ef1114c3a1a2012e70be55646d2dfbba77adb0858 +size 41 diff --git a/tasks/sansegundo2023/gurobi_solution_log/tiny_log.jsonl b/tasks/sansegundo2023/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..050894e131f7c93898a31ea7d676a62283ee3460 --- /dev/null +++ b/tasks/sansegundo2023/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:574b2247f5166ee6d264913295db4112751b8d94a41694b9ec010ca8c8a5185c +size 40 diff --git a/tasks/sansegundo2023/instance/large_instance_1.json b/tasks/sansegundo2023/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5e920c6d3a18dec2b931781fdbf31b0105ef858b --- /dev/null +++ b/tasks/sansegundo2023/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8234bf3db859229fa2ac312a20b376b14f39457c221225fdef65f6af66a03fb2 +size 5605016 diff --git a/tasks/sansegundo2023/instance/large_instance_2.json b/tasks/sansegundo2023/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..590613a3592ca98220383d03614a827d0cbad5e9 --- /dev/null +++ b/tasks/sansegundo2023/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fecf46b78692db3ca3b3f122ab8e15ffb43a83844716fc5ceea1c237b7538aaf +size 2812361 diff --git a/tasks/sansegundo2023/instance/large_instance_3.json b/tasks/sansegundo2023/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8f8f825702ee9363d1848dbd06efb5f47e89945c --- /dev/null +++ b/tasks/sansegundo2023/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e4c87e5a33abc5358cdb32ec9c00fa99dc3ab380eb7313561d3bfe39d28e7a9 +size 5594998 diff --git a/tasks/sansegundo2023/instance/large_instance_4.json b/tasks/sansegundo2023/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..aadf64b946f7b1a52c13bf0181568f14abd2d4b1 --- /dev/null +++ b/tasks/sansegundo2023/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d897fa029acdb96e0d5ec9fdbcb9cc538ff43fe2f2f29ac008ce46de18351ef +size 5584338 diff --git a/tasks/sansegundo2023/instance/large_instance_5.json b/tasks/sansegundo2023/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c504e1c5312bf8baa197c1667704c5d20d6ce649 --- /dev/null +++ b/tasks/sansegundo2023/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4bd114c588694ff6e9a511d25b98f10bc39c9cef49cb9ca9e94e6cf068ac08a4 +size 5503150 diff --git a/tasks/sansegundo2023/instance/tiny_instance.json b/tasks/sansegundo2023/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b72414704e27ec06ad40571117978472ec5e21d0 --- /dev/null +++ b/tasks/sansegundo2023/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2323fb6213c0521837c176e730e012077e2fed6e1d448e6d586c8f560e513242 +size 420844 diff --git a/tasks/sansegundo2023/instance_schema.json b/tasks/sansegundo2023/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9fb868682dc2018ed047d30cb37e38170b958786 --- /dev/null +++ b/tasks/sansegundo2023/instance_schema.json @@ -0,0 +1,11 @@ +{ + "num_vertices": " Total number of vertices in the undirected graph.", + "target_density": " Target probability that an edge exists between any pair of vertices in the Erdos-Renyi random graph.", + "actual_density": " Realized fraction of possible edges present in the generated graph.", + "num_edges": " Total number of edges in the graph.", + "greedy_clique_size": " Size of a clique found by a greedy heuristic, serving as a known lower bound on the maximum clique size.", + "greedy_clique": " Vertex indices belonging to the greedy heuristic clique.", + "vertices": " List of all vertex indices in the graph.", + "edges": " Each entry is a pair of vertex indices representing an undirected edge, with the smaller index first.", + "adjacency_list": " For each vertex, the sorted list of neighboring vertex indices that share an edge with it." +} \ No newline at end of file diff --git a/tasks/sansegundo2023/mathematical_formulation.md b/tasks/sansegundo2023/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..d6aa340743cf3b3a4fad5a2267dfe591b6928aea --- /dev/null +++ b/tasks/sansegundo2023/mathematical_formulation.md @@ -0,0 +1,30 @@ +# Original Formulation: Maximum Clique Problem (MCP) + +San Segundo, Furini, Alvarez, Pardalos. “CliSAT: A new exact algorithm for hard maximum clique problems,” *EJOR*, 2023. Section 3.6, equations (9a)–(9c). + +## Sets and Indices + +- $G = (V,E)$: a simple undirected graph with vertex set $V$ and edge set $E$. + +- $\bar{E}(G) = \bigl\{\{u,v\} : u,v\in V,\ u\neq v,\ \{u,v\}\notin E\bigr\}$: edge set of the complement graph $\bar G$ (pairs of non-adjacent vertices). + +## Decision Variables + +$$x_u \in \{0,1\}, \quad \forall u \in V, + \qquad x_u = 1 \iff u \text{ belongs to the selected clique.}$$ + +## Natural ILP Formulation (9a)–(9c) + +$$\begin{align} + \omega(G) \ =\ \max\ & \sum_{u \in V} x_u \tag{9a}\\ + \text{s.t.}\ & x_u + x_v \le 1, + && \forall\, \{u,v\} \in \bar{E}(G), \tag{9b}\\ + & x_u \in \{0,1\}, + && \forall\, u \in V. \tag{9c} +\end{align}$$ + +## Optional Strengthening (eq. 10) + +The LP relaxation of (9a)–(9c) is weak (upper bound $\ge |V|/2$). The paper therefore replaces (9b) by independent-set inequalities: given a collection $\mathscr{C}$ of independent sets of $G$ covering all pairs $\{u,v\}\in\bar{E}(G)$, $$\begin{align} + \sum_{u \in I} x_u \le 1, \quad \forall\, I \in \mathscr{C}. \tag{10} +\end{align}$$ The ILP used as the baseline in the paper’s computational experiments is (9a) + (10) + (9c); the original formulation as stated in the paper, however, is (9a)–(9c). diff --git a/tasks/sansegundo2023/problem_description.txt b/tasks/sansegundo2023/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..e60a0e7ed74b9c8c7f3688ababb62bed03a27730 --- /dev/null +++ b/tasks/sansegundo2023/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +Given a simple undirected graph defined by a set of vertices and a set of edges, the goal is to find a clique of maximum size, where a clique is a subset of vertices in which every pair of vertices is connected by an edge. The input specifies the number of vertices, the number of edges, the complete list of vertices (indexed from zero), and the complete list of edges as pairs of vertex indices. An adjacency list representation is also provided, mapping each vertex to the list of its neighbors. + +The task is to select a subset of the vertices such that the number of selected vertices is as large as possible, subject to the requirement that every two selected vertices must be connected by an edge in the graph. Equivalently, for every pair of distinct vertices u and v that are NOT connected by an edge in the graph, at most one of u and v may be selected. The goal is to maximize the total number of selected vertices subject to this pairwise non-adjacency restriction. diff --git a/tasks/sansegundo2023/solution_logger.py b/tasks/sansegundo2023/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/sansegundo2023/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/sansegundo2023/solution_schema.json b/tasks/sansegundo2023/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fb2e2496d34a9885efdb15d9b7cd1449bf7c362b --- /dev/null +++ b/tasks/sansegundo2023/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Size of the largest clique found in the graph.", + "clique_vertices": " Vertices selected to form the maximum clique, where every pair is connected by an edge." +} diff --git a/tasks/savelsbergh1997/feasibility_check.py b/tasks/savelsbergh1997/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c2823c3752769b58ea6d72760ac754b7b613c39f --- /dev/null +++ b/tasks/savelsbergh1997/feasibility_check.py @@ -0,0 +1,431 @@ +""" +Feasibility checker for the Generalized Assignment Problem (GAP). + +Reference: Savelsbergh (1997), "A Branch-and-Price Algorithm for the +Generalized Assignment Problem", Operations Research 45(6):831-841. + +Checks the Standard Integer Programming Formulation (Formulation 1): + + max sum_{i,j} p_{ij} x_{ij} + + subject to + (1) sum_{i=1..m} x_{ij} = 1, for j = 1,...,n + (2) sum_{j=1..n} w_{ij} x_{ij} <= c_i, for i = 1,...,m + (3) x_{ij} in {0, 1}, for all i, j + (4) reported objective_value must equal recomputed + sum_{i,j} p_{ij} x_{ij} within tolerance (anti-gaming check). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +TOL = 1e-5 +EPS = 1e-5 + + +def check_feasibility(instance, solution): + """ + Check all hard constraints of the GAP standard IP formulation. + + Returns a dict with feasibility results. + """ + m = instance["num_agents"] + n = instance["num_jobs"] + profits = instance["profits"] # profits[i][j] + weights = instance["weights"] # weights[i][j] + capacities = instance["capacities"] # capacities[i] + + assignment = solution["assignment"] # dict: str(j) -> agent i + + violations = [] + violation_magnitudes = [] + + # --------------------------------------------------------------- + # Build the x_{ij} matrix from the assignment dict + # --------------------------------------------------------------- + x = [[0] * n for _ in range(m)] + for j_str, i_val in assignment.items(): + j = int(j_str) + i = int(i_val) + if 0 <= i < m and 0 <= j < n: + x[i][j] += 1 # use += to detect duplicates + + # --------------------------------------------------------------- + # Constraint (1): sum_{i=1..m} x_{ij} = 1, for each j = 1,...,n + # Equality constraint: violation_amount = |LHS - RHS| + # --------------------------------------------------------------- + constraint_1_violated = False + for j in range(n): + lhs = sum(x[i][j] for i in range(m)) + rhs = 1.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + constraint_1_violated = True + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + if lhs == 0: + violations.append( + f"Constraint (1): Job {j} is not assigned to any agent " + f"(sum_i x_{{i,{j}}} = {lhs}, expected 1)" + ) + elif lhs > 1: + violations.append( + f"Constraint (1): Job {j} is assigned to {lhs} agents " + f"(sum_i x_{{i,{j}}} = {lhs}, expected 1)" + ) + else: + violations.append( + f"Constraint (1): Job {j} assignment sum is {lhs} " + f"(expected 1)" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # --------------------------------------------------------------- + # Constraint (2): sum_{j=1..n} w_{ij} x_{ij} <= c_i, for each i + # <= constraint: violation_amount = max(LHS - RHS, 0) + # --------------------------------------------------------------- + constraint_2_violated = False + for i in range(m): + lhs = sum(weights[i][j] * x[i][j] for j in range(n)) + rhs = float(capacities[i]) + violation_amount = max(lhs - rhs, 0.0) + if violation_amount > TOL: + constraint_2_violated = True + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint (2): Agent {i} capacity exceeded " + f"(load = {lhs}, capacity = {rhs}, excess = {violation_amount})" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # --------------------------------------------------------------- + # Constraint (3): x_{ij} in {0, 1} for all i, j + # Each x_{ij} must be exactly 0 or 1. + # Treat as equality to nearest integer: violation = |x_{ij} - round(x_{ij})| + # --------------------------------------------------------------- + constraint_3_violated = False + for i in range(m): + for j in range(n): + val = x[i][j] + if val not in (0, 1): + nearest_bin = round(val) + violation_amount = abs(val - nearest_bin) + if violation_amount > TOL: + constraint_3_violated = True + rhs = float(nearest_bin) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint (3): x_{{{i},{j}}} = {val} is not binary " + f"(expected 0 or 1)" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(val), + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + elif val > 1: + # x_{ij} > 1 means job assigned multiple times to same agent + constraint_3_violated = True + rhs = 1.0 + violation_amount = abs(val - rhs) + normalizer = max(abs(rhs), EPS) + ratio = violation_amount / normalizer + violations.append( + f"Constraint (3): x_{{{i},{j}}} = {val} is not binary " + f"(expected 0 or 1)" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(val), + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # Also check that assignment keys reference valid jobs in range [0, n) + for j_str, i_val in assignment.items(): + j = int(j_str) + i = int(i_val) + if j < 0 or j >= n: + violations.append( + f"Constraint (1): Job index {j} is out of range [0, {n-1}]" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": 0.0, + "rhs": 1.0, + "raw_excess": 1.0, + "normalizer": 1.0, + "ratio": 1.0, + }) + if i < 0 or i >= m: + violations.append( + f"Constraint (3): Agent index {i} is out of range [0, {m-1}] " + f"for job {j}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(i), + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": EPS, + "ratio": 1.0 / EPS, + }) + + # --------------------------------------------------------------- + # Constraint (4): objective consistency (anti-gaming). + # Reported objective_value must equal recomputed + # sum_{i,j} p_{ij} x_{ij} + # within tolerance. Catches LLM-evolved exploits that fabricate + # objective_value while keeping assignment feasible. + # --------------------------------------------------------------- + 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(m): + for j in range(n): + if x[i][j]: + true_obj += float(profits[i][j]) * x[i][j] + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor. Profits are + # integers so any honest reporter will match exactly; the slack + # only forgives float-roundtrip noise. + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + normalizer = max(abs(true_obj), EPS) + ratio = abs_diff / normalizer + violations.append( + f"Constraint (4): Objective consistency violated: " + f"reported objective_value={reported} differs from " + f"recomputed sum_{{i,j}} p_{{ij}} x_{{ij}}={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.3g})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # --------------------------------------------------------------- + # Build result + # --------------------------------------------------------------- + violated_constraints = sorted(set( + vm["constraint"] for vm in violation_magnitudes + )) + 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 GAP (Savelsbergh 1997)" + ) + 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) + + if result["feasible"]: + print(f"FEASIBLE — no constraint violations detected.") + else: + print(f"INFEASIBLE — {len(result['violations'])} violation(s) found:") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/savelsbergh1997/gurobi_code.py b/tasks/savelsbergh1997/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe109667254e704212db30e295a83666508886d --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_code.py @@ -0,0 +1,164 @@ +""" +Gurobi implementation of the standard Integer Programming formulation for the +Generalized Assignment Problem (GAP) - Maximization form. + +Reference: Savelsbergh (1997), "A Branch-and-Price Algorithm for the Generalized +Assignment Problem", Operations Research 45(6):831-841. + +Formulation 1 (Standard IP): + max sum_{i,j} p_{ij} x_{ij} + s.t. sum_{i} x_{ij} = 1, for all j (each job assigned to exactly one agent) + sum_{j} w_{ij} x_{ij} <= c_i, for all i (capacity constraints) + x_{ij} in {0, 1} +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path): + """Load a GAP instance from a JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def solve_gap(instance_path, solution_path, time_limit): + """Solve the GAP using Gurobi with the standard IP formulation.""" + data = load_instance(instance_path) + + m = data["num_agents"] + n = data["num_jobs"] + profits = data["profits"] # profits[i][j] + weights = data["weights"] # weights[i][j] + capacities = data["capacities"] # capacities[i] + + # Create model + model = gp.Model("GAP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables: x[i][j] = 1 if job j is assigned to agent i + x = {} + for i in range(m): + for j in range(n): + x[i, j] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{j}", + obj=profits[i][j]) + + model.setAttr("ModelSense", GRB.MAXIMIZE) + model.update() + + # Constraint (1): Each job is assigned to exactly one agent + for j in range(n): + model.addConstr( + gp.quicksum(x[i, j] for i in range(m)) == 1, + name=f"assign_{j}" + ) + + # Constraint (2): Capacity constraint for each agent + for i in range(m): + model.addConstr( + gp.quicksum(weights[i][j] * x[i, j] for j in range(n)) <= capacities[i], + name=f"capacity_{i}" + ) + + # Optimize + model.optimize() + + # Extract solution + solution = { + "problem": data.get("problem", "GAP"), + "objective": "maximize", + "num_agents": m, + "num_jobs": n, + "solver": "Gurobi", + "formulation": "Standard IP (Formulation 1)", + } + + if model.SolCount > 0: + obj_val = model.ObjVal + solution["objective_value"] = obj_val + solution["status"] = model.Status + solution["status_description"] = { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.INF_OR_UNBD: "INF_OR_UNBD", + GRB.UNBOUNDED: "UNBOUNDED", + }.get(model.Status, f"STATUS_{model.Status}") + solution["mip_gap"] = model.MIPGap if hasattr(model, "MIPGap") else None + solution["best_bound"] = model.ObjBound + + # Extract assignment + assignment = {} + for j in range(n): + for i in range(m): + if x[i, j].X > 0.5: + assignment[str(j)] = i + break + solution["assignment"] = assignment + + # Verify capacity constraints + agent_loads = [0] * m + for j_str, i in assignment.items(): + j = int(j_str) + agent_loads[i] += weights[i][j] + solution["agent_loads"] = agent_loads + solution["capacities"] = capacities + solution["capacity_feasible"] = all( + agent_loads[i] <= capacities[i] for i in range(m) + ) + else: + solution["objective_value"] = None + solution["status"] = model.Status + solution["status_description"] = "NO_SOLUTION_FOUND" + + # 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"Solution written to {solution_path}") + if model.SolCount > 0: + print(f"Objective value: {obj_val}") + print(f"Status: {solution['status_description']}") + else: + print("No feasible solution found.") + + +def main(): + parser = argparse.ArgumentParser( + description="Solve GAP using Gurobi (Standard IP Formulation)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path for the output solution JSON file.") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve_gap(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/savelsbergh1997/gurobi_feasi_result/large_feasi_result_1.json b/tasks/savelsbergh1997/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/savelsbergh1997/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/savelsbergh1997/gurobi_feasi_result/large_feasi_result_2.json b/tasks/savelsbergh1997/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/savelsbergh1997/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/savelsbergh1997/gurobi_feasi_result/large_feasi_result_3.json b/tasks/savelsbergh1997/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/savelsbergh1997/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/savelsbergh1997/gurobi_feasi_result/large_feasi_result_4.json b/tasks/savelsbergh1997/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/savelsbergh1997/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/savelsbergh1997/gurobi_feasi_result/large_feasi_result_5.json b/tasks/savelsbergh1997/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/savelsbergh1997/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/savelsbergh1997/gurobi_feasi_result/tiny_feasi_result.json b/tasks/savelsbergh1997/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/savelsbergh1997/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/savelsbergh1997/gurobi_solution/large_solution_1.json b/tasks/savelsbergh1997/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9eb5e7cfa5e5d94d4b8c90c539a4ddb96712c077 --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50c83cf0e9a1ceb61efdb3d0b69a50a787933dcfc2d18957d18fff0cfc4e1bae +size 2153 diff --git a/tasks/savelsbergh1997/gurobi_solution/large_solution_2.json b/tasks/savelsbergh1997/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c0d3f24fa8c16e6f107e0480bb0c5931766cd3c8 --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4a9506857caf81244c230579b6c4d18ba0ffc1e91ba8c025d55e7dcdc3fa1c2 +size 2114 diff --git a/tasks/savelsbergh1997/gurobi_solution/large_solution_3.json b/tasks/savelsbergh1997/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..6b1c09ae1d797392bf8625a298044196b56011dc --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d5db6bf227089bbad95551a66e3f6317d352dec07a86660c1e54652a66fd08b +size 2084 diff --git a/tasks/savelsbergh1997/gurobi_solution/large_solution_4.json b/tasks/savelsbergh1997/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..bd36e9aacb46a17c7f422db8ee3d21b3b07fd44b --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b40010be6d2f4eb73e2dbe08d4391557add339f3855e630aba3463e2134cb61 +size 2088 diff --git a/tasks/savelsbergh1997/gurobi_solution/large_solution_5.json b/tasks/savelsbergh1997/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d3cb174dbe6d8e4917908912e188d8e9da75dd66 --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd0d65d09a403eba965b68ea5ae76c1a865fc62b3ed1496339f9237ffa5df175 +size 2148 diff --git a/tasks/savelsbergh1997/gurobi_solution/tiny_solution.json b/tasks/savelsbergh1997/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..ad19f7444b3451a0e85d94e6663337719a0681fe --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3eef00c5d1fb3dadf472347898954a58ee6ce14ff64133c3e469a36a8439dfb3 +size 858 diff --git a/tasks/savelsbergh1997/gurobi_solution_log/large_log_1.jsonl b/tasks/savelsbergh1997/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1d1e150b24433738abc114f3d75c9487e00277a8 --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2e8ba2810a1367081e47651082ec2fa01f26dc4c47c83247649311a31b321ff +size 524 diff --git a/tasks/savelsbergh1997/gurobi_solution_log/large_log_2.jsonl b/tasks/savelsbergh1997/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9a08b2b9cf833878af566c5c4b3b54ff9ed5961b --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ee8eee61e1a43b370d9c24ef58a815f792ce9c89b208a8da7e0988e988bed66 +size 42 diff --git a/tasks/savelsbergh1997/gurobi_solution_log/large_log_3.jsonl b/tasks/savelsbergh1997/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..47986f1429346ae014c8959a92a96b2a2aaeac84 --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2de9331999229fca06f32021705b2cedd7598a236e226771af8faee7b00fd6d +size 42 diff --git a/tasks/savelsbergh1997/gurobi_solution_log/large_log_4.jsonl b/tasks/savelsbergh1997/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..13dd8dc2454ee6106d0ede7c66e42464dd9b7dea --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8619d0a97eae6fb5ba6eeecf01c86cb987231c3cc7ae3a7440f371e7cb6cf1c1 +size 42 diff --git a/tasks/savelsbergh1997/gurobi_solution_log/large_log_5.jsonl b/tasks/savelsbergh1997/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..39a7606f85be0b7895e8c6c93c1bb7707f3198d1 --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76354544e1cd55ecadd75d7d5b34855285698b35db490f2666882ead097a3cc3 +size 610 diff --git a/tasks/savelsbergh1997/gurobi_solution_log/tiny_log.jsonl b/tasks/savelsbergh1997/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3c6d3f32c782d2ac2327b89545ef0291f98eb67c --- /dev/null +++ b/tasks/savelsbergh1997/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b4e01d0feaee3bb7a99b516d055f230dc1dd1c1e8dd58177852da042ef36a15 +size 42 diff --git a/tasks/savelsbergh1997/instance/large_instance_1.json b/tasks/savelsbergh1997/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..f8fe86d085347d4205b93b3d127fe96c8f6f3561 --- /dev/null +++ b/tasks/savelsbergh1997/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2366ca8e07fe30320b4757e2b78578ecc844bba3129bff32b87eb90036c8ee6 +size 45168 diff --git a/tasks/savelsbergh1997/instance/large_instance_2.json b/tasks/savelsbergh1997/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..5a121dc71575398a6e6e6d6ac712b4b3b33a0f43 --- /dev/null +++ b/tasks/savelsbergh1997/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:daddb11eefd68a9d9fc5794205f1810b0bfab722a594ec8b84dcfd3f0839d4b4 +size 39454 diff --git a/tasks/savelsbergh1997/instance/large_instance_3.json b/tasks/savelsbergh1997/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c84b92321584a1b267deca87638c520d004e0edb --- /dev/null +++ b/tasks/savelsbergh1997/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4af7ff602ad8199c0299c4355f6826720fa99e56ee6ac4599d3970dba6e5bb8a +size 39487 diff --git a/tasks/savelsbergh1997/instance/large_instance_4.json b/tasks/savelsbergh1997/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d741bfc4b7141915be7a17666097315f8554d6ce --- /dev/null +++ b/tasks/savelsbergh1997/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86a0a1220c1e940014c88c420d5f42f2c9a91963e1ec1e0d43087de2c9d31335 +size 39431 diff --git a/tasks/savelsbergh1997/instance/large_instance_5.json b/tasks/savelsbergh1997/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c0efefb8df107bf02b66b07af3393727848d0edf --- /dev/null +++ b/tasks/savelsbergh1997/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6604e7625914aa5199c0adebc3a2c4c319603b9d163a97b4f4a604f8560f3c22 +size 41132 diff --git a/tasks/savelsbergh1997/instance/tiny_instance.json b/tasks/savelsbergh1997/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..8933069c570158a885bab378d3fa8779f5f7a343 --- /dev/null +++ b/tasks/savelsbergh1997/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f56fe42e19fa696eecbff7038a13fb4b6ed8bce5534d0f012fa2d01afb2ac229 +size 2427 diff --git a/tasks/savelsbergh1997/instance_schema.json b/tasks/savelsbergh1997/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..899fc4d4bf3a389cbe490d4027664406120ffb3e --- /dev/null +++ b/tasks/savelsbergh1997/instance_schema.json @@ -0,0 +1,7 @@ +{ + "num_agents": " Number of agents available to perform jobs.", + "num_jobs": " Number of jobs that must be assigned to agents.", + "profits": " Profit earned when a given agent performs a given job.", + "weights": " Amount of resource capacity consumed when a given agent performs a given job.", + "capacities": " Maximum total weight of jobs that each agent can handle." +} diff --git a/tasks/savelsbergh1997/mathematical_formulation.md b/tasks/savelsbergh1997/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..81b5de76c3d4da8cd2562a96078c7ebfad26136e --- /dev/null +++ b/tasks/savelsbergh1997/mathematical_formulation.md @@ -0,0 +1,33 @@ +# Sets and Indices + +- $m$: number of agents, indexed by $i \in \{1,\ldots,m\}$. + +- $n$: number of jobs, indexed by $j \in \{1,\ldots,n\}$. + +# Parameters + +- $p_{ij} \in \mathbb{Z}_+$: profit associated with assigning job $j$ to agent $i$. + +- $w_{ij} \in \mathbb{Z}_+$: capacity consumption on agent $i$ if job $j$ is assigned to agent $i$. + +- $c_i \in \mathbb{Z}_+$: capacity of agent $i$. + +# Decision Variables + +- $x_{ij} \in \{0,1\}$: equals $1$ if job $j$ is assigned to agent $i$, and $0$ otherwise, for $i \in \{1,\ldots,m\}$, $j \in \{1,\ldots,n\}$. + +# Objective + +Maximize total profit of the assignment: $$\begin{align} + \max \quad & \sum_{i=1}^{m} \sum_{j=1}^{n} p_{ij}\, x_{ij} \tag{1} +\end{align}$$ + +# Constraints + +$$\begin{align} + \sum_{i=1}^{m} x_{ij} &= 1, && j \in \{1,\ldots,n\} \tag{2} \\ + \sum_{j=1}^{n} w_{ij}\, x_{ij} &\le c_i, && i \in \{1,\ldots,m\} \tag{3} \\ + x_{ij} &\in \{0,1\}, && i \in \{1,\ldots,m\},\ j \in \{1,\ldots,n\} \tag{4} +\end{align}$$ + +Constraint (2) is the semi-assignment constraint (each job assigned to exactly one agent); (3) is the knapsack/capacity constraint per agent; (4) gives binary integrality. diff --git a/tasks/savelsbergh1997/problem_description.txt b/tasks/savelsbergh1997/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..a57840df324e50e696be0377f3632cd22fdd0e79 --- /dev/null +++ b/tasks/savelsbergh1997/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A company must assign a set of jobs to a set of agents. There are n jobs and m agents. Each job must be assigned to exactly one agent, and every job must be assigned. Each possible pairing of a job with an agent has an associated profit, which is a nonnegative integer representing the value earned when that particular agent performs that particular job. Each possible pairing also has an associated weight, which is a nonnegative integer representing the amount of the agent's resource capacity consumed if that agent performs that job. Every agent has a fixed positive integer capacity limiting the total weight of all jobs assigned to it. + +The input data specifies the number of agents, the number of jobs, a profit value for every agent-job pair, a weight value for every agent-job pair, and a capacity for each agent. Profits and weights are provided as two-dimensional arrays indexed by agent and job, and capacities are provided as a one-dimensional array indexed by agent. + +The company must decide which single agent each job is assigned to. Every job must be assigned to exactly one agent, meaning no job may be left unassigned and no job may be split across multiple agents. For each agent, the total weight of all jobs assigned to that agent must not exceed that agent's capacity. The goal is to maximize the total profit, computed as the sum of the profits corresponding to the chosen agent-job assignments across all jobs. diff --git a/tasks/savelsbergh1997/solution_logger.py b/tasks/savelsbergh1997/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/savelsbergh1997/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/savelsbergh1997/solution_schema.json b/tasks/savelsbergh1997/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e834a27c5834bcc841d353fbe0bd8a349558ad99 --- /dev/null +++ b/tasks/savelsbergh1997/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total profit earned from all agent-job assignments.", + "assignment": " Agent assigned to each job." +} diff --git a/tasks/schwerdfeger2016/feasibility_check.py b/tasks/schwerdfeger2016/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fdd0caae6855b53bf2a73a7b14291cd6c8aa48 --- /dev/null +++ b/tasks/schwerdfeger2016/feasibility_check.py @@ -0,0 +1,410 @@ +""" +Feasibility checker for P || NSSWD (Workload Balancing on Identical Parallel Machines). + +Checks the hard constraints from the mathematical formulation: + Constraint 1 (Eq. 3): sum_j p_j * x_{ij} = C_i, for each machine i + Constraint 2 (Eq. 4): sum_i x_{ij} = 1, for each job j + Constraint 3 (Eq. 5): x_{ij} in {0, 1}, for all i, j + Constraint 4 (Eq. 2): objective_value consistency with assignment + (Tier C: full recompute of NSSWD from x_{ij}) +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignment', 'machine_completion_times', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + n = instance["num_jobs"] + m = instance["num_machines"] + p = instance["processing_times"] # list of length n + + assignment = solution.get("assignment", {}) + machine_completion_times = solution.get("machine_completion_times", {}) + + # Build assignment matrix: for each job, which machines is it assigned to? + job_assignment_count = [0] * n + job_assignments = [[] for _ in range(n)] # which machines each job is on + + for machine_key, job_list in assignment.items(): + for j in job_list: + if 0 <= j < n: + job_assignment_count[j] += 1 + job_assignments[j].append(machine_key) + + # ------------------------------------------------------------------ + # Constraint 1 (Eq. 3): sum_j p_j * x_{ij} = C_i for each machine i + # ------------------------------------------------------------------ + for machine_key, job_list in assignment.items(): + computed_completion = sum(p[j] for j in job_list if 0 <= j < n) + reported_completion = machine_completion_times.get(machine_key, 0) + if isinstance(reported_completion, str): + reported_completion = float(reported_completion) + + lhs = computed_completion + rhs = reported_completion + violation_amount = abs(lhs - rhs) + + if violation_amount > tol: + violated_constraints.add(1) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 1 violated on machine {machine_key}: " + f"sum(p_j) = {lhs}, reported C_i = {rhs}, diff = {violation_amount:.6f}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ------------------------------------------------------------------ + # Constraint 2 (Eq. 4): sum_i x_{ij} = 1 for each job j + # ------------------------------------------------------------------ + for j in range(n): + count = job_assignment_count[j] + lhs = count + rhs = 1 + violation_amount = abs(lhs - rhs) + + if violation_amount > tol: + violated_constraints.add(2) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + if count == 0: + msg = f"Constraint 2 violated: job {j} is not assigned to any machine" + else: + machines_str = ", ".join(str(mk) for mk in job_assignments[j]) + msg = ( + f"Constraint 2 violated: job {j} is assigned to " + f"{count} machines ({machines_str}) instead of exactly 1" + ) + violations.append(msg) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ------------------------------------------------------------------ + # Constraint 3 (Eq. 5): x_{ij} in {0, 1} — domain/integrality + # Check that all job indices in assignments are valid (0..n-1) + # and that the solution uses exactly m machines. + # ------------------------------------------------------------------ + for machine_key, job_list in assignment.items(): + for j in job_list: + if not isinstance(j, int) or j < 0 or j >= n: + violated_constraints.add(3) + lhs = float(j) if isinstance(j, (int, float)) else 0.0 + rhs = 0.0 # expected: valid index in [0, n-1] + violation_amount = 1.0 # binary domain violation + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 3 violated: invalid job index {j} " + f"on machine {machine_key} (valid range: 0..{n-1})" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(lhs) if isinstance(j, (int, float)) else 0.0, + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # Check number of machines matches + num_machines_in_sol = len(assignment) + if num_machines_in_sol != m: + violated_constraints.add(3) + lhs = float(num_machines_in_sol) + rhs = float(m) + violation_amount = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 3 violated: solution has {num_machines_in_sol} machines " + f"but instance requires {m}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + # ------------------------------------------------------------------ + # Constraint 4 (Eq. 2): objective_value consistency (Tier C) + # Full recompute of NSSWD = (1/mu) * sqrt(sum_i (C_i - mu)^2) from the + # assignment. The solution carries every variable the objective + # depends on (the per-machine job lists), so an exact recomputation + # is possible. Reject when the reported value disagrees beyond a + # tight tolerance: this catches obj=0 / obj=MAX_FLOAT exploits. + # ------------------------------------------------------------------ + reported_obj_raw = solution.get("objective_value") + if reported_obj_raw is not None and m > 0 and sum(p) > 0: + try: + reported_obj = float(reported_obj_raw) + except (TypeError, ValueError): + reported_obj = None + if reported_obj is not None and math.isfinite(reported_obj): + mu = sum(p) / m + # Use the same C_i the assignment implies (ignore reported C_i: + # constraint 1 already validates that link). + C = [sum(p[j] for j in job_list if 0 <= j < n) + for job_list in assignment.values()] + sq_dev = sum((c - mu) ** 2 for c in C) + true_obj = math.sqrt(sq_dev) / mu if mu > 0 else 0.0 + abs_diff = abs(reported_obj - true_obj) + # Tight tolerance: Gurobi-reported obj matches recompute to + # exact float on the reference solutions, so 1e-8 absolute + # floor with 1e-6 relative is safe against FP noise while + # still catching obj=0 exploits on small-obj instances + # (true_obj ~5e-4 here, so diff ~5e-4 >> 1e-8). + obj_tol = max(1e-8, 1e-6 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(4) + normalizer = max(abs(true_obj), eps) + ratio = abs_diff / normalizer + violations.append( + f"Constraint 4 violated: reported objective_value=" + f"{reported_obj} differs from recomputed NSSWD=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported_obj), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + elif reported_obj is not None: + # Non-finite (inf / nan) reported objective: also a violation. + violated_constraints.add(4) + violations.append( + f"Constraint 4 violated: reported objective_value is " + f"non-finite ({reported_obj_raw})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float("inf") if reported_obj == float("inf") else 0.0, + "rhs": 0.0, + "raw_excess": float("inf"), + "normalizer": eps, + "ratio": float("inf"), + }) + + # Build result + sorted_violated = sorted(violated_constraints) + feasible = len(sorted_violated) == 0 + + result = { + "feasible": feasible, + "violated_constraints": sorted_violated, + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for P || NSSWD" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance" + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution" + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result" + ) + args = parser.parse_args() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + 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/schwerdfeger2016/gurobi_code.py b/tasks/schwerdfeger2016/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..45bff40192bfb862ccf13ecdc9937138b0030d8c --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_code.py @@ -0,0 +1,197 @@ +""" +Gurobi implementation of P || NSSWD +Minimizes the normalized sum of squared workload deviations on identical parallel machines. +Source: Schwerdfeger & Walter (2016), Computers & Operations Research 73 (2016) 84-91 +""" + +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 compute_nsswd(completions, mu): + """Compute NSSWD value given machine completion times and average mu.""" + if mu == 0: + return 0.0 + return math.sqrt(sum((c - mu) ** 2 for c in completions)) / mu + + +def solve(instance_path, solution_path, time_limit): + # Load instance + with open(instance_path, "r") as f: + inst = json.load(f) + + processing_times = inst["processing_times"] # already sorted descending per paper + n_orig = len(processing_times) + m_orig = inst["num_machines"] + + # Sort jobs descending (p_1 >= p_2 >= ... >= p_n) + processing_times = sorted(processing_times, reverse=True) + + # --- Preprocessing / Reduction (Fig. 1 in paper) --- + # If p_1 >= mu, assign that job alone to a machine and remove both. + jobs = list(range(n_orig)) # indices into processing_times + p = {j: processing_times[j] for j in jobs} + active_jobs = list(jobs) + removed_assignments = [] # list of (machine_label, job_index) + + machine_counter = 0 + P_total = sum(p[j] for j in active_jobs) + m_active = m_orig + + i = 0 + while i < len(active_jobs): + if m_active <= 0: + break + mu_current = P_total / m_active + job_i = active_jobs[i] + if p[job_i] >= mu_current: + removed_assignments.append((machine_counter, job_i)) + machine_counter += 1 + active_jobs.pop(i) + P_total -= p[job_i] + m_active -= 1 + # do not increment i; next job slides into position i + else: + break # jobs are sorted; if p[i] < mu then all remaining < mu + + # Remaining jobs and machines after reduction + n = len(active_jobs) + m = m_active + + mu = P_total / m if m > 0 else 0.0 + + # Build Gurobi model + model = gp.Model("P_NSSWD") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 0) + + # Decision variables: x[i,j] = 1 if active job j assigned to active machine i + # i in 0..m-1, j indexes into active_jobs list + x = {} + for i in range(m): + for jidx, j in enumerate(active_jobs): + x[i, jidx] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}_{jidx}") + + # Completion time auxiliary variables C[i] + C = {} + for i in range(m): + C[i] = model.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name=f"C_{i}") + + model.update() + + # Constraint (3): sum_j p_j * x[i,j] = C[i] + for i in range(m): + model.addConstr( + gp.quicksum(p[active_jobs[jidx]] * x[i, jidx] for jidx in range(n)) == C[i], + name=f"completion_{i}" + ) + + # Constraint (4): each job assigned to exactly one machine + for jidx in range(n): + model.addConstr( + gp.quicksum(x[i, jidx] for i in range(m)) == 1, + name=f"assign_{jidx}" + ) + + # Objective: minimize sum_i (C_i - mu)^2 (equivalent to minimizing NSSWD, Eq. 6) + # This is a quadratic objective (binary quadratic program). + # NOTE: Since mu is constant for a given instance, minimizing sum (C_i - mu)^2 + # is equivalent to minimizing NSSWD (see Eq. 6 in paper). + obj = gp.quicksum((C[i] - mu) * (C[i] - mu) for i in range(m)) + model.setObjective(obj, GRB.MINIMIZE) + + model.optimize() + + # Extract solution + status = model.Status + has_solution = status in (GRB.OPTIMAL, GRB.TIME_LIMIT, GRB.SUBOPTIMAL) and model.SolCount > 0 + + if has_solution: + # Build assignment: machine -> list of original job indices + assignment = {} + completions = [] + + # Pre-fill removed (preprocessed) machines + for mac_label, job_idx in removed_assignments: + assignment[mac_label] = [job_idx] + + for i in range(m): + mac_label = machine_counter + i + assignment[mac_label] = [] + c_val = 0.0 + for jidx, j in enumerate(active_jobs): + if x[i, jidx].X > 0.5: + assignment[mac_label].append(j) + c_val += p[j] + completions.append(c_val) + + # Add removed machines' completion times + removed_completions = [p[job_idx] for _, job_idx in removed_assignments] + all_completions = removed_completions + completions + + mu_full = sum(processing_times[j] for j in range(n_orig)) / m_orig + nsswd_val = compute_nsswd(all_completions, mu_full) + + # Convert assignment keys to strings for JSON + assignment_out = {str(k): v for k, v in assignment.items()} + + solution = { + "objective_value": nsswd_val, + "status": "optimal" if status == GRB.OPTIMAL else "feasible", + "num_machines": m_orig, + "num_jobs": n_orig, + "assignment": assignment_out, + "machine_completion_times": {str(k): sum(processing_times[j] for j in v) + for k, v in assignment.items()}, + } + else: + solution = { + "objective_value": None, + "status": "infeasible_or_no_solution", + "num_machines": m_orig, + "num_jobs": n_orig, + } + + 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']}") + print(f"Objective (NSSWD): {solution['objective_value']}") + print(f"Solution written to: {solution_path}") + + +def main(): + parser = argparse.ArgumentParser(description="Gurobi solver for P || NSSWD") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to write the solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + solve(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_1.json b/tasks/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/schwerdfeger2016/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/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_2.json b/tasks/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/schwerdfeger2016/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/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_3.json b/tasks/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/schwerdfeger2016/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/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_4.json b/tasks/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/schwerdfeger2016/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/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_5.json b/tasks/schwerdfeger2016/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/schwerdfeger2016/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/schwerdfeger2016/gurobi_feasi_result/tiny_feasi_result.json b/tasks/schwerdfeger2016/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/schwerdfeger2016/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/schwerdfeger2016/gurobi_solution/large_solution_1.json b/tasks/schwerdfeger2016/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..29d3f8431786b3a50c991852c98c3439b5991e3f --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a48e9ab1e1c932eb5d8b4039763d4ee72de049a3906116b4c8cfb1d53c895405 +size 3614 diff --git a/tasks/schwerdfeger2016/gurobi_solution/large_solution_2.json b/tasks/schwerdfeger2016/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..ad1eb41bd6d96d8ce17709287d16527d785cc140 --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1324255afa9db6190a8e3ecdb71b897f10e12b25e60aeecf13221444e5212f39 +size 3615 diff --git a/tasks/schwerdfeger2016/gurobi_solution/large_solution_3.json b/tasks/schwerdfeger2016/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e9f633c703205a9ff0e1b08d4562b13e2aed8c50 --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:237c8e545ad998337345b11891dd82f9503750a824985c7d585ed5c9d9998ad9 +size 3615 diff --git a/tasks/schwerdfeger2016/gurobi_solution/large_solution_4.json b/tasks/schwerdfeger2016/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..98fdd36945b1ab07288c112e59175da513b3d285 --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75fbb2f19445c84d97aad0b862d1656fb1f8f6d704214b70db67f57cd4076349 +size 3616 diff --git a/tasks/schwerdfeger2016/gurobi_solution/large_solution_5.json b/tasks/schwerdfeger2016/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..1792afc68643ab3cd5cdd5036bcf6c03aa2bc7fd --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a31cd5ed0a2c0830f153dd88f0f7de1b436e866002569d942e02bc6317e7d05b +size 3614 diff --git a/tasks/schwerdfeger2016/gurobi_solution/tiny_solution.json b/tasks/schwerdfeger2016/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..b14552eb1113e575508603e0a23e46777066abe3 --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db0a38897d119234da104679c59a04e3b5895b83f3ec1ae88b060d62bf5c7ed8 +size 321 diff --git a/tasks/schwerdfeger2016/gurobi_solution_log/tiny_log.jsonl b/tasks/schwerdfeger2016/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f54d596d4d7fc0ccb75b158ecf0b8a73fecca696 --- /dev/null +++ b/tasks/schwerdfeger2016/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cea09c7bdab33cb3ebbac7b43e83dd18ed72633799b06f8d27390bc5f0bc723e +size 54 diff --git a/tasks/schwerdfeger2016/instance/large_instance_1.json b/tasks/schwerdfeger2016/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9afac5aa9a09c7a9b1cb8c20bc1fb3e184c8f633 --- /dev/null +++ b/tasks/schwerdfeger2016/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b794f08ebb5054d3e6aa471334d2b50cf0cf71c28f345a5ca2f7377177f543c +size 2865 diff --git a/tasks/schwerdfeger2016/instance/large_instance_2.json b/tasks/schwerdfeger2016/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1275dfdaebd536b1d17ffcc44b4a508fca49a896 --- /dev/null +++ b/tasks/schwerdfeger2016/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bab3be8dec41b1ccfb4c7151917ddb8a9eb01ec8452c42d65002b45eadfb8382 +size 3176 diff --git a/tasks/schwerdfeger2016/instance/large_instance_3.json b/tasks/schwerdfeger2016/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..adb1f4437ea4adecb16be182da7fd2481bb1cf8f --- /dev/null +++ b/tasks/schwerdfeger2016/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c21ff1f52a6e5b9787143e38baecec3836805f56c90e4513e9ff1f8a77109106 +size 3109 diff --git a/tasks/schwerdfeger2016/instance/large_instance_4.json b/tasks/schwerdfeger2016/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..ec16a6c453608cda2c8ff94723342e26a423ed2e --- /dev/null +++ b/tasks/schwerdfeger2016/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4728853fc7e0ffb1daf529fc3e475034fd13e8951dc17f6220bd29efd72e060c +size 3097 diff --git a/tasks/schwerdfeger2016/instance/large_instance_5.json b/tasks/schwerdfeger2016/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..579f0bb1b4015c6ae57e1636823d8b13054cdd7a --- /dev/null +++ b/tasks/schwerdfeger2016/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d4d77df2cd480f7134c0991ab7f28e65bca193c345069a63245c4b77a95dc82 +size 3040 diff --git a/tasks/schwerdfeger2016/instance/tiny_instance.json b/tasks/schwerdfeger2016/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c4c080bacee974f920ba7c8fb812259f3d36c61b --- /dev/null +++ b/tasks/schwerdfeger2016/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94366110e807ddb2c7056fc4751de5217370445ee207d4822efdf47437b8de0d +size 483 diff --git a/tasks/schwerdfeger2016/instance_schema.json b/tasks/schwerdfeger2016/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..20b9c9ad8d777f5d6ad8e86c5acd44269734e00f --- /dev/null +++ b/tasks/schwerdfeger2016/instance_schema.json @@ -0,0 +1,5 @@ +{ + "num_machines": " Number of identical parallel machines available to process jobs.", + "num_jobs": " Number of independent jobs to be assigned across the machines.", + "processing_times": " Processing time of each job, listed in nonincreasing order." +} \ No newline at end of file diff --git a/tasks/schwerdfeger2016/mathematical_formulation.md b/tasks/schwerdfeger2016/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..c180519d54395e778331f4a205faa1ca879f34b3 --- /dev/null +++ b/tasks/schwerdfeger2016/mathematical_formulation.md @@ -0,0 +1,43 @@ +# Original Formulation: Workload Balancing on Identical Parallel Machines ($P \parallel \mathrm{NSSWD}$) + +*Source: A fast and effective subset sum based improvement procedure for workload balancing on identical parallel machines, Stefan Schwerdfeger & Rico Walter, Computers & Operations Research 73 (2016) 84–91.* + +## Sets and Indices + +$$\begin{align*} +\mathcal{I} &: \text{set of } m \ge 2 \text{ identical parallel machines, indexed by } i = 1, \ldots, m, \\ +\mathcal{J} &: \text{set of } n > m \text{ independent jobs, indexed by } j = 1, \ldots, n. +\end{align*}$$ + +## Parameters + +$$\begin{align*} +p_j \in \mathbb{N} &: \text{integer processing time of job } j \ (j = 1, \ldots, n);\\ + &\quad \text{w.l.o.g. } p_1 \ge p_2 \ge \cdots \ge p_n > 0, \\ +\mu = \frac{1}{m}\sum_{j=1}^{n} p_j &: \text{average machine completion time.} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x_{ij} &\in \{0,1\} : \text{$1$ if job $j$ is assigned to machine $i$, $0$ otherwise},\\ +C_i &: \text{completion time of machine $i$ (auxiliary, fixed by constraint (3)).} +\end{align*}$$ + +## Objective + +The normalized sum of squared workload deviations (NSSWD-criterion) is defined as $$\begin{equation} +\mathrm{NSSWD} = \frac{1}{\mu}\left[\sum_{i=1}^{m}\left(C_i - \mu\right)^2\right]^{1/2}. +\tag{1} +\end{equation}$$ $$\begin{equation} +\text{Minimize}\quad z = \frac{1}{\mu}\left[\sum_{i=1}^{m}\left(C_i - \mu\right)^2\right]^{1/2}. +\tag{2} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{j=1}^{n} p_j\, x_{ij} &= C_i, & i &= 1, \ldots, m, \tag{3}\\ +\sum_{i=1}^{m} x_{ij} &= 1, & j &= 1, \ldots, n, \tag{4}\\ +x_{ij} &\in \{0,1\}, & i &= 1, \ldots, m;\ j = 1, \ldots, n. \tag{5} +\end{align}$$ diff --git a/tasks/schwerdfeger2016/problem_description.txt b/tasks/schwerdfeger2016/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..03b33620d3b7d99176164521dd0dbc70011e06e0 --- /dev/null +++ b/tasks/schwerdfeger2016/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A facility operates a set of identical parallel machines and must schedule a collection of independent jobs across them. The number of machines is at least two, and the number of jobs strictly exceeds the number of machines. Each job has a known positive integer processing time. Every job must be assigned to exactly one machine, and each machine processes all jobs assigned to it without interruption, so that a machine's completion time equals the total processing time of the jobs it receives. The average machine completion time is defined as the sum of all job processing times divided by the number of machines. + +The goal is to assign every job to a machine so as to minimize the normalized sum of squared workload deviations. This measure is computed by taking, for each machine, the squared difference between that machine's completion time and the average machine completion time, summing these squared differences over all machines, taking the square root of that sum, and then dividing by the average machine completion time. Because the average machine completion time is fixed for a given instance, minimizing this normalized deviation measure is equivalent to minimizing the sum of the squared completion times across all machines. + +The input data for each instance specifies the number of machines, the number of jobs, and the processing time of every job. Processing times are positive integers. Jobs are labeled so that their processing times appear in nonincreasing order. diff --git a/tasks/schwerdfeger2016/solution_logger.py b/tasks/schwerdfeger2016/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/schwerdfeger2016/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/schwerdfeger2016/solution_schema.json b/tasks/schwerdfeger2016/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..900433a93d4a4f9b68fcaa63b10cb15da611c032 --- /dev/null +++ b/tasks/schwerdfeger2016/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Normalized sum of squared workload deviations across all machines.", + "assignment": " List of job indices (into processing_times) assigned to each machine.", + "machine_completion_times": " Total processing time of all jobs assigned to each machine." +} \ No newline at end of file diff --git a/tasks/segundo2019/feasibility_check.py b/tasks/segundo2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..37baf875551ff242d1340cc6bef29619b14114fe --- /dev/null +++ b/tasks/segundo2019/feasibility_check.py @@ -0,0 +1,484 @@ +""" +Feasibility checker for the Maximum Edge-Weighted Clique Problem (MEWCP). + +Checks the F1 (Nonedge) formulation from Segundo et al. (2019): + + Constraint 1 (tag 27): x_u + x_v <= 1, for all {u,v} in E_bar (non-edges) + Constraint 2 (tag 6): y_e <= x_u, for all e = {u,v} in E + Constraint 3 (tag 7): y_e <= x_v, for all e = {u,v} in E + Constraint 4 (tag 8): x_u in {0,1}, for all u in V + Constraint 5 (tag 9): y_e in {0,1}, for all e in E + Constraint 6 (Obj): reported objective_value == sum_{e in E} c_e * y_e + (Tier C anti-exploit: reject solutions whose + reported obj disagrees with the value recomputed + from clique_edges and instance edge weights.) +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('clique_edges', 'clique_vertices', '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 edge_key(u, v): + return (min(u, v), max(u, v)) + + +def check_feasibility(instance_path, solution_path, result_path): + with open(instance_path, "r") as f: + instance = json.load(f) + with open(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(result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return _frontieror_contract_result + + graph = instance["graph"] + vertices = set(graph["vertices"]) + edges_raw = graph["edges"] # [[u, v, w], ...] + + # Build edge set and weight map + edge_set = set() + edge_weight = {} + for u, v, w in edges_raw: + k = edge_key(u, v) + edge_set.add(k) + edge_weight[k] = w + + # Extract solution + clique_vertices = solution["clique_vertices"] + clique_edges = solution["clique_edges"] # [[u, v], ...] per solution_schema.json + + # Build x and y from solution + # x_u = 1 if u in clique_vertices, else 0 + x = {u: 1.0 for u in clique_vertices} + # y_e = 1 if edge in clique_edges, else 0 + y = {} + for entry in clique_edges: + u, v = entry[0], entry[1] + k = edge_key(u, v) + y[k] = 1.0 + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint 1 (tag 27): x_u + x_v <= 1 for all non-edges {u,v} in E_bar + # ========================================================================= + # If two clique vertices are NOT connected by an edge, this is violated. + clique_list = list(clique_vertices) + for i in range(len(clique_list)): + for j in range(i + 1, len(clique_list)): + u, v = clique_list[i], clique_list[j] + k = edge_key(u, v) + if k not in edge_set: + # This is a non-edge, and both x_u=1, x_v=1 => LHS=2, RHS=1 + lhs = x.get(u, 0.0) + x.get(v, 0.0) + rhs = 1.0 + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(1) + violations.append( + f"Constraint 1 (non-edge): vertices {u} and {v} are both " + f"in the clique but are not connected by an edge " + f"(x_{u} + x_{v} = {lhs} > {rhs})" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 2 (tag 6): y_e <= x_u for all e = {u,v} in E + # ========================================================================= + # For each edge in clique_edges, the first endpoint must be in clique_vertices. + for entry in clique_edges: + u, v = entry[0], entry[1] + k = edge_key(u, v) + y_val = y.get(k, 0.0) + # Check y_e <= x_u (u is the smaller index in k) + x_u_val = x.get(k[0], 0.0) + lhs = y_val + rhs = x_u_val + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(2) + violations.append( + f"Constraint 2 (edge-vertex linking): edge ({k[0]},{k[1]}) has " + f"y=1 but vertex {k[0]} not in clique (y_e={lhs} > x_{k[0]}={rhs})" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 3 (tag 7): y_e <= x_v for all e = {u,v} in E + # ========================================================================= + for entry in clique_edges: + u, v = entry[0], entry[1] + k = edge_key(u, v) + y_val = y.get(k, 0.0) + # Check y_e <= x_v (v is the larger index in k) + x_v_val = x.get(k[1], 0.0) + lhs = y_val + rhs = x_v_val + violation_amount = lhs - rhs + if violation_amount > TOL: + violated_constraints.add(3) + violations.append( + f"Constraint 3 (edge-vertex linking): edge ({k[0]},{k[1]}) has " + f"y=1 but vertex {k[1]} not in clique (y_e={lhs} > x_{k[1]}={rhs})" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 4 (tag 8): x_u in {0, 1} for all u in V + # ========================================================================= + # Check that all clique vertices are valid graph vertices (x=1 only for + # valid vertices; all others are implicitly 0). + for u in clique_vertices: + x_val = x.get(u, 0.0) + if u not in vertices: + # Vertex not in graph, so x_u = 1 is assigned to a non-existent vertex + lhs = x_val + rhs = 0.0 # should be 0 since vertex doesn't exist + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(4) + violations.append( + f"Constraint 4 (binary x): vertex {u} is not in the graph " + f"but assigned x_{u} = {x_val}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + # Check integrality + if abs(x_val - round(x_val)) > TOL: + violated_constraints.add(4) + violations.append( + f"Constraint 4 (binary x): x_{u} = {x_val} is not binary" + ) + nearest_int = round(x_val) + violation_amount = abs(x_val - nearest_int) + normalizer = max(abs(nearest_int), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": x_val, + "rhs": nearest_int, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 5 (tag 9): y_e in {0, 1} for all e in E + # ========================================================================= + # Check that all clique edges are valid graph edges. + for entry in clique_edges: + u, v = entry[0], entry[1] + k = edge_key(u, v) + y_val = y.get(k, 0.0) + if k not in edge_set: + # Edge not in graph, y_e = 1 for a non-existent edge + lhs = y_val + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(5) + violations.append( + f"Constraint 5 (binary y): edge ({k[0]},{k[1]}) is not in " + f"the graph but assigned y_e = {y_val}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs, + "rhs": rhs, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + # Check integrality + if abs(y_val - round(y_val)) > TOL: + violated_constraints.add(5) + violations.append( + f"Constraint 5 (binary y): y_({k[0]},{k[1]}) = {y_val} is not binary" + ) + nearest_int = round(y_val) + violation_amount = abs(y_val - nearest_int) + normalizer = max(abs(nearest_int), EPS) + violation_magnitudes.append({ + "constraint": 5, + "lhs": y_val, + "rhs": nearest_int, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": violation_amount / normalizer, + }) + + # ========================================================================= + # Constraint 6 (Obj-consistency): reported objective_value must equal + # sum_{e in E} c_e * y_e (Tier C: catch LLMs that lie about their obj + # while keeping the clique structure feasible). + # ========================================================================= + 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: + # Full recompute: y is binary-valued (1 if edge in clique_edges, + # 0 otherwise); obj = sum of weights of clique_edges that are in E. + # Edges in clique_edges but not in E contribute 0 (and are already + # flagged by Constraint 5). + true_obj = 0.0 + for k_ce in y: + if k_ce in edge_weight: + true_obj += float(edge_weight[k_ce]) + abs_diff = abs(reported - true_obj) + # Edge weights c_e are positive integers (c_e = (u+v) mod 200 + 1 + # for DIMACS instances); any honest obj is an integer sum. Use + # tol = max(0.5, 1e-3 * |true_obj|) so a unit-off integer + # mismatch still fires but pure float noise doesn't. + tol = max(0.5, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(6) + violations.append( + f"Constraint 6 (objective consistency): reported " + f"objective_value={reported} differs from recomputed " + f"sum_e(c_e * y_e)={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + normalizer = max(abs(true_obj), EPS) + violation_magnitudes.append({ + "constraint": 6, + "lhs": reported, + "rhs": true_obj, + "raw_excess": abs_diff, + "normalizer": normalizer, + "ratio": abs_diff / normalizer, + }) + + # Build result + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + with open(result_path, "w") as f: + json.dump(result, f, indent=2) + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Check feasibility of a candidate MEWCP solution." + ) + 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() + result = check_feasibility(args.instance_path, args.solution_path, args.result_path) + if result["feasible"]: + print("Solution is FEASIBLE.") + else: + print(f"Solution is INFEASIBLE. Violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/segundo2019/gurobi_code.py b/tasks/segundo2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..e4fdedfe97835ad622864acc613005d824bee432 --- /dev/null +++ b/tasks/segundo2019/gurobi_code.py @@ -0,0 +1,152 @@ +""" +Maximum Edge-Weighted Clique Problem (MEWCP) solver using Gurobi. + +Implements the F1 (Nonedge) formulation from Segundo et al. (2019): + + max sum_{e in E} c_e * y_e + + s.t. x_u + x_v <= 1 for all {u,v} in E_bar (non-edges) + y_e <= x_u for all e={u,v} in E + y_e <= x_v for all e={u,v} in E + x_u in {0,1} for all u in V + y_e in {0,1} for all e={u,v} in E +""" + +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_mewcp(instance_path: str, solution_path: str, time_limit: float) -> None: + # Load instance + with open(instance_path, "r") as f: + data = json.load(f) + + graph = data["graph"] + vertices = graph["vertices"] + edges = graph["edges"] # list of [u, v, weight] + n = graph["num_vertices"] + + # Build adjacency set for efficient non-edge checking + adj = set() + for u, v, _w in edges: + adj.add((min(u, v), max(u, v))) + + # Create model + model = gp.Model("MEWCP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + + # Decision variables + x = model.addVars(vertices, vtype=GRB.BINARY, name="x") + y = {} + for u, v, w in edges: + key = (min(u, v), max(u, v)) + if key not in y: + y[key] = model.addVar(vtype=GRB.BINARY, name=f"y_{key[0]}_{key[1]}") + + # Objective: maximize sum of c_e * y_e + edge_weight = {} + for u, v, w in edges: + key = (min(u, v), max(u, v)) + edge_weight[key] = w + + model.setObjective( + gp.quicksum(edge_weight[key] * y[key] for key in y), + GRB.MAXIMIZE, + ) + + # Constraints (27): x_u + x_v <= 1 for all non-edges + for i in range(len(vertices)): + for j in range(i + 1, len(vertices)): + u, v = vertices[i], vertices[j] + key = (min(u, v), max(u, v)) + if key not in adj: + model.addConstr(x[u] + x[v] <= 1) + + # Constraints (6) and (7): y_e <= x_u, y_e <= x_v for all edges + for u, v, _w in edges: + key = (min(u, v), max(u, v)) + ye = y[key] + model.addConstr(ye <= x[u]) + model.addConstr(ye <= x[v]) + + # Optimize + model.optimize() + + # Extract solution + solution = { + "objective_value": None, + "clique_vertices": [], + "clique_edges": [], + } + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + clique_verts = [u for u in vertices if x[u].X > 0.5] + solution["clique_vertices"] = clique_verts + + clique_set = set(clique_verts) + for key, ye in y.items(): + if ye.X > 0.5: + u, v = key + if u in clique_set and v in clique_set: + solution["clique_edges"].append( + [u, v, edge_weight[key]] + ) + + # Write solution + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + status_map = { + GRB.OPTIMAL: "OPTIMAL", + GRB.TIME_LIMIT: "TIME_LIMIT", + GRB.INFEASIBLE: "INFEASIBLE", + GRB.UNBOUNDED: "UNBOUNDED", + } + status_str = status_map.get(model.Status, f"OTHER({model.Status})") + print(f"Status: {status_str}") + if model.SolCount > 0: + print(f"Objective: {model.ObjVal}") + print(f"Clique size: {len(solution['clique_vertices'])}") + print(f"Clique edges: {len(solution['clique_edges'])}") + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the Maximum Edge-Weighted Clique Problem (MEWCP) using Gurobi." + ) + parser.add_argument( + "--instance_path", type=str, required=True, help="Path to the JSON instance file." + ) + parser.add_argument( + "--solution_path", type=str, required=True, help="Path to write the JSON solution file." + ) + parser.add_argument( + "--time_limit", type=int, default=3600, help="Gurobi time limit in seconds." + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + solve_mewcp(args.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/segundo2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/segundo2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019/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/segundo2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/segundo2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019/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/segundo2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/segundo2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019/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/segundo2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/segundo2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019/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/segundo2019/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/segundo2019/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/segundo2019/gurobi_solution/large_solution_1.json b/tasks/segundo2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a969f0d206d0a1e1ce90d639bb1f6ee70992101f --- /dev/null +++ b/tasks/segundo2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa3c2665faeb9fd0d8a1a2c48fbf411b384e7ea3a12f4c709b29a23c21b8ee17 +size 99 diff --git a/tasks/segundo2019/gurobi_solution/large_solution_2.json b/tasks/segundo2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e60d5418afd80444c729d9aa75a3f15e3c6cce74 --- /dev/null +++ b/tasks/segundo2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:844ea9d0577a7f7ef6953222f78067b9a53272a1faa944aa9a4e0e8b702940d6 +size 99 diff --git a/tasks/segundo2019/gurobi_solution/large_solution_5.json b/tasks/segundo2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..4fdd5b854d81f0796262cd3c37506708b55e8783 --- /dev/null +++ b/tasks/segundo2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3324baf370a8a75cf37b35ff9221fe0029a71e416534b5e957c8c483fcc55c4d +size 98 diff --git a/tasks/segundo2019/gurobi_solution/tiny_solution.json b/tasks/segundo2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..bb2b819c30bd5d30a08828b3ffd520b9e2e64f25 --- /dev/null +++ b/tasks/segundo2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:267487a2d63132fa36cfbb4453f8b23ede8e0568df0e843f00f66d6763621137 +size 573 diff --git a/tasks/segundo2019/gurobi_solution/tiny_solution_2.json b/tasks/segundo2019/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..75ded142bb4b311426bbc1f2d392d036324bede0 --- /dev/null +++ b/tasks/segundo2019/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a11a379764de6b0e17d5768c253e475bddda61c088008297d19ae954bcfc5062 +size 110 diff --git a/tasks/segundo2019/gurobi_solution_log/large_log_1.jsonl b/tasks/segundo2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..672c592396bffcec30936925dcf3dbe75db2ea31 --- /dev/null +++ b/tasks/segundo2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf15ded306831ff573dd362c75e6f8564101406c05ac8862a8fb2f16214f969c +size 42 diff --git a/tasks/segundo2019/gurobi_solution_log/large_log_2.jsonl b/tasks/segundo2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..54daa7854c50c008775c93cb6e609ecebd89e3c9 --- /dev/null +++ b/tasks/segundo2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06cdb312cd9947abcc5a01f5e963137790e8c73ce0e51bea0dcfb429ea22d657 +size 42 diff --git a/tasks/segundo2019/gurobi_solution_log/large_log_5.jsonl b/tasks/segundo2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f42f826c3ad9e9cc4eaece75c06a3fed5d1876fb --- /dev/null +++ b/tasks/segundo2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ecb56fbd56f79c9d41f573fa61c6d30f9cbe5d8095ed5872fd5cbb5fc3598834 +size 42 diff --git a/tasks/segundo2019/gurobi_solution_log/tiny_log.jsonl b/tasks/segundo2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7307eeddde86e252f40ad17afdd38232fc13071a --- /dev/null +++ b/tasks/segundo2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6e18ec0eca4aa59047649af8189721d1306292db674cc7e1975c94ccd74d0bb +size 41 diff --git a/tasks/segundo2019/instance/large_instance_1.json b/tasks/segundo2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0e4fc49e2a485b0c0560a44d54eeaa5a55235d6a --- /dev/null +++ b/tasks/segundo2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52b7f3ec467dd384a7e836067ece22be39a5a28a9918050203a3485aed6a9621 +size 34757562 diff --git a/tasks/segundo2019/instance/large_instance_2.json b/tasks/segundo2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..2936dcef784b8768a8de9a54fcaded2a279baa6c --- /dev/null +++ b/tasks/segundo2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fedd4b48f3f89abed4934d471f5c7cfb4d0d9062fc887da5c3bde981e644707d +size 34681347 diff --git a/tasks/segundo2019/instance/large_instance_5.json b/tasks/segundo2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8655875c9a482aaeae8d0eca9adc5d46c7d3a14d --- /dev/null +++ b/tasks/segundo2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b31076b659f28a3a73fc81582f6c699b628c41d1840f6435aa1ad3ded54e2263 +size 34761665 diff --git a/tasks/segundo2019/instance/tiny_instance.json b/tasks/segundo2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..f5e372fee224c559578e849fd8fca4a7b100f257 --- /dev/null +++ b/tasks/segundo2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a772f495acde2cae13addeb709d82842978dbf28abe635259ed52aa38161ff32 +size 121719 diff --git a/tasks/segundo2019/instance/tiny_instance_2.json b/tasks/segundo2019/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..939b937e0bcc8a195224233469c873d22e2d6f74 --- /dev/null +++ b/tasks/segundo2019/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7b721a3f24c0024780b23c3b16465145f500924a23ffc55e7e2c975432c0844 +size 5428351 diff --git a/tasks/segundo2019/instance_schema.json b/tasks/segundo2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c610e30277c8e905058731bcf78329532e3f3a8f --- /dev/null +++ b/tasks/segundo2019/instance_schema.json @@ -0,0 +1,8 @@ +{ + "graph": { + "num_vertices": " Total number of vertices in the graph available for inclusion in the clique.", + "num_edges": " Total number of edges in the graph.", + "vertices": " Identifiers of all vertices in the graph.", + "edges": " Each entry is a triple [u, v, weight] giving an undirected edge between two vertices together with the positive weight earned when both endpoints are selected." + } +} diff --git a/tasks/segundo2019/mathematical_formulation.md b/tasks/segundo2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..47e07c09f7d4f653c3ba1a34bcbde77ffa65d9e1 --- /dev/null +++ b/tasks/segundo2019/mathematical_formulation.md @@ -0,0 +1,46 @@ +# Original Formulation: Maximum Edge-Weighted Clique Problem (MEWCP) + +*Source: A new branch-and-bound algorithm for the maximum edge-weighted clique problem, Pablo San Segundo, Stefano Coniglio, Fabio Furini, Ivana Ljubić, 2019.* + +- $G=(V,E)$: simple undirected graph with $|V|$ vertices and $|E|$ edges. + +- $C \subseteq V$: a clique (every pair of its vertices is joined by an edge of $E$). + +- $E[C] := \{\, e=\{u,v\}\in E : u,v \in C \,\}$: edges with both endpoints in $C$. + +- $N(u) := \{\, v\in V : \{u,v\}\in E \,\}$: neighborhood of vertex $u$. + +- $\overline{G}=(V,\overline{E})$: complement graph, where $\overline{E} := \{\, e=\{u,v\}, u,v\in V : e\notin E \,\}$ is the set of *non-edges* of $G$. + +- $\mathscr{I}$: the set of all (maximal) independent sets of $G$ (i.e. cliques of $\overline{G}$). + +- $\delta(u) \subseteq E$: subset of edges incident to vertex $u$. + +- $\omega(G)$: clique number of $G$ (number of vertices of a largest clique). + +## Parameters + +- $c_e \in \mathbb{R}^{+}$: strictly positive weight of each edge $e\in E$ (weight function $c:E\to\mathbb{R}^{+}$). + +## Decision Variables + +- $x_u \in \{0,1\}$, $u\in V$: $x_u=1$ iff vertex $u$ belongs to the chosen clique. + +- $y_e \in \{0,1\}$, $e=\{u,v\}\in E$: $y_e=1$ iff both endpoints $u$ and $v$ of edge $e$ belong to the chosen clique. + +## Objective + +The MEWCP seeks a clique maximizing the total weight of the edges whose endpoints are both in the clique: $$\begin{align} +\max \quad & \sum_{e \in E} c_e\, y_e \tag{4} +\end{align}$$ + +## Constraints + +$$\begin{align} +\text{s.t.}\quad +& \sum_{v \in I} x_v \;\le\; 1, && I \in \mathscr{I} \tag{5}\\ +& y_e \;\le\; x_u, && e=\{u,v\}\in E \tag{6}\\ +& y_e \;\le\; x_v, && e=\{u,v\}\in E \tag{7}\\ +& x_u \in \{0,1\}, && u \in V \tag{8}\\ +& y_e \in \{0,1\}, && e \in E \tag{9} +\end{align}$$ diff --git a/tasks/segundo2019/problem_description.txt b/tasks/segundo2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..e303e29bd14b07949e39a15703db6d0355b64068 --- /dev/null +++ b/tasks/segundo2019/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +Given a simple undirected graph with a specified set of vertices and a specified set of edges, where each edge carries a strictly positive weight, the task is to select a subset of vertices that forms a clique, meaning every pair of selected vertices must be directly connected by an edge in the graph. The input data provides the full list of vertices, the full list of edges (each identified by its two endpoint vertices), and a weight for every edge. The edge weight for an edge is computed as the sum of its two endpoint vertex indices taken modulo 200, plus one, though in general any positive weight may be supplied. + +The goal is to choose which vertices belong to the clique and, correspondingly, which edges have both endpoints inside the clique, so as to maximize the total weight summed over all edges whose two endpoints are both selected. An edge is considered part of the solution only if both of its endpoint vertices are chosen; specifically, including an edge requires that its first endpoint is selected, and separately requires that its second endpoint is selected. If either endpoint is excluded, that edge contributes nothing to the total weight. For every pair of vertices that are not connected by an edge in the graph (a "non-edge"), at most one of the two may be selected, which enforces the requirement that the chosen vertices form a clique. diff --git a/tasks/segundo2019/solution_logger.py b/tasks/segundo2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/segundo2019/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/segundo2019/solution_schema.json b/tasks/segundo2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..cb967db2affc3a7b817e2a289d43d3f076e8481a --- /dev/null +++ b/tasks/segundo2019/solution_schema.json @@ -0,0 +1,7 @@ +{ + "objective_value": " Total weight of the chosen clique: sum of edge weights c_e over all edges with both endpoints in the clique.", + "clique_vertices": " Sorted list of vertex ids selected into the clique (corresponds to x_v = 1 in the MEWCP formulation).", + "clique_edges": [ + " One [u, v] pair per edge whose both endpoints lie in the clique (i.e., y_e = 1). Each pair is given with u < v." + ] +} diff --git a/tasks/segundo2019b/feasibility_check.py b/tasks/segundo2019b/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..908e2366f4a78bf356a59d006acb1c388e960a1e --- /dev/null +++ b/tasks/segundo2019b/feasibility_check.py @@ -0,0 +1,366 @@ +""" +Feasibility Checker for Maximum Weighted Clique Problem (MWCP) +============================================================== +Checks whether a candidate solution satisfies all hard constraints from +Segundo, Furini, Artieda (2019). + +Hard constraints (numbered top-to-bottom from the formulation section): + Constraint 1 (Eq. 3 / Eq. 20): Independent-set / edge constraints. + For every pair (u, v) in the complement edge set (i.e., u and v are + NOT adjacent in G), at most one can be selected: x_u + x_v <= 1. + Equivalently, the selected vertices must form a clique in G. + Constraint 2 (Eq. 4): Binary domain. + x_v in {0, 1} for all v in V. Each selected vertex must be a valid + vertex of the graph, and no vertex may appear more than once. + Constraint 3 (Eq. 2, obj consistency): Objective recomputation. + The reported objective_value must equal sum_{v in clique} w(v) + within a small tolerance. Guards against LLM score-gaming where a + candidate returns a fabricated objective_value while the clique + itself satisfies constraints 1-2. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('clique_vertices', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + graph = instance["graph"] + num_vertices = graph["num_vertices"] + edges = graph["edges"] + weights = instance["vertex_weights"] + + # Build adjacency set + edge_set = set() + for u, v in edges: + edge_set.add((min(u, v), max(u, v))) + + # Extract clique from solution (handle both formats) + if "clique" in solution: + clique = list(solution["clique"]) + elif "clique_vertices" in solution: + clique = list(solution["clique_vertices"]) + else: + raise ValueError("Solution has neither 'clique' nor 'clique_vertices' field.") + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ------------------------------------------------------------------ + # Constraint 2 (Eq. 4): Binary domain — x_v in {0, 1}, v in V + # Each selected vertex must be a valid vertex index and appear at most once. + # ------------------------------------------------------------------ + + # Check for invalid vertex indices + for v in clique: + if not isinstance(v, int) or v < 0 or v >= num_vertices: + violated_constraints.add(2) + # LHS = x_v (which is 1 for a selected vertex), RHS = 0 (vertex doesn't exist) + # violation_amount = 1 (selecting a non-existent vertex) + lhs = 1.0 + rhs = 0.0 + raw_excess = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Vertex {v} is not a valid vertex index (must be in 0..{num_vertices - 1})." + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # Check for duplicate vertices + seen = {} + for v in clique: + seen[v] = seen.get(v, 0) + 1 + for v, count in seen.items(): + if count > 1: + violated_constraints.add(2) + # LHS = count (number of times selected), RHS = 1 (binary) + lhs = float(count) + rhs = 1.0 + raw_excess = abs(lhs - rhs) + normalizer = max(abs(rhs), eps) + violations.append( + f"Vertex {v} appears {count} times in the clique (must appear at most once)." + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 1 (Eq. 3 / Eq. 20): Clique / independent-set constraints + # For every pair (u, v) NOT in E: x_u + x_v <= 1 + # If both u and v are selected, LHS = 2 > RHS = 1 => violated. + # ------------------------------------------------------------------ + unique_clique = list(set(clique)) + for i in range(len(unique_clique)): + for j in range(i + 1, len(unique_clique)): + u, v = unique_clique[i], unique_clique[j] + pair = (min(u, v), max(u, v)) + if pair not in edge_set: + # This pair is in the complement edge set — constraint violated + violated_constraints.add(1) + lhs = 2.0 # x_u + x_v = 1 + 1 + rhs = 1.0 # <= 1 + raw_excess = lhs - rhs # 1.0 + normalizer = max(abs(rhs), eps) + violations.append( + f"Vertices {u} and {v} are both selected but not adjacent in G " + f"(complement edge constraint x_{u} + x_{v} <= 1 violated)." + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 3 (Eq. 2): Objective consistency (full recompute) + # The MWCP objective is sum_{v in clique} w(v). Every variable that + # determines the objective (the clique itself) is in the solution, so + # we can recompute exactly and compare to the reported value. + # Only valid, distinct vertex indices contribute (mirrors what the + # Gurobi-style ILP would compute for x_v=1). + # ------------------------------------------------------------------ + 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 v in set(clique): + if isinstance(v, int) and 0 <= v < num_vertices: + true_obj += float(weights[v]) + abs_diff = abs(reported - true_obj) + # Vertex weights are positive integers (w(v_i) = (i mod 200) + 1); + # objective is an integer sum. Use a strict tolerance: 0.5 + # catches any integer mismatch by >=1, plus a 0.1% relative + # cushion for huge cliques where float drift could matter. + obj_tol = max(0.5, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(3) + lhs = reported + rhs = true_obj + raw_excess = abs_diff + normalizer = max(abs(rhs), eps) + violations.append( + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed sum_v(w[v]*x_v)=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.3g})." + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": raw_excess / normalizer, + }) + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for the Maximum Weighted Clique Problem (MWCP)." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the instance JSON file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the candidate solution JSON file.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the feasibility result JSON file.") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE") + else: + print(f"INFEASIBLE — violated constraints: {result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/segundo2019b/gurobi_code.py b/tasks/segundo2019b/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4952f18d187b0f6fc3ff897e026da68bfedf0047 --- /dev/null +++ b/tasks/segundo2019b/gurobi_code.py @@ -0,0 +1,138 @@ +""" +Maximum Weighted Clique Problem (MWCP) — Edge Formulation (Equation 20) + +Formulation: + max sum_{v in V} w(v) * x_v + s.t. x_u + x_v <= 1 for all (u, v) in complement(E) + x_v in {0, 1} for all v in V + +Every pair of vertices NOT connected by an edge in G cannot both be in the +clique. This is equivalent to requiring that the selected vertices form a +clique in the original graph. +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, "r") as f: + data = json.load(f) + return data + + +def solve_mwcp(instance, time_limit): + graph = instance["graph"] + num_vertices = graph["num_vertices"] + vertices = graph["vertices"] + edges = graph["edges"] + weights = instance["vertex_weights"] + + # Build adjacency set for quick lookup + edge_set = set() + for u, v in edges: + edge_set.add((min(u, v), max(u, v))) + + model = gp.Model("MWCP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + + # Decision variables: x_v = 1 if vertex v is in the clique + x = model.addVars(vertices, vtype=GRB.BINARY, name="x") + + # Objective: maximize total weight of selected vertices + model.setObjective( + gp.quicksum(weights[v] * x[v] for v in vertices), GRB.MAXIMIZE + ) + + # Constraints: for every pair (u, v) NOT in E, x_u + x_v <= 1 + for i in range(num_vertices): + for j in range(i + 1, num_vertices): + u = vertices[i] + v = vertices[j] + pair = (min(u, v), max(u, v)) + if pair not in edge_set: + model.addConstr(x[u] + x[v] <= 1) + + model.optimize() + + result = { + "objective_value": None, + "clique_vertices": [], + "clique_weight": None, + "status": model.Status, + "status_name": None, + "mip_gap": None, + } + + 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"] = str(model.Status) + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + clique = [v for v in vertices if x[v].X > 0.5] + result["clique_vertices"] = clique + result["clique_weight"] = sum(weights[v] for v in clique) + try: + result["mip_gap"] = model.MIPGap + except Exception: + result["mip_gap"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the Maximum Weighted Clique Problem using Gurobi (Edge Formulation)." + ) + 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=int, default=3600, help="Gurobi time limit in seconds." + ) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + result = solve_mwcp(instance, args.time_limit) + + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Status: {result['status_name']}") + print(f"Objective value: {result['objective_value']}") + print(f"Clique size: {len(result['clique_vertices'])}") + print(f"Clique vertices: {result['clique_vertices']}") + print(f"Solution written to {args.solution_path}") + + +if __name__ == "__main__": + main() diff --git a/tasks/segundo2019b/gurobi_feasi_result/large_feasi_result_1.json b/tasks/segundo2019b/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019b/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/segundo2019b/gurobi_feasi_result/large_feasi_result_2.json b/tasks/segundo2019b/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019b/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/segundo2019b/gurobi_feasi_result/large_feasi_result_3.json b/tasks/segundo2019b/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019b/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/segundo2019b/gurobi_feasi_result/large_feasi_result_4.json b/tasks/segundo2019b/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019b/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/segundo2019b/gurobi_feasi_result/large_feasi_result_5.json b/tasks/segundo2019b/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019b/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/segundo2019b/gurobi_feasi_result/tiny_feasi_result.json b/tasks/segundo2019b/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/segundo2019b/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/segundo2019b/gurobi_solution/large_solution_1.json b/tasks/segundo2019b/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..4a6d34dcc9c0421c620598aa0609a5ae3bb10006 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ab2e584aea4526024741f2eb3ada35d751afd4d76e3988ca998162993e6064a +size 252 diff --git a/tasks/segundo2019b/gurobi_solution/large_solution_2.json b/tasks/segundo2019b/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..799ffa3369acd2dadcbe32b3a76e538ba895c0f5 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30968aa2541e1be47fe02e521c095482dd33a3bc8cde0b63022c5188623c602f +size 1174 diff --git a/tasks/segundo2019b/gurobi_solution/large_solution_3.json b/tasks/segundo2019b/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3f1905749bb69cbe44abf1b9dfd8f26881dec2a8 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1cb0a25116be275031ff0a74015b50fd23ba7e4134eab97f4821d891a317f83 +size 503 diff --git a/tasks/segundo2019b/gurobi_solution/large_solution_4.json b/tasks/segundo2019b/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..cf918fc1c8a2505fd901b6ea43e8bf55e233aaf4 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87c4f1afbd28c342175b532e95cedba15c5c8c6aabd27720754cd2741e4310fb +size 1740 diff --git a/tasks/segundo2019b/gurobi_solution/large_solution_5.json b/tasks/segundo2019b/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ea278ef2cbfb2a61db22e6ed5376e8eea3469d33 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b015a7b560965680efd3281d43a25dd6ebd9082892b30d2bf3fcf999e61186d4 +size 252 diff --git a/tasks/segundo2019b/gurobi_solution/tiny_solution.json b/tasks/segundo2019b/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..e40ad51ea0da0f042dac8381f50feca60be5bc15 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42f8753ed35d555d1f716ff37ade1fda30885c975e2cf4874d5440624cc941bd +size 286 diff --git a/tasks/segundo2019b/gurobi_solution_log/large_log_1.jsonl b/tasks/segundo2019b/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..db2c63c15abffa7646db7bd96d0722e110d9ef34 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0e31ae88055d6833dc59946de7e6c18cafe22ea062e99da89fd68fe83c46186 +size 43 diff --git a/tasks/segundo2019b/gurobi_solution_log/large_log_2.jsonl b/tasks/segundo2019b/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..764d760c1ea49d64e0fab383ef530e953b17ab04 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bca67fb72b69aee2d12b771099310f189f8356f1596d89c4bcf166739a53e1d +size 45 diff --git a/tasks/segundo2019b/gurobi_solution_log/large_log_3.jsonl b/tasks/segundo2019b/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0fdb620240ce91d8c6a29f0d521cb1df7dc3c86d --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dcba017cd7eea4327952aebe88618451693544b35e07c74113a66a7e86f44a63 +size 44 diff --git a/tasks/segundo2019b/gurobi_solution_log/large_log_4.jsonl b/tasks/segundo2019b/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f34de1d4d3e79831740b146e7049382f42d7ddf5 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56927d8238842e63d27c2dc0abdc81cccc7023aa9191c49af41904a4d8d9d881 +size 45 diff --git a/tasks/segundo2019b/gurobi_solution_log/large_log_5.jsonl b/tasks/segundo2019b/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb7b99a1cec119746395f140e0421f8c509f2f5d --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3cb7dbe9d28b65bd7d92a0efe2b4ff4f2b0ee44c64a1e1e14810afe2ff61cbf +size 43 diff --git a/tasks/segundo2019b/gurobi_solution_log/tiny_log.jsonl b/tasks/segundo2019b/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..34b7a3876a3dda962a9ed65fe8c98e21dd5e1208 --- /dev/null +++ b/tasks/segundo2019b/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c08443905ae363b14079f382da65047749191f9ab5337f304ddf6b08382a6d12 +size 42 diff --git a/tasks/segundo2019b/instance/large_instance_1.json b/tasks/segundo2019b/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..fbeeb5b749e383d3f3519500874f14e0a03f3742 --- /dev/null +++ b/tasks/segundo2019b/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c0bed9440ec79b29f61b7868601f2696223ec262b5dd02b59f977a74b6df800 +size 38926704 diff --git a/tasks/segundo2019b/instance/large_instance_2.json b/tasks/segundo2019b/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c8b183d37b0333a8d7828c15c53675135a3e10df --- /dev/null +++ b/tasks/segundo2019b/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30cf20f0ab7cd19aab0bab2c8cd8c927e5a6a404cbafc8c03f366466a3c93f95 +size 38190757 diff --git a/tasks/segundo2019b/instance/large_instance_3.json b/tasks/segundo2019b/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ef7700f66f975f8326841c2410c1678e49011c44 --- /dev/null +++ b/tasks/segundo2019b/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73aa95cdc6c83c901e55a1a5138b52a48ba88e62ab889aa4b8dd5f5d4c5a4734 +size 17196431 diff --git a/tasks/segundo2019b/instance/large_instance_4.json b/tasks/segundo2019b/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a5677fa58acdd456ec63880849b0b90b9628d3ba --- /dev/null +++ b/tasks/segundo2019b/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68aa7e08b994a913a8c4c9230e8845205b8f84f134610833fa249de9bcc55c6c +size 16889012 diff --git a/tasks/segundo2019b/instance/large_instance_5.json b/tasks/segundo2019b/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..b035970416b6f6b56b50f7e4cee579f2a34a5937 --- /dev/null +++ b/tasks/segundo2019b/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa59263a0454e8b908a9aab1f56318ccaddc35f0f88ab73108cd9d4ad6539eca +size 38929976 diff --git a/tasks/segundo2019b/instance/tiny_instance.json b/tasks/segundo2019b/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..41e0738ed5d4dbd7792a0f79fe3cd36e7763758d --- /dev/null +++ b/tasks/segundo2019b/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cb4834025205430b82f147a6f230812ece8c1fb3e3d6395ca67a6b47304f9d4 +size 317257 diff --git a/tasks/segundo2019b/instance_schema.json b/tasks/segundo2019b/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3683fa401c6af921b7e9246a662ab3115fc3db4c --- /dev/null +++ b/tasks/segundo2019b/instance_schema.json @@ -0,0 +1,9 @@ +{ + "graph": { + "num_vertices": " Total number of vertices in the graph.", + "num_edges": " Total number of edges in the graph.", + "vertices": " List of all vertex identifiers in the graph.", + "edges": " Each entry is a pair [u, v] representing an undirected edge between vertex u and vertex v." + }, + "vertex_weights": " Weight assigned to each vertex, where the i-th entry is the weight of vertex i." +} diff --git a/tasks/segundo2019b/mathematical_formulation.md b/tasks/segundo2019b/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..326cd1f2f089b4fe090e2c7bfa5bd51f6bc3ec42 --- /dev/null +++ b/tasks/segundo2019b/mathematical_formulation.md @@ -0,0 +1,26 @@ +# Sets and Indices + +- $G = (V, E)$: a simple undirected graph with vertex set $V$ and edge set $E$. + +- $\mathscr{I}$: the collection of all independent sets of $G$ (i.e., subsets $I \subseteq V$ such that no two vertices of $I$ are joined by an edge in $E$). + +# Parameters + +- $w: V \to \mathbb{R}_+$: a positive weight associated with each vertex $v \in V$. + +# Decision Variables + +- $x_v \in \{0,1\}$ for each $v \in V$: equals $1$ if vertex $v$ is selected in the clique, $0$ otherwise. + +# Objective + +Maximize the total weight of vertices selected in the clique: $$\begin{align} + \omega(G, w) \;=\; \max \quad & \sum_{v \in V} w(v)\, x_v \tag{2} +\end{align}$$ + +# Constraints + +Independent-set (clique-on-complement) constraints: for each independent set of $G$, at most one vertex may be chosen in the clique. $$\begin{align} + \sum_{v \in I} x_v &\le 1, && \forall\, I \in \mathscr{I} \tag{3} \\ + x_v &\in \{0,1\}, && \forall\, v \in V \tag{4} +\end{align}$$ diff --git a/tasks/segundo2019b/problem_description.txt b/tasks/segundo2019b/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..b84c9925197e53c15e8f9fe9a313e3eab7e44f72 --- /dev/null +++ b/tasks/segundo2019b/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +Given a simple undirected graph with a specified number of vertices and a specified set of edges (each edge connecting two distinct vertices, with no self-loops and no repeated edges), every vertex carries a positive weight. The input data consists of the full list of vertices, the full list of edges (each given as a pair of vertex identifiers), and the weight of each vertex, which is computed as the remainder of the vertex index divided by 200, plus one. + +A clique in the graph is any subset of vertices such that every pair of vertices in the subset is directly connected by an edge. The task is to select a subset of vertices that forms a clique and whose total weight, defined as the sum of the individual weights of all selected vertices, is as large as possible. The goal is to maximize this total weight. + +For every pair of vertices that are not connected by an edge in the original graph, at most one of the two may be selected. Equivalently, the selected set of vertices must be pairwise adjacent: for any two chosen vertices, there must exist an edge between them in the graph. Each vertex is either selected or not, and any number of vertices may be selected provided the clique requirement is satisfied. diff --git a/tasks/segundo2019b/solution_logger.py b/tasks/segundo2019b/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/segundo2019b/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/segundo2019b/solution_schema.json b/tasks/segundo2019b/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..21c446eec2bcd3930519e3cdfd5e9365cbdba1ca --- /dev/null +++ b/tasks/segundo2019b/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Total sum of vertex weights for the selected clique.", + "clique_vertices": " Vertices chosen to form the maximum weighted clique." +} diff --git a/tasks/seker2021/feasibility_check.py b/tasks/seker2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..1b67eaff9835a2f72384028bb11cb0b16f3c411a --- /dev/null +++ b/tasks/seker2021/feasibility_check.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Selective Graph Coloring (SEL-COL) solutions. + +Checks constraints from: + - Model 1 (gurobi solutions with coloring): Constraints 1-6 + - Model 2 (efficient/cutting-plane solutions): Constraints 7-10 + +Constraint numbering (top to bottom from math_model.txt): + 1 (1b): w_ik <= y_k for all i in V, k in {1,...,P} + 2 (1c): w_ik + w_jk <= 1 for all {i,j} in E, k in {1,...,P} + 3 (1d): sum_{i in V_p} sum_k w_ik = 1 for all p in {1,...,P} + 4 (1e): y_k in {0,1} for all k in {1,...,P} + 5 (1f): w_ik in {0,1} for all i in V, k in {1,...,P} + 6 (2): y_k <= y_{k-1} for all k in {2,...,P} + 7 (3b): sum_{i in V_p} x_i = 1 for all p in {1,...,P} + 8 (3c): t >= chi(G[x]) + 9 (3d): t >= 0 + 10 (3e): x_i in {0,1} for all i in V + 11 (obj): reported objective_value must equal sum_k y_k = number of + distinct colors used by selected vertices (full recompute). +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('coloring', 'objective_value', 'selected_vertices') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + +tol = 1e-5 +eps = 1e-5 + + +def load_json(path): + with open(path, "r") as f: + return json.load(f) + + +# --------------------------------------------------------------------------- +# Maximum clique solver (branch-and-bound with greedy coloring bound) +# --------------------------------------------------------------------------- + +def maximum_clique(adj, vertices): + """Find a maximum clique in the subgraph defined by adj and vertices.""" + if not vertices: + return [] + + best = [] + + def greedy_coloring(vlist): + color = {} + max_c = 0 + for v in vlist: + used = {color[u] for u in vlist if u in color and u in adj[v]} + c = 1 + while c in used: + c += 1 + color[v] = c + if c > max_c: + max_c = c + return color, max_c + + def expand(clique, candidates): + nonlocal best + if not candidates: + if len(clique) > len(best): + best = list(clique) + return + if len(clique) + len(candidates) <= len(best): + return + + color, _ = greedy_coloring(candidates) + sorted_cands = sorted(candidates, key=lambda v: color[v], reverse=True) + + for v in sorted_cands: + if len(clique) + color[v] <= len(best): + return + clique.append(v) + new_cands = [u for u in sorted_cands if u in adj[v] and u != v] + expand(clique, new_cands) + clique.pop() + + verts = sorted(vertices, key=lambda v: len(adj.get(v, set())), reverse=True) + + # Greedy initial clique + for v in verts: + if all(u in adj.get(v, set()) for u in best): + best.append(v) + + expand([], verts) + return best + + +# --------------------------------------------------------------------------- +# Violation recording helper +# --------------------------------------------------------------------------- + +def record_violation(violated_set, violations, violation_magnitudes, + constraint_idx, msg, lhs, rhs, violation_amount): + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violated_set.add(constraint_idx) + violations.append(msg) + violation_magnitudes.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(ratio), + }) + + +# --------------------------------------------------------------------------- +# Model 1 checker (gurobi solutions) +# --------------------------------------------------------------------------- + +def check_gurobi_solution(instance, solution): + """Check Model 1 constraints 1-6 for a gurobi solution.""" + violations = [] + violation_magnitudes = [] + violated_set = set() + + num_vertices = instance["graph"]["num_vertices"] + edges = [tuple(e) for e in instance["graph"]["edges"]] + clusters = instance["partition"]["clusters"] + P = instance["partition"]["num_clusters"] + + selected_vertices = solution["selected_vertices"] # dict: cluster_str -> vertex + coloring = solution["coloring"] # dict: vertex_str -> color + + # Reconstruct w_ik and y_k + w = {} + for i in range(num_vertices): + for k in range(P): + w[(i, k)] = 0 + y = {k: 0 for k in range(P)} + + for cluster_str, vertex in selected_vertices.items(): + vertex = int(vertex) + color = int(coloring[str(vertex)]) + w[(vertex, color)] = 1 + y[color] = 1 + + def add(ci, msg, lhs, rhs, va): + record_violation(violated_set, violations, violation_magnitudes, + ci, msg, lhs, rhs, va) + + # Constraint 1 (1b): w_ik <= y_k + for i in range(num_vertices): + for k in range(P): + lhs = w[(i, k)] + rhs = y[k] + va = max(0, lhs - rhs) + if va > tol: + add(1, f"Constraint 1 (1b) violated: w[{i},{k}]={lhs} > y[{k}]={rhs}", + lhs, rhs, va) + + # Constraint 2 (1c): w_ik + w_jk <= 1 for each edge and color + for (i, j) in edges: + for k in range(P): + lhs = w[(i, k)] + w[(j, k)] + rhs = 1 + va = max(0, lhs - rhs) + if va > tol: + add(2, f"Constraint 2 (1c) violated: w[{i},{k}]+w[{j},{k}]={lhs} > 1; " + f"adjacent vertices {i},{j} share color {k}", + lhs, rhs, va) + + # Constraint 3 (1d): sum_{i in V_p} sum_k w_ik = 1 + for p_idx, cluster in enumerate(clusters): + lhs = sum(w[(i, k)] for i in cluster for k in range(P)) + rhs = 1 + va = abs(lhs - rhs) + if va > tol: + add(3, f"Constraint 3 (1d) violated: cluster {p_idx} has " + f"{int(lhs)} vertex-color assignments (expected 1)", + lhs, rhs, va) + + # Constraint 4 (1e): y_k in {{0,1}} + for k in range(P): + val = y[k] + nearest = round(val) + va = abs(val - nearest) + if va > tol: + add(4, f"Constraint 4 (1e) violated: y[{k}]={val} is not binary", + val, nearest, va) + + # Constraint 5 (1f): w_ik in {{0,1}} + for i in range(num_vertices): + for k in range(P): + val = w[(i, k)] + nearest = round(val) + va = abs(val - nearest) + if va > tol: + add(5, f"Constraint 5 (1f) violated: w[{i},{k}]={val} is not binary", + val, nearest, va) + + # Constraint 6 (2): y_k <= y_{k-1} for k in {2,...,P} — symmetry breaking. + # NOTE 2026-05-19: This is a MODEL-LEVEL constraint that's only added to speed + # up the solver by removing equivalent color permutations. It is NOT part of + # the underlying SEL-COL problem definition (any coloring with the same set + # of colors used is equally valid). The checker reconstructs y[k] from + # `coloring` (y[k]=1 iff some selected vertex uses color k); solver's + # solution.json doesn't preserve y values when a paid-for color happens to + # have no vertex assigned (model permitted by symbreak). Removing this + # check: solutions where colors are non-contiguously labeled are still + # feasible if all OTHER constraints hold. Objective consistency (constraint + # 11 below) already verifies obj_value matches actual colors used. + + # Constraint 11 (obj): reported objective_value must equal the number of + # distinct colors used by selected vertices (sum_k y_k). Full recompute is + # possible because all obj-determining variables (selected_vertices and + # coloring) are present in the solution. Defends against LLM exploits that + # report obj=0 or obj=sys.float_info.max while producing a valid coloring. + 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 = number of distinct colors actually assigned to selected + # vertices (== sum_k y_k under the reconstruction above). + true_obj = float(sum(1 for k in range(P) if y[k] == 1)) + abs_diff = abs(reported - true_obj) + # Objective is an integer count; any mismatch by >= 1 must fire. + tolerance = 0.5 + if abs_diff > tolerance: + add(11, + f"Constraint 11 (obj) violated: reported objective_value=" + f"{reported} differs from recomputed sum_k y_k=" + f"{true_obj} (number of distinct colors used by selected " + f"vertices; |diff|={abs_diff:.3g}, tol={tolerance:.3g})", + reported, true_obj, abs_diff) + + return { + "feasible": len(violated_set) == 0, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + +# --------------------------------------------------------------------------- +# Model 2 checker (efficient / cutting-plane solutions) — REMOVED. +# +# The previous `check_efficient_solution` path verified Model 2 cutting-plane +# constraints (3b)-(3e), including `t >= chi(G[x])`, on solutions keyed by +# `selected_vertices` / `max_clique`. Model 2 is a reformulation used inside +# the paper's cutting-plane algorithm; a generated algorithm operating on the +# SEL-COL problem description produces Model 1 output (`coloring`), not Model +# 2 variables. Keeping that branch as dead code was misleading, so it has +# been removed. Any Model-1-style solution now always goes through +# `check_gurobi_solution` below. +# --------------------------------------------------------------------------- + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for SEL-COL solutions" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + 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_gurobi_solution(instance, solution) + + 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/seker2021/gurobi_code.py b/tasks/seker2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..c7529de057de154b529f07d9ab49b70ab7e7eb79 --- /dev/null +++ b/tasks/seker2021/gurobi_code.py @@ -0,0 +1,136 @@ +""" +Gurobi implementation of Model 1 (IP formulation) for the Selective Graph Coloring +problem (SEL-COL) from Seker, Ekim, Taskin (2021). + +Model 1 uses binary variables y_k (color k used) and w_ik (vertex i gets color k), +with symmetry-breaking constraints y_k <= y_{k-1}. +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, "r") as f: + return json.load(f) + + +def solve(instance, time_limit): + num_vertices = instance["graph"]["num_vertices"] + edges = [tuple(e) for e in instance["graph"]["edges"]] + clusters = instance["partition"]["clusters"] + P = instance["partition"]["num_clusters"] # number of clusters = max colors needed + + V = list(range(num_vertices)) + + model = gp.Model("SEL_COL_Model1") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # y_k: 1 if color k is used (k in 0..P-1) + y = model.addVars(P, vtype=GRB.BINARY, name="y") + # w_ik: 1 if vertex i is selected and assigned color k + w = model.addVars(num_vertices, P, vtype=GRB.BINARY, name="w") + + # Objective (1a): minimize number of colors used + model.setObjective(gp.quicksum(y[k] for k in range(P)), GRB.MINIMIZE) + + # Constraint (1b): w_ik <= y_k + for i in V: + for k in range(P): + model.addConstr(w[i, k] <= y[k], name=f"link_{i}_{k}") + + # Constraint (1c): w_ik + w_jk <= 1 for each edge {i,j} and each color k + for (i, j) in edges: + for k in range(P): + model.addConstr(w[i, k] + w[j, k] <= 1, name=f"edge_{i}_{j}_{k}") + + # Constraint (1d): exactly one vertex selected per cluster + for p_idx, cluster in enumerate(clusters): + model.addConstr( + gp.quicksum(w[i, k] for i in cluster for k in range(P)) == 1, + name=f"cluster_{p_idx}", + ) + + # Symmetry-breaking constraints (2): y_k <= y_{k-1} + for k in range(1, P): + model.addConstr(y[k] <= y[k - 1], name=f"symbreak_{k}") + + model.optimize() + + # Extract solution + result = { + "objective_value": None, + "status": model.Status, + "selected_vertices": {}, + "coloring": {}, + } + + if model.SolCount > 0: + # Extract which vertex is selected per cluster and its color + for p_idx, cluster in enumerate(clusters): + for i in cluster: + for k in range(P): + if w[i, k].X > 0.5: + result["selected_vertices"][str(p_idx)] = i + result["coloring"][str(i)] = k + break + + # Report objective as DISTINCT colors actually assigned (not sum y_k). + # The model's sum y_k can exceed this when symmetry-breaking forces + # y[k]=1 at low indices that aren't actually used by any vertex. + # Checker reconstructs y[k] only from `coloring`, so report obj that + # matches checker's view to avoid spurious obj-mismatch violations. + # NOTE 2026-05-19: was `model.ObjVal` (= sum y_k including symbreak + # padding), causing obj=59 reported vs obj=34 used = checker reject. + distinct_colors = len(set(result["coloring"].values())) + result["objective_value"] = float(distinct_colors) + else: + # No feasible solution found + result["objective_value"] = None + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve SEL-COL using Model 1 (IP) 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 for the output solution JSON file") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + result = solve(instance, args.time_limit) + + with open(args.solution_path, "w") as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + +if __name__ == "__main__": + main() diff --git a/tasks/seker2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/seker2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/seker2021/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/seker2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/seker2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/seker2021/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/seker2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/seker2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/seker2021/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/seker2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/seker2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/seker2021/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/seker2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/seker2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/seker2021/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/seker2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/seker2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/seker2021/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/seker2021/gurobi_solution/large_solution_1.json b/tasks/seker2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..8c655aea140f2538b994c72ee57d3f87f4d22333 --- /dev/null +++ b/tasks/seker2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd19c787a465073e88ff02badbe58d952939576eecb21cd545a0e94a3951ea8f +size 2030 diff --git a/tasks/seker2021/gurobi_solution/large_solution_2.json b/tasks/seker2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..2ed919d5a2ba5a8bf10b549e3482fa273539d984 --- /dev/null +++ b/tasks/seker2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29cafc11b6aa558d1402e59da4be5744cd2e82756b10f606832aa9a8a5a44ca9 +size 2054 diff --git a/tasks/seker2021/gurobi_solution/large_solution_3.json b/tasks/seker2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ad4871c92fdec0e910316d00f07f7fd6e6ead243 --- /dev/null +++ b/tasks/seker2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e238e6bde36228b3d4b8ed0a87c9e6bd0128576c09e956565b84d8662fa081b2 +size 1911 diff --git a/tasks/seker2021/gurobi_solution/large_solution_4.json b/tasks/seker2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..7245dfd2b28ec7201bb5aacf31fce96367dfa681 --- /dev/null +++ b/tasks/seker2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6e1cd187ae0b50c2e8e3183961cfe09e27ca2998116d79ac81a374df8295d31 +size 2045 diff --git a/tasks/seker2021/gurobi_solution/large_solution_5.json b/tasks/seker2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ca1fdb31d0e4022d639cc1ea3b809bd34b0e3e04 --- /dev/null +++ b/tasks/seker2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:099b9929ee99168fbe341e984e747276650ee7bd5014db0741db3c288ea02520 +size 1983 diff --git a/tasks/seker2021/gurobi_solution/tiny_solution.json b/tasks/seker2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..7159cf9db7247c8209d39cd5d23d869d1233ddd6 --- /dev/null +++ b/tasks/seker2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:452fde7d97b81a05d222243e2bd903a8eedf3c4176ab2f06d3baa3351fbb4631 +size 395 diff --git a/tasks/seker2021/gurobi_solution_log/large_log_1.jsonl b/tasks/seker2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6af4ed0a3d7f42766b187cf44417e74e85d64c77 --- /dev/null +++ b/tasks/seker2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6abc0521ad218096eb35034b09ecda47ff8615e90384310d1cf0fe7d1facc4ac +size 294 diff --git a/tasks/seker2021/gurobi_solution_log/large_log_2.jsonl b/tasks/seker2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..de35b73f2601e688891d3f48c00c9e523226dc04 --- /dev/null +++ b/tasks/seker2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1ce07a76fbe1f46b060f266c48e9470be34cc7e440af27905988afe901a537c +size 84 diff --git a/tasks/seker2021/gurobi_solution_log/large_log_3.jsonl b/tasks/seker2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..464f33a1ec782f5fd1e2ee3b623a868f1c3005f5 --- /dev/null +++ b/tasks/seker2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7501664d16981ec1434d8838d0f57aafa0d08a778a76dc5c8908715f04c1bafd +size 170 diff --git a/tasks/seker2021/gurobi_solution_log/large_log_4.jsonl b/tasks/seker2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0ac16afb9dd9f10a5e3d0a7f499a1da5d521523f --- /dev/null +++ b/tasks/seker2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47019fdd67f82ac6eb81638cd89ce7872e6a4e16185b5489784a11bd7938bc1e +size 84 diff --git a/tasks/seker2021/gurobi_solution_log/large_log_5.jsonl b/tasks/seker2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cb3744b82cd38712e88a085355ca8f68a203d56c --- /dev/null +++ b/tasks/seker2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7357a73ea5071949f715742308ce71bc3ab688bd7f98b3fa8f952a1c2c166288 +size 125 diff --git a/tasks/seker2021/gurobi_solution_log/tiny_log.jsonl b/tasks/seker2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..03f8bccd3f6c9de6910bd50d91645702cecf68ae --- /dev/null +++ b/tasks/seker2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3575cc3a3542f9d158916515935c0f3a2b253b43c309b2c5eb18afbd761c9672 +size 40 diff --git a/tasks/seker2021/instance/large_instance_1.json b/tasks/seker2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a69c6f35baebd19de183c4db042ff62bbce0740f --- /dev/null +++ b/tasks/seker2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c00c40cfba31d5675ee5cf95e82ebbd4868fabd77a85a7fea320608f455092de +size 3572568 diff --git a/tasks/seker2021/instance/large_instance_2.json b/tasks/seker2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e3166e7cc8d659c1d3412814a5ed9d3af923f870 --- /dev/null +++ b/tasks/seker2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:175675437e9a6ff7b22ba9f0b4477f433acf42ba5ed45424f45cd6e3f7f1dbba +size 3545711 diff --git a/tasks/seker2021/instance/large_instance_3.json b/tasks/seker2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..4dcba19d9260e46f0e1ac8376fdcab112b5e2f4f --- /dev/null +++ b/tasks/seker2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29e9ad55667b0c369d1d5de6273d6228a6bf937f1550ea2aa529fec36d099bbb +size 3637155 diff --git a/tasks/seker2021/instance/large_instance_4.json b/tasks/seker2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..6a631ae1b156621549e63c3727bf559d12a393e7 --- /dev/null +++ b/tasks/seker2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5382d03821a417071599d72e3107581630fb70f478486dd7ee4b8eeaf6890232 +size 3631098 diff --git a/tasks/seker2021/instance/large_instance_5.json b/tasks/seker2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c2f68256cffc27e6af82862ea59003f3775d87be --- /dev/null +++ b/tasks/seker2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d54edd12d02bed7d5dfbf10dc98fdad1b6d6d038aae13d1af92fc0eb1249d7a +size 3722039 diff --git a/tasks/seker2021/instance/tiny_instance.json b/tasks/seker2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..db07f1721ea0d99bcaa54aa5372b7ced9e013fb1 --- /dev/null +++ b/tasks/seker2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:365543b55139e1ef1c0514febbdc281c99eec9f2b0044112865f594abf8d8341 +size 6600 diff --git a/tasks/seker2021/instance_schema.json b/tasks/seker2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d52dde22e0a66a5d8f3dfcb489efd459c07f9446 --- /dev/null +++ b/tasks/seker2021/instance_schema.json @@ -0,0 +1,11 @@ +{ + "graph": { + "num_vertices": " Total number of vertices in the perfect graph.", + "num_edges": " Total number of edges in the perfect graph.", + "edges": " Each edge defined by its two endpoint vertices, with the smaller vertex index listed first." + }, + "partition": { + "num_clusters": " Number of disjoint clusters into which the vertices are partitioned.", + "clusters": " Vertex indices belonging to each cluster, where every vertex appears in exactly one cluster." + } +} diff --git a/tasks/seker2021/mathematical_formulation.md b/tasks/seker2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..fb9ef26c9443b8fb83ff4ec80bc92649433173f3 --- /dev/null +++ b/tasks/seker2021/mathematical_formulation.md @@ -0,0 +1,30 @@ +# Sets and Indices + +- $G=(V,E)$: undirected (perfect) graph with vertex set $V=\{1,\ldots,n\}$ and edge set $E$. + +- $\{V_1, V_2, \ldots, V_P\}$: partition of $V$ into $P$ clusters; $p \in \{1,\ldots,P\}$ indexes clusters. + +- $k \in \{1,\ldots,P\}$: color index (at most $P$ colors are needed). + +# Decision Variables + +- $y_k \in \{0,1\}$: equals $1$ if color $k$ is used, $0$ otherwise, for $k \in \{1,\ldots,P\}$. + +- $w_{ik} \in \{0,1\}$: equals $1$ if vertex $i \in V$ is selected and assigned color $k$, $0$ otherwise, for $i \in V,\, k \in \{1,\ldots,P\}$. + +# Model 1 + +$$\begin{align} + \min \quad & \sum_{k=1}^{P} y_k \tag{1a} \\ + \text{s.t.}\quad & w_{ik} \le y_k, && \forall\, i \in V,\ k \in \{1,\ldots,P\} \tag{1b} \\ + & w_{ik} + w_{jk} \le 1, && \forall\, \{i,j\} \in E,\ k \in \{1,\ldots,P\} \tag{1c} \\ + & \sum_{i \in V_p} \sum_{k=1}^{P} w_{ik} = 1, && \forall\, p \in \{1,\ldots,P\} \tag{1d} \\ + & y_k \in \{0,1\}, && \forall\, k \in \{1,\ldots,P\} \tag{1e} \\ + & w_{ik} \in \{0,1\}, && \forall\, i \in V,\ k \in \{1,\ldots,P\} \tag{1f} +\end{align}$$ + +# Symmetry-Breaking Constraints + +The following constraints are added to Model 1 to break color-index symmetry: $$\begin{align} + y_k \le y_{k-1}, && \forall\, k \in \{2,\ldots,P\} \tag{2} +\end{align}$$ diff --git a/tasks/seker2021/problem_description.txt b/tasks/seker2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..90f7b4ec73e0abff37ece50ca7d865eed76f3e05 --- /dev/null +++ b/tasks/seker2021/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A perfect graph is given, consisting of a set of vertices and a set of edges connecting pairs of vertices. The vertices are partitioned into a number of disjoint clusters, where every vertex belongs to exactly one cluster and each cluster contains at least one vertex. The input data specifies the total number of vertices, the complete list of edges (each defined by its two endpoint vertices), the number of clusters, and the membership of each vertex in its cluster. + +Exactly one vertex must be selected from each cluster. The selected vertices, together with the edges of the original graph that connect pairs of selected vertices, form an induced subgraph. The selected vertices must then be colored so that no two selected vertices sharing an edge receive the same color. + +The goal is to choose one vertex per cluster and assign one color to each chosen vertex, respecting the edge-conflict rule above, so as to minimize the total number of distinct colors used across all selected vertices. diff --git a/tasks/seker2021/solution_logger.py b/tasks/seker2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/seker2021/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/seker2021/solution_schema.json b/tasks/seker2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..afb27a18e381f5f3d8e0a21bb796ef0c701f13ce --- /dev/null +++ b/tasks/seker2021/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total number of distinct colors used across all selected vertices.", + "selected_vertices": " The vertex chosen from each cluster.", + "coloring": " The color assigned to each selected vertex." +} diff --git a/tasks/song2021/feasibility_check.py b/tasks/song2021/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5b04b1aff6a6c321334a8e85780ecd7aac5bc4c4 --- /dev/null +++ b/tasks/song2021/feasibility_check.py @@ -0,0 +1,699 @@ +""" +Feasibility checker for the Resource Loading Problem (RLP). + +Checks candidate solutions against the Execution-Interval formulation +(Section 4.1) from Song, Kis & Leus (2020). + +Hard constraints checked (numbered top-to-bottom in the EI formulation): + 1. Constraint (15): Intensity bounds linking y and a variables + 2. Constraint (16): Exactly one execution interval per order + 3. Constraint (17): Binary domain for a variables (interval feasibility) + 4. Constraint (6): Total intensity per order equals 1 + 5. Constraint (7): Nonregular capacity z_t >= sum_j p_j*y_jt - C_t + 6. Constraint (8): Non-negativity of intensity y_jt >= 0 + 7. Constraint (9): Non-negativity of nonregular capacity z_t >= 0 + 8. Objective consistency (Eq.14): reported objective_value must equal + sum_j w_j * max(0, l_chosen_j - d_j) + sigma * sum_t z_t +""" + +import json +import argparse +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('nonregular_capacity_by_period', 'objective_value', 'orders_solution') +_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 enumerate_execution_intervals(order, H): + """ + Enumerate all feasible execution intervals for an order. + (k, l) in E_j iff: + r_j <= k <= l <= H, + (l - k + 1) * LB_j <= 1, + (l - k + 1) * UB_j >= 1. + """ + r_j = order['release_date_r'] + LB_j = order['intensity_lower_bound_LB'] + UB_j = order['intensity_upper_bound_UB'] + + intervals = [] + for k in range(r_j, H + 1): + for l in range(k, H + 1): + length = l - k + 1 + if length * LB_j <= 1.0 + 1e-9 and length * UB_j >= 1.0 - 1e-9: + intervals.append((k, l)) + return intervals + + +def check_feasibility(instance, solution): + """Check all hard constraints of the EI formulation.""" + + tol = 1e-5 + eps = 1e-5 + + H = instance['planning_horizon_H'] + capacities = instance['capacities'] + sigma = instance['unit_cost_nonregular_capacity_sigma'] + orders_data = {o['order_id']: o for o in instance['orders']} + orders_sol = solution.get('orders_solution', []) + nonregular_by_period = solution.get('nonregular_capacity_by_period', {}) + + violations = [] + violation_magnitudes = [] + + # Build solution lookup + sol_by_id = {} + for os in orders_sol: + sol_by_id[os['order_id']] = os + + # Precompute feasible intervals for each order + feasible_intervals = {} + for order in instance['orders']: + j = order['order_id'] + feasible_intervals[j] = enumerate_execution_intervals(order, H) + + # ========================================================================= + # Constraint 1 — (15): Intensity bounds linking y and a + # LB_j * sum_{(k,l): k<=t<=l} a^j_{kl} <= y_{jt} + # <= UB_j * sum_{(k,l): k<=t<=l} a^j_{kl} + # + # In the integer solution, exactly one a^j_{kl}=1 for the chosen interval. + # So for t in [k_chosen, l_chosen], the bounds become LB_j <= y_jt <= UB_j. + # For t outside the chosen interval, y_jt must be 0. + # ========================================================================= + for order in instance['orders']: + j = order['order_id'] + LB_j = order['intensity_lower_bound_LB'] + UB_j = order['intensity_upper_bound_UB'] + r_j = order['release_date_r'] + + if j not in sol_by_id: + continue + + osol = sol_by_id[j] + interval = osol.get('chosen_interval') + if interval is None: + continue + + k_chosen, l_chosen = interval + + intensities = osol.get('intensities', {}) + + for t in range(r_j, H + 1): + y_jt = float(intensities.get(str(t), 0.0)) + in_interval = (k_chosen <= t <= l_chosen) + + if in_interval: + # sum of covering a's = 1, so bounds are LB_j and UB_j + # Check lower bound: LB_j <= y_jt + lb_violation = LB_j - y_jt + if lb_violation > tol: + rhs_val = LB_j + lhs_val = y_jt + raw_excess = lb_violation + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 1 (Eq.15 lower): Order {j}, period {t}: " + f"y_jt={y_jt:.8f} < LB_j={LB_j:.8f}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # Check upper bound: y_jt <= UB_j + ub_violation = y_jt - UB_j + if ub_violation > tol: + lhs_val = y_jt + rhs_val = UB_j + raw_excess = ub_violation + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 1 (Eq.15 upper): Order {j}, period {t}: " + f"y_jt={y_jt:.8f} > UB_j={UB_j:.8f}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + else: + # Outside interval: y_jt must be 0 (sum of covering a's = 0) + if y_jt > tol: + lhs_val = y_jt + rhs_val = 0.0 + raw_excess = y_jt + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 1 (Eq.15): Order {j}, period {t}: " + f"y_jt={y_jt:.8f} > 0 but period is outside chosen interval " + f"[{k_chosen},{l_chosen}]" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint 2 — (16): Exactly one execution interval per order + # sum_{(k,l) in E_j} a^j_{kl} = 1 + # + # In the solution, each order should have exactly one chosen_interval. + # ========================================================================= + for order in instance['orders']: + j = order['order_id'] + if j not in sol_by_id: + lhs_val = 0.0 + rhs_val = 1.0 + raw_excess = 1.0 + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 2 (Eq.16): Order {j} has no chosen interval" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + else: + osol = sol_by_id[j] + if osol.get('chosen_interval') is None: + lhs_val = 0.0 + rhs_val = 1.0 + raw_excess = 1.0 + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 2 (Eq.16): Order {j} has null chosen interval" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint 3 — (17): Binary domain / interval feasibility + # a^j_{kl} in {0,1}, and (k,l) must be in E_j + # + # Check that the chosen interval is a valid member of E_j. + # ========================================================================= + for order in instance['orders']: + j = order['order_id'] + if j not in sol_by_id: + continue + osol = sol_by_id[j] + interval = osol.get('chosen_interval') + if interval is None: + continue + + k_chosen, l_chosen = interval + valid_intervals = feasible_intervals[j] + + if (k_chosen, l_chosen) not in valid_intervals: + # Compute how far off the interval is from feasibility + r_j = order['release_date_r'] + LB_j = order['intensity_lower_bound_LB'] + UB_j = order['intensity_upper_bound_UB'] + length = l_chosen - k_chosen + 1 + + detail_parts = [] + if k_chosen < r_j: + detail_parts.append(f"k={k_chosen} < r_j={r_j}") + if l_chosen > H: + detail_parts.append(f"l={l_chosen} > H={H}") + if length * LB_j > 1.0 + 1e-9: + detail_parts.append( + f"length*LB={length * LB_j:.6f} > 1" + ) + if length * UB_j < 1.0 - 1e-9: + detail_parts.append( + f"length*UB={length * UB_j:.6f} < 1" + ) + + detail = "; ".join(detail_parts) if detail_parts else "unknown reason" + + # Violation amount: measure how much interval length conditions are off + viol_lb = max(0.0, length * LB_j - 1.0) + viol_ub = max(0.0, 1.0 - length * UB_j) + viol_release = max(0.0, r_j - k_chosen) + viol_horizon = max(0.0, l_chosen - H) + raw_excess = max(viol_lb, viol_ub, float(viol_release), float(viol_horizon)) + if raw_excess < tol: + raw_excess = 1.0 # flag as violated anyway + normalizer = max(1.0, eps) + ratio = raw_excess / normalizer + + violations.append( + f"Constraint 3 (Eq.17): Order {j}, interval [{k_chosen},{l_chosen}] " + f"is not a feasible execution interval ({detail})" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": 0.0, + "rhs": 0.0, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint 4 — (6): Total intensity equals 1 + # sum_{t=r_j}^{H} y_{jt} = 1 for all j + # ========================================================================= + for order in instance['orders']: + j = order['order_id'] + r_j = order['release_date_r'] + if j not in sol_by_id: + continue + osol = sol_by_id[j] + intensities = osol.get('intensities', {}) + + total_intensity = sum(float(v) for v in intensities.values()) + + raw_excess = abs(total_intensity - 1.0) + if raw_excess > tol: + lhs_val = total_intensity + rhs_val = 1.0 + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 4 (Eq.6): Order {j}: sum of intensities = " + f"{total_intensity:.8f} != 1.0" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint 5 — (7): Nonregular capacity + # z_t >= sum_{j} p_j * y_{jt} - C_t for t = 1,...,H + # + # The solution reports z_t via nonregular_capacity_by_period. + # z_t must be >= max(0, sum_j p_j*y_jt - C_t). + # ========================================================================= + for t in range(1, H + 1): + C_t = capacities[t - 1] + + # Compute resource usage in period t + resource_usage = 0.0 + for order in instance['orders']: + j = order['order_id'] + p_j = order['work_content_p'] + if j not in sol_by_id: + continue + osol = sol_by_id[j] + intensities = osol.get('intensities', {}) + y_jt = float(intensities.get(str(t), 0.0)) + resource_usage += p_j * y_jt + + required_z = resource_usage - C_t # z_t >= this value + + z_t = float(nonregular_by_period.get(str(t), 0.0)) + + # z_t >= resource_usage - C_t + lhs_val = z_t + rhs_val = required_z + violation_amount = required_z - z_t # how much RHS exceeds LHS + if violation_amount > tol: + normalizer = max(abs(rhs_val), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 5 (Eq.7): Period {t}: z_t={z_t:.8f} < " + f"resource_usage - C_t = {resource_usage:.8f} - {C_t} = " + f"{required_z:.8f}" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": violation_amount, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint 6 — (8): Non-negativity of intensity y_jt >= 0 + # ========================================================================= + for order in instance['orders']: + j = order['order_id'] + if j not in sol_by_id: + continue + osol = sol_by_id[j] + intensities = osol.get('intensities', {}) + + for t_str, y_val in intensities.items(): + y_jt = float(y_val) + if -y_jt > tol: # y_jt < -tol + lhs_val = y_jt + rhs_val = 0.0 + raw_excess = -y_jt + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 6 (Eq.8): Order {j}, period {t_str}: " + f"y_jt={y_jt:.8f} < 0" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint 7 — (9): Non-negativity of nonregular capacity z_t >= 0 + # ========================================================================= + for t in range(1, H + 1): + z_t = float(nonregular_by_period.get(str(t), 0.0)) + if -z_t > tol: # z_t < -tol + lhs_val = z_t + rhs_val = 0.0 + raw_excess = -z_t + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 7 (Eq.9): Period {t}: z_t={z_t:.8f} < 0" + ) + violation_magnitudes.append({ + "constraint": 7, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # ========================================================================= + # Constraint 8 — (14): Objective consistency (Tier C anti-exploit check) + # reported objective_value must equal + # sum_j w_j * max(0, l_chosen_j - d_j) + sigma * sum_t z_t + # + # All variables that determine the EI-formulation objective (the chosen + # interval per order, which fixes T^j_{kl}=max(0,l-d_j), and z_t) are + # present in the solution, so a full recompute is exact up to FP noise. + # ========================================================================= + reported_obj_raw = solution.get('objective_value') + if reported_obj_raw is not None: + try: + reported_obj = float(reported_obj_raw) + except (TypeError, ValueError): + reported_obj = None + if reported_obj is not None and math.isfinite(reported_obj): + tardiness_cost = 0.0 + for order in instance['orders']: + j = order['order_id'] + d_j = order['due_date_d'] + w_j = order['tardiness_cost_w'] + if j not in sol_by_id: + continue + interval = sol_by_id[j].get('chosen_interval') + if interval is None: + continue + _, l_chosen = interval + T_j = max(0, int(l_chosen) - int(d_j)) + tardiness_cost += float(w_j) * float(T_j) + + z_sum = 0.0 + for v in nonregular_by_period.values(): + try: + z_sum += float(v) + except (TypeError, ValueError): + pass + + true_obj = tardiness_cost + float(sigma) * z_sum + + abs_diff = abs(reported_obj - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + lhs_val = reported_obj + rhs_val = true_obj + raw_excess = abs_diff + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 8 (Eq.14): Objective consistency violated: " + f"reported objective_value={reported_obj} differs from " + f"recomputed sum_j w_j*max(0,l-d_j) + sigma*sum_t z_t=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 8, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + else: + # Non-finite or unparseable reported objective is itself an + # exploit signal (e.g. NaN, inf, sys.float_info.max sometimes + # parses as a finite huge number but inf does not). + lhs_val = float('nan') if reported_obj is None else reported_obj + rhs_val = 0.0 + raw_excess = 1.0 + normalizer = max(abs(rhs_val), eps) + ratio = raw_excess / normalizer + violations.append( + f"Constraint 8 (Eq.14): Objective consistency violated: " + f"reported objective_value={reported_obj_raw} is not a finite number" + ) + violation_magnitudes.append({ + "constraint": 8, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio + }) + + # Build result + violated_constraints = sorted(set(vm['constraint'] for vm in violation_magnitudes)) + 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 Resource Loading Problem (RLP) " + "using the Execution-Interval formulation." + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result.") + args = parser.parse_args() + + with open(args.instance_path, 'r') as f: + instance = json.load(f) + + with open(args.solution_path, 'r') as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + 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/song2021/gurobi_code.py b/tasks/song2021/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a415a98574efcfc332f3d9973c064c1785254f02 --- /dev/null +++ b/tasks/song2021/gurobi_code.py @@ -0,0 +1,325 @@ +""" +Gurobi implementation of the Execution-Interval (EI) formulation for the +Resource Loading Problem (RLP). + +Paper: Song, Kis & Leus (2020), "Polyhedral Results and Branch-and-Cut for + the Resource Loading Problem", INFORMS Journal on Computing. + +This implements the Execution-Interval formulation (Section 4.1, Eqs 14-17 + 6-9): + - Binary variables a^j_{kl} for choosing execution intervals + - Continuous variables y_{jt} for intensity assignments + - Continuous variables z_t for nonregular capacity + +The formulation is provably stronger than the three time-indexed formulations +(Proposition 4 of the paper). +""" + +import json +import argparse +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(instance_path): + """Load problem instance from JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def enumerate_execution_intervals(order, H): + """ + Enumerate all feasible execution intervals for an order. + + A feasible execution interval (k, l) for order j must satisfy: + r_j <= k <= l <= H + (l - k + 1) * LB_j <= 1 + (l - k + 1) * UB_j >= 1 + """ + r_j = order['release_date_r'] + LB_j = order['intensity_lower_bound_LB'] + UB_j = order['intensity_upper_bound_UB'] + + intervals = [] + for k in range(r_j, H + 1): + for l in range(k, H + 1): + length = l - k + 1 + if length * LB_j <= 1.0 + 1e-9 and length * UB_j >= 1.0 - 1e-9: + intervals.append((k, l)) + return intervals + + +def compute_interval_bounds(order, k, l): + """ + Compute tighter per-interval bounds (Eqs 25-26). + + UB_{kl} = min{ UB_j, 1 - LB_j * (l - k) } + LB_{kl} = max{ LB_j, 1 - UB_j * (l - k) } + """ + LB_j = order['intensity_lower_bound_LB'] + UB_j = order['intensity_upper_bound_UB'] + + UB_kl = min(UB_j, 1.0 - LB_j * (l - k)) + LB_kl = max(LB_j, 1.0 - UB_j * (l - k)) + + return LB_kl, UB_kl + + +def solve_rlp(instance_path, solution_path, time_limit): + """Build and solve the EI formulation using Gurobi.""" + data = load_instance(instance_path) + + H = data['planning_horizon_H'] + n = data['num_orders_n'] + sigma = data['unit_cost_nonregular_capacity_sigma'] + capacities = data['capacities'] + orders = data['orders'] + + # Preprocess: enumerate execution intervals and compute parameters + E = {} # E[j] = list of (k, l) tuples + T_tard = {} # T_tard[j][(k,l)] = tardiness for interval + LB_kl = {} # LB_kl[j][(k,l)] = tighter lower bound + UB_kl = {} # UB_kl[j][(k,l)] = tighter upper bound + + for order in orders: + j = order['order_id'] + d_j = order['due_date_d'] + + E[j] = enumerate_execution_intervals(order, H) + T_tard[j] = {} + LB_kl[j] = {} + UB_kl[j] = {} + + for (k, l) in E[j]: + T_tard[j][(k, l)] = max(0, l - d_j) + lb, ub = compute_interval_bounds(order, k, l) + LB_kl[j][(k, l)] = lb + UB_kl[j][(k, l)] = ub + + # Build Gurobi model + model = gp.Model("RLP_EI") + model.setParam("TimeLimit", time_limit) + # Paper uses single thread + model.setParam("Threads", 1) + + # Decision variables + # a^j_{kl} in {0,1}: binary execution interval selection + a = {} + for order in orders: + j = order['order_id'] + for (k, l) in E[j]: + a[j, k, l] = model.addVar(vtype=GRB.BINARY, name=f"a_{j}_{k}_{l}") + + # y_{jt} >= 0: intensity of order j in period t + y = {} + for order in orders: + j = order['order_id'] + r_j = order['release_date_r'] + for t in range(r_j, H + 1): + y[j, t] = model.addVar(lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, + name=f"y_{j}_{t}") + + # z_t >= 0: nonregular capacity in period t + z = {} + for t in range(1, H + 1): + z[t] = model.addVar(lb=0.0, vtype=GRB.CONTINUOUS, name=f"z_{t}") + + model.update() + + # Objective function (Eq. 14): + # min sum_j sum_{(k,l) in E_j} w_j * T^j_{kl} * a^j_{kl} + sigma * sum_t z_t + obj = gp.LinExpr() + for order in orders: + j = order['order_id'] + w_j = order['tardiness_cost_w'] + for (k, l) in E[j]: + if T_tard[j][(k, l)] > 0: + obj += w_j * T_tard[j][(k, l)] * a[j, k, l] + for t in range(1, H + 1): + obj += sigma * z[t] + model.setObjective(obj, GRB.MINIMIZE) + + # Constraint (16): Exactly one execution interval per order + # sum_{(k,l) in E_j} a^j_{kl} = 1 for all j + for order in orders: + j = order['order_id'] + model.addConstr( + gp.quicksum(a[j, k, l] for (k, l) in E[j]) == 1, + name=f"one_interval_{j}" + ) + + # Constraint (15): Intensity bounds linking y and a variables + # LB_j * sum_{(k,l) in E_j: k<=t<=l} a^j_{kl} <= y_{jt} + # <= UB_j * sum_{(k,l) in E_j: k<=t<=l} a^j_{kl} + for order in orders: + j = order['order_id'] + r_j = order['release_date_r'] + LB_j = order['intensity_lower_bound_LB'] + UB_j = order['intensity_upper_bound_UB'] + + for t in range(r_j, H + 1): + covering = [(k, l) for (k, l) in E[j] if k <= t <= l] + if covering: + sum_a = gp.quicksum(a[j, k, l] for (k, l) in covering) + model.addConstr(y[j, t] >= LB_j * sum_a, + name=f"lb_intensity_{j}_{t}") + model.addConstr(y[j, t] <= UB_j * sum_a, + name=f"ub_intensity_{j}_{t}") + else: + # No execution interval covers this period, intensity must be 0 + model.addConstr(y[j, t] == 0, + name=f"zero_intensity_{j}_{t}") + + # Constraint (6): Total intensity equals 1 + # sum_{t=r_j}^{H} y_{jt} = 1 for all j + for order in orders: + j = order['order_id'] + r_j = order['release_date_r'] + model.addConstr( + gp.quicksum(y[j, t] for t in range(r_j, H + 1)) == 1, + name=f"total_intensity_{j}" + ) + + # Constraint (7): Nonregular capacity + # z_t >= sum_j y_{jt} * p_j - C_t for all t + for t in range(1, H + 1): + C_t = capacities[t - 1] # 0-indexed in the array + resource_usage = gp.LinExpr() + for order in orders: + j = order['order_id'] + r_j = order['release_date_r'] + p_j = order['work_content_p'] + if t >= r_j: + resource_usage += y[j, t] * p_j + model.addConstr(z[t] >= resource_usage - C_t, + name=f"nonregular_cap_{t}") + + # Solve + print(f"Model has {model.NumVars} variables and {model.NumConstrs} constraints") + model.optimize() + + # Extract solution + result = { + "problem_name": data.get("problem_name", "RLP"), + "solver": "Gurobi", + "formulation": "Execution-Interval (EI)", + "status": model.Status, + "status_description": "", + "objective_value": None, + "solve_time_seconds": model.Runtime, + "gap": None, + "orders_solution": [] + } + + if model.Status == GRB.OPTIMAL: + result["status_description"] = "Optimal" + result["objective_value"] = model.ObjVal + result["gap"] = 0.0 + elif model.Status == GRB.TIME_LIMIT: + result["status_description"] = "Time limit reached" + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["gap"] = model.MIPGap + else: + result["objective_value"] = None + result["gap"] = None + elif model.SolCount > 0: + result["status_description"] = f"Status code {model.Status}" + result["objective_value"] = model.ObjVal + result["gap"] = model.MIPGap if hasattr(model, 'MIPGap') else None + else: + result["status_description"] = f"No feasible solution found (status {model.Status})" + result["objective_value"] = None + + # Extract detailed solution if available + if model.SolCount > 0: + for order in orders: + j = order['order_id'] + r_j = order['release_date_r'] + d_j = order['due_date_d'] + w_j = order['tardiness_cost_w'] + + # Find chosen execution interval + chosen_interval = None + for (k, l) in E[j]: + if a[j, k, l].X > 0.5: + chosen_interval = (k, l) + break + + # Extract intensities + intensities = {} + for t in range(r_j, H + 1): + val = y[j, t].X + if val > 1e-8: + intensities[str(t)] = round(val, 8) + + tardiness = 0 + if chosen_interval: + tardiness = max(0, chosen_interval[1] - d_j) + + order_sol = { + "order_id": j, + "chosen_interval": list(chosen_interval) if chosen_interval else None, + "tardiness": tardiness, + "tardiness_cost": w_j * tardiness, + "intensities": intensities + } + result["orders_solution"].append(order_sol) + + # Compute nonregular capacity details + nonregular_capacity = {} + total_nonregular = 0.0 + for t in range(1, H + 1): + val = z[t].X + if val > 1e-8: + nonregular_capacity[str(t)] = round(val, 8) + total_nonregular += val + result["total_nonregular_capacity"] = round(total_nonregular, 8) + result["nonregular_capacity_by_period"] = nonregular_capacity + + # Write solution + with open(solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"\nSolution written to {solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']}") + print(f"Status: {result['status_description']}") + if result["gap"] is not None: + print(f"Gap: {result['gap']:.4%}") + + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Solve the Resource Loading Problem using the Execution-Interval " + "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 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_rlp(args.instance_path, args.solution_path, args.time_limit) diff --git a/tasks/song2021/gurobi_feasi_result/large_feasi_result_1.json b/tasks/song2021/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/song2021/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/song2021/gurobi_feasi_result/large_feasi_result_2.json b/tasks/song2021/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/song2021/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/song2021/gurobi_feasi_result/large_feasi_result_3.json b/tasks/song2021/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/song2021/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/song2021/gurobi_feasi_result/large_feasi_result_4.json b/tasks/song2021/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/song2021/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/song2021/gurobi_feasi_result/large_feasi_result_5.json b/tasks/song2021/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/song2021/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/song2021/gurobi_feasi_result/tiny_feasi_result.json b/tasks/song2021/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/song2021/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/song2021/gurobi_solution/large_solution_1.json b/tasks/song2021/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c3daa2418cb769fc2b335d2900a2591b71579b07 --- /dev/null +++ b/tasks/song2021/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8853510bfe3607c8fb57b4170cb435b6ce2272dd1ae413c959a9f337c8fdef92 +size 54988 diff --git a/tasks/song2021/gurobi_solution/large_solution_2.json b/tasks/song2021/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8ac6dc64243b9077c64d5b271370e2487e17e9bd --- /dev/null +++ b/tasks/song2021/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:305c54e25b0926ba67c3277af344f8079100a6c1f23066b02159a074e94cf632 +size 58634 diff --git a/tasks/song2021/gurobi_solution/large_solution_3.json b/tasks/song2021/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..491181fb19e32ef2fcfa7550c9a31a70993be6ff --- /dev/null +++ b/tasks/song2021/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e4d6f78df4f13d876619ae65f7deae7066af3fd6a46f36eb8bebc3aa769e405 +size 59354 diff --git a/tasks/song2021/gurobi_solution/large_solution_4.json b/tasks/song2021/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..61f6a379388fd552bfa3db39b1f5cbb0b105dc50 --- /dev/null +++ b/tasks/song2021/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24543a586d8652d69295144c80f079df9c4975f5b63cfd8dd29612615f720f14 +size 51448 diff --git a/tasks/song2021/gurobi_solution/large_solution_5.json b/tasks/song2021/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..2dd934a403f1eaed9e80dadd0cd00cf270d5c5b3 --- /dev/null +++ b/tasks/song2021/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cade1ecc6dcdbeb592e62720bf37ae0592f46c58bb9dfb6667e0039a0497a0e8 +size 61028 diff --git a/tasks/song2021/gurobi_solution/tiny_solution.json b/tasks/song2021/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..5a8ad0307c9c1d477e4e5c6bc1833fedbfcb658a --- /dev/null +++ b/tasks/song2021/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51a7f14fc236d3382484f6d63e3d6b0478ba03028f1207ea6ffb8b2905dcc60e +size 8639 diff --git a/tasks/song2021/gurobi_solution_log/large_log_1.jsonl b/tasks/song2021/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..273cef67b8aac561b188d12c32172b54e66598d2 --- /dev/null +++ b/tasks/song2021/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b8f35b31f62fb191edd059b37071a79653d7c0007ca293758635ac97f6c7c6a +size 275 diff --git a/tasks/song2021/gurobi_solution_log/large_log_2.jsonl b/tasks/song2021/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..28cbecbdfe5ee97aa5660df8faecb051170e5817 --- /dev/null +++ b/tasks/song2021/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48e8ca69da799fbc5946a1a46fc055688b3c402de03a745593ce94d218cc8b74 +size 108 diff --git a/tasks/song2021/gurobi_solution_log/large_log_3.jsonl b/tasks/song2021/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e457a24a59e4656fbdb9a022b9057b4e4c8f5fad --- /dev/null +++ b/tasks/song2021/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:199aed1106056126d4cf00c938bf6bdd4c91c4442da005988a96f6e4b27e4565 +size 273 diff --git a/tasks/song2021/gurobi_solution_log/large_log_4.jsonl b/tasks/song2021/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6d514a348884b0ab72fc5dfb8a7a47fa318beab1 --- /dev/null +++ b/tasks/song2021/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ed6c7b0325124acf2603592b7336ded1a9726c1849f0d8b4b297c61d236aa22 +size 1733 diff --git a/tasks/song2021/gurobi_solution_log/large_log_5.jsonl b/tasks/song2021/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..35d7b0a51bec4619e38abecdf4ecdaa4b5c45bfe --- /dev/null +++ b/tasks/song2021/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b6a826b71895e2682eddd123d347ba5d50f9759350656ed1b7db328e2dd5133 +size 219 diff --git a/tasks/song2021/gurobi_solution_log/tiny_log.jsonl b/tasks/song2021/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5eabb8b181aa54f386f6c82f1af719ee07888712 --- /dev/null +++ b/tasks/song2021/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb01cd007c8241f7a8b7d21ed9b3436f3ad900dd8994b7a5f041b8f3206d696c +size 380 diff --git a/tasks/song2021/instance/large_instance_1.json b/tasks/song2021/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..11c3b6d9b1bff6869128bbddcfa565a3c10fa19f --- /dev/null +++ b/tasks/song2021/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ca71c9978d8d59229b47340abbe6ffca17e3e7ff94e5b8d9472efb0a0d165b4 +size 50676 diff --git a/tasks/song2021/instance/large_instance_2.json b/tasks/song2021/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..d9bbe5cbebb4068608d94907f92dc54bbe5c5a03 --- /dev/null +++ b/tasks/song2021/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:584d6aa4bd5abcb0ef886b200a2fd9c713c91e8f28fe3bda2f53139640a136a7 +size 50634 diff --git a/tasks/song2021/instance/large_instance_3.json b/tasks/song2021/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..59c3243059910ade240559a83a5a3ba5cb940f39 --- /dev/null +++ b/tasks/song2021/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:373ec48b21a7dcf80c116efbfda6127b680b8b4d5943e8f62f07e35f37a2e69a +size 50538 diff --git a/tasks/song2021/instance/large_instance_4.json b/tasks/song2021/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..a5a344ac2d9a65b2f4e05f971595033c537d4679 --- /dev/null +++ b/tasks/song2021/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e182dd371c86f1285b0d0e6793213a88e1b708fbe071610dd2232f1ba97bec0 +size 50252 diff --git a/tasks/song2021/instance/large_instance_5.json b/tasks/song2021/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..6b322faccf9ddf8953a225d785bd35737d1c4755 --- /dev/null +++ b/tasks/song2021/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93fa2f1f6e6005cd5240b2935aaf75560cf5d1ab8989b4db4b92c6cb4d6c59fa +size 50498 diff --git a/tasks/song2021/instance/tiny_instance.json b/tasks/song2021/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..3486e7003785a58600f9e3b663fdf7157181e60b --- /dev/null +++ b/tasks/song2021/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2496d256d02889d22291699804e20d958a2ae4525bad2877b06646c18f43af2b +size 7746 diff --git a/tasks/song2021/instance_schema.json b/tasks/song2021/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..f335d3dca58c71a7a0db8e196124f60b67c3fe0b --- /dev/null +++ b/tasks/song2021/instance_schema.json @@ -0,0 +1,19 @@ +{ + "planning_horizon_H": " Total number of discrete time periods in the planning horizon.", + "num_orders_n": " Number of orders to be scheduled.", + "unit_cost_nonregular_capacity_sigma": " Cost per unit of nonregular (overtime) capacity used in any period.", + "capacities": " Regular workforce capacity in man-hours available in each period.", + "orders": [ + { + "order_id": " Unique identifier for the order.", + "work_content_p": " Total man-hours of work required to complete the order.", + "lower_exec_interval_length_l": " Minimum number of consecutive periods over which the order must be executed.", + "upper_exec_interval_length_l_bar": " Maximum number of consecutive periods over which the order may be executed.", + "intensity_upper_bound_UB": " Maximum fraction of the order's work content that may be performed in any single period.", + "intensity_lower_bound_LB": " Minimum fraction of the order's work content that must be performed in any period during which the order is active.", + "release_date_r": " Earliest period in which work on the order may begin.", + "due_date_d": " Target completion period after which tardiness penalties apply.", + "tardiness_cost_w": " Per-period penalty cost incurred for each period the order finishes past its due date." + } + ] +} diff --git a/tasks/song2021/mathematical_formulation.md b/tasks/song2021/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..6424c0a033135be1ec3762c490b10e96baba07cd --- /dev/null +++ b/tasks/song2021/mathematical_formulation.md @@ -0,0 +1,68 @@ +# Original Formulation: Resource Loading Problem (RLP) + +*Source: Polyhedral Results and Branch-and-Cut for the Resource Loading Problem, Guopeng Song, Tamás Kis, Roel Leus, 2020 (INFORMS Journal on Computing).* + +The paper’s first explicit MIP defining the problem it studies is the *Pulse Formulation* of Section 3.1 (Equations (1)–(11)), whose notation ($y_{jt}, z_t, T_j$) is introduced when the problem is stated in Section 1 and is carried throughout the paper. This is the canonical original formulation below. The novel Execution-Interval formulation of Section 4.1 (the paper’s main contribution) is reproduced under *Variants*. + +## Sets and Indices + +$$\begin{align*} +&J && \text{set of orders (jobs), indexed by } j = 1,\ldots,n.\\ +&t = 1,\ldots,H && \text{discrete time periods; } H \text{ is the length of the planning horizon.} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +&p_j && \text{work content of order } j \text{ (e.g., man-hours).}\\ +&r_j && \text{release date of order } j,\quad 1 \le r_j \le d_j \le H.\\ +&d_j && \text{due date of order } j.\\ +&LB_j && \text{lower bound on the per-period execution intensity, } 0 < LB_j \le UB_j \le 1.\\ +&UB_j && \text{upper bound on the per-period execution intensity.}\\ +&w_j && \text{tardiness penalty per time period for order } j.\\ +&\sigma && \text{unit cost of nonregular (overtime) capacity.}\\ +&C_t && \text{regular workforce capacity available in period } t. +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +&s_{jt} \in \{0,1\} && \text{$1$ if order $j$ starts in period $t$;}\quad j \in J,\; t = r_j,\ldots,H.\\ +&f_{jt} \in \{0,1\} && \text{$1$ if order $j$ finishes in period $t$;}\quad j \in J,\; t = r_j,\ldots,H.\\ +&y_{jt} \in [0,1] && \text{intensity (fraction of work content) of order $j$ in period $t$;}\quad j \in J,\; t = r_j,\ldots,H.\\ +&T_j \ge 0 && \text{tardiness of order $j$;}\quad j \in J.\\ +&z_t \ge 0 && \text{nonregular capacity used in period $t$;}\quad t = 1,\ldots,H. +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \quad \sum_{j \in J} w_j T_j + \sigma \sum_{t=1}^{H} z_t \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +& \sum_{t=r_j}^{H} s_{jt} = \sum_{t=r_j}^{H} f_{jt} = 1 + && \forall j \in J, \tag{2}\\[4pt] +& \sum_{k=r_j}^{t} f_{jk} \le \sum_{k=r_j}^{t} s_{jk} + && \forall j \in J,\; t = r_j,\ldots,H, \tag{3}\\[4pt] +& T_j \ge \sum_{t=d_j}^{H} f_{jt}\,(t - d_j) + && \forall j \in J, \tag{4}\\[4pt] +& LB_j\!\left( \sum_{k=r_j}^{t} s_{jk} - \sum_{k=r_j}^{t-1} f_{jk} \right) + \le y_{jt} + \le UB_j\!\left( \sum_{k=r_j}^{t} s_{jk} - \sum_{k=r_j}^{t-1} f_{jk} \right) + && \forall j \in J,\; t = r_j,\ldots,H, \tag{5}\\[4pt] +& \sum_{t=r_j}^{H} y_{jt} = 1 + && \forall j \in J, \tag{6}\\[4pt] +& z_t \ge \sum_{j \in J} y_{jt}\, p_j - C_t + && t = 1,\ldots,H, \tag{7}\\[4pt] +& y_{jt} \ge 0 + && \forall j \in J,\; t = r_j,\ldots,H, \tag{8}\\[4pt] +& z_t \ge 0 + && t = 1,\ldots,H, \tag{9}\\[4pt] +& T_j \ge 0 + && \forall j \in J, \tag{10}\\[4pt] +& s_{jt},\, f_{jt} \in \{0,1\} + && \forall j \in J,\; t = r_j,\ldots,H. \tag{11} +\end{align}$$ diff --git a/tasks/song2021/problem_description.txt b/tasks/song2021/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..f9e3daffa4b95576826fb10b126a19cd807c7979 --- /dev/null +++ b/tasks/song2021/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A company must schedule the execution of a set of orders over a discrete planning horizon divided into a given number of time periods. Each period has a known regular workforce capacity measured in man-hours. Each order has a known work content (in man-hours), a release date (the earliest period in which work on the order may begin), a due date (the target completion period), and a per-period tardiness penalty cost. A single global unit cost applies to all nonregular (overtime) capacity used in any period. + +The company must decide, for each order and each time period, the execution intensity of that order in that period, expressed as the fraction of the order's total work content performed during that period. Each order must be executed without preemption: it is worked on during a contiguous block of consecutive periods, starting in exactly one period and finishing in exactly one period, with the finish period no earlier than the start period. The start period must be no earlier than the order's release date. The sum of the intensity fractions assigned to each order across all periods must equal one, meaning that the order's entire work content is completed exactly once. In any period during which an order is being executed (that is, in any period from its start through its finish), the intensity must lie between a given order-specific lower bound and a given order-specific upper bound, where the lower bound is strictly greater than zero and the upper bound is at most one. In periods outside an order's execution window, its intensity is zero. + +For each order, the start period and finish period together define an execution interval, and the schedule must select exactly one execution interval per order from the set of feasible execution intervals for that order. An execution interval is feasible only if its start period is no earlier than the order's release date, its finish period is no later than the end of the planning horizon, and its length (the number of periods from the start period through the finish period, inclusive) is compatible with the order's intensity bounds: the length must be at least the ceiling of one divided by the order's upper intensity bound and at most the floor of one divided by the order's lower intensity bound, since the per-period intensity bounds together with the requirement that the intensities sum to one impose these limits on how many periods the order can occupy. + +For each period, the total resource consumption equals the sum over all orders of each order's intensity in that period multiplied by its work content. Whenever this total exceeds the regular capacity available in that period, the excess is covered by nonregular capacity. Each order's tardiness equals the amount by which its finish period exceeds its due date, or zero if it finishes on time or early. + +The goal is to minimize the total cost, which is the sum of two components: the total weighted tardiness, computed as the sum over all orders of each order's tardiness penalty multiplied by its tardiness, and the total nonregular capacity cost, computed as the unit cost of nonregular capacity multiplied by the sum of nonregular capacity used across all periods. diff --git a/tasks/song2021/solution_logger.py b/tasks/song2021/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/song2021/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/song2021/solution_schema.json b/tasks/song2021/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..fe2a6a3a17322a1a38537f1ccaafc2f21d108c36 --- /dev/null +++ b/tasks/song2021/solution_schema.json @@ -0,0 +1,11 @@ +{ + "objective_value": " Total cost combining weighted tardiness penalties and nonregular capacity costs.", + "orders_solution": [ + { + "order_id": " Unique identifier of the order this entry refers to.", + "chosen_interval": " Start and finish periods of the contiguous execution window assigned to the order.", + "intensities": " Fraction of the order's total work content performed in each period during its execution window." + } + ], + "nonregular_capacity_by_period": " Amount of nonregular (overtime) capacity used in each period where it is positive." +} diff --git a/tasks/spliet2015/feasibility_check.py b/tasks/spliet2015/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b725063f38eaa207eb64d656a896e1b3076472c2 --- /dev/null +++ b/tasks/spliet2015/feasibility_check.py @@ -0,0 +1,451 @@ +""" +Feasibility checker for the Time Window Assignment Vehicle Routing Problem (TWAVRP). + +Checks all hard constraints from the mathematical formulation in Spliet & Gabor (2014). + +Constraints (numbered top-to-bottom from the formulation section of math_model.txt): + Constraint 1: Objective function (not a constraint to check) + Constraint 2: Each customer visited exactly once per scenario + Constraint 3: Service time >= endogenous TW start (y_v) + Constraint 4: Service time <= endogenous TW end (y_v + w_v) + Constraint 5: Binary route variables (x_r^omega in {0,1}) + Constraint 6: Endogenous TW start domain (y_v in [s_v, e_v - w_v]) + Constraint 7: Objective consistency (reported objective_value must equal the + probability-weighted sum of route arc costs recomputed from the + solution's routes and the instance distance matrix). + +Additionally, route feasibility conditions from the model are checked as implicit +hard constraints embedded within the route definitions: + - (i) Capacity constraint per route per scenario + - (ii) Exogenous time window constraints + - (iii) Travel time consistency (arrival at j >= departure from i + travel time) +These are checked as sub-parts of Constraint 5 (a route variable being 1 means +the route must be feasible). +""" + +import argparse +import json +import math + +TOL = 1e-5 +EPS_NORM = 1e-5 + + +def load_json(path): + with open(path) as f: + return json.load(f) + + +def make_violation(constraint, lhs, rhs, raw_excess, description): + normalizer = max(abs(rhs), EPS_NORM) + ratio = raw_excess / normalizer + return { + "constraint": constraint, + "lhs": lhs, + "rhs": rhs, + "raw_excess": raw_excess, + "normalizer": normalizer, + "ratio": ratio, + "description": description, + } + + +def check_feasibility(instance, solution): + violations = [] + violation_magnitudes = [] + violated_set = set() + + schema_errors = [] + if not isinstance(solution, dict): + schema_errors.append("solution must be a JSON object") + else: + if "objective_value" not in solution or solution["objective_value"] is None: + schema_errors.append("missing required solution field: objective_value") + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or not math.isfinite(float(objective)) + ): + schema_errors.append("objective_value must be a finite number") + for field in ("routes", "time_windows"): + if ( + field not in solution + or not isinstance(solution[field], dict) + or not solution[field] + ): + schema_errors.append(f"{field} must be a non-empty JSON object") + if schema_errors: + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": schema_errors, + "violation_magnitudes": [], + } + + n = instance["num_customers"] + depot_node = 0 + end_depot = n + 1 + customers = {c["id"]: c for c in instance["customers"]} + scenarios = instance["scenarios"] + n_scenarios = len(scenarios) + dist = instance["distance_matrix"] + Q = instance["vehicle_capacity"] + + # Parse solution + time_windows = solution["time_windows"] # str(v) -> [y_v, y_v + w_v] + routes_by_scenario = solution["routes"] # str(scenario_1based) -> list of route dicts + + # Extract y_v values (endogenous TW start) and w_v + y = {} + for c in instance["customers"]: + v = c["id"] + sv = str(v) + if sv in time_windows: + y[v] = time_windows[sv][0] + else: + y[v] = None + + w = {} + for c in instance["customers"]: + v = c["id"] + w[v] = c["endogenous_time_window_width"] + + # Build exogenous time windows + exo_tw = {} + exo_tw[0] = instance["depot"]["exogenous_time_window"] + for c in instance["customers"]: + exo_tw[c["id"]] = c["exogenous_time_window"] + exo_tw[end_depot] = instance["depot"]["exogenous_time_window"] + + # ========================================================================= + # Constraint 6: y_v in [s_v, e_v - w_v] for all v in V' + # This is two bounds: + # 6a: y_v >= s_v (>= constraint) + # 6b: y_v <= e_v - w_v (<= constraint) + # ========================================================================= + for c in instance["customers"]: + v = c["id"] + sv_exo = c["exogenous_time_window"][0] # s_v + ev_exo = c["exogenous_time_window"][1] # e_v + wv = c["endogenous_time_window_width"] # w_v + yv = y[v] + + if yv is None: + violations.append(f"Customer {v}: endogenous TW start y_{v} not specified in solution") + violated_set.add(6) + violation_magnitudes.append(make_violation(6, 0, sv_exo, sv_exo, f"Customer {v}: y_{v} missing")) + continue + + # 6a: y_v >= s_v + excess_6a = sv_exo - yv # how much RHS exceeds LHS for >= constraint + if excess_6a > TOL: + violations.append( + f"Constraint 6: Customer {v} endogenous TW start y_{v}={yv:.4f} < s_{v}={sv_exo}" + ) + violated_set.add(6) + violation_magnitudes.append(make_violation(6, yv, sv_exo, excess_6a, + f"Customer {v}: y_{v}={yv:.4f} < s_{v}={sv_exo}")) + + # 6b: y_v <= e_v - w_v + upper = ev_exo - wv + excess_6b = yv - upper # how much LHS exceeds RHS for <= constraint + if excess_6b > TOL: + violations.append( + f"Constraint 6: Customer {v} endogenous TW start y_{v}={yv:.4f} > e_{v}-w_{v}={upper:.4f}" + ) + violated_set.add(6) + violation_magnitudes.append(make_violation(6, yv, upper, excess_6b, + f"Customer {v}: y_{v}={yv:.4f} > e_{v}-w_{v}={upper:.4f}")) + + # ========================================================================= + # Per-scenario checks + # ========================================================================= + for om_idx in range(n_scenarios): + scenario = scenarios[om_idx] + om_key = str(om_idx + 1) # scenarios are 1-indexed in solution + demands = scenario["demands"] # list indexed by customer_index (0-based for customers 1..n) + + # Get demand map: customer_id -> demand + dem = {} + for ci, c in enumerate(instance["customers"]): + dem[c["id"]] = demands[ci] + + # Get routes for this scenario + if om_key not in routes_by_scenario: + # No routes for this scenario - all customers unvisited + for c in instance["customers"]: + v = c["id"] + violations.append( + f"Constraint 2: Customer {v} not visited in scenario {om_idx+1} (no routes)" + ) + violated_set.add(2) + violation_magnitudes.append(make_violation(2, 0, 1, 1.0, + f"Customer {v} visit count=0 in scenario {om_idx+1}")) + continue + + sc_routes = routes_by_scenario[om_key] + + # Count visits per customer and collect service times + visit_count = {c["id"]: 0 for c in instance["customers"]} + service_time_sum = {c["id"]: 0.0 for c in instance["customers"]} + + for ri, route_info in enumerate(sc_routes): + route = route_info["route"] # list of node ids: [0, ..., n+1] + arrival_times = route_info["arrival_times"] # str(node_id) -> arrival time + + # ===================================================================== + # Constraint 5 (route feasibility): Check that each used route is feasible + # A route x_r^omega = 1 must be a valid route satisfying conditions (i)-(iii) + # ===================================================================== + + # Identify customer nodes (exclude depot 0 and end depot n+1) + cust_in_route = [node for node in route if 1 <= node <= n] + + # --- Condition (i): Capacity constraint --- + route_load = sum(dem.get(node, 0) for node in cust_in_route) + excess_cap = route_load - Q # LHS - RHS for <= constraint + if excess_cap > TOL: + violations.append( + f"Constraint 5 (capacity): Scenario {om_idx+1} route {ri+1} " + f"load={route_load} exceeds capacity Q={Q}" + ) + violated_set.add(5) + violation_magnitudes.append(make_violation(5, route_load, Q, excess_cap, + f"Scenario {om_idx+1} route {ri+1}: load={route_load} > Q={Q}")) + + # --- Condition (ii): Exogenous time window constraints --- + for node in route: + if node == 0 or node == end_depot: + continue + at_key = str(node) + if at_key not in arrival_times: + continue + arr = arrival_times[at_key] + s_exo, e_exo = exo_tw[node] + + # arr >= s_v (exogenous) + excess_early = s_exo - arr + if excess_early > TOL: + violations.append( + f"Constraint 5 (exogenous TW): Scenario {om_idx+1} route {ri+1} " + f"customer {node} arrival={arr:.4f} < exogenous start={s_exo}" + ) + violated_set.add(5) + violation_magnitudes.append(make_violation(5, arr, s_exo, excess_early, + f"Scenario {om_idx+1} route {ri+1} customer {node}: " + f"arrival={arr:.4f} < exo_start={s_exo}")) + + # arr <= e_v (exogenous) + excess_late = arr - e_exo + if excess_late > TOL: + violations.append( + f"Constraint 5 (exogenous TW): Scenario {om_idx+1} route {ri+1} " + f"customer {node} arrival={arr:.4f} > exogenous end={e_exo}" + ) + violated_set.add(5) + violation_magnitudes.append(make_violation(5, arr, e_exo, excess_late, + f"Scenario {om_idx+1} route {ri+1} customer {node}: " + f"arrival={arr:.4f} > exo_end={e_exo}")) + + # --- Condition (iii): Travel time consistency --- + # Service at j >= service at i + t_{ij} when j visited directly after i + for k in range(len(route) - 1): + i_node = route[k] + j_node = route[k + 1] + at_i_key = str(i_node) + at_j_key = str(j_node) + + if at_i_key in arrival_times and at_j_key in arrival_times: + arr_i = arrival_times[at_i_key] + arr_j = arrival_times[at_j_key] + travel = dist[i_node][j_node] + earliest_j = arr_i + travel + + # arr_j >= arr_i + t_{ij} (>= constraint) + excess_travel = earliest_j - arr_j + if excess_travel > TOL: + violations.append( + f"Constraint 5 (travel time): Scenario {om_idx+1} route {ri+1} " + f"arc ({i_node}->{j_node}): arrival at {j_node}={arr_j:.4f} " + f"< departure from {i_node} ({arr_i:.4f}) + travel ({travel:.4f}) " + f"= {earliest_j:.4f}" + ) + violated_set.add(5) + violation_magnitudes.append(make_violation(5, arr_j, earliest_j, excess_travel, + f"Scenario {om_idx+1} route {ri+1}: " + f"arr({j_node})={arr_j:.4f} < arr({i_node})+t={earliest_j:.4f}")) + + # Accumulate visit counts and service times for constraint 2/3/4 checks + for node in cust_in_route: + visit_count[node] += 1 + at_key = str(node) + if at_key in arrival_times: + service_time_sum[node] += arrival_times[at_key] + + # ===================================================================== + # Constraint 2: Each customer visited exactly once per scenario + # sum_r a_r^v x_r^omega = 1 for all v in V', omega in Omega + # ===================================================================== + for c in instance["customers"]: + v = c["id"] + count = visit_count[v] + rhs = 1 + violation_amount = abs(count - rhs) + if violation_amount > TOL: + violations.append( + f"Constraint 2: Customer {v} visited {count} time(s) in scenario {om_idx+1}" + ) + violated_set.add(2) + violation_magnitudes.append(make_violation(2, count, rhs, violation_amount, + f"Customer {v} visit_count={count} in scenario {om_idx+1}")) + + # ===================================================================== + # Constraint 3: Service time >= y_v + # sum_r t_r^v x_r^omega >= y_v for all v in V', omega in Omega + # ===================================================================== + for c in instance["customers"]: + v = c["id"] + if y[v] is None: + continue + if visit_count[v] == 0: + continue # already caught by constraint 2 + lhs = service_time_sum[v] + rhs_val = y[v] + # >= constraint: violation if RHS > LHS + excess = rhs_val - lhs + if excess > TOL: + violations.append( + f"Constraint 3: Scenario {om_idx+1} customer {v} " + f"service_time={lhs:.4f} < y_{v}={rhs_val:.4f}" + ) + violated_set.add(3) + violation_magnitudes.append(make_violation(3, lhs, rhs_val, excess, + f"Scenario {om_idx+1} customer {v}: service_time={lhs:.4f} < y_{v}={rhs_val:.4f}")) + + # ===================================================================== + # Constraint 4: Service time <= y_v + w_v + # sum_r t_r^v x_r^omega <= y_v + w_v for all v in V', omega in Omega + # ===================================================================== + for c in instance["customers"]: + v = c["id"] + if y[v] is None: + continue + if visit_count[v] == 0: + continue # already caught by constraint 2 + lhs = service_time_sum[v] + rhs_val = y[v] + w[v] + # <= constraint: violation if LHS > RHS + excess = lhs - rhs_val + if excess > TOL: + violations.append( + f"Constraint 4: Scenario {om_idx+1} customer {v} " + f"service_time={lhs:.4f} > y_{v}+w_{v}={rhs_val:.4f}" + ) + violated_set.add(4) + violation_magnitudes.append(make_violation(4, lhs, rhs_val, excess, + f"Scenario {om_idx+1} customer {v}: service_time={lhs:.4f} > y_{v}+w_{v}={rhs_val:.4f}")) + + # ========================================================================= + # Constraint 7: Objective consistency (Tier C defense). + # Recompute obj = sum_omega p_omega * sum_r c_r where c_r is the sum of arc + # costs along route r in scenario omega (from instance distance matrix). + # All variables required (routes per scenario, probabilities, distance + # matrix) are present in the solution + instance, so a full recompute is + # possible. Reject when the reported objective_value differs beyond a 0.1% + # relative tolerance with a 1e-3 absolute floor. + # ========================================================================= + reported_obj_raw = solution.get("objective_value") + try: + reported_obj = float(reported_obj_raw) if reported_obj_raw is not None else None + except (TypeError, ValueError): + reported_obj = None + + if reported_obj is not None and not (math.isnan(reported_obj) or math.isinf(reported_obj)): + true_obj = 0.0 + for scenario in scenarios: + sc_id = scenario["scenario_id"] + p_omega = float(scenario["probability"]) + sc_routes = routes_by_scenario.get(str(sc_id), []) + scenario_cost = 0.0 + for route_info in sc_routes: + route = route_info.get("route", []) + for k in range(len(route) - 1): + i_node = route[k] + j_node = route[k + 1] + scenario_cost += float(dist[i_node][j_node]) + true_obj += p_omega * scenario_cost + + abs_diff = abs(reported_obj - true_obj) + tol_obj = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol_obj: + violations.append( + f"Constraint 7: Objective consistency violated: reported objective_value=" + f"{reported_obj} differs from recomputed sum_omega p_omega * sum_r c_r=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={tol_obj:.3g})" + ) + violated_set.add(7) + violation_magnitudes.append(make_violation(7, reported_obj, true_obj, abs_diff, + f"Reported obj={reported_obj} vs recomputed={true_obj} (|diff|={abs_diff:.3g})")) + elif reported_obj_raw is not None: + # Non-finite or unparseable reported objective is itself a violation. + violations.append( + f"Constraint 7: Objective consistency violated: reported objective_value=" + f"{reported_obj_raw!r} is not a finite real number" + ) + violated_set.add(7) + violation_magnitudes.append(make_violation(7, 0.0, 0.0, float("inf"), + f"Reported obj={reported_obj_raw!r} not a finite real number")) + + # Build result + # Remove description from violation_magnitudes for output + output_magnitudes = [] + for vm in violation_magnitudes: + output_magnitudes.append({ + "constraint": vm["constraint"], + "lhs": vm["lhs"], + "rhs": vm["rhs"], + "raw_excess": vm["raw_excess"], + "normalizer": vm["normalizer"], + "ratio": vm["ratio"], + }) + + feasible = len(violated_set) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": output_magnitudes, + } + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for TWAVRP (Spliet & Gabor 2014)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print(f"FEASIBLE - No constraint violations found.") + else: + print(f"INFEASIBLE - {len(result['violated_constraints'])} constraint(s) violated: " + f"{result['violated_constraints']}") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + main() diff --git a/tasks/spliet2015/gurobi_code.py b/tasks/spliet2015/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..3b43ed1edeb8c6023322a686aa285f9c035651d3 --- /dev/null +++ b/tasks/spliet2015/gurobi_code.py @@ -0,0 +1,356 @@ +""" +Gurobi-based solver for the Time Window Assignment Vehicle Routing Problem (TWAVRP). + +Reference: Spliet & Gabor (2014), "The Time Window Assignment Vehicle Routing Problem", + Transportation Science. + +This implements a compact arc-flow MILP formulation equivalent to the route-based +formulation (1)-(6) in the paper. The route-based formulation has an exponential +(infinite for continuous time) number of variables and requires column generation. +Instead, we use arc-flow variables z[i,j,omega] and arrival time variables t[v,omega] +to model the same problem compactly. + +ASSUMPTION (INFERRED): The paper's formulation is route-based with an infinite number +of route variables. We use a standard arc-flow VRP formulation that is equivalent for +integer solutions. This is a standard transformation; see e.g., Desrochers et al. (1992). + +ASSUMPTION (INFERRED): Service time at each customer is 0. The paper does not specify +a positive service duration, and the test instances use travel time = Euclidean distance +with wide time windows, suggesting zero service time. **NOT SPECIFIED IN PAPER**. + +ASSUMPTION (INFERRED): The ending depot n+1 has the same exogenous time window as +the starting depot 0, i.e., [6, 22]. **NOT SPECIFIED IN PAPER** but standard. +""" + +import argparse +import json +import math +import sys +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +try: + import gurobipy as gp + from gurobipy import GRB +except ImportError: + print("Error: gurobipy is required. Install Gurobi and its Python interface.") + sys.exit(1) + + +def load_instance(instance_path): + """Load instance from JSON file.""" + with open(instance_path, 'r') as f: + data = json.load(f) + return data + + +def solve_twavrp(data, time_limit): + """ + Solve the TWAVRP using a compact arc-flow MILP formulation. + + Sets: + V = {0, 1, ..., n, n+1} where 0 = start depot, n+1 = end depot, 1..n = customers + V' = {1, ..., n} = customers + Omega = set of scenarios + + Decision variables: + z[i,j,omega] in {0,1}: 1 if arc (i,j) is used in scenario omega + t[v,omega] >= 0: arrival/service time at node v in scenario omega + y[v]: start of endogenous time window for customer v in V' + + Objective: min sum_{omega} p_omega * sum_{(i,j)} c_ij * z[i,j,omega] + """ + n = data["num_customers"] + customers_data = data["customers"] + depot = data["depot"] + scenarios = data["scenarios"] + Q = data["vehicle_capacity"] + dist = data["distance_matrix"] + + num_scenarios = len(scenarios) + + # Node indices: 0 = start depot, 1..n = customers, n+1 = end depot + V = list(range(n + 2)) + V_prime = list(range(1, n + 1)) + depot_start = 0 + depot_end = n + 1 + + # Exogenous time windows + tw = {} + tw[depot_start] = (depot["exogenous_time_window"][0], depot["exogenous_time_window"][1]) + for c in customers_data: + tw[c["id"]] = (c["exogenous_time_window"][0], c["exogenous_time_window"][1]) + tw[depot_end] = tw[depot_start] + + # Endogenous time window widths + w = {} + for c in customers_data: + w[c["id"]] = c["endogenous_time_window_width"] + + # Travel costs = travel times = Euclidean distance (per paper Section 4.1) + c_travel = {} + t_travel = {} + for i in V: + for j in V: + c_travel[i, j] = dist[i][j] + t_travel[i, j] = dist[i][j] + + # Demands per scenario + demands = {} + for s_idx, sc in enumerate(scenarios): + for c_idx, cust in enumerate(customers_data): + demands[cust["id"], s_idx] = sc["demands"][c_idx] + demands[depot_start, s_idx] = 0 + demands[depot_end, s_idx] = 0 + + probs = [sc["probability"] for sc in scenarios] + + # Create arcs: no self-loops, no arcs INTO start depot, no arcs OUT OF end depot, + # no arc from start depot directly to end depot (would be empty route - not needed + # since all customers must be visited) + arcs = [] + for i in V: + for j in V: + if i == j: + continue + if j == depot_start: + continue + if i == depot_end: + continue + # Allow depot_start -> depot_end only if there could be empty routes, + # but since each customer must be visited exactly once, skip it + if i == depot_start and j == depot_end: + continue + arcs.append((i, j)) + + # ---- Build Gurobi Model ---- + model = gp.Model("TWAVRP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 1) + + # Decision Variables + + # z[i,j,omega]: binary, 1 if arc (i,j) used in scenario omega + z = {} + for omega in range(num_scenarios): + for (i, j) in arcs: + z[i, j, omega] = model.addVar(vtype=GRB.BINARY, name=f"z_{i}_{j}_{omega}") + + # t[v, omega]: continuous service/arrival time at node v in scenario omega + t_var = {} + for omega in range(num_scenarios): + for v in V: + t_var[v, omega] = model.addVar( + lb=tw[v][0], ub=tw[v][1], + vtype=GRB.CONTINUOUS, name=f"t_{v}_{omega}") + + # y[v]: start of endogenous time window (first-stage decision) + y = {} + for v in V_prime: + y[v] = model.addVar( + lb=tw[v][0], ub=tw[v][1] - w[v], + vtype=GRB.CONTINUOUS, name=f"y_{v}") + + model.update() + + # ---- Objective ---- + model.setObjective( + gp.quicksum( + probs[omega] * c_travel[i, j] * z[i, j, omega] + for omega in range(num_scenarios) + for (i, j) in arcs + ), + GRB.MINIMIZE + ) + + # ---- Constraints per scenario ---- + for omega in range(num_scenarios): + + # (2) Each customer visited exactly once: in-degree = 1 + for v in V_prime: + model.addConstr( + gp.quicksum(z[i, v, omega] for i in V if (i, v, omega) in z) == 1, + name=f"in_{v}_{omega}") + + # Flow conservation: out-degree = in-degree for customers + for v in V_prime: + model.addConstr( + gp.quicksum(z[v, j, omega] for j in V if (v, j, omega) in z) == 1, + name=f"out_{v}_{omega}") + + # Depot: vehicles leaving start = vehicles arriving at end + model.addConstr( + gp.quicksum(z[depot_start, j, omega] for j in V if (depot_start, j, omega) in z) == + gp.quicksum(z[i, depot_end, omega] for i in V if (i, depot_end, omega) in z), + name=f"depot_balance_{omega}") + + # Time precedence (MTZ-like): t[j] >= t[i] + t_ij - M*(1-z[i,j]) + # Big-M: M_ij = max(0, tw[i][1] + t_travel[i,j] - tw[j][0]) + # This is valid because: t[i] <= tw[i][1], t[j] >= tw[j][0] + # When z=0: t[j] >= t[i] + t_ij - M is trivially satisfied + for (i, j) in arcs: + if i == depot_end or j == depot_start: + continue + M_ij = max(0, tw[i][1] + t_travel[i, j] - tw[j][0]) + model.addConstr( + t_var[j, omega] >= t_var[i, omega] + t_travel[i, j] - M_ij * (1 - z[i, j, omega]), + name=f"time_{i}_{j}_{omega}") + + # Subtour elimination via single-commodity flow + # u[v, omega] = cumulative load when arriving at customer v + # u[v] >= d_v, u[v] <= Q + # u[j] >= u[i] + d[j] - Q*(1 - z[i,j]) for customer-to-customer arcs + + # MTZ-like capacity constraints + u = {} + for omega in range(num_scenarios): + for v in V_prime: + u[v, omega] = model.addVar( + lb=demands[v, omega], ub=Q, + vtype=GRB.CONTINUOUS, name=f"u_{v}_{omega}") + model.update() + + for omega in range(num_scenarios): + for (i, j) in arcs: + if i in V_prime and j in V_prime: + # u[j] >= u[i] + d[j] - Q*(1 - z[i,j]) + model.addConstr( + u[j, omega] >= u[i, omega] + demands[j, omega] - Q * (1 - z[i, j, omega]), + name=f"cap_{i}_{j}_{omega}") + elif i == depot_start and j in V_prime: + # u[j] >= d[j] (already by lb, but also from depot route start) + # u[j] <= Q * z[0,j] + Q * (1 - z[0,j]) is trivially Q + # We only need: when z[0,j]=1, u[j] = d[j] (start of route) + # Actually u[j] >= d[j] always, and the chain propagation handles the rest + pass + + # Endogenous time window constraints: linking y and t + for omega in range(num_scenarios): + for v in V_prime: + # (3) t[v,omega] >= y[v] + model.addConstr(t_var[v, omega] >= y[v], name=f"tw_lb_{v}_{omega}") + # (4) t[v,omega] <= y[v] + w[v] + model.addConstr(t_var[v, omega] <= y[v] + w[v], name=f"tw_ub_{v}_{omega}") + + # ---- Solve ---- + model.optimize() + + # ---- Extract Solution ---- + result = { + "objective_value": None, + "status": None, + "time_windows": {}, + "routes": {} + } + + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["status"] = "optimal" if model.Status == GRB.OPTIMAL else "feasible" + + # Extract time window assignments + for v in V_prime: + yv = y[v].X + result["time_windows"][str(v)] = [round(yv, 4), round(yv + w[v], 4)] + + # Extract routes per scenario + for omega in range(num_scenarios): + scenario_routes = [] + # Build adjacency from solution + next_node = {} + for (i, j) in arcs: + if z[i, j, omega].X > 0.5: + if i not in next_node: + next_node[i] = [] + next_node[i].append(j) + + # Trace routes from depot_start + if depot_start in next_node: + for first_cust in next_node[depot_start]: + route = [depot_start] + current = first_cust + visited_in_route = set() + while current != depot_end: + if current in visited_in_route: + break # safety + route.append(current) + visited_in_route.add(current) + nxt = next_node.get(current, [depot_end]) + current = nxt[0] if nxt else depot_end + route.append(depot_end) + + # Get arrival times + times = {} + for node in route: + times[str(node)] = round(t_var[node, omega].X, 4) + + route_cost = sum(c_travel[route[k], route[k+1]] + for k in range(len(route) - 1)) + + scenario_routes.append({ + "route": route, + "arrival_times": times, + "cost": round(route_cost, 4) + }) + + result["routes"][str(omega + 1)] = scenario_routes + + if model.Status == GRB.OPTIMAL: + result["optimality_gap"] = 0.0 + else: + result["optimality_gap"] = model.MIPGap + + else: + result["objective_value"] = None + result["status"] = "infeasible_or_no_solution" + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the TWAVRP using Gurobi (compact arc-flow MILP 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 to write the solution JSON file.") + parser.add_argument("--time_limit", type=int, required=True, + help="Maximum solver runtime in seconds.") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + data = load_instance(args.instance_path) + print(f"Loaded instance with {data['num_customers']} customers and " + f"{len(data['scenarios'])} scenarios.") + + result = solve_twavrp(data, args.time_limit) + + with open(args.solution_path, 'w') as f: + result["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(result, f, indent=2) + + print(f"Solution written to {args.solution_path}") + if result["objective_value"] is not None: + print(f"Objective value: {result['objective_value']:.4f}") + print(f"Status: {result['status']}") + else: + print("No feasible solution found.") + + +if __name__ == "__main__": + main() diff --git a/tasks/spliet2015/gurobi_feasi_result/large_feasi_result_1.json b/tasks/spliet2015/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/spliet2015/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/spliet2015/gurobi_feasi_result/large_feasi_result_2.json b/tasks/spliet2015/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/spliet2015/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/spliet2015/gurobi_feasi_result/large_feasi_result_3.json b/tasks/spliet2015/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/spliet2015/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/spliet2015/gurobi_feasi_result/large_feasi_result_4.json b/tasks/spliet2015/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/spliet2015/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/spliet2015/gurobi_feasi_result/large_feasi_result_5.json b/tasks/spliet2015/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/spliet2015/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/spliet2015/gurobi_feasi_result/tiny_feasi_result.json b/tasks/spliet2015/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/spliet2015/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/spliet2015/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/spliet2015/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/spliet2015/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/spliet2015/gurobi_solution/large_solution_1.json b/tasks/spliet2015/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0cfba96aea242b084a40a9c230ffd7d59392485f --- /dev/null +++ b/tasks/spliet2015/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3f7ba41998f5b8c41b4696274a078dba8ded9f97d312f5472425cbcb5253b04 +size 6938 diff --git a/tasks/spliet2015/gurobi_solution/large_solution_2.json b/tasks/spliet2015/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b313f1a2ad138568816bf8f806907041f5a83816 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f0f4d5c94c96dcdaa54729f53700a97494144de9ba5c846c8797d2375a81b43 +size 7400 diff --git a/tasks/spliet2015/gurobi_solution/large_solution_3.json b/tasks/spliet2015/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..451b485ffe339ba30b64fb95534d3f99ed034043 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77fa3114ea4e3823aa1ed60752588ba1b5329dc7948bd1965d0be443f4942d28 +size 7262 diff --git a/tasks/spliet2015/gurobi_solution/large_solution_4.json b/tasks/spliet2015/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..adf37343bf6e980c3c31f90894eec96bd37c14e6 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:055e50392ec783a2985ba8d38cc759acaaca0d5109cbb2f453384b98703e1e95 +size 7071 diff --git a/tasks/spliet2015/gurobi_solution/large_solution_5.json b/tasks/spliet2015/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..d2a8b8ebff6c6491f37758bdef139a1012a89f83 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:91579fb0713fdf605afe2ae56c5f4e1f2550b4efb40bf8ef347da9da2e7922d5 +size 7268 diff --git a/tasks/spliet2015/gurobi_solution/tiny_solution.json b/tasks/spliet2015/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..cfd292286ed85cc581ca29711c59bb4e57a2e830 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:641cda28b8fdf37d8896f18f6215a1b569a8eb1eec1f56ae4e0b7b05a0d43010 +size 2093 diff --git a/tasks/spliet2015/gurobi_solution/tiny_solution_2.json b/tasks/spliet2015/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c44b95e612a12000e7fbdf8f56d4565f0ec50f98 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20db0dc4d3b97013b06ada9238ff13bf014b79df97e409648033facdbcda64c4 +size 3093 diff --git a/tasks/spliet2015/gurobi_solution_log/large_log_1.jsonl b/tasks/spliet2015/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4fe58b7040193213b2699dddb16a10d0c99a5404 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d18b9a7d54ddf36f4a7ae321bccb9d8b4458b655cce83389cf1bd8bb9627c97 +size 1846 diff --git a/tasks/spliet2015/gurobi_solution_log/large_log_2.jsonl b/tasks/spliet2015/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..37f157ade2176ff8e13857bb41a92d3f71350475 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:119ba53731d98d379b1706d67f00fac9f5799dde34de73f16dc06cc9eaf397d1 +size 1304 diff --git a/tasks/spliet2015/gurobi_solution_log/large_log_3.jsonl b/tasks/spliet2015/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..69c515a489e94e46f80b1bcb0e2b0f49d7805385 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ea420659914aca153d7d4bf1700bf9d3782365fbf1f7157040592b8f381d4bb +size 1127 diff --git a/tasks/spliet2015/gurobi_solution_log/large_log_4.jsonl b/tasks/spliet2015/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ac3c38390083a1453804f197d8081a80b8f16791 --- /dev/null +++ b/tasks/spliet2015/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66dddeca103f77987abaa51a1eec49e15caa44bb353b54daed15a7bee705bae1 +size 1864 diff --git a/tasks/spliet2015/gurobi_solution_log/large_log_5.jsonl b/tasks/spliet2015/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8fb79639df810aeaed4d81488e20f16734cb967f --- /dev/null +++ b/tasks/spliet2015/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1fc922a5330dd69201fb5babe8bede4c84d5df9decdb7acda6b582003bbeb87 +size 1578 diff --git a/tasks/spliet2015/gurobi_solution_log/tiny_log.jsonl b/tasks/spliet2015/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..87a7dc2e91c34cd60b78d46de154fada09a15efe --- /dev/null +++ b/tasks/spliet2015/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bedcacb0c70a4864d44a63814c43014ce9374ae4c46ac0b5e0e2ae4d524da6bf +size 220 diff --git a/tasks/spliet2015/instance/large_instance_1.json b/tasks/spliet2015/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6bc9ec8cbe16f8664a1d666832a5a29937d21127 --- /dev/null +++ b/tasks/spliet2015/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2383161009de8109f6eaa7406cf1b6c20c7a0dfbd14b82ab32aef1d9f85b1609 +size 17027 diff --git a/tasks/spliet2015/instance/large_instance_2.json b/tasks/spliet2015/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..9305ecd8941965643a68c02598fec360fec823a1 --- /dev/null +++ b/tasks/spliet2015/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37102cd6476cfdf3752f34d0b24a4901721775cfaf34abf1c4d694da90002dd9 +size 15983 diff --git a/tasks/spliet2015/instance/large_instance_3.json b/tasks/spliet2015/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..202cb4445c492e5778d285e8ef08a9ca4e1cea61 --- /dev/null +++ b/tasks/spliet2015/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b8e1f2b5aa42ad58a32d81a3492a3d7e032ac85ca5959a21dade8c0043876bd +size 15985 diff --git a/tasks/spliet2015/instance/large_instance_4.json b/tasks/spliet2015/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..de9e03266c4c9ca58b0aa10c04b7ed3fbb8ff0a7 --- /dev/null +++ b/tasks/spliet2015/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85a2c7486eaf9d975bb1ce3cbc29282284341368cca1a30f74e42031bbb0e389 +size 15987 diff --git a/tasks/spliet2015/instance/large_instance_5.json b/tasks/spliet2015/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8982d2a3eaf70011f0a200c77e2862943b80549f --- /dev/null +++ b/tasks/spliet2015/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18203296b25b15926ccbd178ddc91b09cf521fc9a1e9973fe53160df8d1e0739 +size 15969 diff --git a/tasks/spliet2015/instance/tiny_instance.json b/tasks/spliet2015/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..0b7bc0bede3396b46414a1adbd1d9fa8560435fc --- /dev/null +++ b/tasks/spliet2015/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fba9c9ea17860e75598e65016a700e162b4886cbaa14df7e5dd5ab5e447f0305 +size 4181 diff --git a/tasks/spliet2015/instance/tiny_instance_2.json b/tasks/spliet2015/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4789beb97683872b8c6e1df9e43dd760c686b1f8 --- /dev/null +++ b/tasks/spliet2015/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:334361b1596ae1e1b6536b6ff30a3196c3cfdeeb057b65b25646b0f683aa887b +size 5726 diff --git a/tasks/spliet2015/instance_schema.json b/tasks/spliet2015/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..3346562de88922ea00c06e3c55c7abae892297c8 --- /dev/null +++ b/tasks/spliet2015/instance_schema.json @@ -0,0 +1,29 @@ +{ + "num_customers": " Total number of customers to be served.", + "depot": { + "id": " Identifier for the depot node in the distance matrix.", + "x": " Horizontal coordinate of the depot location.", + "y": " Vertical coordinate of the depot location.", + "exogenous_time_window": " Earliest departure and latest return time for vehicles at the depot." + }, + "vehicle_capacity": " Maximum total demand a single vehicle can carry on one route.", + "num_vehicles": " Availability of vehicles for routing ('unlimited' means no fleet size constraint).", + "endogenous_time_window_width": " Duration of the narrow delivery time window to be assigned to each customer.", + "customers": [ + { + "id": " Unique identifier for the customer, corresponding to the row/column index in the distance matrix.", + "x": " Horizontal coordinate of the customer location.", + "y": " Vertical coordinate of the customer location.", + "exogenous_time_window": " Earliest and latest times during which a delivery is permitted at this customer.", + "endogenous_time_window_width": " Duration of the narrow delivery time window to be assigned to this customer." + } + ], + "scenarios": [ + { + "scenario_id": " Unique identifier for the demand scenario.", + "probability": " Likelihood of this demand scenario occurring.", + "demands": " Quantity of goods requested by each customer under this scenario, ordered by customer id." + } + ], + "distance_matrix": " Travel cost and travel time between each pair of locations, where row/column 0 is the start depot, 1 through num_customers are customers, and num_customers+1 is the end depot." +} \ No newline at end of file diff --git a/tasks/spliet2015/mathematical_formulation.md b/tasks/spliet2015/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..ad57e76f5fb8e20aa79315c03127fa81b4bf8d30 --- /dev/null +++ b/tasks/spliet2015/mathematical_formulation.md @@ -0,0 +1,65 @@ +# Original Formulation: Time Window Assignment Vehicle Routing Problem (TWAVRP) + +*Source: The Time Window Assignment Vehicle Routing Problem, Remy Spliet, Adriana F. Gabor, 2014 (Transportation Science, Articles in Advance).* + +## Sets and Indices + +$$\begin{align*} +G = (V, A) &: \text{complete graph}. \\ +V = \{0, 1, \dots, n+1\} &: \text{set of locations; } 0 \text{ is the starting depot, } n+1 \text{ the ending depot}. \\ +V' = \{1, \dots, n\} &: \text{set of customers}. \\ +A &: \text{set of arcs of } G. \\ +\Omega &: \text{set of scenarios, each representing a realization of demand}. \\ +R(\omega) &: \text{set of all feasible routes for scenario } \omega \in \Omega. \\ +(i,j) &: \text{arc index, } (i,j) \in A. \\ +v &: \text{location/customer index.} \\ +r &: \text{route index.} \\ +\omega &: \text{scenario index.} +\end{align*}$$ + +## Parameters + +$$\begin{align*} +c_{ij} \geq 0 &: \text{travel cost along arc } (i,j) \text{ (satisfies the triangle inequality)}. \\ +t_{ij} \geq 0 &: \text{travel time along arc } (i,j) \text{ (satisfies the triangle inequality)}. \\ +Q &: \text{capacity of each vehicle (unlimited number of identical vehicles)}. \\ +p_\omega &: \text{probability that scenario } \omega \text{ occurs}. \\ +d_v^\omega &: \text{demand at location } v \text{ in scenario } \omega, \text{ with } 0 < d_v^\omega \leq Q \text{ for } v \in V', \\ + &\quad \text{ and } d_0^\omega = d_{n+1}^\omega = 0. \\ +[s_v, e_v] &: \text{exogenous time window at location } v \in V. \\ +w_v &: \text{prescribed width of the endogenous time window of customer } v \in V', \\ + &\quad \text{ assumed } s_v \leq e_v - w_v. \\ +a_r^v &: \text{number of times customer } v \in V' \text{ is visited by route } r. \\ +t_r^v &: \text{cumulative time of service of customer } v \in V' \text{ on route } r \\ + &\quad (0 \text{ if not visited; the service time if visited once; the sum if visited multiple times)}. \\ +c_r = \sum_{i=1}^{k} c_{r_i} &: \text{cost of route } r \text{ with arcs } \{r_1, \dots, r_k\}. +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x_r^\omega &\in \{0,1\} : \text{equals } 1 \text{ if route } r \text{ is used in scenario } \omega, \text{ and } 0 \text{ otherwise.} \\ +y_v &\in [s_v,\, e_v - w_v] : \text{start time of the endogenous time window assigned to customer } v \in V' \\ + &\quad \text{(assigned before demand is revealed; identical across all scenarios).} +\end{align*}$$ + +## Objective + +$$\begin{align} +\min \;\; \sum_{\omega \in \Omega} p_\omega \sum_{r \in R(\omega)} c_r\, x_r^\omega \tag{1} +\end{align}$$ + +## Constraints + +$$\begin{align} +\sum_{r \in R(\omega)} a_r^v\, x_r^\omega &= 1 + && \forall v \in V', \; \forall \omega \in \Omega, \tag{2} \\[4pt] +\sum_{r \in R(\omega)} t_r^v\, x_r^\omega &\geq y_v + && \forall v \in V', \; \forall \omega \in \Omega, \tag{3} \\[4pt] +\sum_{r \in R(\omega)} t_r^v\, x_r^\omega &\leq y_v + w_v + && \forall v \in V', \; \forall \omega \in \Omega, \tag{4} \\[4pt] +x_r^\omega &\in \{0,1\} + && \forall \omega \in \Omega, \; \forall r \in R(\omega), \tag{5} \\[4pt] +y_v &\in [s_v,\, e_v - w_v] + && \forall v \in V'. \tag{6} +\end{align}$$ diff --git a/tasks/spliet2015/problem_description.txt b/tasks/spliet2015/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..d48100c9b67c05fef8b98524d9bf1fc7a5ee88a8 --- /dev/null +++ b/tasks/spliet2015/problem_description.txt @@ -0,0 +1,13 @@ +# Problem Description + +A distribution company operates a fleet of identical vehicles, each with a known cargo capacity, to deliver goods from a central depot to a set of customers. The depot has a starting location and an ending location (vehicles depart from and return to the depot), and there are a known number of customers, each at a fixed geographic position. Travel costs and travel times between every pair of locations (including the depot endpoints and all customers) are given and satisfy the triangle inequality. + +Customer demand is uncertain at the time delivery time windows must be set. Uncertainty is represented by a finite set of demand scenarios, each with a known probability of occurrence and a specific demand quantity for every customer. Every customer's demand in every scenario is strictly positive and does not exceed the vehicle capacity. Depot demand is zero in all scenarios. + +Each customer has an exogenous time window, a broad interval during which deliveries are permitted (for example, imposed by local regulations or store operating hours). The depot also has an exogenous time window governing when vehicles may depart and return. In addition, each customer has a prescribed endogenous time window width, which is assumed not to exceed the length of that customer's exogenous time window. The company must assign to each customer an endogenous time window whose width equals this prescribed value. The start of each customer's endogenous time window may be placed anywhere such that the entire endogenous window falls within the customer's exogenous time window; that is, the start time must be no earlier than the beginning of the exogenous window and no later than the end of the exogenous window minus the endogenous width. + +The endogenous time window assignments are made before demand is revealed and are fixed across all scenarios. After demand becomes known under a particular scenario, the company must design vehicle routes for that scenario. A route is a path beginning at the starting depot, visiting a sequence of customers, and ending at the ending depot. A route is valid for a given scenario if the total demand of customers on the route does not exceed the vehicle capacity, service at every location on the route occurs within that location's exogenous time window, and for any two consecutively visited locations the service time at the second is no earlier than the service time at the first plus the travel time between them (vehicles may wait at a location if they arrive before the exogenous window opens). An unlimited number of vehicles is available. + +The company must choose two things simultaneously: the endogenous time window start time for every customer (a single assignment used across all scenarios), and for each scenario a collection of valid routes. Every customer must be visited exactly once in every scenario. In every scenario, the time at which each customer is served must fall within that customer's assigned endogenous time window; specifically, the service time must be no earlier than the endogenous window start and no later than the endogenous window start plus the endogenous width. + +The goal is to minimize the expected total travel cost, computed as the probability-weighted sum over all scenarios of the total route costs used in each scenario, where the cost of a route is the sum of the travel costs along its arcs. diff --git a/tasks/spliet2015/solution_logger.py b/tasks/spliet2015/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/spliet2015/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/spliet2015/solution_schema.json b/tasks/spliet2015/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b97c22c4583ecba1a64b1ad0423a46298424e2d6 --- /dev/null +++ b/tasks/spliet2015/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Expected total travel cost, computed as the probability-weighted sum of route costs across all demand scenarios.", + "time_windows": " Assigned narrow delivery time window for each customer as a two-element list [start, end] that is fixed across all scenarios.", + "routes": " Collection of vehicle routes used in each demand scenario; each entry contains 'route' (ordered list of node ids beginning at the start depot, visiting customers, and ending at the end depot), 'arrival_times' (service time at each visited node, keyed by node id as a string), and 'cost' (total travel cost along the route)." +} diff --git a/tasks/taninmis2022/feasibility_check.py b/tasks/taninmis2022/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d0cb72558b02808d5873849dfa0ae5a537e0fd4b --- /dev/null +++ b/tasks/taninmis2022/feasibility_check.py @@ -0,0 +1,1431 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the MM-SMIP Power System Capacity Expansion model. + +Checks all hard constraints from the mathematical formulation (Taninmis et al., 2022): + Upper-level: (1b)-(1g) -> Constraints 1-6 + Lower-level: (2b)-(2o) -> Constraints 7-20 + Objective consistency -> Constraint 21 (exact recomputation from a full + operating witness, or trusted fixed-investment recourse when the public + solution contains first-stage decisions only) + +Usage: + python feasibility_check.py \ + --instance_path instance_1.json \ + --solution_path efficient_solution_1.json \ + --result_path efficient_feasi_result_1.json +""" + +import argparse +import json +import math +from pathlib import Path + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('alpha', 'f_bwd', 'f_fwd', 'gamma', 'investments', 'objective_value', 'p_gen', 'r_stor', 's_res', 'u_stor', 'v_stor') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = ('investments',) +_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 safe_float(val): + """Convert to float, replacing inf/nan with large finite values for JSON compatibility.""" + v = float(val) + if math.isinf(v): + return 1e30 if v > 0 else -1e30 + if math.isnan(v): + return 0.0 + return v + + +def record_violation(violations_list, magnitudes_list, constraint_idx, message, lhs, rhs, raw_excess): + """Record a single constraint violation.""" + normalizer = max(abs(rhs), EPS) + ratio = raw_excess / normalizer if not math.isinf(raw_excess) else 1e30 + violations_list.append((constraint_idx, message)) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": safe_float(lhs), + "rhs": safe_float(rhs), + "raw_excess": safe_float(raw_excess), + "normalizer": safe_float(normalizer), + "ratio": safe_float(ratio), + }) + + +def _effective_tol(lhs, rhs): + """Tolerance that accommodates solver numerical noise. Combines an + absolute floor (1e-4, looser than the prior 1e-5 which rejected + gurobi MIPGap-level dust) with a relative-magnitude floor for cases + where the constraint operates on values much larger than 1.""" + ABS_TOL = 1e-4 + REL_TOL = 1e-4 # 0.01% relative slack + return max(ABS_TOL, REL_TOL * max(abs(lhs), abs(rhs))) + + +def check_le(lhs, rhs): + """Check lhs <= rhs. Returns (violated, raw_excess).""" + excess = lhs - rhs + return excess > _effective_tol(lhs, rhs), max(excess, 0.0) + + +def check_ge(lhs, rhs): + """Check lhs >= rhs. Returns (violated, raw_excess).""" + excess = rhs - lhs + return excess > _effective_tol(lhs, rhs), max(excess, 0.0) + + +def check_eq(lhs, rhs): + """Check lhs == rhs. Returns (violated, raw_excess).""" + excess = abs(lhs - rhs) + return excess > _effective_tol(lhs, rhs), excess + + +def build_ancestor_path(node_by_id, nid): + """Build path from root to node nid.""" + path = [] + cur = nid + while cur is not None: + path.append(cur) + cur = node_by_id[cur]["parent_id"] + path.reverse() + return path + + +def build_demand_growth(tree, sp): + """Compute demand growth factor for each node.""" + node_by_id = {n["id"]: n for n in tree} + dg_high = 1.0 + sp["demand_growth_high_percent"] + dg_low = 1.0 + sp["demand_growth_low_percent"] + demand_growth = {} + demand_growth[tree[0]["id"]] = 1.0 # root + + for n in tree: + nid = n["id"] + children = n["children"] + if len(children) >= 2: + demand_growth[children[0]] = demand_growth[nid] * dg_high + demand_growth[children[1]] = demand_growth[nid] * dg_low + elif len(children) == 1: + demand_growth[children[0]] = demand_growth[nid] * dg_high + + return demand_growth + + +def build_cost_mult(tree, sp): + """Cumulative investment-cost multiplier along each node's path. + + Mirrors gurobi_code.py's build_scenario_tree_info: first child increases + cost by cost_variation_percent, second child decreases it. Root = 1.0. + """ + cost_var = sp["cost_variation_percent"] + cost_mult = {tree[0]["id"]: 1.0} + for n in tree: + nid = n["id"] + children = n["children"] + if len(children) >= 2: + cost_mult[children[0]] = cost_mult[nid] * (1.0 + cost_var) + cost_mult[children[1]] = cost_mult[nid] * (1.0 - cost_var) + elif len(children) == 1: + cost_mult[children[0]] = cost_mult[nid] * (1.0 + cost_var) + return cost_mult + + +def get_effective_pmax(gen, day_data, ll_scen, hour_h): + """Effective Pmax for a generator considering renewable profiles.""" + pmax = gen["Pmax_MW"] + gtype = gen["type"] + if gtype == "solar": + return pmax * day_data["solar_profile"][hour_h] * ll_scen["solar_multipliers"][hour_h] + elif gtype == "wind": + return pmax * ll_scen["wind_power_factors"][hour_h] + return pmax + + +def _complete_investment_witness(instance, solution): + """Validate and normalize the dense node/asset build-decision witness.""" + investments = solution.get("investments") + if not isinstance(investments, dict): + raise ValueError("investments must be a JSON object") + system = instance["system"] + expected_nodes = {str(node["id"]) for node in instance["scenario_tree"]} + if set(investments) != expected_nodes: + raise ValueError("investments must exactly cover every scenario-tree node") + + family_assets = { + "generators": [g for g in system["generators"] if not g["existing"]], + "lines": [line for line in system["transmission_lines"] if not line["existing"]], + "storage": [unit for unit in system["storage"] if not unit["existing"]], + } + normalized = {} + for node_key in sorted(expected_nodes): + node_entry = investments[node_key] + if not isinstance(node_entry, dict): + raise ValueError(f"investment node {node_key} must be an object") + if set(node_entry) != set(family_assets): + raise ValueError( + f"investment node {node_key} must contain generators, lines, storage" + ) + normalized[node_key] = {} + for family, assets in family_assets.items(): + decisions = node_entry[family] + if not isinstance(decisions, dict): + raise ValueError(f"{node_key}.{family} must be an object") + expected_ids = {str(asset["id"]) for asset in assets} + if set(decisions) != expected_ids: + raise ValueError( + f"{node_key}.{family} must exactly cover all candidate IDs" + ) + normalized[node_key][family] = {} + for asset_id, raw_value in decisions.items(): + if isinstance(raw_value, bool) or not isinstance(raw_value, (int, float)): + raise ValueError(f"{node_key}.{family}.{asset_id} must be binary") + value = float(raw_value) + if not math.isfinite(value) or abs(value - round(value)) > TOL or round(value) not in (0, 1): + raise ValueError(f"{node_key}.{family}.{asset_id} must be binary") + normalized[node_key][family][asset_id] = int(round(value)) + return normalized + + +def _recompute_full_witness_objective(instance, solution): + """Recompute the current benchmark's secant-linearized objective exactly.""" + normalized = _complete_investment_witness(instance, solution) + alpha = solution.get("alpha") + gamma = solution.get("gamma") + generation = solution.get("p_gen", solution.get("p")) + if not all(isinstance(values, dict) for values in (alpha, gamma, generation)): + raise ValueError("full operational objective needs alpha, gamma, and p_gen") + + system = instance["system"] + generators = system["generators"] + candidate_gens = [g for g in generators if not g["existing"]] + candidate_lines = [line for line in system["transmission_lines"] if not line["existing"]] + candidate_storage = [unit for unit in system["storage"] if not unit["existing"]] + tree = instance["scenario_tree"] + sp = instance["scenario_parameters"] + cost_mult = build_cost_mult(tree, sp) + + objective = 0.0 + for node in tree: + node_id = node["id"] + node_key = str(node_id) + probability = float(node["probability"]) + multiplier = cost_mult[node_id] + for generator in candidate_gens: + value = normalized[node_key]["generators"][str(generator["id"])] + objective += ( + probability * multiplier * generator["capital_cost_per_kW"] + * generator["Pmax_MW"] * 1000.0 * value + ) + for line in candidate_lines: + value = normalized[node_key]["lines"][str(line["id"])] + objective += ( + probability * multiplier * line["capital_cost_per_kW"] + * line["flow_limit_MW"] * 1000.0 * value + ) + for unit in candidate_storage: + value = normalized[node_key]["storage"][str(unit["id"])] + objective += ( + probability * multiplier * unit["capital_cost_per_kW"] + * unit["capacity_MW"] * 1000.0 * value + ) + + day_ids = [day["id"] for day in instance["representative_days"]] + scenario_count = sp["num_lower_level_scenarios_per_day"] + hours = range(sp["hours_per_day"]) + expected_count = len(tree) * len(day_ids) * scenario_count * len(hours) * len(generators) + if len(alpha) != expected_count or len(gamma) != expected_count or len(generation) != expected_count: + raise ValueError("operational objective fields do not have exact dense key coverage") + + for node in tree: + node_id = node["id"] + weight = float(node["probability"]) / (len(day_ids) * scenario_count) + for day_id in day_ids: + for scenario in range(scenario_count): + for hour in hours: + for generator in generators: + generator_id = generator["id"] + key = f"{node_id},{day_id},{scenario},{hour},{generator_id}" + a_value = float(alpha[key]) + start_value = float(gamma[key]) + power_value = float(generation[key]) + if not all(math.isfinite(v) for v in (a_value, start_value, power_value)): + raise ValueError(f"non-finite operational value at {key}") + marginal = ( + generator["b_cost"] + + generator["c_cost"] * generator["Pmax_MW"] + ) + objective += weight * ( + generator["startup_cost"] * start_value + + generator["a_cost"] * a_value + + marginal * power_value + ) + return objective + + +def check_feasibility(instance, solution): + """Check all hard constraints. Returns (feasible, violated_constraints, violations, violation_magnitudes).""" + + violations_list = [] # list of (constraint_idx, message) + magnitudes_list = [] # list of magnitude dicts + + # ------------------------------------------------------------------------- + # Extract instance data + # ------------------------------------------------------------------------- + system = instance["system"] + sp = instance["scenario_parameters"] + gp_params = instance["global_parameters"] + tree = instance["scenario_tree"] + rep_days = instance["representative_days"] + ll_scenarios = instance["lower_level_scenarios"] + + generators = system["generators"] + lines = system["transmission_lines"] + storage_units = system["storage"] + loads = system["loads"] + buses = system["buses"] + + node_by_id = {n["id"]: n for n in tree} + node_ids = [n["id"] for n in tree] + + existing_gens = [g for g in generators if g["existing"]] + candidate_gens = [g for g in generators if not g["existing"]] + candidate_lines = [l for l in lines if not l["existing"]] + candidate_storage = [s for s in storage_units if not s["existing"]] + + num_hours = sp["hours_per_day"] + num_rep_days = sp["num_representative_days"] + num_ll_scenarios = sp["num_lower_level_scenarios_per_day"] + + RM = gp_params["reserve_margin_requirement"] + SR_pct = gp_params["spinning_reserve_percent"] + derating = gp_params["derating_factors"] + + load_by_bus = {} + for ld in loads: + load_by_bus[ld["bus"]] = load_by_bus.get(ld["bus"], 0.0) + ld["annual_peak_load_MW"] + + day_by_id = {d["id"]: d for d in rep_days} + day_ids = [d["id"] for d in rep_days] + hours = list(range(num_hours)) + ll_scen_ids = list(range(num_ll_scenarios)) + + demand_growth = build_demand_growth(tree, sp) + + # Generator/storage/line lookups + gen_by_id = {g["id"]: g for g in generators} + line_by_id = {l["id"]: l for l in lines} + stor_by_id = {s["id"]: s for s in storage_units} + + gens_at_bus = {b: [g for g in generators if g["bus"] == b] for b in buses} + storage_at_bus = {b: [s for s in storage_units if s["bus"] == b] for b in buses} + + # ------------------------------------------------------------------------- + # Extract solution variables + # ------------------------------------------------------------------------- + investments = solution.get("investments", None) + + # Check if solution has any variable data at all + has_investments = investments is not None and len(investments) > 0 + + # Check for operational variables + alpha_sol = solution.get("alpha", None) + gamma_sol = solution.get("gamma", None) + p_sol = solution.get("p_gen", solution.get("p", None)) + s_sol = solution.get("s_res", solution.get("s", None)) + f_fwd_sol = solution.get("f_fwd", None) + f_bwd_sol = solution.get("f_bwd", None) + f_sol = solution.get("f", None) # alternative flow format + u_sol = solution.get("u_stor", solution.get("u", None)) + v_sol = solution.get("v_stor", solution.get("v", None)) + r_sol = solution.get("r_stor", solution.get("r", None)) + + has_operational = all(x is not None for x in [alpha_sol, p_sol]) + + # If solution has no variable data at all, there is nothing to check. + # Return feasible=None to indicate "no solution available" rather than + # a genuine feasibility failure. + if not has_investments and not has_operational: + status = solution.get("status", None) + obj = solution.get("objective_value", None) + if status and ("infeasible" in str(status).lower() or str(status) == "gurobi_status_4"): + reason = "Solver reported infeasible/unbounded status; no decision variables available." + elif obj is None and not has_investments: + reason = "Solution contains no decision variables and null objective; cannot verify feasibility." + else: + reason = "Solution contains only an objective value but no decision variable values; cannot verify any constraint." + + return None, [], [reason], [] + + + # ------------------------------------------------------------------------- + # Build kappa (cumulative capacity) from investment decisions + # ------------------------------------------------------------------------- + # x_gen[n][gid], x_line[n][lid], x_stor[n][sid] = 0 or 1 + x_gen = {} + x_line = {} + x_stor = {} + kappa_gen = {} + kappa_line = {} + kappa_stor = {} + + if has_investments: + for n in node_ids: + nstr = str(n) + node_inv = investments.get(nstr, investments.get(n, {})) + x_gen[n] = {} + x_line[n] = {} + x_stor[n] = {} + + gen_inv = node_inv.get("generators", {}) + for g in candidate_gens: + gid = g["id"] + x_gen[n][gid] = gen_inv.get(gid, 0) + + line_inv = node_inv.get("lines", {}) + for l in candidate_lines: + lid = l["id"] + x_line[n][lid] = line_inv.get(lid, 0) + + stor_inv = node_inv.get("storage", {}) + for s in candidate_storage: + sid = s["id"] + x_stor[n][sid] = stor_inv.get(sid, 0) + + # Compute kappa from x using constraints (1b)-(1d) + for n in node_ids: + node = node_by_id[n] + parent_id = node["parent_id"] + kappa_gen[n] = {} + kappa_line[n] = {} + kappa_stor[n] = {} + + for g in candidate_gens: + gid = g["id"] + if parent_id is None: + kappa_gen[n][gid] = x_gen[n].get(gid, 0) + else: + kappa_gen[n][gid] = kappa_gen[parent_id].get(gid, 0) + x_gen[n].get(gid, 0) + + for l in candidate_lines: + lid = l["id"] + if parent_id is None: + kappa_line[n][lid] = x_line[n].get(lid, 0) + else: + kappa_line[n][lid] = kappa_line[parent_id].get(lid, 0) + x_line[n].get(lid, 0) + + for s in candidate_storage: + sid = s["id"] + if parent_id is None: + kappa_stor[n][sid] = x_stor[n].get(sid, 0) + else: + kappa_stor[n][sid] = kappa_stor[parent_id].get(sid, 0) + x_stor[n].get(sid, 0) + + # ------------------------------------------------------------------------- + # Sanity check: trivial all-zero candidate investments + missing operational + # data + suspiciously low objective. Reserve-margin (1f) alone can pass if + # existing capacity already covers (1+RM)*peak_demand, so the upper-level + # checks would otherwise mark such a claim feasible. Refuse it because the + # operational cost (running existing generators against demand for every + # hour of every scenario) is implicit in the objective and cannot + # legitimately be near zero unless demand itself is zero. + if has_investments and not has_operational: + all_zero = True + for n in node_ids: + for g in candidate_gens: + if x_gen[n].get(g["id"], 0): + all_zero = False + break + if not all_zero: + break + for l in candidate_lines: + if x_line[n].get(l["id"], 0): + all_zero = False + break + if not all_zero: + break + for s in candidate_storage: + if x_stor[n].get(s["id"], 0): + all_zero = False + break + if not all_zero: + break + + if all_zero: + obj = solution.get("objective_value", None) + try: + obj_val = float(obj) if obj is not None else None + except (TypeError, ValueError): + obj_val = None + min_var_cost = min( + (g.get("variable_cost_per_MWh", 0.0) for g in existing_gens + if g.get("variable_cost_per_MWh", 0.0) > 0), + default=0.0, + ) + total_demand_MW = sum(load_by_bus.get(b, 0.0) for b in buses) + total_hours = (num_hours * num_rep_days * num_ll_scenarios + * len(node_ids)) + cost_lb = min_var_cost * total_demand_MW * total_hours * 0.01 + if obj_val is not None and cost_lb > 0 and obj_val < cost_lb: + msg = ( + f"Trivial all-zero candidate investment with objective={obj_val} " + f"below 1% of implicit operational cost lower bound={cost_lb:.0f} " + f"(min_var_cost={min_var_cost}/MWh × demand={total_demand_MW}MW " + f"× hours={total_hours}); operational decisions not provided so " + f"feasibility cannot be verified at the lower level." + ) + violations_list.append((-1, msg)) + magnitudes_list.append({ + "constraint": -1, "lhs": obj_val, "rhs": cost_lb, + "raw_excess": cost_lb - obj_val, + "normalizer": max(cost_lb, EPS), + "ratio": (cost_lb - obj_val) / max(cost_lb, EPS), + }) + + # ========================================================================= + # CONSTRAINT CHECKS - UPPER LEVEL + # ========================================================================= + + if has_investments: + # --- Constraint 1: (1b) kappa^n_g = kappa^{p(n)}_g + a_g * x^n_g --- + # This is an equality constraint. kappa is derived from x, so if we + # derived kappa ourselves it will always hold. But if the solution + # provides kappa directly, we should verify. Since the solution only + # provides x (investments), and we compute kappa from x, constraint 1 + # is automatically satisfied by construction. We still include the + # check for completeness with the solution-provided kappa if available. + sol_kappa_gen = solution.get("kappa_gen", None) + if sol_kappa_gen is not None: + for n in node_ids: + node = node_by_id[n] + parent_id = node["parent_id"] + for g in candidate_gens: + gid = g["id"] + a_g = g["Pmax_MW"] + nstr = str(n) + sol_k = sol_kappa_gen.get(nstr, {}).get(gid, None) + if sol_k is not None: + parent_k = 0.0 + if parent_id is not None: + pstr = str(parent_id) + parent_k = sol_kappa_gen.get(pstr, {}).get(gid, 0.0) + expected = parent_k + a_g * x_gen[n].get(gid, 0) + violated, excess = check_eq(sol_k, expected) + if violated: + record_violation(violations_list, magnitudes_list, 1, + f"(1b) Capacity tracking violated for generator {gid} at node {n}: " + f"kappa={sol_k}, expected={expected}", + sol_k, expected, excess) + + # --- Constraint 2: (1c) kappa^n_l = kappa^{p(n)}_l + a_l * x^n_l --- + # Same logic as above - satisfied by construction from x. + + # --- Constraint 3: (1d) kappa^n_s = kappa^{p(n)}_s + a_s * x^n_s --- + # Same logic - satisfied by construction from x. + + # --- Constraint 4: (1e) kappa^n_g <= a_g, kappa^n_l <= a_l, kappa^n_s <= a_s --- + # Since kappa is normalized (bounded by 1 in gurobi code, a_g cancels), + # check cumulative build <= 1 (at most once). + for n in node_ids: + for g in candidate_gens: + gid = g["id"] + k_val = kappa_gen[n].get(gid, 0) + # kappa / a_g <= 1, or equivalently kappa <= a_g + # In our representation, kappa counts builds (0 or 1 each), so kappa <= 1 + violated, excess = check_le(k_val, 1.0) + if violated: + record_violation(violations_list, magnitudes_list, 4, + f"(1e) Capacity upper bound violated for generator {gid} at node {n}: " + f"cumulative builds={k_val} > 1", + k_val, 1.0, excess) + + for l in candidate_lines: + lid = l["id"] + k_val = kappa_line[n].get(lid, 0) + violated, excess = check_le(k_val, 1.0) + if violated: + record_violation(violations_list, magnitudes_list, 4, + f"(1e) Capacity upper bound violated for line {lid} at node {n}: " + f"cumulative builds={k_val} > 1", + k_val, 1.0, excess) + + for s in candidate_storage: + sid = s["id"] + k_val = kappa_stor[n].get(sid, 0) + violated, excess = check_le(k_val, 1.0) + if violated: + record_violation(violations_list, magnitudes_list, 4, + f"(1e) Capacity upper bound violated for storage {sid} at node {n}: " + f"cumulative builds={k_val} > 1", + k_val, 1.0, excess) + + # --- Constraint 5: (1f) Reserve margin --- + # sum_{j:J_hat(j)=j_hat} (sum_{g in G_j} DF_g*a_g + sum_{g in G'_j} DF_g*kappa^n_g*a_g) + # >= (1 + RM) * PK^n_{j_hat} + # Single region (all buses), PK = sum of peak loads * demand_growth + for n in node_ids: + total_peak = sum(load_by_bus.get(b, 0.0) for b in buses) * demand_growth[n] + rhs = (1.0 + RM) * total_peak + + # Derated existing capacity + lhs = sum(derating.get(g["type"], 1.0) * g["Pmax_MW"] for g in existing_gens) + # Derated candidate capacity + for g in candidate_gens: + gid = g["id"] + df = derating.get(g["type"], 1.0) + k_val = kappa_gen[n].get(gid, 0) + lhs += df * g["Pmax_MW"] * k_val + + violated, excess = check_ge(lhs, rhs) + if violated: + record_violation(violations_list, magnitudes_list, 5, + f"(1f) Reserve margin violated at node {n}: " + f"derated capacity={lhs:.2f} MW < required={(rhs):.2f} MW", + lhs, rhs, excess) + + # --- Constraint 6: (1g) Binary and non-negativity --- + for n in node_ids: + for g in candidate_gens: + gid = g["id"] + xv = x_gen[n].get(gid, 0) + if not (xv == 0 or xv == 1 or abs(xv) < TOL or abs(xv - 1) < TOL): + excess = min(abs(xv), abs(xv - 1)) + record_violation(violations_list, magnitudes_list, 6, + f"(1g) Binary violated for x_gen[{n}][{gid}]={xv}", + xv, round(xv), excess) + kv = kappa_gen[n].get(gid, 0) + if kv < -TOL: + record_violation(violations_list, magnitudes_list, 6, + f"(1g) Non-negativity violated for kappa_gen[{n}][{gid}]={kv}", + kv, 0.0, abs(kv)) + + for l in candidate_lines: + lid = l["id"] + xv = x_line[n].get(lid, 0) + if not (xv == 0 or xv == 1 or abs(xv) < TOL or abs(xv - 1) < TOL): + excess = min(abs(xv), abs(xv - 1)) + record_violation(violations_list, magnitudes_list, 6, + f"(1g) Binary violated for x_line[{n}][{lid}]={xv}", + xv, round(xv), excess) + + for s in candidate_storage: + sid = s["id"] + xv = x_stor[n].get(sid, 0) + if not (xv == 0 or xv == 1 or abs(xv) < TOL or abs(xv - 1) < TOL): + excess = min(abs(xv), abs(xv - 1)) + record_violation(violations_list, magnitudes_list, 6, + f"(1g) Binary violated for x_stor[{n}][{sid}]={xv}", + xv, round(xv), excess) + + # ========================================================================= + # CONSTRAINT CHECKS - LOWER LEVEL + # ========================================================================= + + if has_operational: + for n in node_ids: + for k in day_ids: + day_data = day_by_id[k] + load_profile = day_data["load_profile"] + ll_scens = ll_scenarios[str(k)] + + for pidx in ll_scen_ids: + scen = ll_scens[pidx] + demand_mult = scen["demand_multipliers"] + + for h in hours: + growth = demand_growth[n] + + for g in generators: + gid = g["id"] + is_candidate = not g["existing"] + key = f"{n},{k},{pidx},{h},{gid}" + + a_val = float(alpha_sol.get(key, 0.0)) + g_val = float(gamma_sol.get(key, 0.0)) if gamma_sol else 0.0 + p_val = float(p_sol.get(key, 0.0)) if p_sol else 0.0 + s_val = float(s_sol.get(key, 0.0)) if s_sol else 0.0 + + eff_pmax = get_effective_pmax(g, day_data, scen, h) + + # --- Constraint 7: (2b) alpha <= kappa/a for candidates --- + if is_candidate and has_investments: + k_frac = kappa_gen[n].get(gid, 0) + violated, excess = check_le(a_val, k_frac) + if violated: + record_violation(violations_list, magnitudes_list, 7, + f"(2b) Commitment exceeds capacity for {gid} at n={n},k={k},p={pidx},h={h}: " + f"alpha={a_val} > kappa_frac={k_frac}", + a_val, k_frac, excess) + + # --- Constraint 9: (2d) gamma >= alpha_h - alpha_{h-1} --- + if h >= 1: + prev_key = f"{n},{k},{pidx},{h-1},{gid}" + a_prev = float(alpha_sol.get(prev_key, 0.0)) + rhs_val = a_val - a_prev + violated, excess = check_ge(g_val, rhs_val) + if violated: + record_violation(violations_list, magnitudes_list, 9, + f"(2d) Startup indicator violated for {gid} at n={n},k={k},p={pidx},h={h}: " + f"gamma={g_val} < alpha_h - alpha_h-1={rhs_val}", + g_val, rhs_val, excess) + else: + # h=0: alpha_{-1} = 0 + violated, excess = check_ge(g_val, a_val) + if violated: + record_violation(violations_list, magnitudes_list, 9, + f"(2d) Startup indicator violated for {gid} at n={n},k={k},p={pidx},h=0: " + f"gamma={g_val} < alpha={a_val}", + g_val, a_val, excess) + + # --- Constraint 10: (2e) p + s <= Pmax*alpha or kappa --- + if is_candidate and has_investments: + k_frac = kappa_gen[n].get(gid, 0) + cap = k_frac * g["Pmax_MW"] + # For renewables, also limited by eff_pmax * alpha + if g["type"] in ("solar", "wind"): + cap = min(cap, eff_pmax * a_val) + else: + cap = eff_pmax * a_val + else: + cap = eff_pmax * a_val + + lhs_val = p_val + s_val + violated, excess = check_le(lhs_val, cap) + if violated: + record_violation(violations_list, magnitudes_list, 10, + f"(2e) Max output violated for {gid} at n={n},k={k},p={pidx},h={h}: " + f"p+s={lhs_val:.4f} > cap={cap:.4f}", + lhs_val, cap, excess) + + # --- Constraint 11: (2f) Pmin*alpha <= p --- + pmin_val = g["Pmin_MW"] + lhs_val = pmin_val * a_val + violated, excess = check_le(lhs_val, p_val) + if violated: + record_violation(violations_list, magnitudes_list, 11, + f"(2f) Min output violated for {gid} at n={n},k={k},p={pidx},h={h}: " + f"Pmin*alpha={lhs_val:.4f} > p={p_val:.4f}", + lhs_val, p_val, excess) + + # --- Constraint 13: (2h) Ramp limits --- + if h >= 1: + prev_key = f"{n},{k},{pidx},{h-1},{gid}" + p_prev = float(p_sol.get(prev_key, 0.0)) + ramp = g["ramp_MW_per_h"] + # Ramp up: p_h - p_{h-1} <= RU + ru_lhs = p_val - p_prev + violated, excess = check_le(ru_lhs, ramp) + if violated: + record_violation(violations_list, magnitudes_list, 13, + f"(2h) Ramp-up violated for {gid} at n={n},k={k},p={pidx},h={h}: " + f"p_h-p_h-1={ru_lhs:.4f} > RU={ramp}", + ru_lhs, ramp, excess) + # Ramp down: p_{h-1} - p_h <= RD + rd_lhs = p_prev - p_val + violated, excess = check_le(rd_lhs, ramp) + if violated: + record_violation(violations_list, magnitudes_list, 13, + f"(2h) Ramp-down violated for {gid} at n={n},k={k},p={pidx},h={h}: " + f"p_h-1-p_h={rd_lhs:.4f} > RD={ramp}", + rd_lhs, ramp, excess) + + # --- Constraint 8: (2c) Min up/down time --- + for g in generators: + gid = g["id"] + min_on = g["min_on_h"] + min_off = g["min_off_h"] + + if h >= 1: + key_h = f"{n},{k},{pidx},{h},{gid}" + key_hm1 = f"{n},{k},{pidx},{h-1},{gid}" + a_h = float(alpha_sol.get(key_h, 0.0)) + a_hm1 = float(alpha_sol.get(key_hm1, 0.0)) + startup = a_h - a_hm1 # positive if started + + # Min up time: if started at h, must stay on for min_on hours + if min_on > 0 and startup > TOL: + for tau in range(h, min(h + min_on, num_hours)): + key_tau = f"{n},{k},{pidx},{tau},{gid}" + a_tau = float(alpha_sol.get(key_tau, 0.0)) + # alpha_tau >= alpha_h - alpha_{h-1} + violated, excess = check_ge(a_tau, startup) + if violated: + record_violation(violations_list, magnitudes_list, 8, + f"(2c) Min up-time violated for {gid} at n={n},k={k},p={pidx}: " + f"started at h={h}, alpha[{tau}]={a_tau:.4f} < startup_diff={startup:.4f}", + a_tau, startup, excess) + + # Min down time: if shut down at h, must stay off for min_off hours + shutdown = a_hm1 - a_h # positive if shut down + if min_off > 0 and shutdown > TOL: + for tau in range(h, min(h + min_off, num_hours)): + key_tau = f"{n},{k},{pidx},{tau},{gid}" + a_tau = float(alpha_sol.get(key_tau, 0.0)) + # 1 - alpha_tau >= shutdown + lhs_val = 1.0 - a_tau + violated, excess = check_ge(lhs_val, shutdown) + if violated: + record_violation(violations_list, magnitudes_list, 8, + f"(2c) Min down-time violated for {gid} at n={n},k={k},p={pidx}: " + f"shutdown at h={h}, 1-alpha[{tau}]={lhs_val:.4f} < shutdown_diff={shutdown:.4f}", + lhs_val, shutdown, excess) + + # --- Constraint 12: (2g) Spinning reserve --- + for b in buses: + demand_b = load_by_bus.get(b, 0.0) * growth * load_profile[h] * demand_mult[h] + sr_req = SR_pct * demand_b + + sr_total = 0.0 + for g in gens_at_bus[b]: + key = f"{n},{k},{pidx},{h},{g['id']}" + sr_total += float(s_sol.get(key, 0.0)) if s_sol else 0.0 + + violated, excess = check_ge(sr_total, sr_req) + if violated: + record_violation(violations_list, magnitudes_list, 12, + f"(2g) Spinning reserve violated at bus {b}, n={n},k={k},p={pidx},h={h}: " + f"reserve={sr_total:.4f} < required={sr_req:.4f}", + sr_total, sr_req, excess) + + # --- Constraint 14: (2i) Storage dynamics --- + for s in storage_units: + sid = s["id"] + eff = s["efficiency"] + key = f"{n},{k},{pidx},{h},{sid}" + r_val = float(r_sol.get(key, 0.0)) if r_sol else 0.0 + u_val = float(u_sol.get(key, 0.0)) if u_sol else 0.0 + v_val = float(v_sol.get(key, 0.0)) if v_sol else 0.0 + + if h == 0: + # r^1 = 0 + violated, excess = check_eq(r_val, 0.0) + if violated: + record_violation(violations_list, magnitudes_list, 14, + f"(2i) Initial storage violated for {sid} at n={n},k={k},p={pidx}: " + f"r[0]={r_val} != 0", + r_val, 0.0, excess) + else: + prev_key = f"{n},{k},{pidx},{h-1},{sid}" + r_prev = float(r_sol.get(prev_key, 0.0)) if r_sol else 0.0 + v_prev = float(v_sol.get(prev_key, 0.0)) if v_sol else 0.0 + u_prev = float(u_sol.get(prev_key, 0.0)) if u_sol else 0.0 + expected = r_prev + eff * v_prev - u_prev + violated, excess = check_eq(r_val, expected) + if violated: + record_violation(violations_list, magnitudes_list, 14, + f"(2i) Storage dynamics violated for {sid} at n={n},k={k},p={pidx},h={h}: " + f"r={r_val:.4f} != expected={expected:.4f}", + r_val, expected, excess) + + # --- Constraint 15: (2j) u <= r --- + for s in storage_units: + sid = s["id"] + key = f"{n},{k},{pidx},{h},{sid}" + r_val = float(r_sol.get(key, 0.0)) if r_sol else 0.0 + u_val = float(u_sol.get(key, 0.0)) if u_sol else 0.0 + violated, excess = check_le(u_val, r_val) + if violated: + record_violation(violations_list, magnitudes_list, 15, + f"(2j) Withdrawal exceeds stored energy for {sid} at n={n},k={k},p={pidx},h={h}: " + f"u={u_val:.4f} > r={r_val:.4f}", + u_val, r_val, excess) + + # --- Constraint 16: (2k) r <= kappa_s (candidate storage) --- + if has_investments: + for s in candidate_storage: + sid = s["id"] + key = f"{n},{k},{pidx},{h},{sid}" + r_val = float(r_sol.get(key, 0.0)) if r_sol else 0.0 + cap = s["capacity_MW"] * kappa_stor[n].get(sid, 0) + violated, excess = check_le(r_val, cap) + if violated: + record_violation(violations_list, magnitudes_list, 16, + f"(2k) Storage capacity violated for {sid} at n={n},k={k},p={pidx},h={h}: " + f"r={r_val:.4f} > cap={cap:.4f}", + r_val, cap, excess) + + # --- Constraint 17: (2l) Power balance --- + for b in buses: + demand_b = load_by_bus.get(b, 0.0) * growth * load_profile[h] * demand_mult[h] + + # Generation + gen_sum = 0.0 + for g in gens_at_bus[b]: + key = f"{n},{k},{pidx},{h},{g['id']}" + gen_sum += float(p_sol.get(key, 0.0)) + + # Storage: u - v + stor_sum = 0.0 + for s in storage_at_bus[b]: + sid = s["id"] + key = f"{n},{k},{pidx},{h},{sid}" + u_val = float(u_sol.get(key, 0.0)) if u_sol else 0.0 + v_val = float(v_sol.get(key, 0.0)) if v_sol else 0.0 + stor_sum += u_val - v_val + + # Flow: need to handle both f_fwd/f_bwd and generic f formats + flow_sum = 0.0 + for l in lines: + lid = l["id"] + loss = l["loss_factor"] + fkey = f"{n},{k},{pidx},{h},{lid}" + + if f_fwd_sol is not None and f_bwd_sol is not None: + fwd = float(f_fwd_sol.get(fkey, 0.0)) + bwd = float(f_bwd_sol.get(fkey, 0.0)) + if l["to_bus"] == b: + flow_sum += (1.0 - loss) * fwd - bwd + elif l["from_bus"] == b: + flow_sum += (1.0 - loss) * bwd - fwd + elif f_sol is not None: + # Signed flow: positive = from_bus -> to_bus + f_val = float(f_sol.get(fkey, 0.0)) + if l["to_bus"] == b: + flow_sum += (1.0 - loss) * f_val + elif l["from_bus"] == b: + flow_sum -= f_val + + lhs_val = gen_sum + stor_sum + flow_sum + violated, excess = check_eq(lhs_val, demand_b) + if violated: + record_violation(violations_list, magnitudes_list, 17, + f"(2l) Power balance violated at bus {b}, n={n},k={k},p={pidx},h={h}: " + f"supply={lhs_val:.4f} != demand={demand_b:.4f}", + lhs_val, demand_b, excess) + + # --- Constraint 18: (2m) Flow limits --- + for l in lines: + lid = l["id"] + is_cand = not l["existing"] + fkey = f"{n},{k},{pidx},{h},{lid}" + + if is_cand and has_investments: + cap = l["flow_limit_MW"] * kappa_line[n].get(lid, 0) + else: + cap = l["flow_limit_MW"] + + if f_fwd_sol is not None and f_bwd_sol is not None: + fwd = float(f_fwd_sol.get(fkey, 0.0)) + bwd = float(f_bwd_sol.get(fkey, 0.0)) + violated, excess = check_le(fwd, cap) + if violated: + record_violation(violations_list, magnitudes_list, 18, + f"(2m) Forward flow limit violated for {lid} at n={n},k={k},p={pidx},h={h}: " + f"f_fwd={fwd:.4f} > cap={cap:.4f}", + fwd, cap, excess) + violated, excess = check_le(bwd, cap) + if violated: + record_violation(violations_list, magnitudes_list, 18, + f"(2m) Backward flow limit violated for {lid} at n={n},k={k},p={pidx},h={h}: " + f"f_bwd={bwd:.4f} > cap={cap:.4f}", + bwd, cap, excess) + elif f_sol is not None: + f_val = float(f_sol.get(fkey, 0.0)) + violated, excess = check_le(abs(f_val), cap) + if violated: + record_violation(violations_list, magnitudes_list, 18, + f"(2m) Flow limit violated for {lid} at n={n},k={k},p={pidx},h={h}: " + f"|f|={abs(f_val):.4f} > cap={cap:.4f}", + abs(f_val), cap, excess) + + # --- Constraint 19: (2n) Binary constraints --- + for g in generators: + gid = g["id"] + key = f"{n},{k},{pidx},{h},{gid}" + a_val = float(alpha_sol.get(key, 0.0)) + if not (abs(a_val) < TOL or abs(a_val - 1.0) < TOL): + excess = min(abs(a_val), abs(a_val - 1.0)) + record_violation(violations_list, magnitudes_list, 19, + f"(2n) Binary violated for alpha[{gid}] at n={n},k={k},p={pidx},h={h}: " + f"alpha={a_val}", + a_val, round(a_val), excess) + if gamma_sol: + g_val = float(gamma_sol.get(key, 0.0)) + if not (abs(g_val) < TOL or abs(g_val - 1.0) < TOL): + excess = min(abs(g_val), abs(g_val - 1.0)) + record_violation(violations_list, magnitudes_list, 19, + f"(2n) Binary violated for gamma[{gid}] at n={n},k={k},p={pidx},h={h}: " + f"gamma={g_val}", + g_val, round(g_val), excess) + + # --- Constraint 20: (2o) Non-negativity --- + for g in generators: + gid = g["id"] + key = f"{n},{k},{pidx},{h},{gid}" + p_val = float(p_sol.get(key, 0.0)) + if p_val < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"(2o) Non-negativity violated for p[{gid}] at n={n},k={k},p={pidx},h={h}: p={p_val}", + p_val, 0.0, abs(p_val)) + if s_sol: + s_val = float(s_sol.get(key, 0.0)) + if s_val < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"(2o) Non-negativity violated for s[{gid}] at n={n},k={k},p={pidx},h={h}: s={s_val}", + s_val, 0.0, abs(s_val)) + + for s in storage_units: + sid = s["id"] + key = f"{n},{k},{pidx},{h},{sid}" + if r_sol: + r_val = float(r_sol.get(key, 0.0)) + if r_val < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"(2o) Non-negativity violated for r[{sid}] at n={n},k={k},p={pidx},h={h}: r={r_val}", + r_val, 0.0, abs(r_val)) + if u_sol: + u_val = float(u_sol.get(key, 0.0)) + if u_val < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"(2o) Non-negativity violated for u[{sid}] at n={n},k={k},p={pidx},h={h}: u={u_val}", + u_val, 0.0, abs(u_val)) + if v_sol: + v_val = float(v_sol.get(key, 0.0)) + if v_val < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"(2o) Non-negativity violated for v[{sid}] at n={n},k={k},p={pidx},h={h}: v={v_val}", + v_val, 0.0, abs(v_val)) + + for l in lines: + lid = l["id"] + fkey = f"{n},{k},{pidx},{h},{lid}" + if f_fwd_sol: + fwd = float(f_fwd_sol.get(fkey, 0.0)) + if fwd < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"(2o) Non-negativity violated for f_fwd[{lid}] at n={n},k={k},p={pidx},h={h}: f={fwd}", + fwd, 0.0, abs(fwd)) + if f_bwd_sol: + bwd = float(f_bwd_sol.get(fkey, 0.0)) + if bwd < -TOL: + record_violation(violations_list, magnitudes_list, 20, + f"(2o) Non-negativity violated for f_bwd[{lid}] at n={n},k={k},p={pidx},h={h}: f={bwd}", + bwd, 0.0, abs(bwd)) + + # ========================================================================= + # CONSTRAINT 21: Objective consistency (Tier C anti-exploit envelope) + # ========================================================================= + # The solution carries first-stage investment variables only -- second-stage + # dispatch variables (alpha/gamma/p/s/...) may be absent. So we cannot fully + # recompute the objective. Instead bound it: + # obj_LB = inv_exact + ops_LB + # obj_UB = inv_exact + ops_UB + # where inv_exact is computed from x_*, and ops_{LB,UB} use demand, + # renewable capacity, and per-MWh variable-cost ranges. Reject if + # reported_obj falls outside [obj_LB, obj_UB] beyond tolerance. This catches + # both the obj=0 (under-report) and obj=MAX_FLOAT (over-report) exploits. + if has_investments: + reported_obj_raw = solution.get("objective_value", None) + try: + reported_obj = float(reported_obj_raw) if reported_obj_raw is not None else None + except (TypeError, ValueError): + reported_obj = None + if reported_obj is not None and math.isfinite(reported_obj) is False: + # NaN/+-inf as reported: treat as infinite magnitude, always rejected. + # Keep reported_obj for the message. + pass + + if reported_obj is not None: + # ---- Investment cost (EXACT from x_gen / x_line / x_stor) ----- + cost_var = sp.get("cost_variation_percent", 0.0) + cost_mult = build_cost_mult(tree, sp) + inv_cost_exact = 0.0 + for n in node_ids: + node = node_by_id[n] + pi_n = float(node.get("probability", 1.0)) + cm = cost_mult.get(n, 1.0) + for g in candidate_gens: + gid = g["id"] + base = g["capital_cost_per_kW"] * g["Pmax_MW"] * 1000.0 + inv_cost_exact += pi_n * cm * base * x_gen[n].get(gid, 0) + for l in candidate_lines: + lid = l["id"] + base = l["capital_cost_per_kW"] * l["flow_limit_MW"] * 1000.0 + inv_cost_exact += pi_n * cm * base * x_line[n].get(lid, 0) + for s in candidate_storage: + sid = s["id"] + base = s["capital_cost_per_kW"] * s["capacity_MW"] * 1000.0 + inv_cost_exact += pi_n * cm * base * x_stor[n].get(sid, 0) + + # ---- Operational cost lower bound ------------------------------ + # Per (n,k,p,h): demand D_{nkph} must be met by generation (>= + # demand even with losses), of which at most R_{nkph} can come + # from renewables (b=c=0). The non-renewable portion D-R costs at + # least min_b_nonrenew per MWh, where min_b_nonrenew is the min + # linearized marginal cost (b + c*Pmax) over available + # non-renewable generators (existing + built candidates at node n). + # If only renewables exist at node n, min_b_nonrenew defaults to 0 + # and the LB collapses to zero -- correct (no marginal cost floor). + nonrenew_marginal_global = [ + g["b_cost"] + g["c_cost"] * g["Pmax_MW"] + for g in generators if g["type"] not in ("solar", "wind") + ] + ops_lb = 0.0 + ops_ub = 0.0 + for n in node_ids: + node = node_by_id[n] + pi_n = float(node.get("probability", 1.0)) + weight = pi_n / max(1, num_rep_days * num_ll_scenarios) + growth = demand_growth[n] + total_peak = sum(load_by_bus.get(b, 0.0) for b in buses) + + # Available non-renewable generators at this node = existing + # non-renewables + built candidate non-renewables. + avail_nonrenew_marg = [ + g["b_cost"] + g["c_cost"] * g["Pmax_MW"] + for g in existing_gens if g["type"] not in ("solar", "wind") + ] + for g in candidate_gens: + if g["type"] in ("solar", "wind"): + continue + if kappa_gen[n].get(g["id"], 0) >= 1 - TOL: + avail_nonrenew_marg.append( + g["b_cost"] + g["c_cost"] * g["Pmax_MW"]) + min_b_nonrenew = min(avail_nonrenew_marg) if avail_nonrenew_marg else 0.0 + + # Built/existing renewable units at this node, by type. + avail_renew = list(existing_gens) # any existing renewables + avail_renew = [g for g in avail_renew if g["type"] in ("solar", "wind")] + for g in candidate_gens: + if g["type"] in ("solar", "wind"): + if kappa_gen[n].get(g["id"], 0) >= 1 - TOL: + avail_renew.append(g) + + # Per-period max generation cost (for the upper bound). Uses + # the same linearized cost as gurobi_code.py: + # per-hour cost upper bound = sum_g (a_g + (b+c*Pmax)*Pmax_g + SC_g) + per_period_max = 0.0 + for g in generators: + per_period_max += ( + g["a_cost"] + + (g["b_cost"] + g["c_cost"] * g["Pmax_MW"]) * g["Pmax_MW"] + + g["startup_cost"] + ) + + # Iterate (k, p, h) only for the LB; UB uses summed period count. + for k in day_ids: + day_data = day_by_id[k] + lp = day_data["load_profile"] + solar_profile = day_data["solar_profile"] + ll_scens = ll_scenarios[str(k)] + for pidx in ll_scen_ids: + scen = ll_scens[pidx] + dm = scen["demand_multipliers"] + sm = scen["solar_multipliers"] + wpf = scen["wind_power_factors"] + for h in hours: + d_h = total_peak * growth * lp[h] * dm[h] + # Max renewable supply this hour (full capacity + # times available profile/factor). + r_h = 0.0 + for g in avail_renew: + if g["type"] == "solar": + r_h += g["Pmax_MW"] * solar_profile[h] * sm[h] + elif g["type"] == "wind": + r_h += g["Pmax_MW"] * wpf[h] + need_nonrenew = max(0.0, d_h - r_h) + ops_lb += weight * min_b_nonrenew * need_nonrenew + + # Operational UB: each (k,p,h) has cost <= per_period_max. + ops_ub += weight * num_rep_days * num_ll_scenarios * num_hours * per_period_max + + obj_lb = inv_cost_exact + ops_lb + obj_ub = inv_cost_exact + ops_ub + + # Tolerance: 0.1% relative + 1.0 absolute floor. The LB is already + # conservative (max renewable supply, no a_cost, no startup cost), + # and the UB is comically loose (whole fleet at Pmax every hour), + # so this tolerance only guards against floating-point drift. + tol_lb = max(1.0, 1e-3 * abs(obj_lb)) + tol_ub = max(1.0, 1e-3 * abs(obj_ub)) + + rep_finite = math.isfinite(reported_obj) + if (not rep_finite) or (reported_obj < obj_lb - tol_lb): + deficit = (obj_lb - reported_obj) if rep_finite else float("inf") + record_violation( + violations_list, magnitudes_list, 21, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} below lower bound={obj_lb:.6g} " + f"(inv_exact={inv_cost_exact:.6g}, ops_LB={ops_lb:.6g}, " + f"deficit={deficit:.6g}, tol={tol_lb:.3g})", + reported_obj, obj_lb, deficit, + ) + elif (not rep_finite) or (reported_obj > obj_ub + tol_ub): + excess = (reported_obj - obj_ub) if rep_finite else float("inf") + record_violation( + violations_list, magnitudes_list, 21, + f"Objective consistency violated: reported objective_value=" + f"{reported_obj} above upper bound={obj_ub:.6g} " + f"(inv_exact={inv_cost_exact:.6g}, ops_UB={ops_ub:.6g}, " + f"excess={excess:.6g}, tol={tol_ub:.3g})", + reported_obj, obj_ub, excess, + ) + + # Replace the loose envelope as the final certificate. Published + # large solutions carry dense operational decisions, so recompute + # directly; the tiny solution uses the documented first-stage-only + # interface and receives a trusted fixed-investment completion. + if not violations_list and rep_finite: + try: + if not has_operational: + raise ValueError("complete operational witness is required") + expected_obj = _recompute_full_witness_objective( + instance, solution + ) + except Exception as error: + record_violation( + violations_list, + magnitudes_list, + 21, + "Objective consistency trusted completion failed: " + f"{type(error).__name__}: {str(error)[:300]}", + 1.0, + 0.0, + 1.0, + ) + else: + objective_diff = abs(reported_obj - expected_obj) + objective_tol = max( + 1e-4, 1e-6 * max(1.0, abs(expected_obj)) + ) + if objective_diff > objective_tol: + record_violation( + violations_list, + magnitudes_list, + 21, + f"Objective consistency violated: reported " + f"objective_value={reported_obj:.6f} does not equal " + f"trusted fixed-witness value={expected_obj:.6f} " + f"(difference={objective_diff:.6g}, " + f"tol={objective_tol:.6g})", + reported_obj, + expected_obj, + objective_diff, + ) + + # ========================================================================= + # Aggregate results + # ========================================================================= + violated_set = sorted(set(v[0] for v in violations_list)) + # Aggregate messages per constraint index + msg_by_idx = {} + for idx, msg in violations_list: + if idx not in msg_by_idx: + msg_by_idx[idx] = [] + msg_by_idx[idx].append(msg) + + # Build concise violation messages (one per constraint index) + concise_msgs = [] + for idx in violated_set: + msgs = msg_by_idx[idx] + if len(msgs) == 1: + concise_msgs.append(msgs[0]) + else: + concise_msgs.append(f"{msgs[0]} (and {len(msgs)-1} more similar violations)") + + feasible = len(violated_set) == 0 + return feasible, violated_set, concise_msgs, magnitudes_list + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for MM-SMIP Power System Capacity Expansion") + 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 + + 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 is None: + status = "NO_SOLUTION" + elif feasible: + status = "FEASIBLE" + else: + status = "INFEASIBLE" + print(f"Result: {status}") + if feasible is not None and not feasible: + print(f"Violated constraints: {violated_constraints}") + for msg in violations: + print(f" - {msg}") + elif feasible is None: + for msg in violations: + print(f" - {msg}") + 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/taninmis2022/gurobi_code.py b/tasks/taninmis2022/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..9773141418bd51d51dd488c595fc42f893e2917f --- /dev/null +++ b/tasks/taninmis2022/gurobi_code.py @@ -0,0 +1,867 @@ +#!/usr/bin/env python3 +""" +MM-SMIP (Multistage Multiscale Stochastic Mixed Integer Programming) model +for power system capacity expansion, solved monolithically with Gurobi. + +Based on: Taninmis et al. (2022) +""" + +import argparse +import json +import time + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + with open(path, "r") as f: + return json.load(f) + + +def build_scenario_tree_info(instance): + """Build helper mappings for the scenario tree.""" + tree = instance["scenario_tree"] + sp = instance["scenario_parameters"] + + node_by_id = {n["id"]: n for n in tree} + + # Compute demand growth factor and cost multiplier along each node's path + high_growth = sp["demand_growth_high_percent"] + low_growth = sp["demand_growth_low_percent"] + cost_var = sp["cost_variation_percent"] + + # For each node, determine its ancestor path from root + def ancestor_path(nid): + path = [] + cur = nid + while cur is not None: + path.append(cur) + cur = node_by_id[cur]["parent_id"] + path.reverse() + return path + + node_demand_growth = {} # node_id -> cumulative demand growth factor + node_cost_mult = {} # node_id -> cumulative cost multiplier + + for node in tree: + nid = node["id"] + path = ancestor_path(nid) + growth = 1.0 + cost_mult = 1.0 + for i, pid in enumerate(path): + if i == 0: + continue # root: no growth + parent = node_by_id[path[i - 1]] + children = parent["children"] + # First child = high demand growth / cost increase + # Second child = low demand growth / cost decrease + if len(children) >= 2: + child_idx = children.index(pid) + if child_idx == 0: + growth *= (1.0 + high_growth) + cost_mult *= (1.0 + cost_var) + else: + growth *= (1.0 + low_growth) + cost_mult *= (1.0 - cost_var) + else: + # single child fallback + growth *= (1.0 + low_growth) + + node_demand_growth[nid] = growth + node_cost_mult[nid] = cost_mult + + return node_by_id, node_demand_growth, node_cost_mult + + +def build_model(instance, time_limit=None, quiet=False): + """Build the monolithic MM-SMIP Gurobi model.""" + system = instance["system"] + sp = instance["scenario_parameters"] + gp_params = instance["global_parameters"] + rep_days = instance["representative_days"] + ll_scenarios = instance["lower_level_scenarios"] + + generators = system["generators"] + lines = system["transmission_lines"] + storage_units = system["storage"] + loads = system["loads"] + buses = system["buses"] + + node_by_id, node_demand_growth, node_cost_mult = build_scenario_tree_info(instance) + tree = instance["scenario_tree"] + + num_hours = sp["hours_per_day"] + num_rep_days = sp["num_representative_days"] + num_ll_scenarios = sp["num_lower_level_scenarios_per_day"] + + RM = gp_params["reserve_margin_requirement"] + SR_pct = gp_params["spinning_reserve_percent"] + derating = gp_params["derating_factors"] + + # Separate existing and candidate assets + existing_gens = [g for g in generators if g["existing"]] + candidate_gens = [g for g in generators if not g["existing"]] + existing_lines = [l for l in lines if l["existing"]] + candidate_lines = [l for l in lines if not l["existing"]] + existing_storage = [s for s in storage_units if s["existing"]] + candidate_storage = [s for s in storage_units if not s["existing"]] + + all_gens = generators + all_lines = lines + all_storage = storage_units + + # Load by bus + load_by_bus = {ld["bus"]: ld["annual_peak_load_MW"] for ld in loads} + + # Line connectivity helpers: lines incident to each bus + # For each line, track (from_bus, to_bus) + line_from_to = {l["id"]: (l["from_bus"], l["to_bus"]) for l in all_lines} + + # Generators at each bus + gens_at_bus = {} + for b in buses: + gens_at_bus[b] = [g for g in all_gens if g["bus"] == b] + + # Storage at each bus + storage_at_bus = {} + for b in buses: + storage_at_bus[b] = [s for s in all_storage if s["bus"] == b] + + # Lines connected to each bus + lines_at_bus = {} + for b in buses: + lines_at_bus[b] = [l for l in all_lines + if l["from_bus"] == b or l["to_bus"] == b] + + # Node IDs + node_ids = [n["id"] for n in tree] + + # Representative day IDs + day_ids = [d["id"] for d in rep_days] + day_by_id = {d["id"]: d for d in rep_days} + + # Hours + hours = list(range(num_hours)) # 0..23 + + # Scenario indices for lower level + ll_scen_ids = list(range(num_ll_scenarios)) # 0..19 + + # ========================================================================= + # Create Gurobi model + # ========================================================================= + model = gp.Model("MM_SMIP_Capacity_Expansion") + model.setParam("Threads", 1) + if time_limit is not None: + model.setParam("TimeLimit", time_limit) + model.setParam("OutputFlag", 0 if quiet else 1) + # Disable dual reductions so infeasible vs unbounded is distinguished + model.setParam("DualReductions", 0) + # Use barrier for the root LP (much faster for large models) + model.setParam("Method", 2) + # Focus on finding feasible solutions + model.setParam("MIPFocus", 1) + + # ========================================================================= + # UPPER-LEVEL VARIABLES + # ========================================================================= + + # x[n, g_id] = binary build decision for candidate generator g at node n + x_gen = {} + for n in node_ids: + for g in candidate_gens: + x_gen[n, g["id"]] = model.addVar( + vtype=GRB.BINARY, name=f"x_gen_{n}_{g['id']}") + + # x[n, l_id] = binary build decision for candidate line l at node n + x_line = {} + for n in node_ids: + for l in candidate_lines: + x_line[n, l["id"]] = model.addVar( + vtype=GRB.BINARY, name=f"x_line_{n}_{l['id']}") + + # x[n, s_id] = binary build decision for candidate storage s at node n + x_stor = {} + for n in node_ids: + for s in candidate_storage: + x_stor[n, s["id"]] = model.addVar( + vtype=GRB.BINARY, name=f"x_stor_{n}_{s['id']}") + + # kappa[n, g_id] = cumulative available capacity [MW] for candidate gen + kappa_gen = {} + for n in node_ids: + for g in candidate_gens: + kappa_gen[n, g["id"]] = model.addVar( + lb=0.0, ub=g["Pmax_MW"], vtype=GRB.CONTINUOUS, + name=f"kappa_gen_{n}_{g['id']}") + + kappa_line = {} + for n in node_ids: + for l in candidate_lines: + kappa_line[n, l["id"]] = model.addVar( + lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, + name=f"kappa_line_{n}_{l['id']}") + + kappa_stor = {} + for n in node_ids: + for s in candidate_storage: + kappa_stor[n, s["id"]] = model.addVar( + lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, + name=f"kappa_stor_{n}_{s['id']}") + + # ========================================================================= + # LOWER-LEVEL VARIABLES (for each node, rep day, ll scenario, hour) + # ========================================================================= + + # alpha[n,k,p,h,g] = commitment status (binary) + alpha = {} + # gamma[n,k,p,h,g] = startup indicator (binary) + gamma = {} + # p_gen[n,k,p,h,g] = power output (continuous) + p_gen = {} + # s_res[n,k,p,h,g] = spinning reserve contribution (continuous) + s_res = {} + + # Flow variables: bidirectional + # f_fwd[n,k,p,h,l] = flow from from_bus to to_bus + # f_bwd[n,k,p,h,l] = flow from to_bus to from_bus + f_fwd = {} + f_bwd = {} + + # Storage variables + # r[n,k,p,h,s] = stored energy + # u[n,k,p,h,s] = withdrawal (discharge) + # v[n,k,p,h,s] = injection (charge) + r_stor = {} + u_stor = {} + v_stor = {} + + if not quiet: + print("Creating lower-level variables...") + + for n in node_ids: + for k in day_ids: + for p in ll_scen_ids: + for h in hours: + # Generator variables + for g in all_gens: + gid = g["id"] + key = (n, k, p, h, gid) + alpha[key] = model.addVar( + vtype=GRB.BINARY, name=f"alpha_{n}_{k}_{p}_{h}_{gid}") + gamma[key] = model.addVar( + vtype=GRB.BINARY, name=f"gamma_{n}_{k}_{p}_{h}_{gid}") + p_gen[key] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"p_{n}_{k}_{p}_{h}_{gid}") + s_res[key] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"s_{n}_{k}_{p}_{h}_{gid}") + + # Flow variables for all lines + for l in all_lines: + lid = l["id"] + key = (n, k, p, h, lid) + f_fwd[key] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"f_fwd_{n}_{k}_{p}_{h}_{lid}") + f_bwd[key] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"f_bwd_{n}_{k}_{p}_{h}_{lid}") + + # Storage variables + for s in all_storage: + sid = s["id"] + key = (n, k, p, h, sid) + r_stor[key] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"r_{n}_{k}_{p}_{h}_{sid}") + u_stor[key] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"u_{n}_{k}_{p}_{h}_{sid}") + v_stor[key] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + name=f"v_{n}_{k}_{p}_{h}_{sid}") + + model.update() + if not quiet: + print("Variables created. Adding constraints...") + + # ========================================================================= + # UPPER-LEVEL CONSTRAINTS + # ========================================================================= + + # (1b)-(1d) Cumulative capacity tracking + for n in node_ids: + node = node_by_id[n] + parent_id = node["parent_id"] + + for g in candidate_gens: + gid = g["id"] + if parent_id is None: + # Root: kappa = a_g * x (eq 1b, with kappa^0 = 0) + model.addConstr( + kappa_gen[n, gid] == g["Pmax_MW"] * x_gen[n, gid], + name=f"cum_gen_{n}_{gid}") + else: + model.addConstr( + kappa_gen[n, gid] == kappa_gen[parent_id, gid] + g["Pmax_MW"] * x_gen[n, gid], + name=f"cum_gen_{n}_{gid}") + + for l in candidate_lines: + lid = l["id"] + if parent_id is None: + model.addConstr( + kappa_line[n, lid] == x_line[n, lid], + name=f"cum_line_{n}_{lid}") + else: + model.addConstr( + kappa_line[n, lid] == kappa_line[parent_id, lid] + x_line[n, lid], + name=f"cum_line_{n}_{lid}") + + for s in candidate_storage: + sid = s["id"] + if parent_id is None: + model.addConstr( + kappa_stor[n, sid] == x_stor[n, sid], + name=f"cum_stor_{n}_{sid}") + else: + model.addConstr( + kappa_stor[n, sid] == kappa_stor[parent_id, sid] + x_stor[n, sid], + name=f"cum_stor_{n}_{sid}") + + # (1e) Capacity upper bound (max once: kappa <= 1, already in variable bounds) + + # (1f) Reserve margin constraint: single region (all buses) + for n in node_ids: + # Total peak demand at node n + peak_demand_n = sum(load_by_bus.get(b, 0.0) for b in buses) * node_demand_growth[n] + + # Derated capacity of existing generators + existing_cap = sum( + derating.get(g["type"], 1.0) * g["Pmax_MW"] + for g in existing_gens + ) + + # Derated capacity of candidate generators (depends on kappa) + cand_cap_expr = gp.LinExpr(existing_cap) + for g in candidate_gens: + gid = g["id"] + df = derating.get(g["type"], 1.0) + cand_cap_expr += df * kappa_gen[n, gid] + + model.addConstr( + cand_cap_expr >= (1.0 + RM) * peak_demand_n, + name=f"reserve_margin_{n}") + + # ========================================================================= + # LOWER-LEVEL CONSTRAINTS + # ========================================================================= + + if not quiet: + print("Adding lower-level constraints...") + + for n in node_ids: + for k in day_ids: + day = day_by_id[k] + load_profile = day["load_profile"] + solar_profile = day["solar_profile"] + ll_scens = ll_scenarios[str(k)] + + for pidx in ll_scen_ids: + scen = ll_scens[pidx] + demand_mult = scen["demand_multipliers"] + solar_mult = scen["solar_multipliers"] + wind_pf = scen["wind_power_factors"] + + for h in hours: + # Demand at each bus for this (n, k, p, h) + growth = node_demand_growth[n] + + # ---- Generator constraints ---- + for g in all_gens: + gid = g["id"] + key = (n, k, pidx, h, gid) + is_candidate = not g["existing"] + gtype = g["type"] + + # Effective Pmax considering renewables + pmax = g["Pmax_MW"] + if gtype == "solar": + eff_pmax = pmax * solar_profile[h] * solar_mult[h] + elif gtype == "wind": + eff_pmax = pmax * wind_pf[h] + else: + eff_pmax = pmax + + # (2b) Commitment linked to capacity for candidates + if is_candidate: + model.addConstr( + alpha[key] <= kappa_gen[n, gid] / pmax, + name=f"link_alpha_{n}_{k}_{pidx}_{h}_{gid}") + + # (2d) Startup indicator: gamma >= alpha_h - alpha_{h-1} + if h >= 1: + prev_key = (n, k, pidx, h - 1, gid) + model.addConstr( + gamma[key] >= alpha[key] - alpha[prev_key], + name=f"startup_{n}_{k}_{pidx}_{h}_{gid}") + else: + # h=0: alpha_{-1} = 0 + model.addConstr( + gamma[key] >= alpha[key], + name=f"startup_{n}_{k}_{pidx}_{h}_{gid}") + + # (2e) Output + reserve upper bound + if is_candidate: + # Candidate: p + s <= kappa^n_g (eq 2e) + model.addConstr( + p_gen[key] + s_res[key] <= kappa_gen[n, gid], + name=f"pmax_{n}_{k}_{pidx}_{h}_{gid}") + else: + # Existing generator: p + s <= Pmax * alpha (eq 2e) + model.addConstr( + p_gen[key] + s_res[key] <= eff_pmax * alpha[key], + name=f"pmax_{n}_{k}_{pidx}_{h}_{gid}") + + # (2f) Minimum power output + model.addConstr( + p_gen[key] >= g["Pmin_MW"] * alpha[key], + name=f"pmin_{n}_{k}_{pidx}_{h}_{gid}") + + # (2h) Ramp limits + if h >= 1: + prev_key = (n, k, pidx, h - 1, gid) + ramp = g["ramp_MW_per_h"] + model.addConstr( + p_gen[key] - p_gen[prev_key] <= ramp, + name=f"ramp_up_{n}_{k}_{pidx}_{h}_{gid}") + model.addConstr( + p_gen[prev_key] - p_gen[key] <= ramp, + name=f"ramp_dn_{n}_{k}_{pidx}_{h}_{gid}") + + # (2c) Min up/down time constraints + for g in all_gens: + gid = g["id"] + min_on = g["min_on_h"] + min_off = g["min_off_h"] + + if h >= 1: + # Min up time: if unit starts at h (alpha_h - + # alpha_{h-1} = 1), then alpha must be 1 for + # min_on hours. + if min_on > 0: + for tau in range(h, min(h + min_on, num_hours)): + startup_diff = (alpha[(n, k, pidx, h, gid)] + - alpha[(n, k, pidx, h - 1, gid)]) + model.addConstr( + alpha[(n, k, pidx, tau, gid)] >= startup_diff, + name=f"minon_{n}_{k}_{pidx}_{h}_{tau}_{gid}") + + # Min down time: if unit shuts down at h + # (alpha_{h-1} - alpha_h = 1), then alpha must + # be 0 for min_off hours. + if min_off > 0: + for tau in range(h, min(h + min_off, num_hours)): + shutdown_diff = (alpha[(n, k, pidx, h - 1, gid)] + - alpha[(n, k, pidx, h, gid)]) + model.addConstr( + 1 - alpha[(n, k, pidx, tau, gid)] >= shutdown_diff, + name=f"minoff_{n}_{k}_{pidx}_{h}_{tau}_{gid}") + + # ---- Flow constraints (2m) ---- + for l in all_lines: + lid = l["id"] + fkey = (n, k, pidx, h, lid) + is_cand_line = not l["existing"] + + if is_cand_line: + cap_expr_fwd = l["flow_limit_MW"] * kappa_line[n, lid] + cap_expr_bwd = l["flow_limit_MW"] * kappa_line[n, lid] + else: + cap_expr_fwd = l["flow_limit_MW"] + cap_expr_bwd = l["flow_limit_MW"] + + model.addConstr( + f_fwd[fkey] <= cap_expr_fwd, + name=f"fcap_fwd_{n}_{k}_{pidx}_{h}_{lid}") + model.addConstr( + f_bwd[fkey] <= cap_expr_bwd, + name=f"fcap_bwd_{n}_{k}_{pidx}_{h}_{lid}") + + # ---- Storage constraints (2i)-(2k) ---- + for s in all_storage: + sid = s["id"] + skey = (n, k, pidx, h, sid) + eff = s["efficiency"] + is_cand_stor = not s["existing"] + + # (2i) Storage dynamics + if h == 0: + # r^1 = 0 + model.addConstr( + r_stor[skey] == 0, + name=f"stor_init_{n}_{k}_{pidx}_{sid}") + else: + prev_skey = (n, k, pidx, h - 1, sid) + model.addConstr( + r_stor[skey] == r_stor[prev_skey] + + eff * v_stor[prev_skey] + - u_stor[prev_skey], + name=f"stor_dyn_{n}_{k}_{pidx}_{h}_{sid}") + + # (2j) Withdrawal <= stored energy + model.addConstr( + u_stor[skey] <= r_stor[skey], + name=f"stor_with_{n}_{k}_{pidx}_{h}_{sid}") + + # (2k) Storage capacity limit + if is_cand_stor: + model.addConstr( + r_stor[skey] <= s["capacity_MW"] * kappa_stor[n, sid], + name=f"stor_cap_{n}_{k}_{pidx}_{h}_{sid}") + # Also limit charge/discharge to capacity + model.addConstr( + u_stor[skey] <= s["capacity_MW"] * kappa_stor[n, sid], + name=f"stor_dis_cap_{n}_{k}_{pidx}_{h}_{sid}") + model.addConstr( + v_stor[skey] <= s["capacity_MW"] * kappa_stor[n, sid], + name=f"stor_chg_cap_{n}_{k}_{pidx}_{h}_{sid}") + else: + model.addConstr( + r_stor[skey] <= s["capacity_MW"], + name=f"stor_cap_{n}_{k}_{pidx}_{h}_{sid}") + model.addConstr( + u_stor[skey] <= s["capacity_MW"], + name=f"stor_dis_cap_{n}_{k}_{pidx}_{h}_{sid}") + model.addConstr( + v_stor[skey] <= s["capacity_MW"], + name=f"stor_chg_cap_{n}_{k}_{pidx}_{h}_{sid}") + + # ---- Power balance (2l) ---- + for b in buses: + demand_b = (load_by_bus.get(b, 0.0) * growth + * load_profile[h] * demand_mult[h]) + + # Generation at bus b + gen_expr = gp.LinExpr() + for g in gens_at_bus[b]: + gen_expr += p_gen[(n, k, pidx, h, g["id"])] + + # Storage at bus b: withdrawal - injection + stor_expr = gp.LinExpr() + for s in storage_at_bus[b]: + sid = s["id"] + stor_expr += u_stor[(n, k, pidx, h, sid)] + stor_expr -= v_stor[(n, k, pidx, h, sid)] + + # Net flow into bus b + flow_expr = gp.LinExpr() + for l in lines_at_bus[b]: + lid = l["id"] + fb = l["from_bus"] + tb = l["to_bus"] + loss = l["loss_factor"] + fkey = (n, k, pidx, h, lid) + if tb == b: + # Inflow via forward direction + flow_expr += (1.0 - loss) * f_fwd[fkey] + # Outflow via backward direction + flow_expr -= f_bwd[fkey] + else: + # fb == b + # Outflow via forward direction + flow_expr -= f_fwd[fkey] + # Inflow via backward direction + flow_expr += (1.0 - loss) * f_bwd[fkey] + + model.addConstr( + gen_expr + stor_expr + flow_expr == demand_b, + name=f"balance_{n}_{k}_{pidx}_{h}_{b}") + + # ---- Spinning reserve (2g) ---- + for b in buses: + demand_b = (load_by_bus.get(b, 0.0) * growth + * load_profile[h] * demand_mult[h]) + sr_req = SR_pct * demand_b + + sr_expr = gp.LinExpr() + for g in gens_at_bus[b]: + sr_expr += s_res[(n, k, pidx, h, g["id"])] + + model.addConstr( + sr_expr >= sr_req, + name=f"spin_res_{n}_{k}_{pidx}_{h}_{b}") + + if not quiet: + print("Constraints added. Building objective...") + + # ========================================================================= + # OBJECTIVE FUNCTION + # ========================================================================= + + obj = gp.LinExpr() + + # --- Investment costs --- + for n in node_ids: + node = node_by_id[n] + pi_n = node["probability"] + cm = node_cost_mult[n] + + for g in candidate_gens: + gid = g["id"] + base_cost = g["capital_cost_per_kW"] * g["Pmax_MW"] * 1000.0 + obj += pi_n * cm * base_cost * x_gen[n, gid] + + for l in candidate_lines: + lid = l["id"] + base_cost = l["capital_cost_per_kW"] * l["flow_limit_MW"] * 1000.0 + obj += pi_n * cm * base_cost * x_line[n, lid] + + for s in candidate_storage: + sid = s["id"] + base_cost = s["capital_cost_per_kW"] * s["capacity_MW"] * 1000.0 + obj += pi_n * cm * base_cost * x_stor[n, sid] + + # --- Expected operational costs --- + # For each node n: pi_n * (1/num_rep_days_weight) * (1/S) * sum over k,p of OC + # Assume each representative day has equal weight: 1/num_rep_days + # and each lower-level scenario has equal probability: 1/S + # + # The quadratic cost GC(p) = a + b*p + c*p^2 is linearized as + # a + (b + c*Pmax)*p. This is the secant approximation at p=Pmax + # and a valid upper bound on the convex quadratic. The c_cost + # coefficients are very small relative to b_cost (< 3% error at + # Pmax), so the approximation is tight. Linearization allows the + # barrier solver to handle the LP relaxation, which is critical for + # solving the 1.5M-variable model in reasonable time. + for n in node_ids: + node = node_by_id[n] + pi_n = node["probability"] + weight = pi_n / (num_rep_days * num_ll_scenarios) + + for k in day_ids: + for pidx in ll_scen_ids: + for h in hours: + for g in all_gens: + gid = g["id"] + key = (n, k, pidx, h, gid) + + # Startup cost + obj += weight * g["startup_cost"] * gamma[key] + + # Generation cost: a*alpha + (b + c*Pmax)*p + # Linearized from: a*alpha + b*p + c*p^2 + obj += weight * g["a_cost"] * alpha[key] + linearized_b = g["b_cost"] + g["c_cost"] * g["Pmax_MW"] + obj += weight * linearized_b * p_gen[key] + + model.setObjective(obj, GRB.MINIMIZE) + model.update() + + if not quiet: + print(f"Model built: {model.NumVars} variables, {model.NumConstrs} constraints.") + + return model + + +def extract_solution(model, instance): + """Extract solution from solved model.""" + result = {} + + if model.Status == GRB.OPTIMAL: + result["status"] = "optimal" + result["objective_value"] = model.ObjVal + elif model.Status == GRB.TIME_LIMIT: + result["status"] = "time_limit" + if model.SolCount > 0: + result["objective_value"] = model.ObjVal + result["best_bound"] = model.ObjBound + result["mip_gap"] = model.MIPGap + else: + result["objective_value"] = None + result["best_bound"] = model.ObjBound if hasattr(model, "ObjBound") else None + elif model.Status == GRB.INFEASIBLE: + result["status"] = "infeasible" + result["objective_value"] = None + elif model.Status == GRB.UNBOUNDED: + result["status"] = "unbounded" + result["objective_value"] = None + else: + result["status"] = f"gurobi_status_{model.Status}" + result["objective_value"] = model.ObjVal if model.SolCount > 0 else None + + result["solve_time_seconds"] = model.Runtime + result["num_variables"] = model.NumVars + result["num_constraints"] = model.NumConstrs + result["node_count"] = int(model.NodeCount) if hasattr(model, "NodeCount") else None + + # Extract investment decisions if solution exists + if model.SolCount > 0: + investments = {} + tree = instance["scenario_tree"] + candidate_gens = [g for g in instance["system"]["generators"] if not g["existing"]] + candidate_lines = [l for l in instance["system"]["transmission_lines"] if not l["existing"]] + candidate_storage = [s for s in instance["system"]["storage"] if not s["existing"]] + + for node in tree: + n = node["id"] + node_inv = {} + + gen_decisions = {} + for g in candidate_gens: + gid = g["id"] + var = model.getVarByName(f"x_gen_{n}_{gid}") + if var is not None: + gen_decisions[gid] = round(var.X) + node_inv["generators"] = gen_decisions + + line_decisions = {} + for l in candidate_lines: + lid = l["id"] + var = model.getVarByName(f"x_line_{n}_{lid}") + if var is not None: + line_decisions[lid] = round(var.X) + node_inv["lines"] = line_decisions + + stor_decisions = {} + for s in candidate_storage: + sid = s["id"] + var = model.getVarByName(f"x_stor_{n}_{sid}") + if var is not None: + stor_decisions[sid] = round(var.X) + node_inv["storage"] = stor_decisions + + investments[str(n)] = node_inv + + result["investments"] = investments + + # ---- Operational variables (lower-level dispatch) ------------------ + # Written so feasibility_check.py can verify constraints (2b)-(2o) + # (commitment, dispatch, ramp, reserve, power balance, flow, storage) + # against the original problem definition. Keys are + # ``"{n},{k},{pidx},{h},{var_id}"`` exactly matching the lookup format + # used by feasibility_check.py. + sp = instance["scenario_parameters"] + rep_days = instance["representative_days"] + ll_scenarios = instance["lower_level_scenarios"] + generators = instance["system"]["generators"] + lines = instance["system"]["transmission_lines"] + storage_units = instance["system"]["storage"] + + num_hours = sp["hours_per_day"] + num_ll = sp["num_lower_level_scenarios_per_day"] + node_ids = [node["id"] for node in tree] + day_ids = [d["id"] for d in rep_days] + + alpha_out, gamma_out, p_gen_out, s_res_out = {}, {}, {}, {} + f_fwd_out, f_bwd_out = {}, {} + u_stor_out, v_stor_out, r_stor_out = {}, {}, {} + for n in node_ids: + for k in day_ids: + for p in range(num_ll): + for h in range(num_hours): + for g in generators: + gid = g["id"] + key = f"{n},{k},{p},{h},{gid}" + v = model.getVarByName(f"alpha_{n}_{k}_{p}_{h}_{gid}") + if v is not None: + alpha_out[key] = round(v.X) + v = model.getVarByName(f"gamma_{n}_{k}_{p}_{h}_{gid}") + if v is not None: + gamma_out[key] = round(v.X) + v = model.getVarByName(f"p_{n}_{k}_{p}_{h}_{gid}") + if v is not None: + p_gen_out[key] = float(v.X) + v = model.getVarByName(f"s_{n}_{k}_{p}_{h}_{gid}") + if v is not None: + s_res_out[key] = float(v.X) + for l in lines: + lid = l["id"] + key = f"{n},{k},{p},{h},{lid}" + v = model.getVarByName(f"f_fwd_{n}_{k}_{p}_{h}_{lid}") + if v is not None: + f_fwd_out[key] = float(v.X) + v = model.getVarByName(f"f_bwd_{n}_{k}_{p}_{h}_{lid}") + if v is not None: + f_bwd_out[key] = float(v.X) + for s in storage_units: + sid = s["id"] + key = f"{n},{k},{p},{h},{sid}" + v = model.getVarByName(f"u_{n}_{k}_{p}_{h}_{sid}") + if v is not None: + u_stor_out[key] = float(v.X) + v = model.getVarByName(f"v_{n}_{k}_{p}_{h}_{sid}") + if v is not None: + v_stor_out[key] = float(v.X) + v = model.getVarByName(f"r_{n}_{k}_{p}_{h}_{sid}") + if v is not None: + r_stor_out[key] = float(v.X) + result["alpha"] = alpha_out + result["gamma"] = gamma_out + result["p_gen"] = p_gen_out + result["s_res"] = s_res_out + result["f_fwd"] = f_fwd_out + result["f_bwd"] = f_bwd_out + result["u_stor"] = u_stor_out + result["v_stor"] = v_stor_out + result["r_stor"] = r_stor_out + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="MM-SMIP Power System Capacity Expansion via Gurobi (monolithic)") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to instance JSON file") + parser.add_argument("--solution_path", type=str, default="gurobi_solution_1.json", + help="Path for output solution JSON") + parser.add_argument("--time_limit", type=int, default=None, + help="Solver time limit in seconds") + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + print(f"Loading instance from {args.instance_path}") + instance = load_instance(args.instance_path) + + print("Building model...") + t0 = time.time() + model = build_model(instance, time_limit=args.time_limit) + build_time = time.time() - t0 + print(f"Model built in {build_time:.1f} seconds.") + + print("Solving...") + model.optimize() + + print("Extracting solution...") + solution = extract_solution(model, instance) + solution["build_time_seconds"] = build_time + solution["instance_path"] = args.instance_path + + 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']:.2f}") + print(f"Status: {solution['status']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/taninmis2022/gurobi_feasi_result/large_feasi_result_1.json b/tasks/taninmis2022/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/taninmis2022/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/taninmis2022/gurobi_feasi_result/large_feasi_result_2.json b/tasks/taninmis2022/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/taninmis2022/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/taninmis2022/gurobi_feasi_result/large_feasi_result_3.json b/tasks/taninmis2022/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/taninmis2022/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/taninmis2022/gurobi_feasi_result/large_feasi_result_4.json b/tasks/taninmis2022/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/taninmis2022/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/taninmis2022/gurobi_feasi_result/large_feasi_result_5.json b/tasks/taninmis2022/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/taninmis2022/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/taninmis2022/gurobi_feasi_result/tiny_feasi_result.json b/tasks/taninmis2022/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/taninmis2022/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/taninmis2022/gurobi_solution/large_solution_1.json b/tasks/taninmis2022/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..32e1f7dcc8d7ca1f9606c409e8f3adb9b9170b9a --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c81791691fcb621f5f520c21461231c90b01e40e76c7482b7e2bb4e7f01cfd98 +size 108314087 diff --git a/tasks/taninmis2022/gurobi_solution/large_solution_2.json b/tasks/taninmis2022/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4c8bb6366784648fe088ea819da56e735ee1edd7 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9feec0e36c0d41e229b17d4eb575962a0e0359108354d87381693808156dfc82 +size 108305064 diff --git a/tasks/taninmis2022/gurobi_solution/large_solution_3.json b/tasks/taninmis2022/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..1524601b4540fdf42e10f836ff1eb65c378d2c16 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc07020076de3ce296a8850a4850d48ab4f83c9ebccb1fd4ad7ceb61e8c3293b +size 108289867 diff --git a/tasks/taninmis2022/gurobi_solution/large_solution_4.json b/tasks/taninmis2022/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..220c5f0cccb1f6d7acbfbf23ed07bccaa5fb38b6 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a721afaad25bdc57d232811d5c79803b44a76d9ecd8c1f1803e1dbaf10619bc +size 108259542 diff --git a/tasks/taninmis2022/gurobi_solution/large_solution_5.json b/tasks/taninmis2022/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c3c3ea7845f41b4513c3f3607a3d73adae875188 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae292c9c7e167a09b784a8d5dbc6b4bcd9a0872775fc3c8b09c37205d08ea1ed +size 108318321 diff --git a/tasks/taninmis2022/gurobi_solution/tiny_solution.json b/tasks/taninmis2022/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..561f3427d3bfaf69ffc84473efed8fa7b3ae01fc --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7992db712a2cf2c94887f9aa7c77610ef86663e9c3aacd35d450967d553ab36a +size 844093 diff --git a/tasks/taninmis2022/gurobi_solution_log/large_log_1.jsonl b/tasks/taninmis2022/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4435e37d59a4e097e0496143fe88fac42243b148 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f196694a8b3de820d37679a2278a191ec8f81e9759da0b9e14b1f2bd005e524 +size 1205 diff --git a/tasks/taninmis2022/gurobi_solution_log/large_log_2.jsonl b/tasks/taninmis2022/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d593b51636b712f993da9c0b025f4c92cd8be271 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b026387d416079b420d7c6ccf234a1a188713fe554694cb5d12df252aa0cd15 +size 2072 diff --git a/tasks/taninmis2022/gurobi_solution_log/large_log_3.jsonl b/tasks/taninmis2022/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..51553f2a7538e71916c04d19b9f69b90ad73d6c3 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9062464af717805c75c5c637eeb60e7615c64a8e9e643616f68b670450c036e +size 1724 diff --git a/tasks/taninmis2022/gurobi_solution_log/large_log_4.jsonl b/tasks/taninmis2022/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..74546229322b72f67d9c7c2a2ebd513d54eca8a8 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7b17f036d8455e0aef76b178b0ea49129eb72ee335d0198e705c4d2bd101c8e +size 1657 diff --git a/tasks/taninmis2022/gurobi_solution_log/large_log_5.jsonl b/tasks/taninmis2022/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd0864f389f8f8187e49272540b303911061c80d --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8699e5b2a2f3eabe1177cb5a271f1530ebe1ccb493d8415cc26f2ced6d407466 +size 1993 diff --git a/tasks/taninmis2022/gurobi_solution_log/tiny_log.jsonl b/tasks/taninmis2022/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..36ff6656df32cd351f677076def31efbfae66d21 --- /dev/null +++ b/tasks/taninmis2022/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e90ce0de5023f1292ec56d8d897767ff64603f14331257e83663cef9723df3a7 +size 493 diff --git a/tasks/taninmis2022/instance/large_instance_1.json b/tasks/taninmis2022/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..c85486f64fe2831b035c5ed409c42845763cef0d --- /dev/null +++ b/tasks/taninmis2022/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:565423c4673ff7afe6b2ff5594775d4b8a5647386082b52ced5794d4592f44c7 +size 690032 diff --git a/tasks/taninmis2022/instance/large_instance_2.json b/tasks/taninmis2022/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..723b97ff08561c1a76a5c333d4a6ea3f8f2be423 --- /dev/null +++ b/tasks/taninmis2022/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12e58bba5ccacc9d5029e1a34cd0fe55d9edcd78f706eeaa513b75e9012b5fba +size 690094 diff --git a/tasks/taninmis2022/instance/large_instance_3.json b/tasks/taninmis2022/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e383daebe31e67ca7c5fe0a73460ca81f83512ff --- /dev/null +++ b/tasks/taninmis2022/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6aa14511dd908f38ec7e4bcec9409c7aca1538686ac76fa938c97e9b4f7abed +size 689970 diff --git a/tasks/taninmis2022/instance/large_instance_4.json b/tasks/taninmis2022/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..792b65c632d7c906f73931ea32d3089f3639395c --- /dev/null +++ b/tasks/taninmis2022/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3656d750e315e8f1f9d7a989afb84955f510535c252b4fb10508a34c46e9634c +size 690359 diff --git a/tasks/taninmis2022/instance/large_instance_5.json b/tasks/taninmis2022/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..acdd1699630bcbb028c9070fedbec65d443f0684 --- /dev/null +++ b/tasks/taninmis2022/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:056741bab64da712f42f4feada6cb276bff254476c66e30ddb7e45dbc2cd1679 +size 690197 diff --git a/tasks/taninmis2022/instance/tiny_instance.json b/tasks/taninmis2022/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..aaeb941538620480c3530d841e0b73fd2169751e --- /dev/null +++ b/tasks/taninmis2022/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94dd5b32db9c5789f8623f00218560381fcc6ca5e46f85d4c34d07bc47633b06 +size 51460 diff --git a/tasks/taninmis2022/instance_schema.json b/tasks/taninmis2022/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..7c220afafa0512b6912ffd985b69e9a4ea16a01e --- /dev/null +++ b/tasks/taninmis2022/instance_schema.json @@ -0,0 +1,116 @@ +{ + "system": { + "system_name": " Name identifying the power system network.", + "num_buses": " Total number of buses (nodes) in the power network.", + "buses": " Identifiers for each bus in the network.", + "generators": [ + { + "id": " Unique identifier for this generator.", + "bus": " Bus where this generator is located.", + "existing": " Whether this generator is already built (true) or is a candidate for investment (false).", + "type": " Fuel or technology type of the generator (e.g., fossil, wind, solar).", + "a_cost": " Constant term of the quadratic generation cost function ($/h).", + "b_cost": " Linear term of the quadratic generation cost function ($/MWh).", + "c_cost": " Quadratic term of the quadratic generation cost function ($/MW^2h).", + "startup_cost": " Cost incurred each time the generator is started up ($).", + "Pmin_MW": " Minimum power output when the generator is committed (MW).", + "Pmax_MW": " Maximum power output capacity of the generator (MW).", + "min_on_h": " Minimum number of consecutive hours the generator must remain on once started.", + "min_off_h": " Minimum number of consecutive hours the generator must remain off once shut down.", + "ramp_MW_per_h": " Maximum change in power output between consecutive hours (MW/h).", + "capital_cost_per_kW": " Investment cost to build this candidate generator ($/kW), zero for existing units." + } + ], + "transmission_lines": [ + { + "id": " Unique identifier for this transmission line.", + "from_bus": " Bus at one end of the transmission line.", + "to_bus": " Bus at the other end of the transmission line.", + "existing": " Whether this line is already built (true) or is a candidate for investment (false).", + "flow_limit_MW": " Maximum power that can flow through this line in either direction (MW).", + "loss_factor": " Fraction of power lost during transmission on this line.", + "capital_cost_per_kW": " Investment cost to build this candidate line ($/kW), zero for existing lines." + } + ], + "storage": [ + { + "id": " Unique identifier for this energy storage unit.", + "bus": " Bus where this storage unit is located.", + "existing": " Whether this storage unit is already built (true) or is a candidate for investment (false).", + "capacity_MW": " Maximum energy that can be stored or discharged per hour (MW).", + "efficiency": " Round-trip efficiency of charging and discharging (fraction between 0 and 1).", + "capital_cost_per_kW": " Investment cost to build this candidate storage unit ($/kW)." + } + ], + "loads": [ + { + "bus": " Bus where this demand is located.", + "annual_peak_load_MW": " Peak electricity demand at this bus in the base year (MW)." + } + ] + }, + "scenario_parameters": { + "num_stages": " Number of investment decision stages in the planning horizon.", + "num_upper_level_scenarios": " Total number of leaf scenarios in the upper-level scenario tree.", + "num_lower_level_scenarios_per_day": " Number of operational uncertainty samples drawn per representative day.", + "num_representative_days": " Number of typical days used to represent annual operations.", + "hours_per_day": " Number of hourly time periods within each representative day.", + "investment_period_years": " Length of each investment stage in years.", + "upper_level_branching_factor": " Number of child nodes per parent in the scenario tree.", + "cost_variation_percent": " Fractional change in investment costs between high and low branches of the scenario tree.", + "demand_growth_high_percent": " Fractional demand growth per stage in the high-growth branch of the scenario tree.", + "demand_growth_low_percent": " Fractional demand growth per stage in the low-growth branch of the scenario tree." + }, + "scenario_tree": [ + { + "id": " Unique identifier for this scenario tree node.", + "stage": " Investment stage to which this node belongs.", + "parent_id": " Identifier of this node's parent node, null for the root.", + "probability": " Unconditional probability of reaching this node from the root.", + "children": " Identifiers of this node's child nodes, empty for leaf nodes." + } + ], + "representative_days": [ + { + "id": " Unique identifier for this representative day.", + "season": " Season of the year this day represents (spring, summer, fall, winter).", + "day_type": " Whether this is a weekday or weekend day.", + "load_profile": " Hourly fraction of peak load for this representative day.", + "solar_profile": " Hourly solar capacity factor for this representative day.", + "wind_weibull_params": { + "k": " Shape parameter of the Weibull distribution used to generate wind speeds for this day.", + "c": " Scale parameter of the Weibull distribution used to generate wind speeds for this day (m/s)." + } + } + ], + "lower_level_scenarios": { + "{representative_day_id}": [ + { + "scenario_id": " Identifier for this operational scenario within a representative day.", + "demand_multipliers": " Hourly random multiplier applied to the base load profile to produce realized demand.", + "solar_multipliers": " Hourly random multiplier applied to the base solar profile to produce realized solar output.", + "wind_power_factors": " Hourly realized wind power capacity factor derived from sampled wind speeds." + } + ] + }, + "global_parameters": { + "reserve_margin_requirement": " Required fraction of excess installed capacity above peak demand for system reliability.", + "storage_efficiency": " Round-trip efficiency applied to all storage units.", + "spinning_reserve_percent": " Fraction of hourly load that must be covered by online spinning reserve.", + "capital_costs_per_kW": { + "coal": " Reference investment cost for coal-fired generation ($/kW).", + "natural_gas": " Reference investment cost for natural gas generation ($/kW).", + "solar": " Reference investment cost for solar generation ($/kW).", + "wind": " Reference investment cost for wind generation ($/kW).", + "transmission_line": " Reference investment cost for transmission lines ($/kW).", + "energy_storage": " Reference investment cost for energy storage ($/kW)." + }, + "derating_factors": { + "fossil": " Capacity credit fraction for fossil generators toward the reserve margin.", + "wind": " Capacity credit fraction for wind generators toward the reserve margin.", + "solar": " Capacity credit fraction for solar generators toward the reserve margin." + }, + "wind_cutin_speed_m_per_s": " Minimum wind speed at which wind turbines begin producing power (m/s).", + "wind_rated_speed_m_per_s": " Wind speed at which wind turbines reach full rated output (m/s)." + } +} diff --git a/tasks/taninmis2022/mathematical_formulation.md b/tasks/taninmis2022/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..2814e4b04cc7a010d0e13d7ff034add84268abf8 --- /dev/null +++ b/tasks/taninmis2022/mathematical_formulation.md @@ -0,0 +1,109 @@ +# Sets and Indices + +- $\mathcal{N}$: nodes of the scenario tree, indexed by $n$; $|\mathcal{N}| = N$; $p(n)$ is the direct predecessor of $n$, with $p(1) = 0$. + +- $\mathscr{P}_n$: scenario path from the root to node $n$. + +- $\mathbb{J}$: buses of the transmission network, indexed by $j$. + +- $\hat{j} \in \{1,\ldots,\hat{R}\}$: reserve-margin regions; $\hat{J}(j) = \hat{j}$ maps buses to regions. + +- $\mathbb{G}_j,\, \mathbb{G}'_j$: existing / potential generators at bus $j$; $\mathbb{G} = \bigcup_j \mathbb{G}_j$, $\mathbb{G}' = \bigcup_j \mathbb{G}'_j$. + +- $\mathbb{L},\, \mathbb{L}'$: existing / potential transmission lines. + +- $\mathbb{S}_j,\, \mathbb{S}'_j$: existing / potential storage devices at bus $j$; $\mathbb{S},\, \mathbb{S}'$ aggregated. + +- $K_n$: representative days at node $n$; $H_k$: hours of day $k$, indexed by $h$. + +- $\mathbb{A},\, \mathbb{A}'$: ordered pairs $(i,j)$ with existing / potential transmission lines. + +# Parameters + +- $\pi_n$: probability of reaching node $n$. + +- $c^n_g, c^n_l, c^n_s$: building costs. + +- $a_g, a_l, a_s$: capacities of generators, lines, storages (MW). + +- $PK^n_{\hat{j}}, RM_{\hat{j}}, DF_g$: peak demand, reserve-margin fraction, derating factor. + +- $SC_g$: start-up cost. The FrontierOR benchmark uses the secant-linearized generation cost $a_g\alpha_g^h + (b_g+c_gP_g^{\max})p_g^h$. + +- $P^{\min}_g, P^{\max}_g$: generator output bounds. + +- $SR^h_j$: spinning-reserve requirement; $RU_g, RD_g$: ramp rates; $L_g$: minimum up time. + +- $D^h_j$: real-time demand; $F_l$: existing-line capacity; $B_{ij}$: transmission-loss fraction; $E_s$: withdrawal efficiency. + +# Decision Variables + +**Upper level (investment, per scenario-tree node $n$):** + +- $x^n_g, x^n_l, x^n_s \in \{0,1\}$: build-decision binaries for generator, line, storage. + +- $\kappa^n_g, \kappa^n_l, \kappa^n_s \ge 0$: available capacities (MW). + +**Lower level (unit commitment, per hour $h$):** + +- $\alpha^h_g \in \{0,1\}$: commitment status of generator $g$. + +- $\gamma^h_g \in \{0,1\}$: start-up indicator of generator $g$. + +- $p^h_g \ge 0$: energy generated (MWh). + +- $s^h_g \ge 0$: spinning reserve (MWh). + +- $u^h_s, v^h_s \ge 0$: storage withdrawal / injection (MWh). + +- $r^h_s \ge 0$: remaining energy in storage (MWh). + +- $f^h_{ij} \in \mathbb{R}$: *signed* energy flow on line $(i,j)$ (MWh), not split into directional components. + +# Upper-Level Investment Model (1a)–(1g) + +The expected total investment cost is $\min\sum_{n \in \mathcal{N}} \pi_n\,\text{TIC}^n(x_n)$, where $$\begin{align} + \text{TIC}^n(x_n) := \min \quad & \sum_{g \in \mathbb{G}'} c^n_g x^n_g + \sum_{l \in \mathbb{L}'} c^n_l x^n_l + \sum_{s \in \mathbb{S}'} c^n_s x^n_s \tag{1a} \\ + \text{s.t.}\quad & \kappa^n_g = \kappa^{p(n)}_g + a_g x^n_g, && \forall\, g \in \mathbb{G}' \tag{1b} \\ + & \kappa^n_l = \kappa^{p(n)}_l + a_l x^n_l, && \forall\, l \in \mathbb{L}' \tag{1c} \\ + & \kappa^n_s = \kappa^{p(n)}_s + a_s x^n_s, && \forall\, s \in \mathbb{S}' \tag{1d} \\ + & \kappa^n_g \le a_g,\ \kappa^n_l \le a_l,\ \kappa^n_s \le a_s, && \forall\, g \in \mathbb{G}',\, l \in \mathbb{L}',\, s \in \mathbb{S}' \tag{1e} \\ + & \sum_{j:\,\hat{J}(j)=\hat{j}} \!\Bigl(\sum_{g \in \mathbb{G}_j} DF_g\, a_g + \sum_{g \in \mathbb{G}'_j} DF_g\, \kappa^n_g \Bigr) \ge (1 + RM_{\hat{j}})\, PK^n_{\hat{j}}, && \forall\, \hat{j} \tag{1f} \\ + & \kappa^n_g, \kappa^n_l, \kappa^n_s \ge 0,\ \ x^n_g, x^n_l, x^n_s \in \{0,1\}, && \forall\, g \in \mathbb{G}',\, l \in \mathbb{L}',\, s \in \mathbb{S}' \tag{1g} +\end{align}$$ (At the root node $n=1$, $\kappa^0_\cdot = 0$.) + +# Lower-Level Unit-Commitment Model (2a)–(2o) + +For each node $n$ and representative day $k \in K_n$, the operating cost is $$\begin{align} + \min \quad & \text{TOC}^k_n = \sum_{h \in H_k} \sum_{g \in \mathbb{G} \cup \mathbb{G}'} \Bigl[ SC_g\, \gamma^h_g + a_g\alpha_g^h + (b_g+c_gP_g^{\max})p_g^h \Bigr] \tag{2a-B} +\end{align}$$ Equation (2a-B) defines the released FrontierOR linearized benchmark. It is the secant approximation of the source paper's convex quadratic cost over $[0,P_g^{\max}]$ and is the objective used by both the bundled Gurobi implementation and checker. Subject to $$\begin{align} + & \alpha^h_g \le \kappa^n_g / a_g, && \forall\, g \in \mathbb{G}',\, h \in H_k \tag{2b} \\ + & \alpha^\tau_g - 1 \le \alpha^h_g - \alpha^{h-1}_g \le \alpha^\tau_g, && \tau = h, \ldots, \min\{h + L_g - 1, |H_k|\},\notag\\ + & && g \in \mathbb{G} \cup \mathbb{G}',\, h \in H_k \tag{2c} \\ + & \gamma^h_g \ge \alpha^h_g - \alpha^{h-1}_g, && \forall\, g \in \mathbb{G} \cup \mathbb{G}',\, h = 2,\ldots,|H_k| \tag{2d} \\ + & p^h_g + s^h_g \le + \begin{cases} + P^{\max}_g \alpha^h_g, & g \in \mathbb{G} \\ + \kappa^n_g, & g \in \mathbb{G}' + \end{cases}, && \forall\, h \in H_k \tag{2e} \\ + & P^{\min}_g \alpha^h_g \le p^h_g, && \forall\, g \in \mathbb{G} \cup \mathbb{G}',\, h \in H_k \tag{2f} \\ + & \sum_{g \in \mathbb{G}_j \cup \mathbb{G}'_j} s^h_g \ge SR^h_j, && \forall\, j \in \mathbb{J},\, h \in H_k \tag{2g} \\ + & p^h_g - p^{h-1}_g \le RU_g,\ \ p^{h-1}_g - p^h_g \le RD_g, && \forall\, g \in \mathbb{G} \cup \mathbb{G}',\, h = 2, \ldots, |H_k| \tag{2h} \\ + & r^1_s = 0, \ \ r^h_s = r^{h-1}_s + E_s\, v^{h-1}_s - u^{h-1}_s, && \forall\, s \in \mathbb{S} \cup \mathbb{S}',\, h = 2,\ldots,|H_k| \tag{2i} \\ + & u^h_s \le r^h_s, && \forall\, s \in \mathbb{S} \cup \mathbb{S}',\, h \in H_k \tag{2j} \\ + & r^h_s \le \kappa^n_s, && \forall\, s \in \mathbb{S}',\, h \in H_k \tag{2k} \\ + & D^h_j + \sum_{i:(j,i) \in \mathbb{A} \cup \mathbb{A}'} f^h_{ji} - \sum_{i:(i,j) \in \mathbb{A} \cup \mathbb{A}'} (1 - B_{ij})\, f^h_{ij} \notag \\ + &\qquad = \sum_{g \in \mathbb{G}_j \cup \mathbb{G}'_j} p^h_g + \sum_{s \in \mathbb{S}_j \cup \mathbb{S}'_j} (u^h_s - v^h_s), && \forall\, j \in \mathbb{J},\, h \in H_k \tag{2l} \\ + & |f^h_{ij}| \le \kappa^n_{ij}, && \forall\, (i,j) \in \mathbb{A} \cup \mathbb{A}',\, h \in H_k \tag{2m} \\ + & \alpha^h_g,\ \gamma^h_g \in \{0,1\}, && \forall\, g \in \mathbb{G} \cup \mathbb{G}',\, h \in H_k \tag{2n} \\ + & p^h_g,\ s^h_g,\ r^h_s,\ u^h_s,\ v^h_s \ge 0,\ \ f^h_{ij} \in \mathbb{R}, && \forall\, g,\, (i,j),\, s,\, h \tag{2o} +\end{align}$$ Flow $f^h_{ij}$ is *signed* (not split into positive/negative directional components); its magnitude is bounded by line capacity $\kappa^n_{ij} \in \{F_l,\, \kappa^n_l\}$ in (2m). + +# Complete Compact MM-SMIP Formulation (3a)–(3d) + +$$\begin{align} + [\text{MM-SMIP}]\!:\;\; \min_{x,y} \quad & \sum_{n \in \mathcal{N}} \pi_n \Bigl[ \text{TIC}^n(x_n) + \sum_{k \in K_n} \mathbf{E}_{\zeta_{n_k}} \min_{y^k_n} \text{TOC}\bigl(y^k_n(\zeta_{n_k})\bigr) \Bigr] \tag{3a} \\ + \text{s.t.}\quad & B\, y^k_n(\zeta_{n_k}) \le V(\zeta_{n_k})\Bigl( b + \sum_{m \in \mathscr{P}_n} A_m\, x_m \Bigr), && \forall\, n \in \mathcal{N},\, k \in K_n,\, \zeta_{n_k} \in \Xi^{n_k} \tag{3b} \\ + & x_n \in X_n \cap \{0,1\}^{G' + L' + S'}, && \forall\, n \in \mathcal{N} \tag{3c} \\ + & y^k_n(\zeta_{n_k}) \in Y^k_n(\zeta_{n_k}), && \forall\, n \in \mathcal{N},\, k \in K_n,\, \zeta_{n_k} \in \Xi^{n_k} \tag{3d} +\end{align}$$ Here (3b) bundles the linkage constraints (2b), (2e), (2k), (2m) coupling upper- and lower-level decisions; (3c) collects upper-level constraints (1b)–(1g); (3d) collects the remaining lower-level UC constraints. diff --git a/tasks/taninmis2022/problem_description.txt b/tasks/taninmis2022/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..7331be0610d8aa7ece4cf69699f32d99532465cc --- /dev/null +++ b/tasks/taninmis2022/problem_description.txt @@ -0,0 +1,17 @@ +# Problem Description + +A power system operator must plan the expansion of generation, transmission, and energy storage infrastructure over a multi-stage planning horizon while simultaneously scheduling the hourly operation of all generation and storage units. The system consists of a set of buses connected by a transmission network. At each bus there may be existing generators, potential (candidate) generators, existing storage devices, potential storage devices, and electricity demand. Buses are grouped into reserve margin regions. The planning horizon is represented as a scenario tree, where each node corresponds to a stage and captures uncertainty in investment costs and long-run demand growth; each node has a known probability of being reached from the root. Within each scenario-tree node, system operations are evaluated over a set of representative days (capturing seasonal and weekday/weekend variation), and each representative day consists of a fixed number of hours. At the operational level, hourly renewable energy output and electricity demand are uncertain and modeled through multiple sampled realizations per representative day. + +The input data specifies, for each bus, the set of existing and candidate generators along with their maximum and minimum power output levels (in MW), start-up costs, generation-cost coefficients, ramp-up and ramp-down rates (in MW per hour), and a minimum up-and-down time (in hours) that applies equally to on and off periods. The FrontierOR benchmark uses the secant-linearized operating cost `a * alpha + (b + c * Pmax) * p`, where `alpha` is commitment and `p` is hourly generation. Thus the supplied `c` coefficient contributes to the linearized marginal rate; this benchmark does not optimize the original `c * p^2` quadratic term directly. Each candidate generator, transmission line, and storage device has a rated capacity (in MW) and a construction cost per unit capacity at each scenario-tree node. Each generator has a derating factor expressing the fraction of its nameplate capacity that counts toward resource adequacy. The data includes, for each existing and candidate transmission line, the flow limit (in MW) and the percentage of energy lost when power is transmitted along that line. For each existing and candidate storage device, a withdrawal efficiency (the fraction of injected energy that can later be withdrawn) and a rated energy capacity are given. Each bus with load has a peak demand value, and hourly demand at each bus in each representative day is specified as a fraction of peak demand via a load profile. Solar generators have hourly capacity profiles, and wind generators have Weibull distribution parameters from which hourly output realizations are sampled. A reserve margin requirement (as a percentage above peak demand) is specified for each reserve margin region, and a spinning reserve requirement (as a percentage of hourly demand) is specified for each bus. + +The operator must decide, at each scenario-tree node, which candidate generators, transmission lines, and storage devices to build. These are once-and-for-all decisions: each candidate infrastructure may be built at most once over the entire planning horizon. The available capacity of each candidate infrastructure at a given scenario-tree node equals its available capacity at the predecessor node plus its rated capacity if it is built at the current node, and this available capacity can never exceed the rated capacity. At the root node, all candidate available capacities start at zero. For each representative day within each scenario-tree node, and for each sampled realization of hourly uncertainties, the operator must also decide the hourly commitment status (on or off) and start-up status of every generator, the hourly power output and spinning reserve contribution of every generator, the hourly energy withdrawal from and injection into every storage device, the hourly stored energy level in every storage device, and the hourly power flow on every transmission line. + +A candidate generator may only be committed in a given hour if it has been built by that scenario-tree node; specifically, its commitment status in any hour cannot exceed the ratio of its available capacity to its rated capacity (which is either zero or one). Once a generator is turned on, it must remain on for at least its minimum up-and-down time; for every hour in which a generator transitions from off to on, its commitment status must remain at one for at least the specified number of consecutive hours (or through the end of the day if fewer hours remain). Symmetrically, once a generator is turned off, it must remain off for at least the same number of hours; for every hour in which a generator transitions from on to off, its commitment status must remain at zero for at least the minimum up-and-down time in consecutive hours (or through the end of the day if fewer hours remain). A generator is recognized as starting up in an hour if its commitment status in that hour exceeds its commitment status in the previous hour; the start-up indicator must be at least as large as this difference. The sum of a generator's power output and spinning reserve contribution in any hour is bounded above by the maximum power output times the commitment status for existing generators, or by the available capacity for candidate generators. When a generator is committed, its power output must be at least its minimum power output times the commitment status. The total spinning reserve provided by all generators at each bus must meet or exceed the spinning reserve requirement at that bus in every hour. The change in a generator's power output between consecutive hours is limited by its ramp-up rate (for increases) and ramp-down rate (for decreases). + +Each storage device begins each representative day with zero stored energy. In each subsequent hour, the stored energy equals the previous hour's stored energy plus the withdrawal efficiency times the energy injected in the previous hour minus the energy withdrawn in the previous hour. Energy withdrawn from a storage device in any hour cannot exceed its current stored energy. For candidate storage devices, the stored energy in any hour cannot exceed the available capacity established by the expansion decisions at the current scenario-tree node. + +At every bus and every hour, energy balance must hold: the demand at the bus plus the total energy sent out on all lines departing that bus minus the total energy received on all lines arriving at that bus (after subtracting transmission losses) must equal the total power generated at that bus plus the net withdrawal (withdrawal minus injection) from all storage devices at that bus. The power flow on each transmission line in every hour is limited by the line's capacity, which for existing lines is the given flow limit and for candidate lines is the available capacity from the expansion decisions. + +In each reserve margin region, the sum of the derated capacities of all existing generators plus the derated available capacities of all candidate generators across all buses in the region must be at least one plus the reserve margin requirement times the peak demand in that region at the current scenario-tree node. + +The goal is to minimize the probability-weighted sum, over all scenario-tree nodes, of the total investment cost at that node plus the expected total operating cost across all representative days and sampled realizations at that node. The investment cost at a node is the sum of construction costs for all generators, transmission lines, and storage devices built at that node. The operating cost for a representative day under a given realization is the sum over all hours of start-up costs plus the benchmark's secant-linearized generation cost `a * alpha + (b + c * Pmax) * p`. diff --git a/tasks/taninmis2022/solution_logger.py b/tasks/taninmis2022/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/taninmis2022/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/taninmis2022/solution_schema.json b/tasks/taninmis2022/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1fe2b16183f9f447699184629a1160ac512ace26 --- /dev/null +++ b/tasks/taninmis2022/solution_schema.json @@ -0,0 +1,19 @@ +{ + "objective_value": " Total expected cost across the scenario tree, combining capital investment expenditures and expected operational costs.", + "alpha": " Complete generator commitment variables keyed by scenario-tree node, representative day, lower-level scenario, hour, and generator.", + "gamma": " Complete generator startup variables using the same composite key convention.", + "p_gen": " Complete generator dispatch variables in MW.", + "s_res": " Complete generator reserve variables in MW.", + "f_fwd": " Complete forward transmission-flow variables in MW.", + "f_bwd": " Complete backward transmission-flow variables in MW.", + "u_stor": " Complete storage charging variables.", + "v_stor": " Complete storage discharging variables.", + "r_stor": " Complete storage state-of-charge variables.", + "investments": { + "": { + "generators": " Whether each candidate generator is built at this scenario tree node (1 = build, 0 = do not build).", + "lines": " Whether each candidate transmission line is built at this scenario tree node (1 = build, 0 = do not build).", + "storage": " Whether each candidate storage unit is built at this scenario tree node (1 = build, 0 = do not build)." + } + } +} diff --git a/tasks/tran2018/feasibility_check.py b/tasks/tran2018/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..0f6b0f3cef47a1dbe3c1a9fcf79766eaba5b6253 --- /dev/null +++ b/tasks/tran2018/feasibility_check.py @@ -0,0 +1,533 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Alternative-Fuel Station Location Problem (ASLP) +as formulated in Tran, Nagy, Nguyen, Wassan (2018). + +Checks the three hard constraints from the [ASLP] formulation: + Constraint 1 (Eq 15): Arc coverage — for each refueled OD pair q (y_q=1), + every directed arc on the round-trip path must be covered by at least + one open station in K^q_{jk}. + Constraint 2 (Eq 16): Station count — exactly p stations are located. + Constraint 3 (Eq 17): Binary integrality — x_i, y_q in {0, 1}. + Constraint 4 (Eq 14, obj consistency): Reported objective_value must equal + the recomputed sum_q f_q * y_q (Tier C defense against score-gaming). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'refueled_od_pairs', 'stations') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +TOL = 1e-5 +EPS = 1e-5 + + +def load_json(path): + with open(path, 'r') as f: + return json.load(f) + + +def build_arc_distance_lookup(arcs): + """Build bidirectional distance lookup from arc list.""" + dist = {} + for arc in arcs: + i, j, d = arc['from'], arc['to'], arc['distance'] + dist[(i, j)] = d + dist[(j, i)] = d + return dist + + +def compute_K_sets(od_pairs, arc_dist, R): + """ + For each OD pair, compute K^q_{jk} for each directed arc on the round trip. + + Returns a list (one per OD pair) of lists of (K_set, covered_by_origin) tuples. + K_set is the set of candidate node IDs; covered_by_origin indicates whether + the arc is automatically covered by the vehicle's initial full tank. + """ + all_arc_info = [] + + for q_idx, od in enumerate(od_pairs): + path = od['shortest_path'] + L = len(path) + + if L < 2: + all_arc_info.append([]) + continue + + # Edge distances along the path + edge_dists = [] + for i in range(L - 1): + d = arc_dist.get((path[i], path[i + 1])) + if d is None: + raise ValueError( + f"No arc distance for ({path[i]}, {path[i+1]}) " + f"on OD pair {q_idx}" + ) + edge_dists.append(d) + + # Round-trip: 2L-1 positions, 2(L-1) arcs + num_positions = 2 * L - 1 + num_arcs = 2 * (L - 1) + + # Node at each round-trip position + rt_nodes = list(path) + list(reversed(path[:-1])) + + # Cumulative distances along the round trip + rt_cum = [0.0] * num_positions + for p_pos in range(1, num_positions): + if p_pos < L: + rt_cum[p_pos] = rt_cum[p_pos - 1] + edge_dists[p_pos - 1] + else: + ret_edge_idx = 2 * (L - 1) - p_pos + rt_cum[p_pos] = rt_cum[p_pos - 1] + edge_dists[ret_edge_idx] + + arc_info = [] + for p in range(num_arcs): + arc_end_cum = rt_cum[p + 1] + + # Origin's initial full tank covers this arc? + if arc_end_cum <= R + 1e-9: + arc_info.append((set(), True)) + continue + + # Find all positions c <= p where refueling covers this arc + K = set() + for c in range(p + 1): + if arc_end_cum - rt_cum[c] <= R + 1e-9: + K.add(rt_nodes[c]) + + arc_info.append((K, False)) + + all_arc_info.append(arc_info) + + return all_arc_info + + +def determine_y_values(solution, od_pairs, all_arc_info, open_stations_set): + """ + Determine y_q values from the solution. + + If the solution has 'refueled_od_pairs', use those (y_q=1 for listed indices). + Otherwise, compute y_q: y_q=1 iff every non-origin-covered arc on the + round trip of OD pair q has at least one open station in its K set. + """ + num_q = len(od_pairs) + y = [0] * num_q + + if 'refueled_od_pairs' in solution: + for q_idx in solution['refueled_od_pairs']: + if 0 <= q_idx < num_q: + y[q_idx] = 1 + else: + # Infer y_q from station placement + for q_idx in range(num_q): + arc_info = all_arc_info[q_idx] + refueled = True + for K_set, covered_by_origin in arc_info: + if covered_by_origin: + continue + if len(K_set.intersection(open_stations_set)) == 0: + refueled = False + break + y[q_idx] = 1 if refueled else 0 + + return y + + +def check_feasibility(instance, solution): + """ + Check all hard constraints and return feasibility result. + """ + n = instance['parameters']['n'] + p = instance['parameters']['p'] + R = instance['parameters']['R'] + nodes = instance['nodes'] + arcs = instance['arcs'] + od_pairs = instance['od_pairs'] + + node_ids = set(node['id'] for node in nodes) + arc_dist = build_arc_distance_lookup(arcs) + + # Extract solution + stations = solution.get('stations', []) + open_stations_set = set(stations) + + # Compute K sets + all_arc_info = compute_K_sets(od_pairs, arc_dist, R) + + # Determine y_q values + y = determine_y_values(solution, od_pairs, all_arc_info, open_stations_set) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ========================================================================= + # Constraint 1 (Eq 15): Arc coverage + # sum_{i in K^q_{jk}} x_i >= y_q + # For each refueled OD pair (y_q=1), every arc must have at least one + # open station in K^q_{jk}. + # ========================================================================= + for q_idx in range(len(od_pairs)): + if y[q_idx] != 1: + continue + + arc_info = all_arc_info[q_idx] + od = od_pairs[q_idx] + + for arc_idx, (K_set, covered_by_origin) in enumerate(arc_info): + if covered_by_origin: + continue + + # LHS = number of open stations in K^q_{jk} + lhs = len(K_set.intersection(open_stations_set)) + rhs = 1.0 # y_q = 1 + + # >= constraint: violation if rhs > lhs + violation_amount = rhs - lhs + if violation_amount > TOL: + violated_constraints.add(1) + origin = od['origin'] + dest = od['destination'] + violations.append( + f"Constraint 1 (Eq 15): OD pair {q_idx} " + f"(origin={origin}, dest={dest}) arc index {arc_idx} " + f"has no open station in K set to cover it " + f"(|K ∩ open| = {lhs}, need >= {rhs})" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint 2 (Eq 16): Station count + # sum_{i in N} x_i = p + # ========================================================================= + lhs = len(stations) + rhs = p + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + violated_constraints.add(2) + violations.append( + f"Constraint 2 (Eq 16): Number of stations is {lhs}, " + f"expected exactly {rhs}" + ) + normalizer = max(abs(rhs), EPS) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer) + }) + + # ========================================================================= + # Constraint 3 (Eq 17): Binary integrality + # x_i in {0, 1} for all i in N + # y_q in {0, 1} for all q in Q + # ========================================================================= + # Check x_i: stations must be valid node IDs (each appearing at most once) + # and all values are implicitly 0 or 1 by the list representation. + # Check for duplicate stations + if len(stations) != len(set(stations)): + violated_constraints.add(3) + from collections import Counter + counts = Counter(stations) + dups = {s: c for s, c in counts.items() if c > 1} + violations.append( + f"Constraint 3 (Eq 17): Duplicate station IDs found: {dups}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(len(stations)), + "rhs": float(len(set(stations))), + "raw_excess": float(len(stations) - len(set(stations))), + "normalizer": float(max(abs(len(set(stations))), EPS)), + "ratio": float((len(stations) - len(set(stations))) / + max(abs(len(set(stations))), EPS)) + }) + + # Check that all station IDs are valid nodes + invalid_stations = open_stations_set - node_ids + if invalid_stations: + violated_constraints.add(3) + violations.append( + f"Constraint 3 (Eq 17): Station IDs not in node set N: " + f"{sorted(invalid_stations)}" + ) + for inv_id in sorted(invalid_stations): + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(inv_id), + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": float(EPS), + "ratio": float(1.0 / EPS) + }) + + # Check y_q integrality (if provided explicitly) + if 'refueled_od_pairs' in solution: + for q_idx in solution['refueled_od_pairs']: + if q_idx < 0 or q_idx >= len(od_pairs): + violated_constraints.add(3) + violations.append( + f"Constraint 3 (Eq 17): refueled_od_pairs index {q_idx} " + f"is out of range [0, {len(od_pairs)-1}]" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(q_idx), + "rhs": float(len(od_pairs) - 1), + "raw_excess": float(q_idx - (len(od_pairs) - 1)), + "normalizer": float(max(abs(len(od_pairs) - 1), EPS)), + "ratio": float((q_idx - (len(od_pairs) - 1)) / + max(abs(len(od_pairs) - 1), EPS)) + }) + + # ========================================================================= + # Constraint 4 (Eq 14, obj consistency): Reported objective_value must + # match recomputed z_0 = sum_q f_q * y_q. Tier C defense against + # LLM score-gaming exploits (e.g. obj=sys.float_info.max). + # ========================================================================= + reported_obj = solution.get('objective_value') + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None and not (math.isnan(reported) or math.isinf(reported)): + true_obj = 0.0 + for q_idx in range(len(od_pairs)): + if y[q_idx] == 1: + true_obj += float(od_pairs[q_idx].get('flow', 0.0)) + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + violated_constraints.add(4) + violations.append( + f"Constraint 4 (Eq 14, obj consistency): reported " + f"objective_value={reported} differs from recomputed " + f"sum_q f_q * y_q={true_obj} " + f"(|diff|={abs_diff:.6g}, tol={tol:.6g})" + ) + normalizer = max(abs(true_obj), EPS) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer) + }) + elif reported is not None: + # NaN/Inf reported obj: reject as obj-consistency violation. + violated_constraints.add(4) + violations.append( + f"Constraint 4 (Eq 14, obj consistency): reported " + f"objective_value={reported_obj} is not a finite number" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float('inf') if math.isinf(reported) else float('nan'), + "rhs": 0.0, + "raw_excess": float('inf'), + "normalizer": float(EPS), + "ratio": float('inf') + }) + + # Build result + feasible = len(violated_constraints) == 0 + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for ASLP (Tran et al., 2018)" + ) + parser.add_argument('--instance_path', type=str, required=True, + help="Path to the JSON instance file") + parser.add_argument('--solution_path', type=str, required=True, + help="Path to the JSON solution file") + parser.add_argument('--result_path', type=str, required=True, + help="Path to write the JSON feasibility result") + args = parser.parse_args() + + instance = load_json(args.instance_path) + solution = load_json(args.solution_path) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result['feasible']: + print(f"FEASIBLE — no constraint violations detected.") + 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/tran2018/gurobi_code.py b/tasks/tran2018/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..48bfe9ea05792a93bdf425d816e68b88330f08e2 --- /dev/null +++ b/tasks/tran2018/gurobi_code.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Alternative-Fuel Station Location Problem (ASLP) +using the [P3] arc-cover/path-cover formulation from Capar et al. (2013), +as adopted in: + +Tran, Nagy, Nguyen, Wassan (2018) "An Efficient Heuristic Algorithm for the +Alternative-Fuel Station Location Problem", EJOR. + +Formulation [ASLP]: + max z_0 = sum_{q in Q} f_q * y_q + s.t. sum_{i in K^q_{jk}} x_i >= y_q, for all q in Q, arc (j,k) in A_q + sum_{i in N} x_i = p + x_i in {0,1}, y_q in {0,1} (y_q relaxed to [0,1] per paper Table 1) + +K^q_{jk} computation uses the round-trip path: the vehicle starts at the +origin with a full tank (range R). For each directed arc on the round trip, +K^q_{jk} is the set of nodes that could have refueled the vehicle such that +it has enough fuel to traverse the arc. +""" + +import argparse +import json +import sys + +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(path): + """Load problem instance from JSON file.""" + with open(path, 'r') as f: + return json.load(f) + + +def build_arc_distance_lookup(arcs): + """Build bidirectional distance lookup from arc list.""" + dist = {} + for arc in arcs: + i, j, d = arc['from'], arc['to'], arc['distance'] + dist[(i, j)] = d + dist[(j, i)] = d + return dist + + +def compute_K_sets(od_pairs, arc_dist, R): + """ + For each OD pair, compute K^q_{jk} for each directed arc on the round trip. + + The round-trip path visits nodes in order: + Forward: n_0, n_1, ..., n_{L-1} + Return: n_{L-2}, n_{L-3}, ..., n_0 + + The vehicle starts at the origin (pos 0) with a full tank of range R. + Any arc whose cumulative distance from the origin is <= R is automatically + covered by the initial fuel and needs no constraint. + + For other arcs, K^q_{jk} = set of nodes at positions c <= p on the round + trip such that rt_cum[p+1] - rt_cum[c] <= R. + + Returns a list of dicts (one per OD pair), each with: + 'arc_constraints': list of {'K': set of node IDs, 'covered': bool} + 'path_nodes': set of node IDs on the path + 'flow': traffic flow volume + """ + all_od_info = [] + + for q_idx, od in enumerate(od_pairs): + path = od['shortest_path'] + L = len(path) + flow = od['flow'] + + if L < 2: + all_od_info.append({ + 'arc_constraints': [], + 'path_nodes': set(path), + 'flow': flow + }) + continue + + # Edge distances along the path + edge_dists = [] + for i in range(L - 1): + d = arc_dist.get((path[i], path[i + 1])) + if d is None: + raise ValueError( + f"No arc distance for ({path[i]}, {path[i+1]}) " + f"on OD pair {q_idx}" + ) + edge_dists.append(d) + + # Round-trip: 2L-1 positions, 2(L-1) arcs + num_positions = 2 * L - 1 + num_arcs = 2 * (L - 1) + + # Node at each round-trip position + rt_nodes = list(path) + list(reversed(path[:-1])) + + # Cumulative distances along the round trip + rt_cum = [0.0] * num_positions + for p in range(1, num_positions): + if p < L: + rt_cum[p] = rt_cum[p - 1] + edge_dists[p - 1] + else: + # Return arc at position p-1 corresponds to forward edge + # at index (2*(L-1) - p) + ret_edge_idx = 2 * (L - 1) - p + rt_cum[p] = rt_cum[p - 1] + edge_dists[ret_edge_idx] + + # For each arc on the round trip, compute K set + arc_constraints = [] + for p in range(num_arcs): + arc_end_cum = rt_cum[p + 1] + + # Check if the origin's initial full tank covers this arc + if arc_end_cum <= R + 1e-9: + arc_constraints.append({'K': set(), 'covered': True}) + continue + + # Find all positions c <= p where refueling at c covers this arc + K = set() + for c in range(p + 1): + if arc_end_cum - rt_cum[c] <= R + 1e-9: + K.add(rt_nodes[c]) + + # Position 0 (origin) cannot be in K here since arc_end_cum > R, + # meaning rt_cum[p+1] - rt_cum[0] = rt_cum[p+1] > R. + # So origin's initial fuel is already accounted for. + + arc_constraints.append({'K': K, 'covered': False}) + + all_od_info.append({ + 'arc_constraints': arc_constraints, + 'path_nodes': set(path), + 'flow': flow + }) + + return all_od_info + + +def main(): + parser = argparse.ArgumentParser( + description="ASLP Solver using Gurobi (P3 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) + + # Load instance + instance = load_instance(args.instance_path) + + n = instance['parameters']['n'] + p = instance['parameters']['p'] + R = instance['parameters']['R'] + nodes = instance['nodes'] + arcs = instance['arcs'] + od_pairs = instance['od_pairs'] + + node_ids = [node['id'] for node in nodes] + + # Build arc distance lookup + arc_dist = build_arc_distance_lookup(arcs) + + # Compute K sets for all OD pairs + all_od_info = compute_K_sets(od_pairs, arc_dist, R) + + # ======================================================================== + # Build Gurobi model for [ASLP] + # ======================================================================== + model = gp.Model("ASLP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + model.setParam("OutputFlag", 1) + + # Decision variables + # x_i: binary, 1 if station at node i + x = {} + for i in node_ids: + x[i] = model.addVar(vtype=GRB.BINARY, name=f"x_{i}") + + # y_q: continuous [0,1] (relaxed from binary per paper Table 1 note: + # "y_q can be relaxed to continuous without affecting optimal integer solution") + y = {} + for q_idx in range(len(od_pairs)): + y[q_idx] = model.addVar( + vtype=GRB.CONTINUOUS, lb=0.0, ub=1.0, name=f"y_{q_idx}" + ) + + model.update() + + # Objective (14): maximize total refueled traffic flow + model.setObjective( + gp.quicksum(all_od_info[q]['flow'] * y[q] + for q in range(len(od_pairs))), + GRB.MAXIMIZE + ) + + # Constraint (16): exactly p stations + model.addConstr( + gp.quicksum(x[i] for i in node_ids) == p, + "station_count" + ) + + # Constraint (15): arc coverage for each OD pair and each arc + for q_idx, od_info in enumerate(all_od_info): + for arc_idx, arc_con in enumerate(od_info['arc_constraints']): + if arc_con['covered']: + # Arc covered by initial fuel at origin - no constraint needed + continue + + K = arc_con['K'] + if len(K) == 0: + # No node can cover this arc -> flow cannot be refueled + model.addConstr( + y[q_idx] == 0, + f"infeasible_q{q_idx}_a{arc_idx}" + ) + else: + model.addConstr( + gp.quicksum(x[i] for i in K) >= y[q_idx], + f"arc_cover_q{q_idx}_a{arc_idx}" + ) + + # Solve + model.optimize() + + # ======================================================================== + # Extract and output solution + # ======================================================================== + solution = {} + if model.SolCount > 0: + solution['objective_value'] = model.ObjVal + solution['stations'] = [i for i in node_ids if x[i].X > 0.5] + solution['refueled_od_pairs'] = [ + q_idx for q_idx in range(len(od_pairs)) if y[q_idx].X > 0.5 + ] + if model.Status == GRB.OPTIMAL: + solution['status'] = 'optimal' + elif model.Status == GRB.TIME_LIMIT: + solution['status'] = 'time_limit' + else: + solution['status'] = 'feasible' + solution['gap'] = model.MIPGap + else: + solution['objective_value'] = 0.0 + solution['stations'] = [] + solution['refueled_od_pairs'] = [] + solution['status'] = 'no_solution' + solution['gap'] = float('inf') + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Solution written to {args.solution_path}") + print(f"Objective value: {solution['objective_value']}") + print(f"Status: {solution['status']}") + + +if __name__ == '__main__': + main() diff --git a/tasks/tran2018/gurobi_feasi_result/large_feasi_result_1.json b/tasks/tran2018/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/tran2018/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/tran2018/gurobi_feasi_result/large_feasi_result_2.json b/tasks/tran2018/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/tran2018/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/tran2018/gurobi_feasi_result/large_feasi_result_3.json b/tasks/tran2018/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/tran2018/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/tran2018/gurobi_feasi_result/large_feasi_result_4.json b/tasks/tran2018/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/tran2018/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/tran2018/gurobi_feasi_result/large_feasi_result_5.json b/tasks/tran2018/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/tran2018/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/tran2018/gurobi_feasi_result/tiny_feasi_result.json b/tasks/tran2018/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/tran2018/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/tran2018/gurobi_solution/large_solution_1.json b/tasks/tran2018/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a289f04f8c2b875dbb4505078c4ad7137da29781 --- /dev/null +++ b/tasks/tran2018/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dce9c9f5264643a2240b537688df4ef8f855d8cee3bb306eeb70391eebcbf790 +size 8740 diff --git a/tasks/tran2018/gurobi_solution/large_solution_2.json b/tasks/tran2018/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..1b4fd9b14f054da600e9f1d1ef09d7be2d97997d --- /dev/null +++ b/tasks/tran2018/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:646a5d67b1dde137f2729841954516c557d5ed2dab9a103163b39406ad7c7c76 +size 3658 diff --git a/tasks/tran2018/gurobi_solution/large_solution_3.json b/tasks/tran2018/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..8740d743b9331888559331af552233d7c235378f --- /dev/null +++ b/tasks/tran2018/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fed0eb76c4929a463195cbe085df14ec56cf2645f1076ca844411bf26cd3ca2 +size 4604 diff --git a/tasks/tran2018/gurobi_solution/large_solution_4.json b/tasks/tran2018/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..b3d0c184f25a36d4a07d4459df1488a8e4b36519 --- /dev/null +++ b/tasks/tran2018/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8529a6115e7b635b4cbba1d76c3abc4399fab6c66b41bb5bd15398b2cdb52ade +size 7984 diff --git a/tasks/tran2018/gurobi_solution/large_solution_5.json b/tasks/tran2018/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ff61d54c5428683350dca335acd7d3ec728eea03 --- /dev/null +++ b/tasks/tran2018/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:230a8840845c7248774a8fd44470190c2b5968295d3933850b4c222f9af9bba3 +size 10839 diff --git a/tasks/tran2018/gurobi_solution/tiny_solution.json b/tasks/tran2018/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..c6c11ef2774495caa3b006c7a6ed7d582a7c3ceb --- /dev/null +++ b/tasks/tran2018/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:daa8dd8bc8107f8d983c633cb7185d0268cb4b6efccb17794ddb94fbd4cc063e +size 225 diff --git a/tasks/tran2018/gurobi_solution_log/large_log_1.jsonl b/tasks/tran2018/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..14d0487163f6cab392af0df9302521b31afe205a --- /dev/null +++ b/tasks/tran2018/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e693f43d517b7f39ea5891c3923b9256cf6903c0bffa2aa31b24e28998c3904 +size 55 diff --git a/tasks/tran2018/gurobi_solution_log/large_log_2.jsonl b/tasks/tran2018/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a496f3bbbd727fb45c988005b5c96ebbd847c24d --- /dev/null +++ b/tasks/tran2018/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41217f02bd22847b1963cdd62c3fcda231dd26a62b6b684cdead63c12d4dc978 +size 54 diff --git a/tasks/tran2018/gurobi_solution_log/large_log_3.jsonl b/tasks/tran2018/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9a6064933f5feb460e5af1a00549adfd98f09391 --- /dev/null +++ b/tasks/tran2018/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8345ad741fc244f33e71dca9e74ee9dacd0274484b1387270e484b9ecb157e06 +size 55 diff --git a/tasks/tran2018/gurobi_solution_log/large_log_4.jsonl b/tasks/tran2018/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..971f8fe475e2f666d9da5bc80d08e8aed699d61d --- /dev/null +++ b/tasks/tran2018/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1f53e2f017485f1b0e5378d96744d873680a98f67de8c6b2ab29ea854fee94c +size 48 diff --git a/tasks/tran2018/gurobi_solution_log/large_log_5.jsonl b/tasks/tran2018/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c355b173d8b88e8526bd69329651e09c585ca8b --- /dev/null +++ b/tasks/tran2018/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf22c332477fcd181f890124227dbf48b6ff2e35d0442e76fde9f75ae8621b3b +size 48 diff --git a/tasks/tran2018/gurobi_solution_log/tiny_log.jsonl b/tasks/tran2018/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5bfa6c191d93b4b94a01888e0d69cfe39d4c6380 --- /dev/null +++ b/tasks/tran2018/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78cd66aa61a5c8ee8913d1d0cde0f530bcac7d0183eb78c382b8c402746c4dcd +size 46 diff --git a/tasks/tran2018/instance/large_instance_1.json b/tasks/tran2018/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..0b1199bc0ee3b9840e3f1ac611d80c78adbf0117 --- /dev/null +++ b/tasks/tran2018/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c75772313ec3018b21b786e859dd41c0749f391bd169e84a86738088083d71ba +size 1326580 diff --git a/tasks/tran2018/instance/large_instance_2.json b/tasks/tran2018/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..67dc4b450639750e046fab44bd9b68599df60b71 --- /dev/null +++ b/tasks/tran2018/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05770a957972bc14f124c0e630c2e8a67f9095e52ff62c22cc25fb66f4f1b865 +size 1297482 diff --git a/tasks/tran2018/instance/large_instance_3.json b/tasks/tran2018/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..014df3ef8ffea007b57b32d601aad6c8f963f4ba --- /dev/null +++ b/tasks/tran2018/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffc5bfce14c95dc7ca75f633c37c29ed8da5a86b9cf2a57cb0f07303d24d59df +size 1305210 diff --git a/tasks/tran2018/instance/large_instance_4.json b/tasks/tran2018/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d2c335b0af6c686cbcea85834b0b99c62394ac0b --- /dev/null +++ b/tasks/tran2018/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f48e1374e294fb3a8a88a56a2e538e54d38e3a7ecd7c14243d9985b9a945f3e +size 1286416 diff --git a/tasks/tran2018/instance/large_instance_5.json b/tasks/tran2018/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..9351c7dc5e9a90b184a1addca0f4b4db57d3a83d --- /dev/null +++ b/tasks/tran2018/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf4c7c396c6ed45b491c5c333177da07ee02c83b9ec36233ab137196d1401447 +size 1310726 diff --git a/tasks/tran2018/instance/tiny_instance.json b/tasks/tran2018/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..6a7a5238dee7e62a27b876ab94b71a66d900cc0c --- /dev/null +++ b/tasks/tran2018/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1c5f4f0c00b9ede61d20079c05e2dccf99a5fcbc7d86f5e2d1b6cc491187672 +size 15951 diff --git a/tasks/tran2018/instance_schema.json b/tasks/tran2018/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..c409d77a3896872753fb6f8f0e2a3b834ca5683f --- /dev/null +++ b/tasks/tran2018/instance_schema.json @@ -0,0 +1,35 @@ +{ + "parameters": { + "n": " Total number of nodes in the transportation network.", + "num_arcs": " Total number of undirected arcs connecting nodes in the network.", + "m": " Number of nodes designated as origin-destination (OD) nodes.", + "num_od_pairs": " Total number of origin-destination pairs with traffic flow.", + "R": " Maximum distance a vehicle can travel on a full tank before needing to refuel.", + "p": " Number of refueling stations to be located." + }, + "nodes": [ + { + "id": " Unique identifier for this node.", + "x": " Horizontal coordinate of this node in the network.", + "y": " Vertical coordinate of this node in the network.", + "weight": " Population proxy weight of this node, used to compute traffic flow via the gravity model." + } + ], + "arcs": [ + { + "from": " Node identifier at one end of this arc.", + "to": " Node identifier at the other end of this arc.", + "distance": " Euclidean distance of this arc between its two endpoint nodes." + } + ], + "od_nodes": " Node identifiers designated as origin-destination nodes.", + "od_pairs": [ + { + "origin": " Node identifier where this traffic flow originates.", + "destination": " Node identifier where this traffic flow is destined.", + "flow": " Volume of round-trip traffic traveling between the origin and destination.", + "shortest_path": " Ordered sequence of node identifiers forming the shortest path from origin to destination.", + "path_distance": " Total distance of the shortest path from origin to destination." + } + ] +} diff --git a/tasks/tran2018/mathematical_formulation.md b/tasks/tran2018/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..39ea613b68035ae5a20e00c13b5cdf00016c3173 --- /dev/null +++ b/tasks/tran2018/mathematical_formulation.md @@ -0,0 +1,37 @@ +# Sets and Indices + +- $N = \{1,2,\ldots,n\}$: set of nodes (candidate station locations), indexed by $i$. + +- $Q$: set of paths (origin-destination pairs), indexed by $q$. + +- $\vec{a}_{jk}$: directed arc from node $j$ to node $k$. + +- $\vec{A}_q$: set of directed arcs traversed on path $q$, sorted from origin to destination and back (round trip). + +- $K^q_{jk}$: set of candidate nodes whose refueling allows a vehicle (with range $R$) to traverse arc $\vec{a}_{jk} \in \vec{A}_q$ without running out of fuel. + +# Parameters + +- $f_q$: volume of traffic flow on path $q \in Q$. + +- $p$: number of stations to be located. + +- $R$: driving range of the vehicles. + +# Decision Variables + +- $x_i \in \{0,1\}$: equals $1$ if a station is located at node $i \in N$, $0$ otherwise. + +- $y_q \in \{0,1\}$: equals $1$ if the flow on path $q \in Q$ is refueled, $0$ otherwise. + +# Formulation \[ASLP\] + +$$\begin{align} + \max \quad z_0 &= \sum_{q \in Q} f_q\, y_q \tag{14} \\ + \text{s.t.}\quad + \sum_{i \in K^q_{jk}} x_i &\ge y_q, && \forall\, q \in Q,\ \vec{a}_{jk} \in \vec{A}_q \tag{15} \\ + \sum_{i \in N} x_i &= p \tag{16} \\ + x_i,\ y_q &\in \{0,1\}, && \forall\, i \in N,\ q \in Q \tag{17} +\end{align}$$ + +Constraints (15) are the arc-coverage conditions: a path $q$ may be counted as refueled only if, for every directed arc on its round trip, at least one station in the corresponding candidate set is open. Constraint (16) forces exactly $p$ stations to be opened, and (17) enforces binarity. diff --git a/tasks/tran2018/problem_description.txt b/tasks/tran2018/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..22e3df25a85bfadc7439a936c6a170ae2b04be3f --- /dev/null +++ b/tasks/tran2018/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A transportation network consists of a set of nodes connected by undirected arcs, where each arc has a known distance. A subset of node pairs serves as origin-destination (OD) pairs, each carrying a known volume of round-trip traffic flow. The traffic between each OD pair travels along a single predetermined shortest path through the network. All vehicles use an alternative fuel and share a common driving range, meaning each vehicle can travel at most a fixed distance on a full tank before needing to refuel. Fuel consumption is proportional to distance traveled, and vehicles are assumed to depart from the origin with a full tank only once at the start of the round trip (there is no refueling at the destination before the return leg). + +The task is to select exactly a specified number of nodes at which to build refueling stations, so as to maximize the total traffic flow volume that can complete its round trip without running out of fuel. A round trip for an OD pair follows the shortest path from origin to destination and then returns along the same path in reverse. The round-trip path is represented as a sequence of directed arcs: first from origin to destination, then from destination back to origin. A given OD pair's traffic flow is considered "refueled" (and its flow volume counts toward the total) only if every directed arc on the round-trip path can be traversed by a vehicle that refuels at one of the open stations. Specifically, directed arcs whose cumulative distance from the origin does not exceed the vehicle's driving range are automatically covered by the initial full tank and require no open station. For each remaining directed arc on the round trip, there must be at least one open station among the set of candidate nodes that can service that arc. A candidate node can service a directed arc if a vehicle that refuels at that node has enough fuel to traverse the arc without running dry, given the vehicle's range and the distances between nodes along the path. Any number of vehicles may refuel at any station. Drivers have full knowledge of station locations along their path and refuel optimally to complete their journey. + +The input data provides the number of nodes, their coordinates, the set of arcs with distances, the number of OD pairs with their origins, destinations, traffic flow volumes, and precomputed shortest paths, the vehicle driving range, and the number of stations to locate. The goal is to maximize the sum of traffic flow volumes over all OD pairs whose round trips are fully serviceable by the chosen station locations. diff --git a/tasks/tran2018/solution_logger.py b/tasks/tran2018/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/tran2018/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/tran2018/solution_schema.json b/tasks/tran2018/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..80060a72d154f65932c6727c052663acc71f5999 --- /dev/null +++ b/tasks/tran2018/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total round-trip traffic flow volume that is successfully refueled by the chosen stations.", + "stations": " Node IDs selected to host a refueling station.", + "refueled_od_pairs": " Indices (into the instance's od_pairs list) of origin-destination pairs whose round-trip traffic is refueled by the chosen stations." +} diff --git a/tasks/vidal2011/feasibility_check.py b/tasks/vidal2011/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..151838309a3c47d88743a5c6fb89d3ca9972be1b --- /dev/null +++ b/tasks/vidal2011/feasibility_check.py @@ -0,0 +1,692 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Multi-Depot Periodic Vehicle Routing Problem (MDPVRP). + +Checks constraints from Vidal et al. (2011), Annex 7.1: + Constraint 1 (eq 6): Each customer assigned exactly one pattern and one depot + Constraint 2 (eq 7): Visits match assigned pattern/depot + Constraint 3 (eq 8): Vehicle leaves depot at most once per period + Constraint 4 (eq 9): Vehicles from depot o cannot leave from other depots + Constraint 5 (eq 10): Flow conservation + Constraint 6 (eq 11): Vehicle capacity + Constraint 7 (eq 12): Route duration + Constraint 8 (eq 13): Subtour elimination + Constraint 9 (eq 14): Binary domain for x + Constraint 10 (eq 15): Binary domain for y + Constraint 11 (obj): Objective-value consistency (reported objective_value + must match recomputed total travel cost summed over + all routes' depot-customer-...-depot tours). +""" + +import argparse +import json +import math + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('assignments', '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 + + +TOL = 1e-5 +EPS = 1e-5 + + +def euclidean_distance(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def add_violation(violations_list, magnitudes_list, constraint_idx, message, lhs, rhs): + violation_amount = abs(lhs - rhs) + if constraint_idx not in [v["constraint"] for v in magnitudes_list]: + pass # we add all instances + violations_list.append({"constraint": constraint_idx, "message": message}) + normalizer = max(abs(rhs), EPS) + magnitudes_list.append({ + "constraint": constraint_idx, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + +def check_feasibility(instance, solution): + # Handle no-solution cases (solver timeout, infeasible, etc.) + obj = solution.get("objective_value") + status_str = solution.get("status_str", "") + has_routes = bool(solution.get("routes")) + has_assignments = bool(solution.get("assignments")) + if ((obj is None or obj == float("inf")) and not has_routes and not has_assignments) or \ + status_str in ("NO_SOLUTION_FOUND", "INFEASIBLE", "INF_OR_UNBD"): + return { + "feasible": None, + "violated_constraints": [], + "violations": [ + f"No solution to check (status={status_str!r}, objective_value={obj!r})" + ], + "violation_magnitudes": [], + } + + n = instance["n"] + d = instance["d"] + t = instance["t"] + m = instance["m"] + Q = instance["vehicle_capacity"] + T = instance["route_duration_limit"] + + depots = instance["depots"] + customers = instance["customers"] + + # Build coordinate lookup + coords = {} + for dep in depots: + coords[dep["id"]] = (dep["x"], dep["y"]) + for cust in customers: + coords[d + cust["id"]] = (cust["x"], cust["y"]) + + depot_indices = list(range(d)) + customer_indices = list(range(d, d + n)) + + # Customer data indexed by vertex id (d + cust_id) + demand = {} + service = {} + freq = {} + patterns = {} + for cust in customers: + vi = d + cust["id"] + demand[vi] = cust["demand"] + service[vi] = cust["service_duration"] + freq[vi] = cust["frequency"] + patterns[vi] = cust["pattern_list"] + for dep_idx in depot_indices: + demand[dep_idx] = 0 + service[dep_idx] = 0 + + # Distance matrix + all_indices = list(range(d + n)) + dist = {} + for i in all_indices: + for j in all_indices: + xi, yi = coords[i] + xj, yj = coords[j] + dist[i, j] = euclidean_distance(xi, yi, xj, yj) + + # Parse solution + routes = solution.get("routes", []) + assignments = solution.get("assignments", {}) + + violations_list = [] + magnitudes_list = [] + + # Domain check: every depot in routes/assignments must be a valid depot + # id; every customer in routes/assignments must be a valid customer id; + # every period must be in [1, instance['p']]; every vehicle index must + # be in [0, m). + valid_depot_ids = {dep["id"] for dep in depots} + valid_customer_ids = {cust["id"] for cust in customers} + P = instance.get("p", 0) + valid_periods = set(range(1, P + 1)) if P else set() + domain_violations = [] + for r_idx, route in enumerate(routes): + if route.get("depot") not in valid_depot_ids: + domain_violations.append( + f"routes[{r_idx}] depot {route.get('depot')!r} not a valid depot id" + ) + if valid_periods and route.get("period") not in valid_periods: + domain_violations.append( + f"routes[{r_idx}] period {route.get('period')!r} not in [1, {P}]" + ) + veh = route.get("vehicle") + if not isinstance(veh, int) or not (1 <= veh <= m): + domain_violations.append( + f"routes[{r_idx}] vehicle {veh!r} not in [1, {m}]" + ) + for cid in route.get("customers", []): + if cid not in valid_customer_ids: + domain_violations.append( + f"routes[{r_idx}] customer {cid!r} not a valid customer id" + ) + for k_str, asgn in assignments.items(): + try: + cid = int(k_str) + except (TypeError, ValueError): + cid = None + if cid not in valid_customer_ids: + domain_violations.append( + f"assignments key {k_str!r} not a valid customer id" + ) + if isinstance(asgn, dict): + if asgn.get("depot") not in valid_depot_ids: + domain_violations.append( + f"assignments[{k_str}].depot = {asgn.get('depot')!r} " + f"not a valid depot id" + ) + if valid_periods: + for per in asgn.get("pattern", []): + if per not in valid_periods: + domain_violations.append( + f"assignments[{k_str}].pattern contains period " + f"{per!r} not in [1, {P}]" + ) + + if domain_violations: + for msg in domain_violations: + violations_list.append({"constraint": 0, "message": f"Domain: {msg}"}) + magnitudes_list.append({ + "constraint": 0, "lhs": 0.0, "rhs": 0.0, + "raw_excess": 1.0, "normalizer": 1.0, "ratio": 1.0, + }) + violated = sorted({v["constraint"] for v in violations_list}) + return { + "feasible": False, + "violated_constraints": violated, + "violations": [v["message"] for v in violations_list], + "violation_magnitudes": magnitudes_list, + } + + # ========================================================================= + # Reconstruct assignment variables y_{ipo} from assignments dict + # assignments: {cust_id_str: {"depot": o, "pattern": [list of periods]}} + # ========================================================================= + # Map each customer to (pattern_index, depot) + cust_assignment = {} # cust_id -> (pattern_index, depot) + for cust in customers: + cid = cust["id"] + key = str(cid) + if key in assignments: + asgn = assignments[key] + assigned_depot = asgn["depot"] + assigned_pattern = tuple(asgn["pattern"]) + # Find pattern index + pat_idx = None + for pi, pat in enumerate(cust["pattern_list"]): + if tuple(pat) == assigned_pattern: + pat_idx = pi + break + if pat_idx is None: + # Pattern not in feasible list - this is a constraint 1 issue + # but we still record the assignment for other checks + pat_idx = -1 + cust_assignment[cid] = (pat_idx, assigned_depot) + elif int(cid) in assignments: + # Handle integer keys + asgn = assignments[int(cid)] + assigned_depot = asgn["depot"] + assigned_pattern = tuple(asgn["pattern"]) + pat_idx = None + for pi, pat in enumerate(cust["pattern_list"]): + if tuple(pat) == assigned_pattern: + pat_idx = pi + break + if pat_idx is None: + pat_idx = -1 + cust_assignment[cid] = (pat_idx, assigned_depot) + + # ========================================================================= + # Reconstruct route structure + # Each route: {depot, period, vehicle (optional), customers: [cust_ids]} + # ========================================================================= + # Build: for each (depot, period, vehicle_idx) -> list of customer ids in visit order + # If vehicle not given, assign sequentially + route_structs = [] + vehicle_counter = {} # (depot, period) -> next vehicle idx + for r in routes: + dep = r["depot"] + per = r["period"] + veh = r.get("vehicle", None) + custs = r["customers"] + if veh is None: + key = (dep, per) + veh = vehicle_counter.get(key, 1) + vehicle_counter[key] = veh + 1 + route_structs.append({ + "depot": dep, + "period": per, + "vehicle": veh, + "customers": custs, + }) + + # ========================================================================= + # Constraint 1 (eq 6): Each customer assigned exactly one pattern+depot + # sum_{p in L_i} sum_{o in V^DEP} y_{ipo} = 1 for all customers + # ========================================================================= + for cust in customers: + cid = cust["id"] + lhs = 1.0 if cid in cust_assignment else 0.0 + rhs = 1.0 + if cid in cust_assignment: + pat_idx, dep = cust_assignment[cid] + if pat_idx == -1: + # Assigned pattern not in feasible list + add_violation(violations_list, magnitudes_list, 1, + f"Customer {cid}: assigned pattern not in feasible pattern list L_i", + 0.0, 1.0) + else: + add_violation(violations_list, magnitudes_list, 1, + f"Customer {cid}: not assigned to any pattern/depot (sum=0, need 1)", + lhs, rhs) + + # ========================================================================= + # Constraint 2 (eq 7): Visit consistency + # sum_j sum_k x_{ijklo} - sum_p a_{pl} y_{ipo} = 0 + # For each customer i, depot o, period l + # Meaning: customer i is visited from depot o on day l iff assigned pattern includes day l at depot o + # ========================================================================= + # Count actual visits per (customer, depot, period) + visit_count = {} # (cust_id, depot, period) -> count of routes visiting this customer + for rs in route_structs: + dep = rs["depot"] + per = rs["period"] + for cid in rs["customers"]: + key = (cid, dep, per) + visit_count[key] = visit_count.get(key, 0) + 1 + + for cust in customers: + cid = cust["id"] + for o in depot_indices: + for l in range(1, t + 1): + # LHS: number of times customer cid visited from depot o on day l + actual_visits = visit_count.get((cid, o, l), 0) + # RHS: expected visits based on assignment + expected = 0.0 + if cid in cust_assignment: + pat_idx, assigned_depot = cust_assignment[cid] + if assigned_depot == o and pat_idx >= 0: + assigned_pattern = cust["pattern_list"][pat_idx] + if l in assigned_pattern: + expected = 1.0 + lhs = float(actual_visits) - expected + rhs = 0.0 + violation_amount = abs(lhs - rhs) + if violation_amount > TOL: + add_violation(violations_list, magnitudes_list, 2, + f"Customer {cid}, depot {o}, period {l}: " + f"actual visits={actual_visits}, expected={expected}", + lhs, rhs) + + # ========================================================================= + # Constraint 3 (eq 8): Vehicle leaves depot at most once per period + # sum_j x_{ojklo} <= 1 for each depot o, vehicle k, period l + # In the solution, each route from depot o on period l with vehicle k means + # the vehicle leaves once. So count routes per (depot, vehicle, period). + # ========================================================================= + route_count_per_veh = {} # (depot, vehicle, period) -> count + for rs in route_structs: + key = (rs["depot"], rs["vehicle"], rs["period"]) + route_count_per_veh[key] = route_count_per_veh.get(key, 0) + 1 + + for key, count in route_count_per_veh.items(): + dep, veh, per = key + lhs = float(count) + rhs = 1.0 + if lhs - rhs > TOL: + add_violation(violations_list, magnitudes_list, 3, + f"Depot {dep}, vehicle {veh}, period {per}: " + f"vehicle departs {count} times (max 1)", + lhs, rhs) + + # Also check that vehicle indices don't exceed m + for rs in route_structs: + if rs["vehicle"] > m: + add_violation(violations_list, magnitudes_list, 3, + f"Depot {rs['depot']}, period {rs['period']}: " + f"vehicle index {rs['vehicle']} exceeds m={m}", + float(rs["vehicle"]), float(m)) + + # ========================================================================= + # Constraint 4 (eq 9): Vehicles from depot o cannot operate from other depots + # In route representation: each route starts/ends at its assigned depot. + # A customer assigned to depot o should only appear in routes from depot o. + # ========================================================================= + for rs in route_structs: + route_depot = rs["depot"] + for cid in rs["customers"]: + if cid in cust_assignment: + _, assigned_depot = cust_assignment[cid] + if route_depot != assigned_depot: + # This customer is visited from a depot that's not its assigned depot + add_violation(violations_list, magnitudes_list, 4, + f"Customer {cid} assigned to depot {assigned_depot} " + f"but visited from depot {route_depot} on period {rs['period']}", + 1.0, 0.0) + + # ========================================================================= + # Constraint 5 (eq 10): Flow conservation + # In a valid route representation (depot -> c1 -> c2 -> ... -> depot), + # flow is automatically conserved. We verify each route forms a valid + # path starting and ending at the depot (no repeated customers within a route). + # ========================================================================= + for rs in route_structs: + custs = rs["customers"] + if len(custs) != len(set(custs)): + from collections import Counter + counts = Counter(custs) + duplicates = {c: cnt for c, cnt in counts.items() if cnt > 1} + for c, cnt in duplicates.items(): + add_violation(violations_list, magnitudes_list, 5, + f"Depot {rs['depot']}, period {rs['period']}, " + f"vehicle {rs['vehicle']}: customer {c} appears {cnt} times " + f"in same route (flow conservation violated)", + float(cnt), 1.0) + + # ========================================================================= + # Constraint 6 (eq 11): Vehicle capacity + # sum_i sum_j q_i * x_{ijklo} <= Q + # For each route, total demand of customers served <= Q + # ========================================================================= + for rs in route_structs: + total_demand = sum(demand[d + cid] for cid in rs["customers"]) + lhs = float(total_demand) + rhs = float(Q) + if lhs - rhs > TOL: + add_violation(violations_list, magnitudes_list, 6, + f"Depot {rs['depot']}, period {rs['period']}, " + f"vehicle {rs['vehicle']}: demand={total_demand} exceeds capacity={Q}", + lhs, rhs) + + # ========================================================================= + # Constraint 7 (eq 12): Route duration + # sum_i sum_j (c_{ij} + tau_i) * x_{ijklo} <= T + # Route duration = travel time + service time of visited customers + # ========================================================================= + for rs in route_structs: + dep = rs["depot"] + custs = rs["customers"] + if not custs: + continue + # Route: depot -> custs[0] -> custs[1] -> ... -> custs[-1] -> depot + # Travel time + travel = dist[dep, d + custs[0]] + for idx in range(len(custs) - 1): + travel += dist[d + custs[idx], d + custs[idx + 1]] + travel += dist[d + custs[-1], dep] + # Service time + svc = sum(service[d + cid] for cid in custs) + duration = travel + svc + lhs = float(duration) + rhs = float(T) + if lhs - rhs > TOL: + add_violation(violations_list, magnitudes_list, 7, + f"Depot {dep}, period {rs['period']}, " + f"vehicle {rs['vehicle']}: duration={duration:.2f} exceeds limit={T}", + lhs, rhs) + + # ========================================================================= + # Constraint 8 (eq 13): Subtour elimination + # In the route-list representation, subtours are impossible if each route + # is a simple path from depot through customers back to depot. + # We already check for duplicates in constraint 5. + # Additionally verify no customer appears in multiple routes for same + # (depot, period) - which would indicate a structural issue. + # ========================================================================= + cust_in_routes = {} # (cust_id, depot, period) -> list of vehicle indices + for rs in route_structs: + for cid in rs["customers"]: + key = (cid, rs["depot"], rs["period"]) + cust_in_routes.setdefault(key, []).append(rs["vehicle"]) + for (cid, dep, per), vehs in cust_in_routes.items(): + if len(vehs) > 1: + lhs = float(len(vehs)) + rhs = 1.0 + add_violation(violations_list, magnitudes_list, 8, + f"Customer {cid} visited by {len(vehs)} vehicles " + f"from depot {dep} on period {per} (subtour/duplication issue)", + lhs, rhs) + + # ========================================================================= + # Constraint 11 (obj): Objective-value consistency + # Recompute total travel cost from the routes (sum of euclidean arc lengths + # along each depot->c1->...->ck->depot tour, over all routes, depots, + # periods, vehicles) and reject when the reported objective_value differs + # by more than 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 and math.isfinite(reported): + true_obj = 0.0 + for rs in route_structs: + dep = rs["depot"] + custs = rs["customers"] + if not custs: + continue + true_obj += dist[dep, d + custs[0]] + for idx in range(len(custs) - 1): + true_obj += dist[d + custs[idx], d + custs[idx + 1]] + true_obj += dist[d + custs[-1], dep] + abs_diff = abs(reported - true_obj) + tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > tol: + add_violation( + violations_list, magnitudes_list, 11, + f"Objective consistency violated: reported objective_value=" + f"{reported} differs from recomputed total travel cost=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={tol:.6g})", + reported, true_obj, + ) + + # ========================================================================= + # Aggregate results + # ========================================================================= + violated_constraint_indices = sorted(set(v["constraint"] for v in violations_list)) + # Aggregate messages per constraint + messages = [] + for ci in violated_constraint_indices: + msgs = [v["message"] for v in violations_list if v["constraint"] == ci] + if len(msgs) <= 3: + messages.extend(msgs) + else: + messages.extend(msgs[:3]) + messages.append(f" ... and {len(msgs) - 3} more violation(s) for constraint {ci}") + + feasible = len(violated_constraint_indices) == 0 + + result = { + "feasible": feasible, + "violated_constraints": violated_constraint_indices, + "violations": messages, + "violation_magnitudes": magnitudes_list if not feasible else [], + } + return result + + +def main(): + parser = argparse.ArgumentParser(description="MDPVRP Feasibility Checker") + parser.add_argument("--instance_path", type=str, required=True, + help="Path to instance JSON file") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to solution JSON file") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write feasibility result JSON file") + args = parser.parse_args() + + with open(args.instance_path, 'r') as f: + instance = json.load(f) + with open(args.solution_path, 'r') as f: + raw = f.read() + # Handle non-standard JSON values (Infinity, NaN) that some solvers emit + raw = raw.replace(': Infinity', ': 1e9999') + raw = raw.replace(':Infinity', ':1e9999') + raw = raw.replace(': -Infinity', ': -1e9999') + raw = raw.replace(':-Infinity', ':-1e9999') + raw = raw.replace(': NaN', ': null') + raw = raw.replace(':NaN', ':null') + solution = json.loads(raw) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, 'w') as f: + json.dump(result, f, indent=2) + + if result["feasible"] is None: + status = "NO_SOLUTION" + elif result["feasible"]: + status = "FEASIBLE" + else: + status = "INFEASIBLE" + print(f"Result: {status}") + if result["feasible"] is None: + print(f" {result['violations'][0] if result['violations'] else 'No solution to check'}") + elif 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/vidal2011/gurobi_code.py b/tasks/vidal2011/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..b25161d8ff903256c2adac2b0e8ead7dc9419956 --- /dev/null +++ b/tasks/vidal2011/gurobi_code.py @@ -0,0 +1,419 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of the Multi-Depot Periodic Vehicle Routing Problem (MDPVRP). + +Five-index vehicle flow formulation from: +Vidal et al. (2011) - "A Hybrid Genetic Algorithm for Multi-Depot and Periodic +Vehicle Routing Problems", CIRRELT-2011-05, Annex 7.1. + +Subtour elimination constraints (13) are handled via lazy constraint callbacks. +""" + +import argparse +import json +import math +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 euclidean_distance(x1, y1, x2, y2): + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + + +def load_instance(path): + with open(path, 'r') as f: + return json.load(f) + + +def build_and_solve(instance, time_limit): + n = instance["n"] + d = instance["d"] + t = instance["t"] + m = instance["m"] + Q = instance["vehicle_capacity"] + T = instance["route_duration_limit"] + depots = instance["depots"] + customers = instance["customers"] + + # Build vertex sets + # Depot vertices: indices 0..d-1 + # Customer vertices: indices d..d+n-1 + num_vertices = d + n + + # Coordinates + coords = {} + for dep in depots: + coords[dep["id"]] = (dep["x"], dep["y"]) # depot ids: 0..d-1 + for cust in customers: + coords[d + cust["id"]] = (cust["x"], cust["y"]) # customer ids shifted by d + + depot_indices = list(range(d)) + customer_indices = list(range(d, d + n)) + all_indices = list(range(num_vertices)) + + # Cost matrix + c = {} + for i in all_indices: + for j in all_indices: + xi, yi = coords[i] + xj, yj = coords[j] + c[i, j] = euclidean_distance(xi, yi, xj, yj) + + # Customer data (indexed by vertex index d+cust_id) + demand = {} + service = {} + freq = {} + patterns = {} + for cust in customers: + vi = d + cust["id"] + demand[vi] = cust["demand"] + service[vi] = cust["service_duration"] + freq[vi] = cust["frequency"] + # patterns: list of lists of period indices (1-based in data) + patterns[vi] = cust["pattern_list"] + + # Depots have zero demand and service time + for dep_idx in depot_indices: + demand[dep_idx] = 0 + service[dep_idx] = 0 + + # Pattern binary constants a_{pl}: for pattern p (index in L_i), period l + # We store pattern_contains[vi] = list of sets, each set contains the periods + pattern_contains = {} + for vi in customer_indices: + pattern_contains[vi] = [] + for pat in patterns[vi]: + pattern_contains[vi].append(set(pat)) + + periods = list(range(1, t + 1)) + vehicles = list(range(1, m + 1)) + + # ========================================================================= + # Build Gurobi Model + # ========================================================================= + model = Model("MDPVRP") + model.setParam("Threads", 1) + model.setParam("TimeLimit", time_limit) + model.setParam("LazyConstraints", 1) + # Reduce output verbosity + model.setParam("OutputFlag", 1) + + # Decision variables + # y[i, p_idx, o]: customer i assigned to pattern index p_idx and depot o + y = {} + for vi in customer_indices: + for p_idx in range(len(patterns[vi])): + for o in depot_indices: + y[vi, p_idx, o] = model.addVar( + vtype=GRB.BINARY, name=f"y_{vi}_{p_idx}_{o}" + ) + + # x[i, j, k, l, o]: vehicle k from depot o on day l travels from i to j + # To manage size, only create variables where they make sense + x = {} + for o in depot_indices: + for l in periods: + for k in vehicles: + for i in all_indices: + for j in all_indices: + if i == j: + continue + x[i, j, k, l, o] = model.addVar( + vtype=GRB.BINARY, name=f"x_{i}_{j}_{k}_{l}_{o}" + ) + + model.update() + + # Objective (5): minimize total routing cost + model.setObjective( + quicksum( + c[i, j] * x[i, j, k, l, o] + for (i, j, k, l, o) in x + ), + GRB.MINIMIZE, + ) + + # Constraint (6): each customer assigned exactly one pattern and one depot + for vi in customer_indices: + model.addConstr( + quicksum( + y[vi, p_idx, o] + for p_idx in range(len(patterns[vi])) + for o in depot_indices + ) + == 1, + name=f"assign_{vi}", + ) + + # Constraint (7): customer visits match assigned pattern/depot + # sum_j sum_k x_{ijklo} - sum_p a_{pl} * y_{ipo} = 0 + # for each customer i, depot o, period l + for vi in customer_indices: + for o in depot_indices: + for l in periods: + lhs_x = quicksum( + x[vi, j, k, l, o] + for k in vehicles + for j in all_indices + if j != vi and (vi, j, k, l, o) in x + ) + lhs_y = quicksum( + (1 if l in pattern_contains[vi][p_idx] else 0) * y[vi, p_idx, o] + for p_idx in range(len(patterns[vi])) + ) + model.addConstr(lhs_x - lhs_y == 0, name=f"visit_{vi}_{o}_{l}") + + # Constraint (8): each vehicle leaves each depot at most once per period + for o in depot_indices: + for k in vehicles: + for l in periods: + model.addConstr( + quicksum( + x[o, j, k, l, o] + for j in all_indices + if j != o and (o, j, k, l, o) in x + ) + <= 1, + name=f"depart_{o}_{k}_{l}", + ) + + # Constraint (9): vehicles from depot o cannot leave from other depots + for o in depot_indices: + for i in depot_indices: + if i == o: + continue + for k in vehicles: + for l in periods: + model.addConstr( + quicksum( + x[i, j, k, l, o] + for j in all_indices + if j != i and (i, j, k, l, o) in x + ) + == 0, + name=f"nodep_{i}_{o}_{k}_{l}", + ) + + # Constraint (10): flow conservation + for vi in all_indices: + for o in depot_indices: + for k in vehicles: + for l in periods: + inflow = quicksum( + x[j, vi, k, l, o] + for j in all_indices + if j != vi and (j, vi, k, l, o) in x + ) + outflow = quicksum( + x[vi, j, k, l, o] + for j in all_indices + if j != vi and (vi, j, k, l, o) in x + ) + model.addConstr( + inflow - outflow == 0, + name=f"flow_{vi}_{o}_{k}_{l}", + ) + + # Constraint (11): vehicle capacity + for o in depot_indices: + for k in vehicles: + for l in periods: + model.addConstr( + quicksum( + demand[i] * x[i, j, k, l, o] + for i in all_indices + for j in all_indices + if i != j and (i, j, k, l, o) in x + ) + <= Q, + name=f"cap_{o}_{k}_{l}", + ) + + # Constraint (12): route duration + for o in depot_indices: + for k in vehicles: + for l in periods: + model.addConstr( + quicksum( + (c[i, j] + service[i]) * x[i, j, k, l, o] + for i in all_indices + for j in all_indices + if i != j and (i, j, k, l, o) in x + ) + <= T, + name=f"dur_{o}_{k}_{l}", + ) + + # Constraint (13): subtour elimination via lazy callbacks + def subtour_callback(model, where): + if where == GRB.Callback.MIPSOL: + for o in depot_indices: + for k in vehicles: + for l in periods: + # Get edges used by this vehicle + edges = [] + for i in customer_indices: + for j in customer_indices: + if i != j and (i, j, k, l, o) in x: + val = model.cbGetSolution(x[i, j, k, l, o]) + if val > 0.5: + edges.append((i, j)) + if not edges: + continue + # Find connected components among customers + visited_nodes = set() + for i, j in edges: + visited_nodes.add(i) + visited_nodes.add(j) + # Check if depot o is reachable + # Build adjacency from all edges (including depot) + adj_full = {node: set() for node in visited_nodes | {o}} + for i in all_indices: + for j in all_indices: + if i != j and (i, j, k, l, o) in x: + val = model.cbGetSolution(x[i, j, k, l, o]) + if val > 0.5: + adj_full.setdefault(i, set()).add(j) + adj_full.setdefault(j, set()).add(i) + # BFS from depot + reached = set() + queue = [o] + while queue: + node = queue.pop() + if node in reached: + continue + reached.add(node) + for nb in adj_full.get(node, []): + if nb not in reached: + queue.append(nb) + # Any customer nodes not reached form subtours + unreached = visited_nodes - reached + if unreached: + # Find connected components in unreached + adj_sub = {node: set() for node in unreached} + for i, j in edges: + if i in unreached and j in unreached: + adj_sub[i].add(j) + adj_sub[j].add(i) + visited_comp = set() + for start in unreached: + if start in visited_comp: + continue + comp = set() + stack = [start] + while stack: + node = stack.pop() + if node in comp: + continue + comp.add(node) + for nb in adj_sub[node]: + if nb not in comp: + stack.append(nb) + visited_comp |= comp + S = list(comp) + if len(S) >= 2: + model.cbLazy( + quicksum( + x[i, j, k, l, o] + for i in S + for j in S + if i != j and (i, j, k, l, o) in x + ) + <= len(S) - 1 + ) + + model.optimize(subtour_callback) + + # Extract solution. When SolCount == 0 (TLE-no-incumbent, INFEAS, etc.) + # leave objective_value as None — emitting float("inf") was a bug that + # made downstream CSV parsers treat the run as a feasible-but-infinite + # solution rather than "no solution found". + obj_val = model.ObjVal if model.SolCount > 0 else None + + # Build solution details + solution = {"objective_value": obj_val} + + if model.SolCount > 0: + routes = [] + for o in depot_indices: + for l in periods: + for k in vehicles: + route_edges = [] + for i in all_indices: + for j in all_indices: + if i != j and (i, j, k, l, o) in x: + if x[i, j, k, l, o].X > 0.5: + route_edges.append((i, j)) + if route_edges: + # Reconstruct route from depot + succ = {i: j for i, j in route_edges} + route_seq = [] + current = o + visited_set = set() + while current in succ and current not in visited_set: + visited_set.add(current) + nxt = succ[current] + route_seq.append(nxt) + current = nxt + # Convert customer indices back to original ids + cust_seq = [v - d for v in route_seq if v in customer_indices] + if cust_seq: + routes.append({ + "depot": o, + "period": l, + "vehicle": k, + "customers": cust_seq, + }) + solution["routes"] = routes + + # Pattern/depot assignments + assignments = {} + for vi in customer_indices: + cust_id = vi - d + for p_idx in range(len(patterns[vi])): + for o in depot_indices: + if y[vi, p_idx, o].X > 0.5: + assignments[cust_id] = { + "depot": o, + "pattern": patterns[vi][p_idx], + } + solution["assignments"] = assignments + + return solution + + +def main(): + parser = argparse.ArgumentParser(description="MDPVRP Gurobi solver") + parser.add_argument("--instance_path", type=str, required=True) + parser.add_argument("--solution_path", type=str, required=True) + parser.add_argument("--time_limit", type=int, required=True) + parser.add_argument("--log_path", type=str, default=None, help="Path to log incumbent solutions") + args = parser.parse_args() + install_gurobi_logger(args.log_path) + + instance = load_instance(args.instance_path) + solution = build_and_solve(instance, args.time_limit) + + with open(args.solution_path, 'w') as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2, default=str) + print(f"Solution written to {args.solution_path}") + print(f"Objective value: {solution['objective_value']}") + + +if __name__ == "__main__": + main() diff --git a/tasks/vidal2011/gurobi_feasi_result/large_feasi_result_1.json b/tasks/vidal2011/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/vidal2011/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/vidal2011/gurobi_feasi_result/large_feasi_result_2.json b/tasks/vidal2011/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/vidal2011/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/vidal2011/gurobi_feasi_result/large_feasi_result_3.json b/tasks/vidal2011/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/vidal2011/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/vidal2011/gurobi_feasi_result/large_feasi_result_4.json b/tasks/vidal2011/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/vidal2011/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/vidal2011/gurobi_feasi_result/large_feasi_result_5.json b/tasks/vidal2011/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/vidal2011/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/vidal2011/gurobi_feasi_result/tiny_feasi_result.json b/tasks/vidal2011/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/vidal2011/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/vidal2011/gurobi_feasi_result/tiny_feasi_result_2.json b/tasks/vidal2011/gurobi_feasi_result/tiny_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/vidal2011/gurobi_feasi_result/tiny_feasi_result_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3269392edcbb7720882e77caadb88b4a9cf2fda04cf482cebd23baace4a531fd +size 102 diff --git a/tasks/vidal2011/gurobi_solution/large_solution_1.json b/tasks/vidal2011/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..5f50a59073c4d4415e0eec0e8a8f24e49ed8b05c --- /dev/null +++ b/tasks/vidal2011/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f734cc56c389dc607104e2a5b952d6d2abaee30c4840903c3b61e54ac0774903 +size 4050 diff --git a/tasks/vidal2011/gurobi_solution/large_solution_2.json b/tasks/vidal2011/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..efc2cc62774a3cbe226b375893b6cabf437dd6b2 --- /dev/null +++ b/tasks/vidal2011/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1f18de9cf242f21be0ffa3392a9bb7ea09e89be5195edccb7721b26fa2e2fff +size 3427 diff --git a/tasks/vidal2011/gurobi_solution/large_solution_3.json b/tasks/vidal2011/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e323a899a56a342fb2526de6eedf2b0eb922130c --- /dev/null +++ b/tasks/vidal2011/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:457db982a06fa38afb5a222984cd25822bbc5c99393984b2b9e379eb8b49910a +size 3448 diff --git a/tasks/vidal2011/gurobi_solution/large_solution_4.json b/tasks/vidal2011/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..31cb7841f5e461c56b9f1c4d27219575b37977dd --- /dev/null +++ b/tasks/vidal2011/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:667f76cd481f68c7acf5c35f133f20d6e61bb542e55bb72f30cfe2741567ee31 +size 3645 diff --git a/tasks/vidal2011/gurobi_solution/large_solution_5.json b/tasks/vidal2011/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..44d9ec43ea05af9e7cc96219f20149728026a108 --- /dev/null +++ b/tasks/vidal2011/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b28d78f22a52342411d6bc25ab126c3c34a22f687d28d0e5872e50fb8f2bfa9 +size 3081 diff --git a/tasks/vidal2011/gurobi_solution/tiny_solution.json b/tasks/vidal2011/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..31f5cfddfb2153949a5fafd2161fcbaef7a4a08e --- /dev/null +++ b/tasks/vidal2011/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:687df129ad51cbb02db47e73b4798b73643b90ea97a0b3d87e24744091d6a100 +size 1634 diff --git a/tasks/vidal2011/gurobi_solution/tiny_solution_2.json b/tasks/vidal2011/gurobi_solution/tiny_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..c2881beaddcb57ce555adc986105e021d115509e --- /dev/null +++ b/tasks/vidal2011/gurobi_solution/tiny_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a6c7d8926fd591c7c902cb56c9f060aa8275da02aad8a573f448e494363d69a +size 2661 diff --git a/tasks/vidal2011/gurobi_solution_log/large_log_1.jsonl b/tasks/vidal2011/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..880e03c4d6e638f34f5fc5cba34951ebe49c161d --- /dev/null +++ b/tasks/vidal2011/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1819a6beeb05fa3e108519441a2a40c64691fa472196ceab11f9c483c91cc5d3 +size 54 diff --git a/tasks/vidal2011/gurobi_solution_log/large_log_2.jsonl b/tasks/vidal2011/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1f034d97adbeaf188b58cd4745e5b52f45d6b571 --- /dev/null +++ b/tasks/vidal2011/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8b3ce71b575f864b73a5b7f800190bf11fafb908f291ebe992fc20ac8a43b7b +size 54 diff --git a/tasks/vidal2011/gurobi_solution_log/large_log_3.jsonl b/tasks/vidal2011/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..114f56b503333f279ec75925a506f5da86c9e46d --- /dev/null +++ b/tasks/vidal2011/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f8497f62f75e60ac4db5210055c667d8a5664b74f32ed11d5b822ec3ac5fe38 +size 162 diff --git a/tasks/vidal2011/gurobi_solution_log/large_log_4.jsonl b/tasks/vidal2011/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..db4741ab12483c6046fdad847bffdcf05463d104 --- /dev/null +++ b/tasks/vidal2011/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1af2aab6d7328e881732ccd33b5edf21e97b9fd32bffc4aa25e3acbc9312cf41 +size 107 diff --git a/tasks/vidal2011/gurobi_solution_log/large_log_5.jsonl b/tasks/vidal2011/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a513457b4d76273162914c18c98c7766187dd68c --- /dev/null +++ b/tasks/vidal2011/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6c91b599be1bbcc506bef9541d5a451c3101b7bc5fe7d5f732b4bb130b490d2 +size 107 diff --git a/tasks/vidal2011/gurobi_solution_log/tiny_log.jsonl b/tasks/vidal2011/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..55ea054c0602f56eb4e3c8332e980d58a263cb8f --- /dev/null +++ b/tasks/vidal2011/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec13e5b0786f0604ef1c2d961540578dca29bf02cf596d72da46733bdf108f37 +size 54 diff --git a/tasks/vidal2011/instance/large_instance_1.json b/tasks/vidal2011/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..7142e5707242689ac048a37c782dac0d47ce3c73 --- /dev/null +++ b/tasks/vidal2011/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3d4d5034a31b0a5f041bc282652939910f61abfb289862904ff37c7b14d14de +size 2412 diff --git a/tasks/vidal2011/instance/large_instance_2.json b/tasks/vidal2011/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..fb84c9901b6c34102a443b67f0754b5ba668094a --- /dev/null +++ b/tasks/vidal2011/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:144fcfb4e42e47d9a8358174352a89c29028e846032affb9c6195f949c2311d2 +size 2452 diff --git a/tasks/vidal2011/instance/large_instance_3.json b/tasks/vidal2011/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..b2cb83fc79aac092c3e8ac3acade904f7f09ca4f --- /dev/null +++ b/tasks/vidal2011/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6f8ba88c5cfabe28b974282ec7ae2d24e9b2d32e19fc93572262dd7fd3aae86 +size 2437 diff --git a/tasks/vidal2011/instance/large_instance_4.json b/tasks/vidal2011/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..264e10814874eeb6a7fd5fb82ad8355cc22ff9fa --- /dev/null +++ b/tasks/vidal2011/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23beedaa0c217a33e657817815a38dee58641aa33b3f3d2da1275150280c0dd3 +size 2388 diff --git a/tasks/vidal2011/instance/large_instance_5.json b/tasks/vidal2011/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8f7f41e5d32169a6bbc2882ffaa8f989b9c10b48 --- /dev/null +++ b/tasks/vidal2011/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:423eca847348032ebef26dd2ad76af6d821ee00bf9b226805671db75a37de0f4 +size 2444 diff --git a/tasks/vidal2011/instance/tiny_instance.json b/tasks/vidal2011/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..17142d05e43d0bf662a84aeb5555765e336f2889 --- /dev/null +++ b/tasks/vidal2011/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a0563122a1191464b5929cce1aa2b320ffef39360d11f4bf831ec678e546c4e +size 2160 diff --git a/tasks/vidal2011/instance/tiny_instance_2.json b/tasks/vidal2011/instance/tiny_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a550d5efb9d720f8b7b4c7b93f801ded57757fb1 --- /dev/null +++ b/tasks/vidal2011/instance/tiny_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b86d0c8053c45d4b25868ae2d0a498636698d484a33581e42070ae636b41e61 +size 4531 diff --git a/tasks/vidal2011/instance_schema.json b/tasks/vidal2011/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..aa11bf5a7f8c9386729799715652659c4a1c8b85 --- /dev/null +++ b/tasks/vidal2011/instance_schema.json @@ -0,0 +1,27 @@ +{ + "problem_type": " Type identifier for the optimization problem.", + "n": " Number of customers to be served.", + "d": " Number of depots from which vehicles operate.", + "t": " Number of periods (days) in the planning horizon.", + "m": " Number of identical vehicles stationed at each depot.", + "vehicle_capacity": " Maximum total demand a single vehicle can carry on one route.", + "route_duration_limit": " Maximum total duration of a single route, including travel times and service times.", + "depots": [ + { + "id": " Zero-based identifier for this depot.", + "x": " Horizontal coordinate of this depot in the service area.", + "y": " Vertical coordinate of this depot in the service area." + } + ], + "customers": [ + { + "id": " Zero-based identifier for this customer.", + "x": " Horizontal coordinate of this customer in the service area.", + "y": " Vertical coordinate of this customer in the service area.", + "demand": " Quantity of goods to be delivered to this customer on each visit.", + "service_duration": " Time spent at this customer's site during each visit.", + "frequency": " Number of times this customer must be visited over the planning horizon.", + "pattern_list": " Feasible visit patterns for this customer, where each pattern is a list of 1-based period indices on which visits occur." + } + ] +} diff --git a/tasks/vidal2011/mathematical_formulation.md b/tasks/vidal2011/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..2a9db0c88f9f257873d42ff62f70a769e57f7076 --- /dev/null +++ b/tasks/vidal2011/mathematical_formulation.md @@ -0,0 +1,76 @@ +# Original Formulation: Multi-Depot Periodic Vehicle Routing Problem (MDPVRP) + +*Source: A Hybrid Genetic Algorithm for Multi-Depot and Periodic Vehicle Routing Problems, Thibaut Vidal, Teodor Gabriel Crainic, Michel Gendreau, Nadia Lahrichi, Walter Rei, 2011 (CIRRELT-2011-05). Five-index vehicle flow formulation, Annex 7.1.* + +## Sets and Indices + +$$\begin{align*} +G = (V, A) \;:\;& \text{complete graph}. \\ +V = V^{\mathrm{DEP}} \cup V^{\mathrm{CST}} \;:\;& \text{complete vertex set}. \\ +V^{\mathrm{DEP}} = \{v_0, \ldots, v_d\} \;:\;& \text{set of depot vertices}. \\ +V^{\mathrm{CST}} = \{v_1, \ldots, v_n\} \;:\;& \text{set of customer vertices},\ i = 1, \ldots, n. \\ +A = \{a_{ij} : i,j \in V\} \;:\;& \text{arc set}. \\ +L_i \;:\;& \text{list of feasible visit combinations (patterns) for customer } i. \\ +v_o \in V^{\mathrm{DEP}} \;:\;& \text{depot index}. \\ +p \in L_i \;:\;& \text{visit-combination (pattern) index for customer } i. \\ +k = 1, \ldots, m \;:\;& \text{vehicle index ($m$ vehicles available at each depot)}. \\ +l = 1, \ldots, t \;:\;& \text{period (day) index ($t$ periods)}. \\ +S \subseteq V^{\mathrm{CST}},\ |S| \geq 2 \;:\;& \text{customer subsets (for subtour elimination)}. +\end{align*}$$ + +## Parameters + +$$\begin{align*} +c_{ij} \;:\;& \text{routing cost (travel time) from vertex } v_i \text{ to vertex } v_j. \\ +q_i \;:\;& \text{non-negative demand of customer } i. \\ +\tau_i \;:\;& \text{service duration at customer } i. \\ +Q \;:\;& \text{vehicle capacity}. \\ +T \;:\;& \text{maximum route duration (total travel time and service time)}. \\ +f_i \;:\;& \text{service frequency of customer } i. \\ +a_{pl} \;:\;& \text{binary constant; } 1 \text{ iff day } l \text{ belongs to visit combination } p,\ 0 \text{ otherwise}. \\ +\tau_o = 0,\ \forall v_o \in V^{\mathrm{DEP}} \;:\;& \text{convention: zero service time at depots}. +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +y_{ipo} \in \{0,1\} \;:\;& 1 \text{ iff customer } i \text{ is assigned to visit combination } p \in L_i \\ + & \text{and depot } o \in V^{\mathrm{DEP}};\ 0 \text{ otherwise}. \\ +x_{ijklo} \in \{0,1\} \;:\;& 1 \text{ iff vehicle } k \text{ coming from depot } o \text{ on day } l \\ + & \text{visits } v_j \text{ immediately after } v_i;\ 0 \text{ otherwise}. +\end{align*}$$ + +## Objective + +$$\begin{equation} +\text{Minimize} \quad \sum_{v_i \in V} \sum_{v_j \in V} \sum_{k=1}^{m} \sum_{l=1}^{t} \sum_{v_o \in V^{\mathrm{DEP}}} c_{ij}\, x_{ijklo} +\tag{5} +\end{equation}$$ + +## Constraints + +$$\begin{align} +& \sum_{p \in L_i} \sum_{v_o \in V^{\mathrm{DEP}}} y_{ipo} = 1 + && v_i \in V^{\mathrm{CST}} \tag{6} \\[4pt] +& \sum_{v_j \in V} \sum_{k=1}^{m} x_{ijklo} - \sum_{p \in L_i} a_{pl}\, y_{ipo} = 0 + && v_i \in V^{\mathrm{CST}};\ v_o \in V^{\mathrm{DEP}};\ l = 1 \ldots t \tag{7} \\[4pt] +& \sum_{v_j \in V} x_{ojklo} \leq 1 + && v_o \in V^{\mathrm{DEP}};\ k = 1 \ldots m;\ l = 1 \ldots t \tag{8} \\[4pt] +& \sum_{v_j \in V} x_{ijklo} = 0 + && v_i \in V^{\mathrm{DEP}};\ v_o \in V^{\mathrm{DEP}};\ v_o \neq v_i; \nonumber \\ +& && \quad k = 1 \ldots m;\ l = 1 \ldots t \tag{9} \\[4pt] +& \sum_{v_j \in V} x_{jiklo} - \sum_{v_j \in V} x_{ijklo} = 0 + && v_i \in V;\ v_o \in V^{\mathrm{DEP}};\ k = 1 \ldots m;\ l = 1 \ldots t \tag{10} \\[4pt] +& \sum_{v_i \in V} \sum_{v_j \in V} q_i\, x_{ijklo} \leq Q + && v_o \in V^{\mathrm{DEP}};\ k = 1 \ldots m;\ l = 1 \ldots t \tag{11} \\[4pt] +& \sum_{v_i \in V} \sum_{v_j \in V} (c_{ij} + \tau_i)\, x_{ijklo} \leq T + && v_o \in V^{\mathrm{DEP}};\ k = 1 \ldots m;\ l = 1 \ldots t \tag{12} \\[4pt] +& \sum_{v_i \in S} \sum_{v_j \in S} x_{ijklo} \leq |S| - 1 + && S \subseteq V^{\mathrm{CST}};\ |S| \geq 2;\ v_o \in V^{\mathrm{DEP}}; \nonumber \\ +& && \quad k = 1 \ldots m;\ l = 1 \ldots t \tag{13} \\[4pt] +& x_{ijklo} \in \{0, 1\} + && v_i \in V;\ v_j \in V;\ v_o \in V^{\mathrm{DEP}}; \nonumber \\ +& && \quad k = 1 \ldots m;\ l = 1 \ldots t \tag{14} \\[4pt] +& y_{ipo} \in \{0, 1\} + && v_i \in V;\ p \in L_i;\ v_o \in V^{\mathrm{DEP}} \tag{15} +\end{align}$$ diff --git a/tasks/vidal2011/problem_description.txt b/tasks/vidal2011/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..41c4b2afd1cc6de50de2a61550054e56cc3bf676 --- /dev/null +++ b/tasks/vidal2011/problem_description.txt @@ -0,0 +1,11 @@ +# Problem Description + +A distribution company operates a fleet of identical vehicles from multiple depots to serve a set of geographically dispersed customers over a planning horizon of several days (periods). The company has a given number of depots and a given number of customers, each located at known coordinates in the plane. A fixed number of identical vehicles is stationed at each depot. Each vehicle has the same carrying capacity and is subject to the same maximum route duration, where route duration is computed as the sum of all travel times and all service times along the route. + +The input data specifies the following for every customer: a two-dimensional location, a demand quantity to be delivered on each visit, a service duration representing the time spent at the customer site, a service frequency indicating how many times the customer must be visited over the planning horizon, and a list of feasible visit patterns, where each pattern is a specific subset of days on which visits may occur. For example, a customer with frequency two and a single feasible pattern consisting of days one and two must be visited on both of those days. The input also specifies the location of each depot and the travel cost (travel time) between every pair of locations, including depot-to-depot, depot-to-customer, and customer-to-customer pairs. The travel costs are defined on a complete graph connecting all depots and all customers. Service time at depots is zero. + +The company must make the following decisions. First, each customer must be assigned to exactly one depot and exactly one of its feasible visit patterns. This assignment is joint: a single choice determines both which depot will serve the customer and on which days that customer will be visited. Once assigned, all visits to a given customer across all periods must originate from the same depot. Second, for each depot and each day, the company must design vehicle routes that begin at the depot, visit a subset of customers, and return to the same depot. Each route is operated by a single vehicle. + +The routes must satisfy several rules. Each vehicle may depart from its home depot at most once per day. A vehicle based at one depot may never depart from or pass through a different depot; routes from a given depot only serve customers assigned to that depot. On each day, a customer assigned to a pattern that includes that day must appear on exactly one route originating from the customer's assigned depot; a customer whose pattern does not include that day must not be visited at all on that day. Every route must form a simple tour starting and ending at its depot, meaning no customer may appear more than once on the same route and no subset of two or more customers may form a disconnected loop. For every vehicle on every day, the total demand of all customers served on its route must not exceed the vehicle capacity, and the total duration of the route, measured as the sum of travel times between consecutive stops plus the service times at all visited customers, must not exceed the maximum route duration. + +The goal is to minimize the total travel cost, computed as the sum of travel costs over all arcs traversed by all vehicles across all depots and all days of the planning horizon. diff --git a/tasks/vidal2011/solution_logger.py b/tasks/vidal2011/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/vidal2011/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/vidal2011/solution_schema.json b/tasks/vidal2011/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..adc7d60ed0a95f14c5f116020bfbd0f3188731bc --- /dev/null +++ b/tasks/vidal2011/solution_schema.json @@ -0,0 +1,12 @@ +{ + "objective_value": " Total travel cost summed over all arcs traversed by all vehicles across all depots and periods.", + "routes": [ + { + "depot": " Identifier of the depot from which this route originates and to which it returns.", + "period": " Period (day) on which this route is operated.", + "vehicle": " Identifier of the vehicle operating this route at its assigned depot.", + "customers": " Ordered sequence of customer identifiers visited along this route, excluding the depot." + } + ], + "assignments": " Joint depot-and-pattern assignment for each customer, where each value is an object with 'depot' (identifier of the depot serving the customer) and 'pattern' (list of periods on which the customer is visited)." +} diff --git a/tasks/walteros2020/feasibility_check.py b/tasks/walteros2020/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..77adff79be5b678925e5c0185e748f246d319f66 --- /dev/null +++ b/tasks/walteros2020/feasibility_check.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for the Maximum Clique Problem. + +Mathematical formulation (Standard IP for Maximum Clique, Section 4 of math_model.txt): + + Decision Variables: + x_v in {0, 1}, v in V (1 if vertex v is in the clique, 0 otherwise) + + Objective: + max sum_{v in V} x_v + + Constraints (numbered top to bottom as they appear in the formulation): + Constraint 1: x_i + x_j <= 1, for all {i, j} in E_bar (non-edges of G) + Constraint 2: objective_value == sum_v x_v + (Tier C obj-consistency: recompute the objective from the + solution variables and reject if the reported value lies.) + +This script checks whether a candidate solution (a set of vertices claimed to +form a clique) satisfies all hard constraints of the IP formulation. +""" + +import argparse +import json + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('clique_vertices', 'objective_value') +_FRONTIEROR_NONEMPTY_SOLUTION_FIELDS = () +_FRONTIEROR_DERIVED_FIELD_RULES = () +_FRONTIEROR_CONDITIONAL_FIELD_RULES = () + + +def _frontieror_validate_solution_contract(solution): + """Return a structured rejection when the public solution contract is absent.""" + violations = [] + if not isinstance(solution, dict): + violations.append("solution must be a JSON object") + else: + missing = [ + field + for field in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS + if field not in solution or solution[field] is None + ] + if missing: + violations.append( + "missing required solution field(s): " + ", ".join(missing) + ) + + for discriminator, expected_value, fields in _FRONTIEROR_CONDITIONAL_FIELD_RULES: + if solution.get(discriminator) != expected_value: + continue + conditional_missing = [ + field + for field in fields + if field not in solution or solution[field] is None + ] + if conditional_missing: + violations.append( + "missing conditionally required solution field(s): " + + ", ".join(conditional_missing) + ) + + empty = [ + field + for field in _FRONTIEROR_NONEMPTY_SOLUTION_FIELDS + if field in solution and solution[field] in (None, [], {}) + ] + if empty: + violations.append( + "empty required decision witness field(s): " + ", ".join(empty) + ) + + for target, operation, source, source_key in _FRONTIEROR_DERIVED_FIELD_RULES: + try: + reported = float(solution[target]) + if operation == "length": + expected = float(len(solution[source])) + elif operation == "mapping_value": + expected = float(solution[source][source_key]) + else: + raise ValueError("unknown derived-field operation") + except (KeyError, TypeError, ValueError, OverflowError): + violations.append( + f"cannot derive {target} from decision witness field {source}" + ) + continue + if ( + reported != reported + or expected != expected + or reported in (float("inf"), float("-inf")) + or expected in (float("inf"), float("-inf")) + or abs(reported - expected) > 1e-6 + ): + violations.append( + f"{target}={reported} does not match the decision-derived " + f"value {expected}" + ) + + if "objective_value" in _FRONTIEROR_REQUIRED_SOLUTION_FIELDS: + objective = solution.get("objective_value") + if ( + isinstance(objective, bool) + or not isinstance(objective, (int, float)) + or objective != objective + or objective in (float("inf"), float("-inf")) + ): + violations.append("objective_value must be a finite JSON number") + + if not violations: + return None + return { + "feasible": False, + "violated_constraints": ["solution_schema"], + "violations": violations, + "violation_magnitudes": [], + } + + +def _frontieror_write_unexpected_rejection(error): + """Turn malformed candidate/checker exceptions into a normal rejection.""" + import json as _frontieror_json + import sys as _frontieror_sys + + result_path = None + for index, argument in enumerate(_frontieror_sys.argv): + if argument == "--result_path" and index + 1 < len(_frontieror_sys.argv): + result_path = _frontieror_sys.argv[index + 1] + break + if argument.startswith("--result_path="): + result_path = argument.split("=", 1)[1] + break + if not result_path: + return False + try: + with open(result_path, "w") as result_handle: + _frontieror_json.dump( + { + "feasible": False, + "violated_constraints": ["malformed_solution"], + "violations": [ + "checker rejected malformed candidate: " + + type(error).__name__ + + ": " + + str(error)[:500] + ], + "violation_magnitudes": [], + }, + result_handle, + indent=2, + ) + except Exception: + return False + return True + + + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["n"] + edges = instance["edges"] + + # Build adjacency set + adj = [set() for _ in range(n)] + for u, v in edges: + adj[u].add(v) + adj[v].add(u) + + # Extract clique vertices from solution (handle both solution formats) + if "clique" in solution: + clique = solution["clique"] + elif "clique_vertices" in solution: + clique = solution["clique_vertices"] + else: + clique = [] + + violations = [] + violation_magnitudes = [] + violated_constraint_set = set() + + # Detect duplicate vertices: each x_v ∈ {0,1}, so a repeated vertex implies + # x_v >= 2 which violates the binary domain. + seen = set() + for v in clique: + if v in seen: + violations.append( + f"Vertex {v} listed more than once in clique_vertices " + f"(implies x_{v} >= 2; binary domain violated).") + violation_magnitudes.append({ + "constraint": "binary_domain", + "lhs": float(clique.count(v)), + "rhs": 1.0, + "raw_excess": float(clique.count(v) - 1), + "normalizer": 1.0, + "ratio": float(clique.count(v) - 1), + }) + violated_constraint_set.add("binary_domain") + seen.add(v) + + # Build binary vector x from the clique + x = [0] * n + for v in clique: + if 0 <= v < n: + x[v] = 1 + + # ------------------------------------------------------------------ + # Constraint 1: x_i + x_j <= 1 for all {i, j} in E_bar (non-edges) + # ------------------------------------------------------------------ + # For every pair of vertices in the clique, they must share an edge. + # Equivalently, for every non-edge {i,j}, x_i + x_j <= 1. + # We only need to check pairs where both x_i=1 and x_j=1. + clique_sorted = sorted(clique) + for idx_a in range(len(clique_sorted)): + for idx_b in range(idx_a + 1, len(clique_sorted)): + i = clique_sorted[idx_a] + j = clique_sorted[idx_b] + if j not in adj[i]: + # {i, j} is a non-edge and both are selected => violation + lhs = x[i] + x[j] # = 2 + rhs = 1.0 + violation_amount = lhs - rhs # = 1.0 + if violation_amount > tol: + violated_constraint_set.add(1) + violations.append( + f"Constraint 1 violated: vertices {i} and {j} are both " + f"in the clique but are not adjacent (non-edge), " + f"x_{i} + x_{j} = {lhs} > {rhs}" + ) + normalizer = max(abs(rhs), eps) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(lhs), + "rhs": float(rhs), + "raw_excess": float(violation_amount), + "normalizer": float(normalizer), + "ratio": float(violation_amount / normalizer), + }) + + # ------------------------------------------------------------------ + # Additional validity checks (not from the IP but ensuring solution + # is well-formed w.r.t. the instance) + # ------------------------------------------------------------------ + # Check that all clique vertex indices are valid (0 <= v < n) + for v in clique: + if v < 0 or v >= n: + violated_constraint_set.add(1) + violations.append( + f"Vertex {v} in clique is out of range [0, {n-1}]" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(v), + "rhs": float(n - 1), + "raw_excess": float(abs(v - (n - 1))), + "normalizer": float(max(abs(n - 1), eps)), + "ratio": float(abs(v - (n - 1)) / max(abs(n - 1), eps)), + }) + + # ------------------------------------------------------------------ + # Constraint 2 (Tier C obj-consistency): reported objective_value must + # equal sum_v x_v -- i.e. the count of distinct in-range clique vertices. + # The obj is integer-valued, so a tolerance of 0.5 fires on any + # integer mismatch by >= 1 while permitting harmless float noise. + # ------------------------------------------------------------------ + reported_obj = solution.get("objective_value") + if reported_obj is not None: + try: + reported = float(reported_obj) + except (TypeError, ValueError): + reported = None + if reported is not None: + true_obj = float(sum(x)) # number of distinct in-range vertices + abs_diff = abs(reported - true_obj) + obj_tol = 0.5 + if abs_diff > obj_tol: + violated_constraint_set.add(2) + violations.append( + f"Constraint 2 violated: reported objective_value=" + f"{reported} differs from recomputed sum_v(x_v)=" + f"{true_obj} (|diff|={abs_diff:.3g}, tol={obj_tol:.3g})" + ) + normalizer = max(abs(true_obj), eps) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(reported), + "rhs": float(true_obj), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + feasible = len(violated_constraint_set) == 0 + + result = { + "feasible": feasible, + "violated_constraints": sorted(violated_constraint_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + + return result + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Maximum Clique solutions." + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance." + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution." + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result." + ) + args = parser.parse_args() + + with open(args.instance_path, "r") as f: + instance = json.load(f) + + with open(args.solution_path, "r") as f: + solution = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(solution) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(instance, solution) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + if result["feasible"]: + print("FEASIBLE: All constraints satisfied.") + else: + print(f"INFEASIBLE: {len(result['violations'])} violation(s) found.") + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/walteros2020/gurobi_code.py b/tasks/walteros2020/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..a768606b9f7473089e1761e482cc98cfcc949ba3 --- /dev/null +++ b/tasks/walteros2020/gurobi_code.py @@ -0,0 +1,137 @@ +""" +Maximum Clique Problem — Gurobi IP Formulation + +Given a simple undirected graph G = (V, E), find a clique C ⊆ V of maximum size. + +IP Formulation: + Decision variables: x_v ∈ {0, 1} for each v ∈ V (1 if vertex v is in the clique) + Objective: max Σ_{v ∈ V} x_v + Constraints: x_i + x_j ≤ 1 for all {i, j} ∈ Ē (non-edges of G) + +NOTE: The complement-based formulation enumerates all non-edges of G. For large, +sparse graphs the number of non-edges can approach n*(n-1)/2 - m, which may be +very memory-intensive. For the instances considered here (e.g. n=1000, m=5985) +this is manageable, but for significantly larger or denser instances an +alternative formulation or decomposition strategy may be necessary. +""" + +import argparse +import json +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def load_instance(instance_path: str) -> tuple: + """Load a graph instance from a JSON file. + + Returns: + n: number of vertices + adj: list of sets representing adjacency sets for each vertex + """ + with open(instance_path, "r") as f: + data = json.load(f) + + n = data["n"] + adj = [set() for _ in range(n)] + for u, v in data["edges"]: + adj[u].add(v) + adj[v].add(u) + + return n, adj + + +def solve(instance_path: str, solution_path: str, time_limit: int) -> None: + n, adj = load_instance(instance_path) + + # --- Build Gurobi model --- + model = gp.Model("MaxClique") + model.setParam("Threads", 1) + + # Binary decision variables: x_v = 1 if vertex v is in the clique + x = model.addVars(n, vtype=GRB.BINARY, name="x") + + # Objective: maximise the number of selected vertices + model.setObjective(gp.quicksum(x[v] for v in range(n)), GRB.MAXIMIZE) + + # Constraints: for every non-edge {i, j}, at most one endpoint in the clique + for i in range(n): + for j in range(i + 1, n): + if j not in adj[i]: + model.addConstr(x[i] + x[j] <= 1) + + # Solver parameters + model.setParam("TimeLimit", time_limit) + + # Solve + model.optimize() + + # --- Extract solution --- + objective_value = None + clique_vertices = [] + + if model.SolCount > 0: + objective_value = round(model.ObjVal) + clique_vertices = [v for v in range(n) if x[v].X > 0.5] + + solution = { + "objective_value": objective_value, + "clique_size": len(clique_vertices), + "clique_vertices": clique_vertices, + "status": model.Status, + "mip_gap": model.MIPGap if model.SolCount > 0 else None, + "runtime": model.Runtime, + } + + with open(solution_path, "w") as f: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, f, indent=2) + + print(f"Objective value: {objective_value}") + print(f"Clique vertices: {clique_vertices}") + + +def main(): + parser = argparse.ArgumentParser( + description="Solve the Maximum Clique problem using Gurobi." + ) + parser.add_argument( + "--instance_path", + type=str, + required=True, + help="Path to the instance JSON file.", + ) + parser.add_argument( + "--solution_path", + type=str, + required=True, + help="Path to write the solution JSON file.", + ) + parser.add_argument( + "--time_limit", + type=int, + default=3600, + help="Time limit for the solver 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.instance_path, args.solution_path, args.time_limit) + + +if __name__ == "__main__": + main() diff --git a/tasks/walteros2020/gurobi_feasi_result/large_feasi_result_1.json b/tasks/walteros2020/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/walteros2020/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/walteros2020/gurobi_feasi_result/large_feasi_result_2.json b/tasks/walteros2020/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/walteros2020/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/walteros2020/gurobi_feasi_result/large_feasi_result_3.json b/tasks/walteros2020/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/walteros2020/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/walteros2020/gurobi_feasi_result/large_feasi_result_4.json b/tasks/walteros2020/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/walteros2020/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/walteros2020/gurobi_feasi_result/large_feasi_result_5.json b/tasks/walteros2020/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/walteros2020/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/walteros2020/gurobi_feasi_result/tiny_feasi_result.json b/tasks/walteros2020/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/walteros2020/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/walteros2020/gurobi_solution/large_solution_1.json b/tasks/walteros2020/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..1fcad3de215cb09e1a2555c5260f456da2b1ef34 --- /dev/null +++ b/tasks/walteros2020/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed7ee55e139b2b0f1b6d159c9ca535a1f66a3d727bba71b116d7461670fb79ca +size 399 diff --git a/tasks/walteros2020/gurobi_solution/large_solution_2.json b/tasks/walteros2020/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e7d61fd44eb9a9ad0e5a5125d40ef8f66fbafa10 --- /dev/null +++ b/tasks/walteros2020/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfd58b907bd26ec25c46b5a6871f64684c7fd9b4a811c46478cb240eb679d826 +size 147 diff --git a/tasks/walteros2020/gurobi_solution/large_solution_3.json b/tasks/walteros2020/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7baa0f09f36b576a9db0b250d45386b17d009e5a --- /dev/null +++ b/tasks/walteros2020/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9866e03e0cd0a60781975916725ad7cc2efb7b003944d2463d77c7498e6c66c +size 155 diff --git a/tasks/walteros2020/gurobi_solution/large_solution_4.json b/tasks/walteros2020/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..dee952fb5cd7047c5ab19471729749ef434337bc --- /dev/null +++ b/tasks/walteros2020/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eaac4dcd9434cbdd350989f945986be1f45667b39c1d2983b0fa770a6fda4bfa +size 187 diff --git a/tasks/walteros2020/gurobi_solution/large_solution_5.json b/tasks/walteros2020/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..c178c104f88ca20f9debc83e3db791d0ff456db9 --- /dev/null +++ b/tasks/walteros2020/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d57101c8623655a2a7bff786cdf217012415d7a4e07652b2262e6524c1f7e52f +size 146 diff --git a/tasks/walteros2020/gurobi_solution/tiny_solution.json b/tasks/walteros2020/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..9ec407e15d44f1e60e0edab8e1bbf33325ff8a6d --- /dev/null +++ b/tasks/walteros2020/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b3c85d859374d183079381137c098c61eb8f460d77d2a5e464cebdddd46b7a0 +size 189 diff --git a/tasks/walteros2020/gurobi_solution_log/large_log_1.jsonl b/tasks/walteros2020/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8e821e4414b9b033a7961e7dbbff991e87047ca3 --- /dev/null +++ b/tasks/walteros2020/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a92e821cf651ce7e7d152b3d8358d43c4ae3aa4000c0f369c68214e3830603ec +size 41 diff --git a/tasks/walteros2020/gurobi_solution_log/large_log_2.jsonl b/tasks/walteros2020/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e43ac65b0a6784821fb21be9e12eaced113cf9e8 --- /dev/null +++ b/tasks/walteros2020/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:418902702cf8f9ecb83105f7d314ac108a57fab1de7c3f89f3bfe1a7982b404e +size 40 diff --git a/tasks/walteros2020/gurobi_solution_log/large_log_3.jsonl b/tasks/walteros2020/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7d6fac234745165acfc7bd7f49833b1dd01cee2e --- /dev/null +++ b/tasks/walteros2020/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef2974d57db62089c9d6140a5ba0207131364a4f217bf9a86c00a4ae0cd81e58 +size 82 diff --git a/tasks/walteros2020/gurobi_solution_log/large_log_4.jsonl b/tasks/walteros2020/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff5e02d49842f18ed30d0fd836f7806cc6e1b4d4 --- /dev/null +++ b/tasks/walteros2020/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ae5a7f033943a1002930deb70e6b4659a19eaa44574324a24fee17d1013f40a +size 83 diff --git a/tasks/walteros2020/gurobi_solution_log/large_log_5.jsonl b/tasks/walteros2020/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7310ad4f8b8a8503c0e7ac50fa61532cc5f4d498 --- /dev/null +++ b/tasks/walteros2020/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a99eaefcd81e6d182dda3d96125c2319a590de78ffb7dc95148a0f83ee981f8 +size 41 diff --git a/tasks/walteros2020/gurobi_solution_log/tiny_log.jsonl b/tasks/walteros2020/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..112167834913ab5f456061073180cc6ffce2445d --- /dev/null +++ b/tasks/walteros2020/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf6d1904ad64fcd0b9c4d19015481d29ceb4d7501f8a81796be5107af0fa06be +size 40 diff --git a/tasks/walteros2020/instance/large_instance_1.json b/tasks/walteros2020/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..bf95e98c5f02a03d733e62417d8d7d944b07fe9f --- /dev/null +++ b/tasks/walteros2020/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c1ea26318b01d779fc8921b5defdfb587cc6de1763c8892b23979cbd3477eab +size 6692 diff --git a/tasks/walteros2020/instance/large_instance_2.json b/tasks/walteros2020/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..712357627c0a2f4d989f8276b22b9b5305226eda --- /dev/null +++ b/tasks/walteros2020/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19c8fbc2c483b31c9c4a0e95a2c63a441f4b66c47ede6ad7197e2fc370bf13eb +size 1365 diff --git a/tasks/walteros2020/instance/large_instance_3.json b/tasks/walteros2020/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..040e0c59de857288d1bd89b9a9cb5aeb99bbb10f --- /dev/null +++ b/tasks/walteros2020/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:154e566e47d12fb5ee73de35a0895213bc4966e454aa32803bef4323cfec6648 +size 111772 diff --git a/tasks/walteros2020/instance/large_instance_4.json b/tasks/walteros2020/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..af75d821eb9e1505855d4ad357bc8d3709855193 --- /dev/null +++ b/tasks/walteros2020/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1852a159b5f0ad5b5bec0f2c293352364dee740ac5be9143fa3991ad24c88d05 +size 67696 diff --git a/tasks/walteros2020/instance/large_instance_5.json b/tasks/walteros2020/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..4ecaa26b9fd57b43dc20edcd2c3ab7d501bf8293 --- /dev/null +++ b/tasks/walteros2020/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f6ecf2fe7a52f834395db9d9ef5fbfdf9fe4680ca3851978a0ecf16873eabe0 +size 1399 diff --git a/tasks/walteros2020/instance/tiny_instance.json b/tasks/walteros2020/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..b1f9bf27f04c71cf1ebbacf1cb70394a2c6f7025 --- /dev/null +++ b/tasks/walteros2020/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98e3c2c7b892a03c8697471204c92f2b59ae1d01bb684e544ba55a29a2489b73 +size 202506 diff --git a/tasks/walteros2020/instance_schema.json b/tasks/walteros2020/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..5b26908b1ceeb7eb57e96d3a43b16eaf0d4a551e --- /dev/null +++ b/tasks/walteros2020/instance_schema.json @@ -0,0 +1,9 @@ +{ + "n": " Total number of vertices in the undirected graph.", + "m": " Total number of edges in the undirected graph.", + "max_degree": " Largest number of edges incident to any single vertex in the graph.", + "degeneracy": " Smallest value d such that every subgraph contains a vertex of degree at most d.", + "omega": " Size of the largest clique known to exist in the graph.", + "clique_core_gap": " Difference between the degeneracy plus one and the maximum clique size.", + "edges": " Each entry is a pair of vertex indices representing an undirected edge in the graph." +} \ No newline at end of file diff --git a/tasks/walteros2020/mathematical_formulation.md b/tasks/walteros2020/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..f503f25e307ea36bdd1ba15ddccb3b0c3154aef6 --- /dev/null +++ b/tasks/walteros2020/mathematical_formulation.md @@ -0,0 +1,40 @@ +# Original Formulation: Maximum Clique Problem (MCP) + +*Source: “Why Is Maximum Clique Often Easy in Practice?”, Jose L. Walteros, Austin Buchanan, 2020.* + +## Sets and Parameters + +$$\begin{align*} +G = (V, E) \quad &\text{simple undirected input graph} + &&\% \text{RECONSTRUCTED --- paper's notation, Sec.\ 2} \\ +V = \{1, \dots, n\}, \; n = |V| \quad &\text{set of vertices} + &&\% \text{RECONSTRUCTED --- not in paper} \\ +E \subseteq \tbinom{V}{2}, \; m = |E| \quad &\text{set of edges} + &&\% \text{RECONSTRUCTED --- not in paper} \\ +\overline{E} = \tbinom{V}{2} \setminus E \quad &\text{set of non-edges (edges of complement } \overline{G}) + &&\% \text{RECONSTRUCTED --- not in paper} +\end{align*}$$ + +## Decision Variables + +$$\begin{align*} +x_v \in \{0,1\}, \quad v \in V \qquad + &\text{$1$ if vertex $v$ is in the clique, $0$ otherwise.} + &&\% \text{RECONSTRUCTED --- not in paper} +\end{align*}$$ + +## Objective + +$$\begin{align} +\max \quad \sum_{v \in V} x_v + \tag{R1} % RECONSTRUCTED --- maximize clique size omega(G) +\end{align}$$ + +## Constraints + +$$\begin{align} +x_i + x_j &\le 1, &&\forall\, \{i,j\} \in \overline{E}, + \tag{R2} \\ % RECONSTRUCTED --- non-adjacent vertices cannot both be chosen +x_v &\in \{0,1\}, &&\forall\, v \in V. + \tag{R3} % RECONSTRUCTED --- not in paper +\end{align}$$ diff --git a/tasks/walteros2020/problem_description.txt b/tasks/walteros2020/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..532298ec835bf67c131bc9739a41f92d5d49ddbe --- /dev/null +++ b/tasks/walteros2020/problem_description.txt @@ -0,0 +1,5 @@ +# Problem Description + +Given a simple, undirected graph specified by a set of vertices numbered from zero up to one less than the total vertex count, and a set of undirected edges where each edge connects two distinct vertices with no parallel edges or self-loops, the task is to select a subset of vertices of maximum size such that every pair of selected vertices is directly connected by an edge. Such a fully interconnected subset is called a clique. The input data provides the number of vertices, the number of edges, and the complete list of edges as pairs of vertex indices. Additional metadata may include the graph's maximum degree, its degeneracy (the smallest value d such that every subgraph contains a vertex of degree at most d), the known maximum clique size, and the clique-core gap (defined as the degeneracy plus one minus the maximum clique size), but these are supplementary and not required for stating the problem. + +The sole decision to be made is which vertices to include in the chosen subset. The only rule governing this selection is that for every pair of vertices in the subset, an edge must exist between them in the given graph. Equivalently, for every pair of vertices in the graph that are not connected by an edge (a "non-edge"), at most one of the two may be selected. The goal is to maximize the total number of vertices in the selected subset. diff --git a/tasks/walteros2020/solution_logger.py b/tasks/walteros2020/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/walteros2020/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/walteros2020/solution_schema.json b/tasks/walteros2020/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..83d78ef81b8014b1db4068a22c8dbd10869be976 --- /dev/null +++ b/tasks/walteros2020/solution_schema.json @@ -0,0 +1,4 @@ +{ + "objective_value": " Number of vertices in the chosen fully interconnected subset.", + "clique_vertices": " Indices of the vertices selected to form the maximum clique." +} diff --git a/tasks/wang2019/feasibility_check.py b/tasks/wang2019/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7c41b710e01108e4af769b2f310c275b82890172 --- /dev/null +++ b/tasks/wang2019/feasibility_check.py @@ -0,0 +1,530 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Service Network Design with Heterogeneous Fleet. +Paper: Wang, Qi, Cheng, Zhang (2019) - EJOR 276, 483-494 + +Checks the arc-based formulation (Equations 1-6): + Constraint 1 (Eq 2): Flow conservation for each commodity at each node + Constraint 2 (Eq 3): Design-balance for each fleet type at each node + Constraint 3 (Eq 4): Capacity linking on each arc + Constraint 4 (Eq 5): Non-negativity of flow variables + Constraint 5 (Eq 6): Integrality and non-negativity of vehicle variables + Constraint 6 (Eq 1): Objective-value consistency -- the reported + objective_value must match the recomputed cost + sum_{k,(i,j)} c_{ij}^k * x_{ij}^k + sum_{f,(i,j)} h_{ij}^f * y_{ij}^f + from the solution variables. Tier C defense against LLM + score-gaming exploits that pass constraints but lie about cost. +""" + +import json +import argparse +from collections import defaultdict + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('flows', 'objective_value', 'vehicles') +_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 _flow_cost(arc, k): + fc = arc.get("flow_costs") + if isinstance(fc, dict): + if str(k) in fc: + return fc[str(k)] + if k in fc: + return fc[k] + elif isinstance(fc, list) and 0 <= k < len(fc): + return fc[k] + return arc["flow_cost"] + + +def _fixed_cost(fleet, arc_id): + ac = fleet.get("arc_fixed_costs") + if isinstance(ac, dict): + if str(arc_id) in ac: + return ac[str(arc_id)] + if arc_id in ac: + return ac[arc_id] + elif isinstance(ac, list) and 0 <= arc_id < len(ac): + return ac[arc_id] + return fleet["fixed_cost"] + + +def check_feasibility(data, sol): + tol = 1e-5 + eps = 1e-5 + + nodes = data["nodes"] + arcs = data["arcs"] + commodities = data["commodities"] + fleet_types = data["fleet_types"] + + arc_set = set() + for a in arcs: + arc_set.add((a["from"], a["to"])) + + successors = defaultdict(list) + predecessors = defaultdict(list) + for a in arcs: + successors[a["from"]].append(a["to"]) + predecessors[a["to"]].append(a["from"]) + + x = defaultdict(float) + for key, val in sol.get("flows", {}).items(): + parts = key.split("_") + k = int(parts[1]) + i = int(parts[2]) + j = int(parts[3]) + x[(k, i, j)] = float(val) + + y = defaultdict(float) + for key, val in sol.get("vehicles", {}).items(): + parts = key.split("_") + f_id = int(parts[1]) + i = int(parts[2]) + j = int(parts[3]) + y[(f_id, i, j)] = float(val) + + violated_constraints = set() + violations = [] + violation_magnitudes = [] + + # ================================================================ + # Constraint 1 (Eq 2): Flow conservation + # ================================================================ + for kd in commodities: + k = kd["id"] + origin = kd["origin"] + dest = kd["destination"] + demand = kd["demand"] + for i in nodes: + if i == origin: + w = demand + elif i == dest: + w = -demand + else: + w = 0 + + outflow = sum(x[(k, i, j)] for j in successors[i]) + inflow = sum(x[(k, j, i)] for j in predecessors[i]) + lhs = outflow - inflow + rhs = float(w) + violation_amount = abs(lhs - rhs) + + if violation_amount > tol: + violated_constraints.add(1) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 1 (Flow conservation): commodity {k} at node {i}: " + f"net flow = {lhs:.6f}, required = {rhs:.6f}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(violation_amount, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + # ================================================================ + # Constraint 2 (Eq 3): Design-balance + # ================================================================ + for fd in fleet_types: + f_id = fd["id"] + for i in nodes: + outflow = sum(y[(f_id, i, j)] for j in successors[i]) + inflow = sum(y[(f_id, j, i)] for j in predecessors[i]) + lhs = outflow - inflow + rhs = 0.0 + violation_amount = abs(lhs - rhs) + + if violation_amount > tol: + violated_constraints.add(2) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 2 (Design-balance): fleet type {f_id} at node {i}: " + f"net vehicles = {lhs:.6f}, required = 0" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(violation_amount, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + # ================================================================ + # Constraint 3 (Eq 4): Capacity linking + # ================================================================ + for a in arcs: + i, j = a["from"], a["to"] + total_flow = sum(x[(kd["id"], i, j)] for kd in commodities) + total_capacity = sum(fd["capacity"] * y[(fd["id"], i, j)] for fd in fleet_types) + lhs = total_flow + rhs = total_capacity + violation_amount = max(lhs - rhs, 0.0) + + if violation_amount > tol: + violated_constraints.add(3) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 3 (Capacity): arc ({i},{j}): " + f"total flow = {lhs:.6f}, capacity = {rhs:.6f}" + ) + violation_magnitudes.append({ + "constraint": 3, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(violation_amount, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + # ================================================================ + # Constraint 4 (Eq 5): Non-negativity of flow variables + # ================================================================ + for kd in commodities: + k = kd["id"] + for a in arcs: + i, j = a["from"], a["to"] + val = x[(k, i, j)] + lhs = val + rhs = 0.0 + violation_amount = max(-lhs, 0.0) + + if violation_amount > tol: + violated_constraints.add(4) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 4 (Non-negativity flow): x_{k}_{i}_{j} = {val:.6f} < 0" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(violation_amount, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + for (k, i, j), val in x.items(): + if (i, j) not in arc_set and val > tol: + violated_constraints.add(4) + violations.append( + f"Constraint 4 (Non-negativity flow): flow x_{k}_{i}_{j} = {val:.6f} " + f"on non-existent arc ({i},{j})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": round(val, 10), + "rhs": 0.0, + "raw_excess": round(val, 10), + "normalizer": eps, + "ratio": round(val / eps, 10) + }) + + # ================================================================ + # Constraint 5 (Eq 6): Integrality and non-negativity of vehicles + # ================================================================ + for fd in fleet_types: + f_id = fd["id"] + for a in arcs: + i, j = a["from"], a["to"] + val = y[(f_id, i, j)] + + if val < -tol: + lhs = val + rhs = 0.0 + violation_amount = -val + violated_constraints.add(5) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 5 (Non-neg vehicle): y_{f_id}_{i}_{j} = {val:.6f} < 0" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(violation_amount, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + if val >= -tol: + rounded = round(val) + int_violation = abs(val - rounded) + if int_violation > tol: + lhs = val + rhs = float(rounded) + violation_amount = int_violation + violated_constraints.add(5) + normalizer = max(abs(rhs), eps) + ratio = violation_amount / normalizer + violations.append( + f"Constraint 5 (Integrality vehicle): y_{f_id}_{i}_{j} = {val:.6f} " + f"is not integer (nearest int = {rounded})" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": round(lhs, 10), + "rhs": round(rhs, 10), + "raw_excess": round(violation_amount, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + for (f_id, i, j), val in y.items(): + if (i, j) not in arc_set and val > tol: + violated_constraints.add(5) + violations.append( + f"Constraint 5 (Vehicle domain): y_{f_id}_{i}_{j} = {val:.6f} " + f"on non-existent arc ({i},{j})" + ) + violation_magnitudes.append({ + "constraint": 5, + "lhs": round(val, 10), + "rhs": 0.0, + "raw_excess": round(val, 10), + "normalizer": eps, + "ratio": round(val / eps, 10) + }) + + # ================================================================ + # Constraint 6 (Eq 1): Objective-value consistency (Tier C) + # reported_obj must match + # sum_{k,(i,j)} c_{ij}^k * x_{ij}^k + # + sum_{f,(i,j)} h_{ij}^f * y_{ij}^f + # recomputed from the solution variables (legal arcs only -- + # flows/vehicles on non-existent arcs are already caught by 4/5). + # ================================================================ + 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: + commodity_ids = [kd["id"] for kd in commodities] + true_obj = 0.0 + for a in arcs: + i, j = a["from"], a["to"] + for k in commodity_ids: + xv = x[(k, i, j)] + if xv: + true_obj += _flow_cost(a, k) * xv + for fd in fleet_types: + f_id = fd["id"] + for a in arcs: + i, j = a["from"], a["to"] + yv = y[(f_id, i, j)] + if yv: + true_obj += _fixed_cost(fd, a["id"]) * yv + + abs_diff = abs(reported - true_obj) + # 0.1% relative tolerance with 1e-3 absolute floor. + obj_tol = max(1e-3, 1e-3 * abs(true_obj)) + if abs_diff > obj_tol: + violated_constraints.add(6) + normalizer = max(abs(true_obj), eps) + ratio = abs_diff / normalizer + violations.append( + f"Constraint 6 (Objective consistency): reported objective_value=" + f"{reported} differs from recomputed total cost=" + f"{true_obj} (|diff|={abs_diff:.6g}, tol={obj_tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 6, + "lhs": round(reported, 10), + "rhs": round(true_obj, 10), + "raw_excess": round(abs_diff, 10), + "normalizer": round(normalizer, 10), + "ratio": round(ratio, 10) + }) + + feasible = len(violated_constraints) == 0 + return { + "feasible": feasible, + "violated_constraints": sorted(violated_constraints), + "violations": violations, + "violation_magnitudes": violation_magnitudes if not feasible else [] + } + + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for Service Network Design (Wang et al. 2019)" + ) + parser.add_argument("--instance_path", type=str, required=True, + help="Path to the JSON instance file.") + parser.add_argument("--solution_path", type=str, required=True, + help="Path to the JSON solution file.") + parser.add_argument("--result_path", type=str, required=True, + help="Path to write the JSON feasibility result.") + args = parser.parse_args() + + with open(args.instance_path, "r") as f: + data = json.load(f) + with open(args.solution_path, "r") as f: + sol = json.load(f) + _frontieror_contract_result = _frontieror_validate_solution_contract(sol) + if _frontieror_contract_result is not None: + with open(args.result_path, "w") as _frontieror_result_handle: + json.dump( + _frontieror_contract_result, + _frontieror_result_handle, + indent=2, + ) + return + + result = check_feasibility(data, sol) + + with open(args.result_path, "w") as f: + json.dump(result, f, indent=2) + + feasible = result["feasible"] + print(f"Feasibility check complete. Result: {'FEASIBLE' if feasible else 'INFEASIBLE'}") + if not feasible: + print(f"Violated constraints: {result['violated_constraints']}") + print(f"Number of violations: {len(result['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/wang2019/gurobi_code.py b/tasks/wang2019/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..29a15ea5f6ba2240ae4205d19e648aecaef322b2 --- /dev/null +++ b/tasks/wang2019/gurobi_code.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +""" +Gurobi implementation of Service Network Design with Heterogeneous Fleet. +Paper: Wang, Qi, Cheng, Zhang (2019) - EJOR 276, 483-494 + +Uses the arc-based formulation (Equations 1-6): + min sum_{k in K} sum_{(i,j) in A} c^k_{ij} * x^k_{ij} + + sum_{f in F} sum_{(i,j) in A} h^f_{ij} * y^f_{ij} + s.t. + (2) Flow conservation for each commodity k at each node i + (3) Design-balance for each fleet type f at each node i + (4) Capacity linking on each arc (i,j) + (5) x^k_{ij} >= 0 + (6) y^f_{ij} in Z_0^+ +""" + +import json +import argparse +import gurobipy as gp +from gurobipy import GRB +import os as _os, sys as _sys +import time +# Walk up from this file's directory to find repo root (containing scripts/). +_GUROBI_CODE_START_TIME = time.time() +_repo = _os.path.dirname(_os.path.abspath(__file__)) +while _repo != _os.path.dirname(_repo) and not _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _repo = _os.path.dirname(_repo) +if _os.path.isdir(_os.path.join(_repo, 'scripts', 'utils')): + _sys.path.insert(0, _repo) +try: + from scripts.utils.gurobi_log_helper import install_gurobi_logger +except ImportError: + def install_gurobi_logger(log_path): # no-op fallback when scripts/ unavailable + pass + + +def main(): + parser = argparse.ArgumentParser( + description="Service Network Design - Gurobi Arc-Based 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 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: + data = json.load(f) + + nodes = data["nodes"] + arcs = data["arcs"] + commodities = data["commodities"] + fleet_types = data["fleet_types"] + + # ---- Cost lookup helpers (paper convention c^k_{ij}, h^f_{ij}) ---- + # An instance MAY supply commodity-indexed flow cost on each arc as + # arc["flow_costs"] # dict {commodity_id: cost} or list indexed by id + # and arc-indexed fixed cost on each fleet type as + # fleet["arc_fixed_costs"] # dict {arc_id: cost} or list indexed by arc id + # When those higher-dimensional fields are absent, fall back to the + # broadcast scalar (arc["flow_cost"], fleet["fixed_cost"]) — equivalent + # to c^k_{ij} = c_{ij} for all k, h^f_{ij} = h^f for all (i,j). + def _flow_cost(arc, k): + fc = arc.get("flow_costs") + if isinstance(fc, dict): + if str(k) in fc: + return fc[str(k)] + if k in fc: + return fc[k] + elif isinstance(fc, list) and 0 <= k < len(fc): + return fc[k] + return arc["flow_cost"] + + def _fixed_cost(fleet, arc_id): + ac = fleet.get("arc_fixed_costs") + if isinstance(ac, dict): + if str(arc_id) in ac: + return ac[str(arc_id)] + if arc_id in ac: + return ac[arc_id] + elif isinstance(ac, list) and 0 <= arc_id < len(ac): + return ac[arc_id] + return fleet["fixed_cost"] + + # Build arc list as tuples and successor/predecessor sets + arc_list = [(a["from"], a["to"]) for a in arcs] + arc_by_endpoints = {} + for a in arcs: + arc_by_endpoints[(a["from"], a["to"])] = a + + successors = {n: [] for n in nodes} + predecessors = {n: [] for n in nodes} + for a in arcs: + successors[a["from"]].append(a["to"]) + predecessors[a["to"]].append(a["from"]) + + # ---- Create Gurobi model ---- + model = gp.Model("SND_ArcBased") + model.setParam("Threads", 1) + model.setParam("TimeLimit", args.time_limit) + + # ---- Decision variables ---- + # x[k, i, j]: continuous flow of commodity k on arc (i,j) + # Per paper Eq. (1) the unit flow cost c^k_{ij} is indexed by both + # commodity k and arc (i,j); _flow_cost() resolves it from the instance + # (commodity-indexed when present, scalar broadcast otherwise). + x = {} + for kd in commodities: + k = kd["id"] + for a in arcs: + i, j = a["from"], a["to"] + x[k, i, j] = model.addVar( + lb=0.0, vtype=GRB.CONTINUOUS, + obj=_flow_cost(a, k), + name=f"x_{k}_{i}_{j}" + ) + + # y[f, i, j]: integer number of vehicles of fleet type f on arc (i,j) + # Per paper Eq. (1) the fixed cost h^f_{ij} is indexed by both fleet + # type f and arc (i,j); _fixed_cost() resolves it from the instance + # (arc-indexed when present, scalar broadcast otherwise). + y = {} + for fd in fleet_types: + f = fd["id"] + for a in arcs: + i, j = a["from"], a["to"] + y[f, i, j] = model.addVar( + lb=0, vtype=GRB.INTEGER, + obj=_fixed_cost(fd, a["id"]), + name=f"y_{f}_{i}_{j}" + ) + + model.update() + + # ---- Constraints ---- + + # Constraint (2): Flow conservation for each commodity k at each node i + # sum_{j in N_i^+} x^k_{ij} - sum_{j in N_i^-} x^k_{ji} = w^k_i + for kd in commodities: + k = kd["id"] + origin = kd["origin"] + destination = kd["destination"] + demand = kd["demand"] + for i in nodes: + if i == origin: + w = demand + elif i == destination: + w = -demand + else: + w = 0 + model.addConstr( + gp.quicksum(x[k, i, j] for j in successors[i]) + - gp.quicksum(x[k, j, i] for j in predecessors[i]) == w, + name=f"flow_{k}_{i}" + ) + + # Constraint (3): Design-balance for each fleet type f at each node i + # sum_{j in N_i^+} y^f_{ij} - sum_{j in N_i^-} y^f_{ji} = 0 + for fd in fleet_types: + f = fd["id"] + for i in nodes: + model.addConstr( + gp.quicksum(y[f, i, j] for j in successors[i]) + - gp.quicksum(y[f, j, i] for j in predecessors[i]) == 0, + name=f"balance_{f}_{i}" + ) + + # Constraint (4): Capacity linking on each arc (i,j) + # sum_{k in K} x^k_{ij} <= sum_{f in F} u^f * y^f_{ij} + for a in arcs: + i, j = a["from"], a["to"] + model.addConstr( + gp.quicksum(x[kd["id"], i, j] for kd in commodities) + <= gp.quicksum(fd["capacity"] * y[fd["id"], i, j] for fd in fleet_types), + name=f"cap_{i}_{j}" + ) + + # ---- Optimize ---- + model.optimize() + + # ---- Extract solution ---- + solution = {} + + if model.SolCount > 0: + solution["objective_value"] = model.ObjVal + + # Flow variables + flows = {} + for kd in commodities: + k = kd["id"] + for a in arcs: + i, j = a["from"], a["to"] + val = x[k, i, j].X + if val > 1e-6: + flows[f"x_{k}_{i}_{j}"] = round(val, 6) + solution["flows"] = flows + + # Vehicle assignment variables + vehicles = {} + for fd in fleet_types: + f = fd["id"] + for a in arcs: + i, j = a["from"], a["to"] + val = y[f, i, j].X + if val > 0.5: + vehicles[f"y_{f}_{i}_{j}"] = int(round(val)) + solution["vehicles"] = vehicles + + if model.Status == GRB.OPTIMAL: + solution["status"] = "optimal" + else: + solution["status"] = "feasible" + try: + solution["mip_gap"] = model.MIPGap + except Exception: + solution["mip_gap"] = None + else: + solution["objective_value"] = None + solution["status"] = "no_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["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/wang2019/gurobi_feasi_result/large_feasi_result_1.json b/tasks/wang2019/gurobi_feasi_result/large_feasi_result_1.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/wang2019/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/wang2019/gurobi_feasi_result/large_feasi_result_2.json b/tasks/wang2019/gurobi_feasi_result/large_feasi_result_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/wang2019/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/wang2019/gurobi_feasi_result/large_feasi_result_3.json b/tasks/wang2019/gurobi_feasi_result/large_feasi_result_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/wang2019/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/wang2019/gurobi_feasi_result/large_feasi_result_4.json b/tasks/wang2019/gurobi_feasi_result/large_feasi_result_4.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/wang2019/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/wang2019/gurobi_feasi_result/large_feasi_result_5.json b/tasks/wang2019/gurobi_feasi_result/large_feasi_result_5.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/wang2019/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/wang2019/gurobi_feasi_result/tiny_feasi_result.json b/tasks/wang2019/gurobi_feasi_result/tiny_feasi_result.json new file mode 100644 index 0000000000000000000000000000000000000000..e305b82c3d6732211d5033415df1a105476e9cf1 --- /dev/null +++ b/tasks/wang2019/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/wang2019/gurobi_solution/large_solution_1.json b/tasks/wang2019/gurobi_solution/large_solution_1.json new file mode 100644 index 0000000000000000000000000000000000000000..17d493b40ec4d1fcfda2ebc9b7e3130b2076071f --- /dev/null +++ b/tasks/wang2019/gurobi_solution/large_solution_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1803c06c927b7c923ec652d95d9e0ea5eca0b6baf3f139f04d0f9367abbd113 +size 34557 diff --git a/tasks/wang2019/gurobi_solution/large_solution_2.json b/tasks/wang2019/gurobi_solution/large_solution_2.json new file mode 100644 index 0000000000000000000000000000000000000000..8d70a000598e0cdf27f01678451bb01a624c6ba7 --- /dev/null +++ b/tasks/wang2019/gurobi_solution/large_solution_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46c1520de31d46da5b1d50912688d0685edae142f7cc3257b3e02f6dbd3c1e86 +size 24328 diff --git a/tasks/wang2019/gurobi_solution/large_solution_3.json b/tasks/wang2019/gurobi_solution/large_solution_3.json new file mode 100644 index 0000000000000000000000000000000000000000..7fccce61de3876e361f390176d268650c9f18cb6 --- /dev/null +++ b/tasks/wang2019/gurobi_solution/large_solution_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54b9f4b937db4829fb0759f9d0cdfd180c90e9060adc818fcb017b54145f9650 +size 30601 diff --git a/tasks/wang2019/gurobi_solution/large_solution_4.json b/tasks/wang2019/gurobi_solution/large_solution_4.json new file mode 100644 index 0000000000000000000000000000000000000000..b597cb4d389ba2ae07f9e3657788e04efd2da70c --- /dev/null +++ b/tasks/wang2019/gurobi_solution/large_solution_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8622f3cb7a058fc89a01529058d82a038975c782903a36b4ec31b3cdd7fe5df +size 26195 diff --git a/tasks/wang2019/gurobi_solution/large_solution_5.json b/tasks/wang2019/gurobi_solution/large_solution_5.json new file mode 100644 index 0000000000000000000000000000000000000000..eec51f8159d09686b1caa82b16641a0fc63f0485 --- /dev/null +++ b/tasks/wang2019/gurobi_solution/large_solution_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0eef60dd057a5bd5d1144f904a6385e8dd0acfee4281373633cc69c67426d774 +size 27516 diff --git a/tasks/wang2019/gurobi_solution/tiny_solution.json b/tasks/wang2019/gurobi_solution/tiny_solution.json new file mode 100644 index 0000000000000000000000000000000000000000..387b59eb2a3b4f57b6a315672bb497135e531d28 --- /dev/null +++ b/tasks/wang2019/gurobi_solution/tiny_solution.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b126c7cb7b6f92c0e46254442069280fec03a1d7949c85934006a642c8ff037 +size 1512 diff --git a/tasks/wang2019/gurobi_solution_log/large_log_1.jsonl b/tasks/wang2019/gurobi_solution_log/large_log_1.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4f971184e5e8867131b622be15df365a11b96dfb --- /dev/null +++ b/tasks/wang2019/gurobi_solution_log/large_log_1.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f52a066cd0d920c74019029fe6f04b15000a7d8a35c1dc88653fc0eba8ae376 +size 2115 diff --git a/tasks/wang2019/gurobi_solution_log/large_log_2.jsonl b/tasks/wang2019/gurobi_solution_log/large_log_2.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8cb99f6ba22037cf8b3c191f8f1aaa6d9e963129 --- /dev/null +++ b/tasks/wang2019/gurobi_solution_log/large_log_2.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81d05db3f6dd18d624eebf2dc56b641821a6c429d24d7fd3e11177b8480e15ff +size 1998 diff --git a/tasks/wang2019/gurobi_solution_log/large_log_3.jsonl b/tasks/wang2019/gurobi_solution_log/large_log_3.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4f4dcb3f0ba67e65761059011ba2bfe48e859fa7 --- /dev/null +++ b/tasks/wang2019/gurobi_solution_log/large_log_3.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87c5ff6a5d6b426f37d81877cb8238a0efe8f4ffb1ecad796dc40827a3a303c4 +size 3679 diff --git a/tasks/wang2019/gurobi_solution_log/large_log_4.jsonl b/tasks/wang2019/gurobi_solution_log/large_log_4.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..342df49acb92fb86e02f447c726758237ee02ab6 --- /dev/null +++ b/tasks/wang2019/gurobi_solution_log/large_log_4.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30a7b153a926a8d4b4a723f326e2f53438d6f6e7978df56db448f04d2e876f8e +size 3061 diff --git a/tasks/wang2019/gurobi_solution_log/large_log_5.jsonl b/tasks/wang2019/gurobi_solution_log/large_log_5.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f103deccdd46e960e705cf2b114be0a4b19ecfa8 --- /dev/null +++ b/tasks/wang2019/gurobi_solution_log/large_log_5.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2926a876daee53d2991eb9bf3e939aaf6806b3821827edd4d5422b6b89b17b9 +size 2391 diff --git a/tasks/wang2019/gurobi_solution_log/tiny_log.jsonl b/tasks/wang2019/gurobi_solution_log/tiny_log.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dce044bdd9055a7e1dab0fdd5f6e6fa3e355a92a --- /dev/null +++ b/tasks/wang2019/gurobi_solution_log/tiny_log.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26cede67c7ff23beb988f6156b3fc5fa44ce50ad1e7d991b8f6a8578b39f3330 +size 98 diff --git a/tasks/wang2019/instance/large_instance_1.json b/tasks/wang2019/instance/large_instance_1.json new file mode 100644 index 0000000000000000000000000000000000000000..a619300c308e30cf82544ca1783bb5d8d68aea86 --- /dev/null +++ b/tasks/wang2019/instance/large_instance_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97b173545b6b204a09156d51be704acb21cea1b19b8b53b330b177964fc39a2a +size 105771 diff --git a/tasks/wang2019/instance/large_instance_2.json b/tasks/wang2019/instance/large_instance_2.json new file mode 100644 index 0000000000000000000000000000000000000000..4fd56b305f7c830e32ea52d4232ee6f20f89f95d --- /dev/null +++ b/tasks/wang2019/instance/large_instance_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70a244179ff8a760cc4245c414d7c0e8f57a8e450ea62ad368b4d06b183074f2 +size 105790 diff --git a/tasks/wang2019/instance/large_instance_3.json b/tasks/wang2019/instance/large_instance_3.json new file mode 100644 index 0000000000000000000000000000000000000000..ea828f58e697576ac01c64a8e6d4d5a229e90375 --- /dev/null +++ b/tasks/wang2019/instance/large_instance_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4c6e993fa54994ad3a317fab18293ad6612bd87911a4f1cec58fd865250b22d +size 105710 diff --git a/tasks/wang2019/instance/large_instance_4.json b/tasks/wang2019/instance/large_instance_4.json new file mode 100644 index 0000000000000000000000000000000000000000..d246b19d610c7a9942d025ef777f773d5a917fa4 --- /dev/null +++ b/tasks/wang2019/instance/large_instance_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7511e93760faed91f5013b58b358c984628dbc47fa0be1f7dfaff39d0e082557 +size 105732 diff --git a/tasks/wang2019/instance/large_instance_5.json b/tasks/wang2019/instance/large_instance_5.json new file mode 100644 index 0000000000000000000000000000000000000000..8d988a31fbd7ba9b1e5d122dea708d1dd8a437dc --- /dev/null +++ b/tasks/wang2019/instance/large_instance_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:087e46aaec23712ff288af68d8f2936f31e3f5d08e9eade593dbb2adb5c20d31 +size 105716 diff --git a/tasks/wang2019/instance/tiny_instance.json b/tasks/wang2019/instance/tiny_instance.json new file mode 100644 index 0000000000000000000000000000000000000000..0dfecced4d1f84dde54c5c66d82e884355c63a0b --- /dev/null +++ b/tasks/wang2019/instance/tiny_instance.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f00584c11a07a5319a319149cd44b4682d7a37b5a194b8b38018a5663ac28f3 +size 4856 diff --git a/tasks/wang2019/instance_schema.json b/tasks/wang2019/instance_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..a22ef49555293dc7888612ad12b4df02a8e45716 --- /dev/null +++ b/tasks/wang2019/instance_schema.json @@ -0,0 +1,30 @@ +{ + "num_nodes": " Total number of terminals in the service network.", + "num_arcs": " Total number of directed service links in the network.", + "num_commodities": " Total number of commodities to be transported.", + "num_fleet_types": " Total number of distinct vehicle types available.", + "nodes": " Set of terminal identifiers in the network.", + "arcs": [ + { + "id": " Unique identifier for this arc.", + "from": " Origin terminal of this directed service link.", + "to": " Destination terminal of this directed service link.", + "flow_cost": " Per-unit cost for shipping one unit of any commodity along this arc." + } + ], + "commodities": [ + { + "id": " Unique identifier for this commodity.", + "origin": " Terminal where this commodity originates.", + "destination": " Terminal where this commodity must be delivered.", + "demand": " Quantity of this commodity that must be shipped from origin to destination." + } + ], + "fleet_types": [ + { + "id": " Unique identifier for this vehicle type.", + "capacity": " Maximum total flow that one vehicle of this type can carry on an arc.", + "fixed_cost": " Cost incurred for deploying one vehicle of this type on any arc." + } + ] +} diff --git a/tasks/wang2019/mathematical_formulation.md b/tasks/wang2019/mathematical_formulation.md new file mode 100644 index 0000000000000000000000000000000000000000..a8a72270a66c6c0962dcccefbb06c79308cc19a7 --- /dev/null +++ b/tasks/wang2019/mathematical_formulation.md @@ -0,0 +1,63 @@ +# Original Formulation: Service Network Design with a Heterogeneous Fleet (SND) + +*Source: A hybrid algorithm for large-scale service network design considering a heterogeneous fleet, Z. Wang, M. Qi, C. Cheng, C. Zhang, European Journal of Operational Research 276 (2019) 483–494.* + +## Sets and Indices + +- $G=(N,A)$: directed graph with node set $N$ and arc set $A$; index $(i,j)\in A$. + +- $K$: set of commodities; index $k\in K$. Commodity $k$ has demand $d^k$, origin node $o(k)$, and destination node $d(k)$. + +- $F$: set of fleet (vehicle) types; index $f\in F$. + +- $N_i^{+}=\{\,j\in N \mid (i,j)\in A\,\}$: set of successor nodes of node $i$. + +- $N_i^{-}=\{\,j\in N \mid (j,i)\in A\,\}$: set of predecessor nodes of node $i$. + +## Parameters + +- $c_{ij}^{k}$: unit flow cost of transporting commodity $k\in K$ on arc $(i,j)\in A$. + +- $h_{ij}^{f}$: fixed cost of utilizing one vehicle of fleet type $f\in F$ on arc $(i,j)\in A$. + +- $u^{f}$: capacity of fleet type $f\in F$. + +- $d^{k}$: demand of commodity $k\in K$. + +- $w_i^{k}$: net supply/demand of commodity $k$ at node $i$, defined as $$w_i^{k}= + \begin{cases} + d^{k} & \text{if } i=o(k),\\ + -d^{k} & \text{if } i=d(k),\\ + 0 & \text{otherwise.} + \end{cases}$$ + +There is no limit on the number of vehicles of each type. + +## Decision Variables + +- $x_{ij}^{k}\ge 0$: continuous variable, the amount of flow of commodity $k\in K$ on arc $(i,j)\in A$. + +- $y_{ij}^{f}\in\mathbb{Z}_0^{+}$: integer variable, the number of vehicles of fleet type $f\in F$ providing transportation services on arc $(i,j)\in A$. + +## Objective + +$$\begin{equation} +\min \ \sum_{k\in K}\sum_{(i,j)\in A} c_{ij}^{k} x_{ij}^{k} + + \sum_{f\in F}\sum_{(i,j)\in A} h_{ij}^{f} y_{ij}^{f} +\tag{1} +\end{equation}$$ + +## Constraints + +$$\begin{align} +\sum_{j\in N_i^{+}} x_{ij}^{k} - \sum_{j\in N_i^{-}} x_{ji}^{k} &= w_i^{k} + && \forall\, i\in N,\ \forall\, k\in K, \tag{2}\\[4pt] +\sum_{j\in N_i^{+}} y_{ij}^{f} - \sum_{j\in N_i^{-}} y_{ji}^{f} &= 0 + && \forall\, i\in N,\ \forall\, f\in F, \tag{3}\\[4pt] +\sum_{k\in K} x_{ij}^{k} &\le \sum_{f\in F} u^{f} y_{ij}^{f} + && \forall\, (i,j)\in A, \tag{4}\\[4pt] +x_{ij}^{k} &\ge 0 + && \forall\, (i,j)\in A,\ \forall\, k\in K, \tag{5}\\[4pt] +y_{ij}^{f} &\in \mathbb{Z}_0^{+} + && \forall\, (i,j)\in A,\ \forall\, f\in F. \tag{6} +\end{align}$$ diff --git a/tasks/wang2019/problem_description.txt b/tasks/wang2019/problem_description.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f2108c87bb4cb83e29b0004b559b30369a8a988 --- /dev/null +++ b/tasks/wang2019/problem_description.txt @@ -0,0 +1,7 @@ +# Problem Description + +A freight transportation carrier operates a service network represented as a directed graph with a given set of nodes (terminals) and a given set of directed arcs (service links between terminals). The carrier must transport a set of commodities through this network, where each commodity has a known origin node, a known destination node, and a known demand quantity that must be shipped in full from origin to destination. The carrier operates a heterogeneous fleet consisting of several vehicle types, each with a known capacity and a known fixed cost per arc for deploying one vehicle of that type on that arc. There is no limit on the number of vehicles available for any type. Each combination of commodity and arc has a known unit flow cost, so that the cost of shipping a given commodity along a given arc equals that unit flow cost multiplied by the quantity of that commodity routed on that arc. + +The carrier must decide two things simultaneously: how to route the flow of each commodity through the network, and how many vehicles of each type to assign to each arc. The flow of each commodity must be balanced at every node: at each node the total outgoing flow of a commodity minus its total incoming flow equals the commodity's demand if that node is the commodity's origin, equals the negative of the demand if that node is the commodity's destination, and equals zero at all other nodes. On every arc, the total flow of all commodities combined must not exceed the total capacity provided by the vehicles assigned to that arc, where total capacity is the sum over all vehicle types of each type's capacity multiplied by the number of vehicles of that type on the arc. The flow of each commodity on each arc cannot be negative. The number of vehicles of each type assigned to each arc must be a whole number that is zero or greater. The number of vehicles of each type must be balanced at every node, meaning that for each vehicle type, the total number of vehicles of that type entering a node across all incoming arcs must equal the total number leaving that node across all outgoing arcs. This balance requirement ensures that vehicles follow cyclical routes through the network so that the fleet is conserved. + +The goal is to minimize the total cost, which is the sum of two components: the total flow cost, computed as the sum over all arcs and all commodities of the unit flow cost times the amount of that commodity routed on that arc, and the total fixed vehicle cost, computed as the sum over all arcs and all vehicle types of the fixed cost times the number of vehicles of that type assigned to that arc. diff --git a/tasks/wang2019/solution_logger.py b/tasks/wang2019/solution_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5393fa935ce71df9da95cee04fe5199077cb8461 --- /dev/null +++ b/tasks/wang2019/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/wang2019/solution_schema.json b/tasks/wang2019/solution_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9031293ae56419c7049c9ca164faf330973b8486 --- /dev/null +++ b/tasks/wang2019/solution_schema.json @@ -0,0 +1,5 @@ +{ + "objective_value": " Total cost comprising flow transportation costs and vehicle deployment costs.", + "flows": " Amount of a commodity routed along a directed arc.", + "vehicles": " Number of vehicles of a given type assigned to a directed arc." +} diff --git a/tasks/wang2025/feasibility_check.py b/tasks/wang2025/feasibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7f346ad705499844c000c5e09fc7b87da474b29a --- /dev/null +++ b/tasks/wang2025/feasibility_check.py @@ -0,0 +1,472 @@ +#!/usr/bin/env python3 +""" +Feasibility checker for Approximately Submodular Function Maximization (ASFM). + +Checks candidate solutions against the hard constraints from the mathematical +formulation in math_model.txt. + +Constraints numbered top-to-bottom from the formulation sections: + Constraint 1 (Eq. 1): |S| <= k, S subset of N + Constraint 2 (Eq. 1): z <= f(S*) (objective consistency with the + original problem; the Eq. 10 reformulation + cuts for S' != S* are BIP tractability + artifacts and are NOT part of Eq. 1's + feasible region) + Constraint 3 (Eq. 10): sum_{i in N} y_i <= k + Constraint 4 (Eq. 10): y_i in {0, 1}, for all i in N + Constraints 5-7 (Eq. 11): implied by 2-4 (Q subset of F) + Constraints 8-12 (Eq. 17): branch-and-cut node specific, not applicable to final solution + Constraint 13 (Tier C): Objective consistency |z - f(S*)| <= tol. + Constraint 2 only catches over-reporting + (z > f(S*)); this bilateral check additionally + catches under-reporting exploits (e.g. obj=0) + that misrepresent the solution's true value. +""" + +import argparse +import json +import numpy as np + +# FRONTIEROR_RELEASE_CONTRACT_V2 +_FRONTIEROR_REQUIRED_SOLUTION_FIELDS = ('objective_value', 'selected_elements') +_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 + + + +# ============================================================================ +# Set function oracle (same as in efficient_algorithm.py / gurobi_code.py) +# ============================================================================ + +def build_set_function(instance): + """Return a callable f(frozenset) based on instance type.""" + inst_type = instance["instance_type"] + data = np.array(instance["data_matrix"]) + m, n = data.shape + + if inst_type == "LOC": + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + return float(np.sum(np.max(data[:, cols], axis=1))) + return f, n, m + + elif inst_type == "COV": + weights = np.array(instance["node_weights"]) + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + covered = np.max(data[:, cols], axis=1) + return float(np.dot(weights, covered)) + return f, n, m + + elif inst_type == "INF": + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + survival = np.prod(1.0 - data[:, cols], axis=1) + return float(np.sum(1.0 - survival)) + return f, n, m + + else: + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + return float(np.sum(np.max(data[:, cols], axis=1))) + return f, n, m + + +# ============================================================================ +# Feasibility checking +# ============================================================================ + +def check_feasibility(instance, solution): + tol = 1e-5 + eps = 1e-5 + + n = instance["n"] + k = instance["k"] + gamma_bar = instance["gamma"] + + f, n_actual, m = build_set_function(instance) + + selected = solution["selected_elements"] + z = solution["objective_value"] + + violations = [] + violation_magnitudes = [] + violated_set = set() + + # Build y vector from selected elements + y = [0] * n + valid_selected = [] + for elem in selected: + if isinstance(elem, int) and 0 <= elem < n: + y[elem] = 1 + valid_selected.append(elem) + + # ------------------------------------------------------------------ + # Constraint 1 (Eq. 1): |S| <= k, S ⊆ N + # ------------------------------------------------------------------ + + # Check S ⊆ N: all elements must be in {0, ..., n-1} + for elem in selected: + if not isinstance(elem, int) or elem < 0 or elem >= n: + violated_set.add(1) + lhs_val = float(elem) if isinstance(elem, (int, float)) else 0.0 + rhs_val = float(n - 1) + raw = max(lhs_val - rhs_val, 0.0) if isinstance(elem, (int, float)) and elem >= n else 1.0 + normalizer = max(abs(rhs_val), eps) + violations.append( + f"Element {elem} is not in N = {{0, ..., {n-1}}}" + ) + violation_magnitudes.append({ + "constraint": 1, + "lhs": lhs_val, + "rhs": rhs_val, + "raw_excess": raw, + "normalizer": normalizer, + "ratio": raw / normalizer, + }) + + # Check |S| <= k + card = len(selected) + if card - k > tol: + violated_set.add(1) + raw = float(card - k) + rhs_val = float(k) + normalizer = max(abs(rhs_val), eps) + violations.append(f"Cardinality |S| = {card} exceeds k = {k}") + violation_magnitudes.append({ + "constraint": 1, + "lhs": float(card), + "rhs": rhs_val, + "raw_excess": raw, + "normalizer": normalizer, + "ratio": raw / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 2 (Eq. 1): z <= f(S*) (objective consistency). + # + # Eq. 10 is a BIP reformulation of Eq. 1; its exponential family + # of cuts indexed by S' is a tractability artifact of that + # reformulation, not part of Eq. 1's feasible region. Enumerating + # the cuts for S' != S* over-enforces the reformulation and can + # reject valid solutions. Only the tight cut at S' = S* is + # semantically meaningful here; it reduces to z <= f(S*). + # ------------------------------------------------------------------ + + S_star = frozenset(valid_selected) + f_S_star = f(S_star) + + # Check z <= f(S*) (tightest upper-bound constraint) + if z - f_S_star > tol: + violated_set.add(2) + raw = z - f_S_star + normalizer = max(abs(f_S_star), eps) + violations.append( + f"Reported objective z = {z} exceeds f(S*) = {f_S_star} " + f"(violates upper-bound constraint for S' = S*)" + ) + violation_magnitudes.append({ + "constraint": 2, + "lhs": float(z), + "rhs": float(f_S_star), + "raw_excess": float(raw), + "normalizer": float(normalizer), + "ratio": float(raw / normalizer), + }) + + # ------------------------------------------------------------------ + # Constraint 3 (Eq. 10): sum_{i in N} y_i <= k + # ------------------------------------------------------------------ + + sum_y = sum(y) + if sum_y - k > tol: + violated_set.add(3) + raw = float(sum_y - k) + rhs_val = float(k) + normalizer = max(abs(rhs_val), eps) + violations.append(f"Sum of y_i = {sum_y} exceeds k = {k}") + violation_magnitudes.append({ + "constraint": 3, + "lhs": float(sum_y), + "rhs": rhs_val, + "raw_excess": raw, + "normalizer": normalizer, + "ratio": raw / normalizer, + }) + + # ------------------------------------------------------------------ + # Constraint 4 (Eq. 10): y_i in {0, 1} for all i in N + # ------------------------------------------------------------------ + + # Check for duplicate elements (would imply y_i > 1) + if len(set(selected)) != len(selected): + violated_set.add(4) + num_dups = len(selected) - len(set(selected)) + violations.append( + f"Duplicate elements in selected_elements ({num_dups} duplicate(s))" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(len(selected)), + "rhs": float(len(set(selected))), + "raw_excess": float(num_dups), + "normalizer": max(float(len(set(selected))), eps), + "ratio": float(num_dups) / max(float(len(set(selected))), eps), + }) + + # Check all elements are non-negative integers + for elem in selected: + if not isinstance(elem, int): + violated_set.add(4) + violations.append( + f"Element {elem} is not an integer (type: {type(elem).__name__})" + ) + violation_magnitudes.append({ + "constraint": 4, + "lhs": float(elem) if isinstance(elem, (int, float)) else 0.0, + "rhs": 0.0, + "raw_excess": 1.0, + "normalizer": eps, + "ratio": 1.0 / eps, + }) + + # ------------------------------------------------------------------ + # Constraint 13 (Tier C obj-recompute): |z - f(S*)| <= tol. + # + # Constraint 2 only catches over-reporting (z > f(S*)); this + # bilateral check additionally catches under-reporting exploits + # (e.g. obj=0 with a non-empty S*), where the candidate + # misrepresents the solution's true value via a fabricated + # objective_value. Only fires when reported z and f(S*) are both + # finite numbers; non-numeric or NaN z is ignored here to avoid + # masking other failure modes. + # ------------------------------------------------------------------ + + try: + reported = float(z) + reported_ok = np.isfinite(reported) + except (TypeError, ValueError): + reported = None + reported_ok = False + + if reported_ok: + abs_diff = abs(reported - f_S_star) + # 0.1% relative tolerance with 1e-3 absolute floor + obj_tol = max(1e-3, 1e-3 * abs(f_S_star)) + if abs_diff > obj_tol: + violated_set.add(13) + normalizer = max(abs(f_S_star), eps) + violations.append( + f"Objective consistency violated: reported objective_value = " + f"{reported} differs from recomputed f(S*) = {f_S_star} " + f"(|diff| = {abs_diff:.6g}, tol = {obj_tol:.6g})" + ) + violation_magnitudes.append({ + "constraint": 13, + "lhs": float(reported), + "rhs": float(f_S_star), + "raw_excess": float(abs_diff), + "normalizer": float(normalizer), + "ratio": float(abs_diff / normalizer), + }) + + # ------------------------------------------------------------------ + # Build result + # ------------------------------------------------------------------ + + result = { + "feasible": len(violated_set) == 0, + "violated_constraints": sorted(violated_set), + "violations": violations, + "violation_magnitudes": violation_magnitudes, + } + return result + + +# ============================================================================ +# Main +# ============================================================================ + +def main(): + parser = argparse.ArgumentParser( + description="Feasibility checker for ASFM candidate solutions" + ) + parser.add_argument( + "--instance_path", type=str, required=True, + help="Path to the JSON file containing the data instance" + ) + parser.add_argument( + "--solution_path", type=str, required=True, + help="Path to the JSON file containing the candidate solution" + ) + parser.add_argument( + "--result_path", type=str, required=True, + help="Path to write the JSON file containing the feasibility result" + ) + args = parser.parse_args() + + with open(args.instance_path) as fp: + instance = json.load(fp) + with open(args.solution_path) as fp: + solution = json.load(fp) + _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 fp: + json.dump(result, fp, indent=2) + + print(f"Feasible: {result['feasible']}") + if not result["feasible"]: + for v in result["violations"]: + print(f" - {v}") + + +if __name__ == "__main__": + try: + main() + except Exception as _frontieror_unexpected_error: + if not _frontieror_write_unexpected_rejection( + _frontieror_unexpected_error + ): + raise diff --git a/tasks/wang2025/gurobi_code.py b/tasks/wang2025/gurobi_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4fd74a9b9a9e761f5757f42869fefc2d2133bd68 --- /dev/null +++ b/tasks/wang2025/gurobi_code.py @@ -0,0 +1,291 @@ +""" +Gurobi implementation of the BIP formulation for Approximately Submodular +Function Maximization (ASFM) from: + "An efficient branch-and-cut algorithm for approximately submodular + function maximization" (Uematsu, Umetani, Kawahara, 2019) + +Uses the Modified Constraint Generation (MCG) algorithm (Section 4.1) +to solve BIP(Q) (Eq. 11) iteratively. +""" + +import argparse +import json +import time +import numpy as np +import gurobipy as gp +from gurobipy import GRB +from itertools import combinations +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# =========================================================================== +# Set function oracle +# =========================================================================== + +def build_set_function(instance): + """Return a callable f(S) based on instance type.""" + inst_type = instance["instance_type"] + data = np.array(instance["data_matrix"]) # m x n + m, n = data.shape + + if inst_type == "LOC": + # Facility Location: f(S) = sum_{i in M} max_{j in S} g_{ij} + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + return float(np.sum(np.max(data[:, cols], axis=1))) + return f, n, m + + elif inst_type == "COV": + # Weighted Coverage: f(S) = sum_{i in M} w_i * max_{j in S} a_{ij} + # data_matrix stores a_{ij} (binary coverage), node_weights stores w_i + weights = np.array(instance["node_weights"]) + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + covered = np.max(data[:, cols], axis=1) + return float(np.dot(weights, covered)) + return f, n, m + + elif inst_type == "INF": + # Bipartite Influence: f(S) = sum_{i in M} (1 - prod_{j in S} (1 - q_{ij})) + # data_matrix stores q_{ij} + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + survival = np.prod(1.0 - data[:, cols], axis=1) + return float(np.sum(1.0 - survival)) + return f, n, m + + else: + # **NOT SPECIFIED IN PAPER**: Unknown instance type. + # Inferred assumption: treat data_matrix as LOC-style. + def f(S): + if len(S) == 0: + return 0.0 + cols = list(S) + return float(np.sum(np.max(data[:, cols], axis=1))) + return f, n, m + + +def marginal_gain(f, S, i): + """f({i} | S) = f(S ∪ {i}) - f(S)""" + return f(S | {i}) - f(S) + + +# =========================================================================== +# Greedy algorithm +# =========================================================================== + +def greedy(f, n, k): + """ + Standard greedy algorithm (Minoux 1978, Nemhauser et al. 1978). + Returns (S, order) where order is the sequence of elements added. + """ + S = set() + order = [] + for _ in range(k): + best_i, best_gain = -1, -float('inf') + for i in range(n): + if i not in S: + g = marginal_gain(f, S, i) + if g > best_gain: + best_gain = g + best_i = i + S.add(best_i) + order.append(best_i) + return S, order + + +# =========================================================================== +# BIP(Q) solver using Gurobi — Modified Constraint Generation (MCG) +# =========================================================================== + +def solve_bip_q(f, n, k, gamma_bar, Q_plus, time_remaining): + """ + Solve BIP(Q^+) (Eq. 11) using Gurobi. + + For each S in Q_plus: + j = argmax_{i in N\\S} f({i}|S) + z <= f(S) + f({j}|S)*y_j + sum_{i in N\\(S∪{j})} (1/gamma_bar)*f({i}|S)*y_i + + Returns (solution_set, objective_value, y_values) + """ + model = gp.Model("BIP_Q") + model.setParam("Threads", 1) + model.setParam("OutputFlag", 0) + model.setParam("TimeLimit", max(1, time_remaining)) + + # Variables + z = model.addVar(lb=-GRB.INFINITY, name="z") + y = {} + for i in range(n): + y[i] = model.addVar(vtype=GRB.BINARY, name=f"y_{i}") + + model.setObjective(z, GRB.MAXIMIZE) + + # Cardinality constraint + model.addConstr(gp.quicksum(y[i] for i in range(n)) <= k, "cardinality") + + # Constraints for each S in Q_plus + N_set = set(range(n)) + for idx, S in enumerate(Q_plus): + S_frozen = frozenset(S) + fS = f(S_frozen) + + # j = argmax_{i in N\S} f({i}|S) + complement = N_set - S_frozen + if len(complement) == 0: + # S = N, constraint is z <= f(N) + model.addConstr(z <= fS, f"cut_{idx}") + continue + + best_j, best_mg = -1, -float('inf') + marginals = {} + for i in complement: + mg = marginal_gain(f, S_frozen, i) + marginals[i] = mg + if mg > best_mg: + best_mg = mg + best_j = i + + # Build constraint + expr = fS + marginals[best_j] * y[best_j] + for i in complement: + if i != best_j: + expr += (1.0 / gamma_bar) * marginals[i] * y[i] + + model.addConstr(z <= expr, f"cut_{idx}") + + model.optimize() + + if model.SolCount > 0: + sol = set() + y_vals = {} + for i in range(n): + y_vals[i] = y[i].X + if y[i].X > 0.5: + sol.add(i) + return sol, model.ObjVal, y_vals + else: + return None, -float('inf'), {} + + +def solve_mcg(f, n, k, gamma_bar, time_limit): + """ + Modified Constraint Generation Algorithm (MCG) from Section 4.1. + Iteratively solves BIP(Q) and adds violated constraints. + """ + start_time = time.time() + + # Step 1: Greedy initial solution + S0, order = greedy(f, n, k) + S_star = set(S0) + f_star = f(frozenset(S_star)) + + # Q = {S^(0)}, Q^+ includes greedy sub-solutions + Q = [set(S0)] + Q_plus_list = [] + for i in range(k + 1): + Q_plus_list.append(set(order[:i])) + # Q_plus includes the greedy sub-solutions + Q_plus = list(Q_plus_list) + + t = 1 + while True: + elapsed = time.time() - start_time + remaining = time_limit - elapsed + if remaining <= 1: + break + + # Step 2: Solve BIP(Q^+) + sol, z_t, y_vals = solve_bip_q(f, n, k, gamma_bar, Q_plus, remaining) + + if sol is None: + break + + # Step 3: Update incumbent + f_sol = f(frozenset(sol)) + if f_sol > f_star: + S_star = set(sol) + f_star = f_sol + + # Step 4: Check convergence + if abs(z_t - f_star) < 1e-9: + break + + if z_t <= f_star + 1e-9: + break + + # Add S^(t) to Q and Q^+ + Q.append(set(sol)) + Q_plus.append(set(sol)) + + t += 1 + + # Safety: avoid infinite loops + # The number of iterations is bounded by C(n,k) + if t > 10000: + break + + return S_star, f_star + + +# =========================================================================== +# Main +# =========================================================================== + +def main(): + parser = argparse.ArgumentParser( + description="Gurobi solver for ASFM via Modified Constraint Generation (MCG)" + ) + 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") + 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) + + with open(args.instance_path, "r") as fp: + instance = json.load(fp) + + n = instance["n"] + k = instance["k"] + gamma_bar = instance["gamma"] # lower bound on submodular ratio used as gamma_bar + + f, n_actual, m = build_set_function(instance) + assert n_actual == n, f"Mismatch: instance n={n}, data columns={n_actual}" + + S_star, f_star = solve_mcg(f, n, k, gamma_bar, args.time_limit) + + solution = { + "objective_value": f_star, + "selected_elements": sorted(list(S_star)), + "instance_id": instance.get("instance_id", None), + } + + with open(args.solution_path, "w") as fp: + solution["runtime"] = time.time() - _GUROBI_CODE_START_TIME + json.dump(solution, fp, indent=2) + + print(f"Objective value: {f_star}") + print(f"Selected elements: {sorted(list(S_star))}") + + +if __name__ == "__main__": + main()